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

@ -2,7 +2,7 @@ package com.intellectualcrafters.jnbt;
/** /**
* The {@code TAG_Double} tag. * The {@code TAG_Double} tag.
* *
*/ */
public final class DoubleTag extends Tag { public final class DoubleTag extends Tag {
@ -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.
@ -13,15 +14,17 @@ import static com.google.common.base.Preconditions.checkNotNull;
public final class ListTag extends Tag { public final class ListTag extends Tag {
private final Class<? extends Tag> type; private final Class<? extends Tag> type;
private final List<Tag> value; private final List<Tag> value;
/** /**
* 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,26 +1,27 @@
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.
*/ */
public class ListTagBuilder { public class ListTagBuilder {
private final Class<? extends Tag> type; private final Class<? extends Tag> type;
private final List<Tag> entries; private final List<Tag> entries;
/** /**
* 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

@ -2,7 +2,7 @@ package com.intellectualcrafters.jnbt;
/** /**
* The {@code TAG_Long} tag. * The {@code TAG_Long} tag.
* *
*/ */
public final class LongTag extends Tag { public final class LongTag extends Tag {
@ -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.
@ -20,42 +17,44 @@ public final class NBTConstants {
private NBTConstants() { private 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;
case TYPE_BYTE: case TYPE_BYTE:
return ByteTag.class; return ByteTag.class;
case TYPE_SHORT: case TYPE_SHORT:
return ShortTag.class; return ShortTag.class;
case TYPE_INT: case TYPE_INT:
return IntTag.class; return IntTag.class;
case TYPE_LONG: case TYPE_LONG:
return LongTag.class; return LongTag.class;
case TYPE_FLOAT: case TYPE_FLOAT:
return FloatTag.class; return FloatTag.class;
case TYPE_DOUBLE: case TYPE_DOUBLE:
return DoubleTag.class; return DoubleTag.class;
case TYPE_BYTE_ARRAY: case TYPE_BYTE_ARRAY:
return ByteArrayTag.class; return ByteArrayTag.class;
case TYPE_STRING: case TYPE_STRING:
return StringTag.class; return StringTag.class;
case TYPE_LIST: case TYPE_LIST:
return ListTag.class; return ListTag.class;
case TYPE_COMPOUND: case TYPE_COMPOUND:
return CompoundTag.class; return CompoundTag.class;
case TYPE_INT_ARRAY: case TYPE_INT_ARRAY:
return IntArrayTag.class; return IntArrayTag.class;
default: default:
throw new IllegalArgumentException("Unknown tag type ID of " + id); throw new IllegalArgumentException("Unknown tag type ID of " + id);
} }
} }

View File

@ -13,10 +13,12 @@ import java.util.Map;
* This class reads <strong>NBT</strong>, or <strong>Named Binary Tag</strong> * This class reads <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* 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 {
@ -25,19 +27,22 @@ 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);
} }
/** /**
* 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);
@ -45,21 +50,24 @@ 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 = "";
} }
@ -68,85 +76,90 @@ 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 {
return new EndTag();
}
case NBTConstants.TYPE_BYTE:
return new ByteTag(name, is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(name, is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(name, is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(name, is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(name, is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(name, is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
byte[] bytes = new byte[length];
is.readFully(bytes);
return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING:
length = is.readShort();
bytes = new byte[length];
is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
int childType = is.readByte();
length = is.readInt();
List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, "", depth + 1);
if (tag instanceof EndTag) {
throw new IOException("TAG_End not permitted in a list.");
} }
tagList.add(tag); else {
} return new EndTag();
return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) {
Tag tag = readTag(depth + 1);
if (tag instanceof EndTag) {
break;
} else {
tagMap.put(tag.getName(), tag);
} }
} case NBTConstants.TYPE_BYTE:
return new ByteTag(name, this.is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(name, this.is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(name, this.is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(name, this.is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(name, this.is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(name, this.is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = this.is.readInt();
byte[] bytes = new byte[length];
this.is.readFully(bytes);
return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING:
length = this.is.readShort();
bytes = new byte[length];
this.is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
final int childType = this.is.readByte();
length = this.is.readInt();
return new CompoundTag(name, tagMap); final List<Tag> tagList = new ArrayList<Tag>();
case NBTConstants.TYPE_INT_ARRAY: for (int i = 0; i < length; ++i) {
length = is.readInt(); final Tag tag = readTagPayload(childType, "", depth + 1);
int[] data = new int[length]; if (tag instanceof EndTag) {
for (int i = 0; i < length; i++) { throw new IOException("TAG_End not permitted in a list.");
data[i] = is.readInt(); }
} tagList.add(tag);
return new IntArrayTag(name, data); }
default:
throw new IOException("Invalid tag type: " + type + "."); return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
final Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) {
final Tag tag = readTag(depth + 1);
if (tag instanceof EndTag) {
break;
}
else {
tagMap.put(tag.getName(), tag);
}
}
return new CompoundTag(name, tagMap);
case NBTConstants.TYPE_INT_ARRAY:
length = this.is.readInt();
final int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = this.is.readInt();
}
return new IntArrayTag(name, data);
default:
throw new IOException("Invalid tag type: " + type + ".");
} }
} }
@Override @Override
public void close() throws IOException { public void close() throws IOException {
is.close(); this.is.close();
} }
} }

View File

@ -11,15 +11,15 @@ import java.util.List;
* This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong> * This class writes <strong>NBT</strong>, or <strong>Named Binary Tag</strong>
* <code>Tag</code> objects to an underlying <code>OutputStream</code>. * <code>Tag</code> objects to an underlying <code>OutputStream</code>.
* </p> * </p>
* *
* <p> * <p>
* The NBT format was created by Markus Persson, and the specification may be * The NBT format was created by Markus Persson, and the specification may be
* found at <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>. * http://www.minecraft.net/docs/NBT.txt</a>.
* </p> * </p>
* *
* @author Graham Edgecombe * @author Graham Edgecombe
* *
*/ */
public final class NBTOutputStream implements Closeable { public final class NBTOutputStream implements Closeable {
@ -31,32 +31,32 @@ public final class NBTOutputStream implements Closeable {
/** /**
* Creates a new <code>NBTOutputStream</code>, which will write data to the * Creates a new <code>NBTOutputStream</code>, which will write data to the
* specified underlying output stream. * specified underlying output stream.
* *
* @param os * @param os
* The output stream. * The output stream.
* @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);
} }
/** /**
* Writes a tag. * Writes a tag.
* *
* @param tag * @param tag
* The tag to write. * The tag to write.
* @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.");
@ -67,112 +67,112 @@ public final class NBTOutputStream implements Closeable {
/** /**
* Writes tag payload. * Writes tag payload.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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);
break; break;
case NBTConstants.TYPE_BYTE: case NBTConstants.TYPE_BYTE:
writeByteTagPayload((ByteTag) tag); writeByteTagPayload((ByteTag) tag);
break; break;
case NBTConstants.TYPE_SHORT: case NBTConstants.TYPE_SHORT:
writeShortTagPayload((ShortTag) tag); writeShortTagPayload((ShortTag) tag);
break; break;
case NBTConstants.TYPE_INT: case NBTConstants.TYPE_INT:
writeIntTagPayload((IntTag) tag); writeIntTagPayload((IntTag) tag);
break; break;
case NBTConstants.TYPE_LONG: case NBTConstants.TYPE_LONG:
writeLongTagPayload((LongTag) tag); writeLongTagPayload((LongTag) tag);
break; break;
case NBTConstants.TYPE_FLOAT: case NBTConstants.TYPE_FLOAT:
writeFloatTagPayload((FloatTag) tag); writeFloatTagPayload((FloatTag) tag);
break; break;
case NBTConstants.TYPE_DOUBLE: case NBTConstants.TYPE_DOUBLE:
writeDoubleTagPayload((DoubleTag) tag); writeDoubleTagPayload((DoubleTag) tag);
break; break;
case NBTConstants.TYPE_BYTE_ARRAY: case NBTConstants.TYPE_BYTE_ARRAY:
writeByteArrayTagPayload((ByteArrayTag) tag); writeByteArrayTagPayload((ByteArrayTag) tag);
break; break;
case NBTConstants.TYPE_STRING: case NBTConstants.TYPE_STRING:
writeStringTagPayload((StringTag) tag); writeStringTagPayload((StringTag) tag);
break; break;
case NBTConstants.TYPE_LIST: case NBTConstants.TYPE_LIST:
writeListTagPayload((ListTag) tag); writeListTagPayload((ListTag) tag);
break; break;
case NBTConstants.TYPE_COMPOUND: case NBTConstants.TYPE_COMPOUND:
writeCompoundTagPayload((CompoundTag) tag); writeCompoundTagPayload((CompoundTag) tag);
break; break;
case NBTConstants.TYPE_INT_ARRAY: case NBTConstants.TYPE_INT_ARRAY:
writeIntArrayTagPayload((IntArrayTag) tag); writeIntArrayTagPayload((IntArrayTag) tag);
break; break;
default: default:
throw new IOException("Invalid tag type: " + type + "."); throw new IOException("Invalid tag type: " + type + ".");
} }
} }
/** /**
* Writes a <code>TAG_Byte</code> tag. * Writes a <code>TAG_Byte</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Byte_Array</code> tag. * Writes a <code>TAG_Byte_Array</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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);
} }
/** /**
* Writes a <code>TAG_Compound</code> tag. * Writes a <code>TAG_Compound</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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?
} }
/** /**
* Writes a <code>TAG_List</code> tag. * Writes a <code>TAG_List</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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));
} }
@ -180,100 +180,101 @@ public final class NBTOutputStream implements Closeable {
/** /**
* Writes a <code>TAG_String</code> tag. * Writes a <code>TAG_String</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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);
} }
/** /**
* Writes a <code>TAG_Double</code> tag. * Writes a <code>TAG_Double</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Float</code> tag. * Writes a <code>TAG_Float</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Long</code> tag. * Writes a <code>TAG_Long</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Int</code> tag. * Writes a <code>TAG_Int</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Short</code> tag. * Writes a <code>TAG_Short</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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());
} }
/** /**
* Writes a <code>TAG_Empty</code> tag. * Writes a <code>TAG_Empty</code> tag.
* *
* @param tag * @param tag
* The tag. * The tag.
* @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,131 +17,160 @@ 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;
case NBTConstants.TYPE_BYTE: case NBTConstants.TYPE_BYTE:
return ByteTag.class; return ByteTag.class;
case NBTConstants.TYPE_SHORT: case NBTConstants.TYPE_SHORT:
return ShortTag.class; return ShortTag.class;
case NBTConstants.TYPE_INT: case NBTConstants.TYPE_INT:
return IntTag.class; return IntTag.class;
case NBTConstants.TYPE_LONG: case NBTConstants.TYPE_LONG:
return LongTag.class; return LongTag.class;
case NBTConstants.TYPE_FLOAT: case NBTConstants.TYPE_FLOAT:
return FloatTag.class; return FloatTag.class;
case NBTConstants.TYPE_DOUBLE: case NBTConstants.TYPE_DOUBLE:
return DoubleTag.class; return DoubleTag.class;
case NBTConstants.TYPE_BYTE_ARRAY: case NBTConstants.TYPE_BYTE_ARRAY:
return ByteArrayTag.class; return ByteArrayTag.class;
case NBTConstants.TYPE_STRING: case NBTConstants.TYPE_STRING:
return StringTag.class; return StringTag.class;
case NBTConstants.TYPE_LIST: case NBTConstants.TYPE_LIST:
return ListTag.class; return ListTag.class;
case NBTConstants.TYPE_COMPOUND: case NBTConstants.TYPE_COMPOUND:
return CompoundTag.class; return CompoundTag.class;
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

@ -16,8 +16,9 @@ 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) {
@ -28,16 +29,16 @@ public abstract class Tag {
/** /**
* Gets the name of this tag. * Gets the name of this 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;
} }
/** /**
* Gets the value of this tag. * Gets the value of this tag.
* *
* @return the value * @return the value
*/ */
public abstract Object getValue(); public abstract Object getValue();

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,57 +49,62 @@ 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;
case '"': case '"':
case '\'': case '\'':
q = c; q = c;
sb = new StringBuffer(); sb = new StringBuffer();
for (;;) { for (;;) {
c = x.next(); c = x.next();
if (c == q) { if (c == q) {
break; break;
}
if ((c == 0) || (c == '\n') || (c == '\r')) {
throw x.syntaxError("Missing close quote '" + q + "'.");
}
sb.append(c);
} }
if (c == 0 || c == '\n' || c == '\r') { return sb.toString();
throw x.syntaxError("Missing close quote '" + q + "'."); case ',':
} x.back();
sb.append(c); return "";
} default:
return sb.toString(); x.back();
case ',': return x.nextTo(',');
x.back();
return "";
default:
x.back();
return x.nextTo(',');
} }
} }
/** /**
* 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,48 +126,52 @@ 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
* method. * A JSONArray of names. This is commonly obtained from the
* @param x A JSONTokener of the source text. * first row of a comma delimited text file using the
* rowToJSONArray
* method.
* @param x
* A JSONTokener of the source text.
* @return A JSONObject combining the names and values. * @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;
} }
/** /**
* 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. *
* @return The escaped result. * @param string
* The source string.
* @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
*/ */
@ -41,16 +42,18 @@ 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
* information. * if the object does not contain enough
* 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,21 +110,22 @@ 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());
} }
switch (x.nextClean()) { switch (x.nextClean()) {
case ',': case ',':
if (x.nextClean() == ']') { if (x.nextClean() == ']') {
return;
}
x.back();
break;
case ']':
return; return;
} default:
x.back(); throw x.syntaxError("Expected a ',' or ']'");
break;
case ']':
return;
default:
throw x.syntaxError("Expected a ',' or ']'");
} }
} }
} }
@ -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.
* *
@ -7,7 +8,7 @@ package com.intellectualcrafters.json;
*/ */
public class JSONException extends RuntimeException { public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0; private static final long serialVersionUID = 0;
private Throwable cause; private Throwable cause;
/** /**
* Constructs a JSONException with an explanatory message. * Constructs a JSONException with an explanatory message.
@ -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;
} }
@ -33,7 +36,7 @@ public class JSONException extends RuntimeException {
* or unknown. * or unknown.
* *
* @return the cause of this exception or null if the cause is nonexistent * @return the cause of this exception or null if the cause is nonexistent
* or unknown. * or unknown.
*/ */
@Override @Override
public Throwable getCause() { public Throwable getCause() {

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,32 +38,32 @@ 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.
* if we are at the outermost level. * @param arrayForm
* true if array form, false if object form.
* @param ja
* The JSONArray that is containing the current tag or null
* if we are at the outermost level.
* @return A JSONArray if the value is the outermost tag, otherwise null. * @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, String attribute;
boolean arrayForm, char c;
JSONArray ja String closeTag = null;
) throws JSONException { int i;
String attribute; JSONArray newja = null;
char c;
String closeTag = null;
int i;
JSONArray newja = null;
JSONObject newjo = null; JSONObject newjo = null;
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); }
while (i > 0);
} }
} else if (token == XML.QUEST) { }
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,22 +410,24 @@ 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;
Iterator<String> keys; Iterator<String> keys;
int length; int length;
Object object; Object object;
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,56 +8,55 @@ 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
*/ */
public class JSONTokener { public class JSONTokener {
private long character; private long character;
private boolean eof; private boolean eof;
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 *
* between 'a' and 'f'. * @param c
* @return An int between 0 and 15, or -1 if c was not a hex digit. * A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/ */
public static int dehexchar(char c) { 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,150 +168,156 @@ 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
* @return A string of n characters. * The number of characters to take.
* @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) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/** /**
* Get the next char in the string, skipping whitespace. * 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>
* @return A String. * &nbsp;<small>(double quote)</small> or <code>'</code>
* @throws JSONException Unterminated string. * &nbsp;<small>(single quote)</small>.
* @return A 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) {
case 0: case 0:
case '\n': case '\n':
case '\r': case '\r':
throw this.syntaxError("Unterminated string"); throw this.syntaxError("Unterminated string");
case '\\':
c = this.next();
switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char)Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
case '\\': case '\\':
case '/': c = this.next();
sb.append(c); switch (c) {
case 'b':
sb.append('\b');
break;
case 't':
sb.append('\t');
break;
case 'n':
sb.append('\n');
break;
case 'f':
sb.append('\f');
break;
case 'r':
sb.append('\r');
break;
case 'u':
sb.append((char) Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
case '\\':
case '/':
sb.append(c);
break;
default:
throw this.syntaxError("Illegal escape.");
}
break; break;
default: default:
throw this.syntaxError("Illegal escape."); if (c == quote) {
} return sb.toString();
break; }
default: sb.append(c);
if (c == quote) {
return sb.toString();
}
sb.append(c);
} }
} }
} }
/** /**
* 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. *
* @return A string. * @param delimiter
* A delimiter character.
* @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
* @return A JSONException object, suitable for throwing * The error message.
* @return A JSONException object, suitable for throwing
*/ */
public JSONException syntaxError(String message) { public JSONException syntaxError(final String message) {
return new JSONException(message + this.toString()); 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
*/ */
@ -62,7 +67,7 @@ public class JSONWriter {
* The comma flag determines if a comma should be output before the next * The comma flag determines if a comma should be output before the next
* value. * value.
*/ */
private boolean comma; private boolean comma;
/** /**
* The current mode. Values: * The current mode. Values:
@ -72,7 +77,7 @@ public class JSONWriter {
* 'k' (key), * 'k' (key),
* 'o' (object). * 'o' (object).
*/ */
protected char mode; protected char mode;
/** /**
* The object/array stack. * The object/array stack.
@ -82,17 +87,17 @@ public class JSONWriter {
/** /**
* The stack top index. A value of 0 indicates that the stack is empty. * The stack top index. A value of 0 indicates that the stack is empty.
*/ */
private int top; private int top;
/** /**
* The writer that will receive the output. * The writer that will receive the output.
*/ */
protected Writer writer; protected Writer writer;
/** /**
* Make a fresh JSONWriter. It can be used to build one JSON text. * 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
* outermost array or object). * started in the wrong place (for example as a key or after the
* end of the
* outermost array or object).
*/ */
public JSONWriter array() throws JSONException { 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
* do not belong in arrays or if the key is null. * If the key is out of place. For example, keys
* do not belong in arrays or if the key is null.
*/ */
public JSONWriter key(String string) throws JSONException { public JSONWriter key(final String string) throws JSONException {
if (string == null) { 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
* outermost array or object). * started in the wrong place (for example as a key or after the
* end of the
* outermost array or object).
*/ */
public JSONWriter object() throws JSONException { 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

@ -32,11 +32,11 @@ package com.intellectualcrafters.json;
* than 3 bytes. Every byte contributes 7 bits to the character. ASCII is * than 3 bytes. Every byte contributes 7 bits to the character. ASCII is
* unmodified. * unmodified.
* *
* Kim UTF-8 * Kim UTF-8
* one byte U+007F U+007F * one byte U+007F U+007F
* two bytes U+3FFF U+07FF * two bytes U+3FFF U+07FF
* three bytes U+10FFF U+FFFF * three bytes U+10FFF U+FFFF
* four bytes U+10FFFF * four bytes U+10FFFF
* *
* Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one * Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one
* byte smaller when encoded in Kim compared to UTF-8. * byte smaller when encoded in Kim compared to UTF-8.
@ -65,23 +65,23 @@ public class Kim {
/** /**
* The byte array containing the kim's content. * The byte array containing the kim's content.
*/ */
private byte[] bytes = null; private byte[] bytes = null;
/** /**
* The kim's hashcode, conforming to Java's hashcode conventions. * The kim's hashcode, conforming to Java's hashcode conventions.
*/ */
private int hashcode = 0; private int hashcode = 0;
/** /**
* The number of bytes in the kim. The number of bytes can be as much as * The number of bytes in the kim. The number of bytes can be as much as
* three times the number of characters. * three times the number of characters.
*/ */
public int length = 0; public int length = 0;
/** /**
* The memoization of toString(). * The memoization of toString().
*/ */
private String string = null; private String string = null;
/** /**
* Make a kim from a portion of a byte array. * Make a kim from a portion of a byte array.
@ -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,37 +64,40 @@ 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;");
break; break;
case '<': case '<':
sb.append("&lt;"); sb.append("&lt;");
break; break;
case '>': case '>':
sb.append("&gt;"); sb.append("&gt;");
break; break;
case '"': case '"':
sb.append("&quot;"); sb.append("&quot;");
break; break;
case '\'': case '\'':
sb.append("&apos;"); sb.append("&apos;");
break; break;
default: default:
sb.append(c); sb.append(c);
} }
} }
return sb.toString(); return sb.toString();
@ -102,52 +106,57 @@ 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;
String string; String string;
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,52 +369,56 @@ 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. *
* @return A string. * @param object
* @throws JSONException * A JSONObject.
*/
public static String toString(Object object) throws JSONException {
return toString(object, null);
}
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
* @param object A JSONObject.
* @param tagName The optional name of the enclosing tag.
* @return A string. * @return A string.
* @throws JSONException * @throws JSONException
*/ */
public static String toString(Object object, String tagName) public static String toString(final Object object) throws JSONException {
throws JSONException { return toString(object, null);
StringBuilder sb = new StringBuilder(); }
int i;
JSONArray ja; /**
JSONObject jo; * Convert a JSONObject into a well-formed, element-normal XML string.
String key; *
Iterator<String> keys; * @param object
int length; * A JSONObject.
String string; * @param tagName
Object value; * The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, final String tagName) throws JSONException {
final StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
String key;
Iterator<String> keys;
int length;
String string;
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,68 +1,74 @@
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
* amp, apos, gt, lt, quot.
*/
public static final java.util.HashMap<String, Character> entity;
/** The table of entity values. It initially contains Character values for static {
* amp, apos, gt, lt, quot. entity = new java.util.HashMap<String, Character>(8);
*/ entity.put("amp", XML.AMP);
public static final java.util.HashMap<String, Character> entity; entity.put("apos", XML.APOS);
entity.put("gt", XML.GT);
static { entity.put("lt", XML.LT);
entity = new java.util.HashMap<String, Character>(8); entity.put("quot", XML.QUOT);
entity.put("amp", XML.AMP); }
entity.put("apos", XML.APOS);
entity.put("gt", XML.GT);
entity.put("lt", XML.LT);
entity.put("quot", XML.QUOT);
}
/** /**
* Construct an XMLTokener from a string. * 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
@ -89,11 +93,12 @@ public class XMLTokener extends JSONTokener {
* @throws JSONException * @throws JSONException
*/ */
public Object nextContent() throws JSONException { public Object nextContent() throws JSONException {
char c; char c;
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,118 +107,127 @@ 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. *
* @return A Character or an entity String if the entity is not recognized. * @param ampersand
* @throws JSONException If missing ';' in XML entity. * An ampersand character.
* @return A Character or an entity String if the entity is not recognized.
* @throws JSONException
* If missing ';' in XML entity.
*/ */
public Object nextEntity(char ampersand) throws JSONException { 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
* what the values actually are. * don't care
* @throws JSONException If a string is not properly closed or if the XML * what the values actually are.
* is badly structured. * @throws JSONException
* If a string is not properly closed or if the XML
* is badly structured.
*/ */
public Object nextMeta() throws JSONException { public Object nextMeta() throws JSONException {
char c; char c;
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");
case '<': case '<':
return XML.LT; return XML.LT;
case '>': case '>':
return XML.GT; return XML.GT;
case '/': case '/':
return XML.SLASH; return XML.SLASH;
case '=': case '=':
return XML.EQ; return XML.EQ;
case '!': case '!':
return XML.BANG; return XML.BANG;
case '?': case '?':
return XML.QUEST; return XML.QUEST;
case '"': case '"':
case '\'': case '\'':
q = c; q = c;
for (;;) { for (;;) {
c = next(); c = next();
if (c == 0) { if (c == 0) {
throw syntaxError("Unterminated string"); throw syntaxError("Unterminated string");
}
if (c == q) {
return Boolean.TRUE;
}
} }
if (c == q) { default:
return Boolean.TRUE; for (;;) {
c = next();
if (Character.isWhitespace(c)) {
return Boolean.TRUE;
}
switch (c) {
case 0:
case '<':
case '>':
case '/':
case '=':
case '!':
case '?':
case '"':
case '\'':
back();
return Boolean.TRUE;
}
} }
}
default:
for (;;) {
c = next();
if (Character.isWhitespace(c)) {
return Boolean.TRUE;
}
switch (c) {
case 0:
case '<':
case '>':
case '/':
case '=':
case '!':
case '?':
case '"':
case '\'':
back();
return Boolean.TRUE;
}
}
} }
} }
/** /**
* Get the next XML Token. These tokens are found inside of angle * 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,90 +235,94 @@ 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");
case '<': case '<':
throw syntaxError("Misplaced '<'"); throw syntaxError("Misplaced '<'");
case '>': case '>':
return XML.GT; return XML.GT;
case '/': case '/':
return XML.SLASH; return XML.SLASH;
case '=': case '=':
return XML.EQ; return XML.EQ;
case '!': case '!':
return XML.BANG; return XML.BANG;
case '?': case '?':
return XML.QUEST; return XML.QUEST;
// Quoted string // Quoted string
case '"': case '"':
case '\'': case '\'':
q = c; q = c;
sb = new StringBuilder(); sb = new StringBuilder();
for (;;) { for (;;) {
c = next(); c = next();
if (c == 0) { if (c == 0) {
throw syntaxError("Unterminated string"); throw syntaxError("Unterminated string");
}
if (c == q) {
return sb.toString();
}
if (c == '&') {
sb.append(nextEntity(c));
}
else {
sb.append(c);
}
} }
if (c == q) { default:
return sb.toString();
} // Name
if (c == '&') {
sb.append(nextEntity(c)); sb = new StringBuilder();
} else { for (;;) {
sb.append(c); sb.append(c);
c = next();
if (Character.isWhitespace(c)) {
return sb.toString();
}
switch (c) {
case 0:
return sb.toString();
case '>':
case '/':
case '=':
case '!':
case '?':
case '[':
case ']':
back();
return sb.toString();
case '<':
case '"':
case '\'':
throw syntaxError("Bad character in a name");
}
} }
}
default:
// Name
sb = new StringBuilder();
for (;;) {
sb.append(c);
c = next();
if (Character.isWhitespace(c)) {
return sb.toString();
}
switch (c) {
case 0:
return sb.toString();
case '>':
case '/':
case '=':
case '!':
case '?':
case '[':
case ']':
back();
return sb.toString();
case '<':
case '"':
case '\'':
throw syntaxError("Bad character in a name");
}
}
} }
} }
/** /**
* Skip characters until past the requested string. * 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

@ -7,55 +7,60 @@ import org.apache.commons.lang.StringUtils;
*/ */
public class AbstractFlag { public class AbstractFlag {
private final String key; private final String key;
/** /**
* AbstractFlag is a parameter used in creating a new Flag * AbstractFlag is a parameter used in creating a new Flag
* *
* @param key * @param key
* 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");
} }
if (key.length() > 16) { if (key.length() > 16) {
throw new IllegalArgumentException("Key must be <= 16 characters"); throw new IllegalArgumentException("Key must be <= 16 characters");
} }
this.key = key.toLowerCase(); this.key = key.toLowerCase();
} }
public String parseValue(String value) {
return value;
}
public String getValueDesc() {
return "Flag value must be alphanumeric";
}
/** public String parseValue(final String value) {
* AbstractFlag key return value;
* }
* @return String
*/
public String getKey() {
return this.key;
}
@Override public String getValueDesc() {
public String toString() { return "Flag value must be alphanumeric";
return this.key; }
}
/**
@Override * AbstractFlag key
public boolean equals(Object other){ *
if (other == null) return false; * @return String
if (other == this) return true; */
if (!(other instanceof AbstractFlag)) return false; public String getKey() {
AbstractFlag otherObj = (AbstractFlag)other; return this.key;
return (otherObj.key.equals(this.key)); }
}
@Override
public String toString() {
return this.key;
}
@Override
public boolean equals(final Object other) {
if (other == null) {
return false;
}
if (other == this) {
return true;
}
if (!(other instanceof AbstractFlag)) {
return false;
}
final AbstractFlag otherObj = (AbstractFlag) other;
return (otherObj.key.equals(this.key));
}
} }

View File

@ -1,13 +1,14 @@
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;
public int z; public int z;
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = C.java >> Generated by: Citymonstret at 2014-08-09 01:43 * >> File = C.java >> Generated by: Citymonstret at 2014-08-09 01:43
*/ */
@ -40,7 +40,7 @@ public enum C {
NOT_CONSOLE("&cFor safety reasons, this command can only be executed by console."), 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."),
@ -150,8 +150,8 @@ public enum C {
*/ */
INVALID_PLAYER("&cPlayer not found: &6%player%."), INVALID_PLAYER("&cPlayer not found: &6%player%."),
/* /*
* *
*/ */
COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."), COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."),
/* /*
* purge * purge
@ -219,7 +219,7 @@ public enum C {
*/ */
PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"), PLOT_INFO_UNCLAIMED("&cPlot &6%s&c is not yet claimed"),
PLOT_INFO("&6ID&7: &a%id%&7\n&6Alias&7: &a%alias%\n&6Owner&7: &a%owner%\n&6Helpers&7: &a%helpers%\n&6Trusted&7: &a%trusted%\n&Denied&7: &a%denied%\n&6Denied&7: &a%denied%\n&6Flags&7: &a%flags%\n&6Biome&7: &a%biome%\n&6Rating&7: &a%rating%&7/&a10\n&6Can build&7: &a%build%"), PLOT_INFO("&6ID&7: &a%id%&7\n&6Alias&7: &a%alias%\n&6Owner&7: &a%owner%\n&6Helpers&7: &a%helpers%\n&6Trusted&7: &a%trusted%\n&Denied&7: &a%denied%\n&6Denied&7: &a%denied%\n&6Flags&7: &a%flags%\n&6Biome&7: &a%biome%\n&6Rating&7: &a%rating%&7/&a10\n&6Can build&7: &a%build%"),
PLOT_INFO_HELPERS("&6Helpers&7: %helpers%"), PLOT_INFO_HELPERS("&6Helpers&7: %helpers%"),
PLOT_INFO_TRUSTED("&6Trusted&7: %trusted%"), PLOT_INFO_TRUSTED("&6Trusted&7: %trusted%"),
PLOT_INFO_DENIED("&6Denied&7: %denied%"), PLOT_INFO_DENIED("&6Denied&7: %denied%"),
@ -230,7 +230,7 @@ public enum C {
PLOT_INFO_ID("&6ID&7: %id%"), PLOT_INFO_ID("&6ID&7: %id%"),
PLOT_INFO_ALIAS("&6Alias&7: %alias%"), PLOT_INFO_ALIAS("&6Alias&7: %alias%"),
PLOT_INFO_SIZE("&6Size&7: %size%"), PLOT_INFO_SIZE("&6Size&7: %size%"),
PLOT_USER_LIST(" &6%user%&c,"), PLOT_USER_LIST(" &6%user%&c,"),
INFO_SYNTAX_CONSOLE("/plot info <world> X;Y"), INFO_SYNTAX_CONSOLE("/plot info <world> X;Y"),
/* /*
@ -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"),
/* /*
@ -344,77 +341,78 @@ public enum C {
/** /**
* Default * Default
*/ */
private String d; private String d;
/** /**
* Translated * Translated
*/ */
private String s; private String s;
/** /**
* Constructor for custom strings. * Constructor for custom strings.
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
C() { C() {
/* /*
* use setCustomString(); * use setCustomString();
*/ */
} }
/** /**
* Constructor * Constructor
* *
* @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;
} }
else { else {
this.s = PlotMain.translations.getString(this.toString()); this.s = PlotMain.translations.getString(this.toString());
} }
if (this.s == null) { if (this.s == null) {
this.s = ""; this.s = "";
} }
} }
public static class Potato { public static class Potato {
} }
/**
* Get the default string
*
* @return default
*/
@SuppressWarnings("unused")
public String d() {
return this.d;
}
/** /**
* Get translated if exists * Get the default string
* *
* @return translated if exists else default * @return default
*/ */
public String s() { @SuppressWarnings("unused")
if(PlotMain.translations != null){ public String d() {
String t = PlotMain.translations.getString(this.toString()); return this.d;
if (t!=null) { }
/**
* Get translated if exists
*
* @return translated if exists else default
*/
public String s() {
if (PlotMain.translations != null) {
final String t = PlotMain.translations.getString(this.toString());
if (t != null) {
this.s = t; this.s = t;
} }
} }
if (this.s.length() < 1) { if (this.s.length() < 1) {
return ""; return "";
} }
return this.s.replace("\\n", "\n"); return this.s.replace("\\n", "\n");
} }
/** /**
* @return translated and color decoded * @return translated and color decoded
*/ */
public String translated() { public String translated() {
return ChatColor.translateAlternateColorCodes('&', this.s()); return ChatColor.translateAlternateColorCodes('&', this.s());
} }
} }

View File

@ -3,265 +3,266 @@ 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;
} }
} }
return Biome.FOREST; return Biome.FOREST;
} }
@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]);
} }
else { else {
Short.parseShort(string); Short.parseShort(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) {
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 {
return new PlotBlock(Short.parseShort(string), (byte) 0); return new PlotBlock(Short.parseShort(string), (byte) 0);
} }
} }
@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) {
if (b==0) return a;
return gcd(b,a%b);
}
private static int gcd(int[] a)
{
int result = a[0];
for(int i = 1; i < a.length; i++)
result = gcd(result, a[i]);
return result;
}
public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") { public static int gcd(final int a, final int b) {
@Override if (b == 0) {
public boolean validateValue(String string) { return a;
try { }
for (String block : string.split(",")) { return gcd(b, a % b);
if (block.contains("%")) { }
String[] split = block.split("%");
Integer.parseInt(split[0]);
block = split[1];
}
if (block.contains(":")) {
String[] split = block.split(":");
Short.parseShort(split[0]);
Short.parseShort(split[1]);
}
else {
Short.parseShort(block);
}
}
return true;
}
catch (Exception e) {
return false;
}
}
@Override private static int gcd(final int[] a) {
public Object parseString(String string) { int result = a[0];
String[] blocks = string.split(","); for (int i = 1; i < a.length; i++) {
ArrayList<PlotBlock> parsedvalues = new ArrayList<PlotBlock>(); result = gcd(result, a[i]);
}
return result;
PlotBlock[] values = new PlotBlock[blocks.length]; }
int[] counts = new int[blocks.length];
int min = 100; public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") {
for (int i = 0; i < blocks.length; i++) { @Override
if (blocks[i].contains("%")) { public boolean validateValue(final String string) {
String[] split = blocks[i].split("%"); try {
blocks[i] = split[1]; for (String block : string.split(",")) {
int value = Integer.parseInt(split[0]); if (block.contains("%")) {
counts[i] = value; final String[] split = block.split("%");
if (value<min) { Integer.parseInt(split[0]);
block = split[1];
}
if (block.contains(":")) {
final String[] split = block.split(":");
Short.parseShort(split[0]);
Short.parseShort(split[1]);
}
else {
Short.parseShort(block);
}
}
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(final String string) {
final String[] blocks = string.split(",");
final ArrayList<PlotBlock> parsedvalues = new ArrayList<PlotBlock>();
final PlotBlock[] values = new PlotBlock[blocks.length];
final int[] counts = new int[blocks.length];
int min = 100;
for (int i = 0; i < blocks.length; i++) {
if (blocks[i].contains("%")) {
final String[] split = blocks[i].split("%");
blocks[i] = split[1];
final int value = Integer.parseInt(split[0]);
counts[i] = value;
if (value < min) {
min = value; 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]);
} }
} }
return parsedvalues.toArray(new PlotBlock[0]);
}
@Override return parsedvalues.toArray(new PlotBlock[0]);
public Object parseObject(Object object) { }
List<String> list = new ArrayList<String>();
for (PlotBlock block : (PlotBlock[]) object) {
list.add((block.id + ":" + (block.data)));
}
return list;
}
};
/** @Override
* Create your own SettingValue object to make the management of plotworld public Object parseObject(final Object object) {
* configuration easier final List<String> list = new ArrayList<String>();
*/ for (final PlotBlock block : (PlotBlock[]) object) {
public static abstract class SettingValue { list.add((block.id + ":" + (block.data)));
private String type; }
return list;
}
};
public SettingValue(String type) { /**
this.type = type; * Create your own SettingValue object to make the management of plotworld
} * configuration easier
*/
public static abstract class SettingValue {
private final String type;
public String getType() { public SettingValue(final String type) {
return this.type; this.type = type;
} }
public Object parseObject(Object object) { public String getType() {
return object; return this.type;
} }
public abstract Object parseString(String string); public Object parseObject(final Object object) {
return object;
}
public abstract boolean validateValue(String string); public abstract Object parseString(final String string);
}
public abstract boolean validateValue(final String string);
}
} }

View File

@ -1,70 +1,70 @@
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;
import org.apache.commons.lang.StringUtils;
import com.intellectualcrafters.plot.Configuration.SettingValue;
public class ConfigurationNode { public class ConfigurationNode {
private String constant; private final String constant;
private Object default_value; private final Object default_value;
private String description; private final String description;
private Object value; private Object value;
private SettingValue type; private final SettingValue type;
public ConfigurationNode(String constant, Object default_value, String description, SettingValue type, public ConfigurationNode(final String constant, final Object default_value, final String description, final SettingValue type, final boolean required) {
boolean required) { this.constant = constant;
this.constant = constant; this.default_value = default_value;
this.default_value = default_value; this.description = description;
this.description = description; this.value = default_value;
this.value = default_value; this.type = type;
this.type = type; }
}
public SettingValue getType() { public SettingValue getType() {
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;
} }
this.value = this.type.parseString(string); this.value = this.type.parseString(string);
return true; return true;
} }
public Object getValue() { public Object getValue() {
if (this.value instanceof String[]) { if (this.value instanceof String[]) {
return Arrays.asList((String[]) this.value); return Arrays.asList((String[]) this.value);
} }
return this.value; return this.value;
} }
public String getConstant() { public String getConstant() {
return this.constant; return this.constant;
} }
public Object getDefaultValue() { public Object getDefaultValue() {
if (this.default_value instanceof String[]) { if (this.default_value instanceof String[]) {
return StringUtils.join((String[]) this.default_value, ","); return StringUtils.join((String[]) this.default_value, ",");
} }
return this.default_value; return this.default_value;
} }
public String getDescription() { public String getDescription() {
return this.description; return this.description;
} }
} }

View File

@ -7,95 +7,95 @@ import org.bukkit.ChatColor;
*/ */
public class ConsoleColors { public class ConsoleColors {
static enum ConsoleColor { static enum ConsoleColor {
RESET("\u001B[0m"), RESET("\u001B[0m"),
BLACK("\u001B[30m"), BLACK("\u001B[30m"),
RED("\u001B[31m"), RED("\u001B[31m"),
GREEN("\u001B[32m"), GREEN("\u001B[32m"),
YELLOW("\u001B[33m"), YELLOW("\u001B[33m"),
BLUE("\u001B[34m"), BLUE("\u001B[34m"),
PURPLE("\u001B[35m"), PURPLE("\u001B[35m"),
CYAN("\u001B[36m"), CYAN("\u001B[36m"),
WHITE("\u001B[37m"), WHITE("\u001B[37m"),
BOLD("\033[1m"), BOLD("\033[1m"),
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;
} }
public String getWin() { public String getWin() {
return this.win; return this.win;
} }
public String getLin() { public String getLin() {
return this.lin; return this.lin;
} }
} }
/* /*
* public static final String ANSI_RESET = "\u001B[0m"; public static final * public static final String ANSI_RESET = "\u001B[0m"; public static final
* String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED = * String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED =
* "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m"; * "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m";
* public static final String ANSI_YELLOW = "\u001B[33m"; public static * public static final String ANSI_YELLOW = "\u001B[33m"; public static
* final String ANSI_BLUE = "\u001B[34m"; public static final String * final String ANSI_BLUE = "\u001B[34m"; public static final String
* ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN = * ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN =
* "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m"; * "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m";
* public static final String ANSI_BOLD = "\033[1m"; public static final * public static final String ANSI_BOLD = "\033[1m"; public static final
* String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC * String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC
* = "\033[3m]"; * = "\033[3m]";
*/ */
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;
case GRAY: case GRAY:
case DARK_GRAY: case DARK_GRAY:
return ConsoleColor.WHITE; return ConsoleColor.WHITE;
case BLACK: case BLACK:
return ConsoleColor.BLACK; return ConsoleColor.BLACK;
case DARK_RED: case DARK_RED:
case RED: case RED:
return ConsoleColor.RED; return ConsoleColor.RED;
case GOLD: case GOLD:
case YELLOW: case YELLOW:
return ConsoleColor.YELLOW; return ConsoleColor.YELLOW;
case DARK_GREEN: case DARK_GREEN:
case GREEN: case GREEN:
return ConsoleColor.GREEN; return ConsoleColor.GREEN;
case AQUA: case AQUA:
case DARK_AQUA: case DARK_AQUA:
return ConsoleColor.CYAN; return ConsoleColor.CYAN;
case LIGHT_PURPLE: case LIGHT_PURPLE:
case DARK_PURPLE: case DARK_PURPLE:
return ConsoleColor.PURPLE; return ConsoleColor.PURPLE;
case BLUE: case BLUE:
case DARK_BLUE: case DARK_BLUE:
return ConsoleColor.BLUE; return ConsoleColor.BLUE;
case UNDERLINE: case UNDERLINE:
return ConsoleColor.UNDERLINE; return ConsoleColor.UNDERLINE;
case ITALIC: case ITALIC:
return ConsoleColor.ITALIC; return ConsoleColor.ITALIC;
case BOLD: case BOLD:
return ConsoleColor.BOLD; return ConsoleColor.BOLD;
default: default:
return ConsoleColor.RESET; return ConsoleColor.RESET;
} }
} }
} }

View File

@ -3,94 +3,93 @@ 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
* key/value pair. For a flag to be usable by a player, you need to register * key/value pair. For a flag to be usable by a player, you need to register
* it with PlotSquared. * it with PlotSquared.
* *
* @param key * @param key
* AbstractFlag * AbstractFlag
* @param value * @param value
* Value must be alphanumerical (can have spaces) and be <= 48 * Value must be alphanumerical (can have spaces) and be <= 48
* characters * characters
* @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)) { }
throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)"); if (!StringUtils.isAlphanumericSpace(tempValue)) {
} throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)");
if (value.length() > 48) { }
throw new IllegalArgumentException("Value must be <= 48 characters"); if (value.length() > 48) {
} throw new IllegalArgumentException("Value must be <= 48 characters");
this.key = key; }
this.value = key.parseValue(value); this.key = key;
if (this.value==null) { this.value = key.parseValue(value);
throw new IllegalArgumentException(key.getValueDesc()); if (this.value == null) {
} throw new IllegalArgumentException(key.getValueDesc());
} }
}
/** /**
* Get the AbstractFlag used in creating the flag * Get the AbstractFlag used in creating the flag
* *
* @return AbstractFlag * @return AbstractFlag
*/ */
public AbstractFlag getAbstractFlag() { public AbstractFlag getAbstractFlag() {
return this.key; return this.key;
} }
/** /**
* Get the key for the AbstractFlag * Get the key for the AbstractFlag
* *
* @return String * @return String
*/ */
public String getKey() { public String getKey() {
return this.key.getKey(); return this.key.getKey();
} }
/** /**
* Get the value * Get the value
* *
* @return String * @return String
*/ */
public String getValue() { public String getValue() {
return this.value; return this.value;
} }
@Override @Override
public String toString() { public String toString() {
if (this.value.equals("")) { if (this.value.equals("")) {
return this.key.getKey(); return this.key.getKey();
} }
return this.key + ":" + this.value; return this.key + ":" + this.value;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(final Object obj) {
if (this == obj) { if (this == obj) {
return true; return true;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
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));
} }
@Override @Override
public int hashCode() { public int hashCode() {
return this.key.getKey().hashCode(); return this.key.getKey().hashCode();
} }
} }

View File

@ -1,146 +1,151 @@
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
// - Plot clear interval // - Plot clear interval
// - Mob cap // - Mob cap
// - customized plot composition // - customized plot composition
// - greeting / leaving message // - greeting / leaving message
// OR in the flag command, allow users to set worldguard flags. // OR in the flag command, allow users to set worldguard flags.
private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>(); private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>();
/** /**
* Register an AbstractFlag with PlotSquared * Register an AbstractFlag with PlotSquared
* *
* @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;
} }
/** /**
* Get a list of registered AbstractFlag objects * Get a list of registered AbstractFlag objects
* *
* @return List (AbstractFlag) * @return List (AbstractFlag)
*/ */
public static List<AbstractFlag> getFlags() { public static List<AbstractFlag> getFlags() {
return flags; return flags;
} }
/** /**
* 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;
} }
/** /**
* Get an AbstractFlag by a string Returns null if flag does not exist * Get an AbstractFlag by a string Returns null if flag does not exist
* *
* @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;
} }
} }
return null; return null;
} }
/** /**
* Get an AbstractFlag by a string * Get an AbstractFlag by a string
* *
* @param string * @param string
* @param create * @param create
* 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;
} }
return getFlag(string); return getFlag(string);
} }
/** /**
* Remove a registered AbstractFlag * Remove a registered AbstractFlag
* *
* @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), "");
} }
else { else {
flags[i] = new Flag(getFlag(split[0], true), split[1]); flags[i] = new Flag(getFlag(split[0], true), split[1]);
} }
} }
return flags; return flags;
} }
/** /**
* Get the flags for a plot * Get the flags for a plot
* *
* @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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = LSetCube.java >> Generated by: Citymonstret at 2014-08-09 01:43 * >> File = LSetCube.java >> Generated by: Citymonstret at 2014-08-09 01:43
*/ */
@ -17,110 +17,108 @@ import org.bukkit.Location;
*/ */
public class LSetCube { public class LSetCube {
/** /**
* Base locations * Base locations
*/ */
private Location l1, l2; private Location l1, l2;
/** /**
* Constructor * Constructor
* *
* @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;
} }
/** /**
* Secondary constructor * Secondary constructor
* *
* @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);
} }
/** /**
* Returns the absolute min. of the cube * Returns the absolute min. of the cube
* *
* @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);
} }
/** /**
* Returns the absolute max. of the cube * Returns the absolute max. of the cube
* *
* @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);
} }
/** /**
* Creates a LCycler for the cube. * Creates a LCycler for the cube.
* *
* @return new lcycler * @return new lcycler
*/ */
public LCycler getCycler() { public LCycler getCycler() {
return new LCycler(this); return new LCycler(this);
} }
/** /**
* @author Citymonstret * @author Citymonstret
*/ */
protected class LCycler { protected class LCycler {
/** /**
* *
*/ */
private Location min; private final Location min;
/** /**
* *
*/ */
private Location max; private final Location max;
/** /**
* *
*/ */
private Location current; private Location current;
/** /**
* @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;
} }
/** /**
* @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());
}
/** /**
* @return * @return
*/ */
public Location getNext() { public Location getNext() {
if (!hasNext()) { if (!hasNext()) {
return null; return null;
} }
this.current = this.current.add(1, 1, 1); this.current = this.current.add(1, 1, 1);
return this.current; return this.current;
} }
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Lag.java >> Generated by: Citymonstret at 2014-08-09 01:43 * >> File = Lag.java >> Generated by: Citymonstret at 2014-08-09 01:43
*/ */
@ -15,79 +15,79 @@ package com.intellectualcrafters.plot;
*/ */
public class Lag implements Runnable { public class Lag implements Runnable {
/** /**
* Tick count * Tick count
*/ */
public static int TC = 0; public static int TC = 0;
/** /**
* Ticks * Ticks
*/ */
public static long[] T = new long[600]; public static long[] T = new long[600];
/** /**
* something :_: * something :_:
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public static long LT = 0L; public static long LT = 0L;
/** /**
* Get the server TPS * Get the server TPS
* *
* @return server tick per second * @return server tick per second
*/ */
public static double getTPS() { public static double getTPS() {
return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100)); return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100));
} }
/** /**
* Return the tick per second (measured in $ticks) * Return the tick per second (measured in $ticks)
* *
* @param ticks * @param ticks
* 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);
} }
/** /**
* Get number of ticks since * Get number of ticks since
* *
* @param tI * @param tI
* Ticks < * Ticks <
* @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;
} }
@Override @Override
public void run() { public void run() {
T[TC % T.length] = System.currentTimeMillis(); T[TC % T.length] = System.currentTimeMillis();
TC++; TC++;
} }
/** /**
* Get lag percentage * Get lag percentage
* *
* @return lag percentage * @return lag percentage
*/ */
public static double getPercentage() { public static double getPercentage() {
return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D); return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D);
} }
/** /**
* Get TPS percentage (of 20) * Get TPS percentage (of 20)
* *
* @return TPS percentage * @return TPS percentage
*/ */
public static double getFullPercentage() { public static double getFullPercentage() {
return getTPS() * 5.0D; return getTPS() * 5.0D;
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Logger.java >> Generated by: Citymonstret at 2014-08-09 01:43 * >> File = Logger.java >> Generated by: Citymonstret at 2014-08-09 01:43
*/ */
@ -23,54 +23,54 @@ import java.util.Date;
*/ */
public class Logger { 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");
} }
} }
public enum LogLevel { public enum LogLevel {
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;
} }
@Override @Override
public String toString() { public String toString() {
return this.name; return this.name;
} }
} }
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

@ -20,104 +20,102 @@ 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) {
s = WorldEdit.getInstance().getSession(p.getName());
}
else {
s = PlotMain.worldEdit.getSession(p);
}
PlotId id = PlayerFunctions.getPlot(l);
if (id != null) {
Plot plot = PlotMain.getPlots(l.getWorld()).get(id);
if (plot != null) {
boolean r;
r =
(plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId())
|| plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId());
if (!r) {
if (p.hasPermission("plots.worldedit.bypass")) {
removeMask(p, s);
return;
}
}
else {
World w = p.getWorld();
Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location tloc = PlotHelper.getPlotTopLoc(w, plot.id);
Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1);
Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ());
LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld();
CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
RegionMask mask = new RegionMask(region);
s.setMask(mask);
return;
}
}
}
if (noMask(s)) {
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
}
}
catch (Exception e) {
// throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?");
}
}
public static boolean noMask(LocalSession s) {
return s.getMask() == null;
}
public static void setNoMask(Player p) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) { if (PlotMain.worldEdit == null) {
s = WorldEdit.getInstance().getSession(p.getName()); s = WorldEdit.getInstance().getSession(p.getName());
} }
else { else {
s = PlotMain.worldEdit.getSession(p); s = PlotMain.worldEdit.getSession(p);
} }
BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
}
catch (Exception e) {
}
}
public static void removeMask(Player p, LocalSession s) {
Mask mask = null;
s.setMask(mask);
}
public static void removeMask(Player p) { final PlotId id = PlayerFunctions.getPlot(l);
try { if (id != null) {
LocalSession s; final Plot plot = PlotMain.getPlots(l.getWorld()).get(id);
if (PlotMain.worldEdit == null) { if (plot != null) {
s = WorldEdit.getInstance().getSession(p.getName()); boolean r;
} r = ((plot.getOwner() != null) && plot.getOwner().equals(p.getUniqueId())) || plot.helpers.contains(DBFunc.everyone) || plot.helpers.contains(p.getUniqueId());
else { if (!r) {
s = PlotMain.worldEdit.getSession(p); if (p.hasPermission("plots.worldedit.bypass")) {
} removeMask(p, s);
removeMask(p, s); return;
} }
catch (Exception e) { }
// throw new else {
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?"); final World w = p.getWorld();
}
} final Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
final Location tloc = PlotHelper.getPlotTopLoc(w, plot.id);
final Vector bvec = new Vector(bloc.getBlockX() + 1, bloc.getBlockY() + 1, bloc.getBlockZ() + 1);
final Vector tvec = new Vector(tloc.getBlockX(), tloc.getBlockY(), tloc.getBlockZ());
final LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld();
final CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
final RegionMask mask = new RegionMask(region);
s.setMask(mask);
return;
}
}
}
if (noMask(s)) {
final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
}
}
catch (final Exception e) {
// throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?");
}
}
public static boolean noMask(final LocalSession s) {
return s.getMask() == null;
}
public static void setNoMask(final Player p) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) {
s = WorldEdit.getInstance().getSession(p.getName());
}
else {
s = PlotMain.worldEdit.getSession(p);
}
final BukkitPlayer plr = PlotMain.worldEdit.wrapPlayer(p);
final Vector p1 = new Vector(69, 69, 69), p2 = new Vector(69, 69, 69);
s.setMask(new RegionMask(new CuboidRegion(plr.getWorld(), p1, p2)));
}
catch (final Exception e) {
}
}
public static void removeMask(final Player p, final LocalSession s) {
final Mask mask = null;
s.setMask(mask);
}
public static void removeMask(final Player p) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) {
s = WorldEdit.getInstance().getSession(p.getName());
}
else {
s = PlotMain.worldEdit.getSession(p);
}
removeMask(p, s);
}
catch (final Exception e) {
// throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?");
}
}
} }

View File

@ -2,19 +2,27 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = PlayerFunctions.java >> Generated by: Citymonstret at 2014-08-09 * >> File = PlayerFunctions.java >> Generated by: Citymonstret at 2014-08-09
* 01:43 * 01:43
*/ */
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.
* *
@ -23,29 +31,29 @@ import java.util.*;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class PlayerFunctions { public class PlayerFunctions {
/** /**
* @param player * @param player
* 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;
} }
/** /**
* @param plot * @param plot
* 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));
@ -53,21 +61,21 @@ 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;
} }
if (plot2 != null) { if (plot2 != null) {
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,205 +84,211 @@ 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 getBottomPlot(world, p);
}
if (plot.settings.getMerged(3)) {
Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y));
if (p==null) {
return plot; return plot;
} }
return getBottomPlot(world, p); return getBottomPlot(world, p);
} }
return plot; if (plot.settings.getMerged(3)) {
} final Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y));
if (p == null) {
return plot;
}
return getBottomPlot(world, p);
}
return plot;
}
public static Plot getTopPlot(World world, Plot plot) { 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)));
} }
if (plot.settings.getMerged(1)) { if (plot.settings.getMerged(1)) {
return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y))); return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x + 1, plot.id.y)));
} }
return plot; return plot;
} }
/** /**
* 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
* @param loc * are treated as small plots)
* @return *
*/ * @param loc
public static PlotId getPlotAbs(Location loc) { * @return
String world = loc.getWorld().getName(); */
PlotManager manager = PlotMain.getPlotManager(world); public static PlotId getPlotAbs(final Location loc) {
if (manager == null) { final String world = loc.getWorld().getName();
return null; final PlotManager manager = PlotMain.getPlotManager(world);
} if (manager == null) {
PlotWorld plotworld = PlotMain.getWorldSettings(world); return null;
return manager.getPlotIdAbs(plotworld, loc); }
} final PlotWorld plotworld = PlotMain.getWorldSettings(world);
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 *
* @return * @param loc
*/ * @return
public static PlotId getPlot(Location loc) { */
String world = loc.getWorld().getName(); public static PlotId getPlot(final Location loc) {
PlotManager manager = PlotMain.getPlotManager(world); final String world = loc.getWorld().getName();
if (manager == null) { final PlotManager manager = PlotMain.getPlotManager(world);
return null; if (manager == null) {
} return null;
PlotWorld plotworld = PlotMain.getWorldSettings(world); }
return manager.getPlotId(plotworld, loc); final PlotWorld plotworld = PlotMain.getWorldSettings(world);
} return manager.getPlotId(plotworld, loc);
}
/**
* Returns the plot a player is currently in.
*
* @param player
* @return
*/
public static Plot getCurrentPlot(final Player player) {
if (!PlotMain.isPlotWorld(player.getWorld())) {
return null;
}
final PlotId id = getPlot(player.getLocation());
final World world = player.getWorld();
if (id == null) {
return null;
}
final HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots != null) {
if (plots.containsKey(id)) {
return plots.get(id);
}
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), world.getName());
}
/** /**
* Returns the plot a player is currently in. * Updates a given plot with another instance
* @param player *
* @return * @deprecated
*/ *
public static Plot getCurrentPlot(Player player) { * @param plot
if (!PlotMain.isPlotWorld(player.getWorld())) { */
return null; @Deprecated
} public static void set(final Plot plot) {
PlotId id = getPlot(player.getLocation()); PlotMain.updatePlot(plot);
World world = player.getWorld(); }
if (id == null) {
return null;
}
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots != null) {
if (plots.containsKey(id)) {
return plots.get(id);
}
}
return new Plot(id, null, Biome.FOREST, new ArrayList<UUID>(), new ArrayList<UUID>(), world.getName());
} /**
* Get the plots for a player
*
* @param plr
* @return
*/
public static Set<Plot> getPlayerPlots(final World world, final Player plr) {
final Set<Plot> p = PlotMain.getPlots(world, plr);
if (p == null) {
return new HashSet<Plot>();
}
return p;
}
/** /**
* Updates a given plot with another instance * Get the number of plots for a player
* @deprecated *
* @param plr
* @return
*/
public static int getPlayerPlotCount(final World world, final Player plr) {
final UUID uuid = plr.getUniqueId();
int count = 0;
for (final Plot plot : PlotMain.getPlots(world).values()) {
if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) {
count++;
}
}
return count;
}
* @param plot /**
*/ * Get the maximum number of plots a player is allowed
@Deprecated *
public static void set(Plot plot) { * @param p
PlotMain.updatePlot(plot); * @return
} */
@SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(final Player p) {
return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS);
}
/** /**
* Get the plots for a player * @return PlotMain.getPlots();
* @param plr * @deprecated
* @return */
*/ @Deprecated
public static Set<Plot> getPlayerPlots(World world, Player plr) { public static Set<Plot> getPlots() {
Set<Plot> p = PlotMain.getPlots(world, plr); return PlotMain.getPlots();
if (p == null) { }
return new HashSet<Plot>();
}
return p;
}
/** /**
* Get the number of plots for a player * \\previous\\
* @param plr *
* @return * @param plr
*/ * @param msg
public static int getPlayerPlotCount(World world, Player plr) { * Was used to wrap the chat client length (Packets out--)
UUID uuid = plr.getUniqueId(); */
int count = 0; public static void sendMessageWrapped(final Player plr, final String msg) {
for (Plot plot: PlotMain.getPlots(world).values()) { plr.sendMessage(msg);
if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) { }
count++;
}
}
return count;
}
/** /**
* Get the maximum number of plots a player is allowed * Send a message to the player
* @param p *
* @return * @param plr
*/ * Player to recieve message
@SuppressWarnings("SuspiciousNameCombination") * @param msg
public static int getAllowedPlots(Player p) { * Message to send
return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS); */
} public static void sendMessage(final Player plr, final String msg) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return;
}
/** if (plr == null) {
* @return PlotMain.getPlots(); PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg);
* @deprecated return;
*/ }
@Deprecated
public static Set<Plot> getPlots() {
return PlotMain.getPlots();
}
/** sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
* \\previous\\ }
*
* @param plr
* @param msg
* Was used to wrap the chat client length (Packets out--)
*/
public static void sendMessageWrapped(Player plr, String msg) {
plr.sendMessage(msg);
}
/** /**
* Send a message to the player * Send a message to the player
* *
* @param plr * @param plr
* Player to recieve message * Player to recieve message
* @param msg * @param c
* Message to send * Caption to send
*/ */
public static void sendMessage(Player plr, String msg) { public static void sendMessage(final Player plr, final C c, final String... args) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return;
}
if (plr==null) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg);
return;
}
sendMessageWrapped(plr, ChatColor.translateAlternateColorCodes('&', C.PREFIX.s() + msg));
}
/** if (plr == null) {
* Send a message to the player PlotMain.sendConsoleSenderMessage(c);
* return;
* @param plr }
* Player to recieve message
* @param c if (c.s().length() < 1) {
* Caption to send return;
*/ }
public static void sendMessage(Player plr, C c, String... args) { String msg = c.s();
if ((args != null) && (args.length > 0)) {
if (plr==null) { for (final String str : args) {
PlotMain.sendConsoleSenderMessage(c); msg = msg.replaceFirst("%s", str);
return; }
} }
sendMessage(plr, msg);
if (c.s().length() < 1) { }
return;
}
String msg = c.s();
if ((args != null) && (args.length > 0)) {
for (String str : args) {
msg = msg.replaceFirst("%s", str);
}
}
sendMessage(plr, msg);
}
} }

View File

@ -2,20 +2,21 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Plot.java >> Generated by: Citymonstret at 2014-08-09 01:43 * >> File = Plot.java >> Generated by: Citymonstret at 2014-08-09 01:43
*/ */
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
@ -25,262 +26,255 @@ import java.util.UUID;
@SuppressWarnings("javadoc") @SuppressWarnings("javadoc")
public class Plot implements Cloneable { public class Plot implements Cloneable {
/** /**
* plot ID * plot ID
*/ */
public PlotId id; public PlotId id;
/** /**
* plot world * plot world
*/ */
public String world; public String world;
/** /**
* plot owner * plot owner
*/ */
public UUID owner; public UUID owner;
/** /**
* Deny Entry * Deny Entry
*/ */
public boolean deny_entry; public boolean deny_entry;
/** /**
* List of helpers (with plot permissions) * List of helpers (with plot permissions)
*/ */
public ArrayList<UUID> helpers; public ArrayList<UUID> helpers;
/** /**
* List of trusted users (with plot permissions) * List of trusted users (with plot permissions)
*/ */
public ArrayList<UUID> trusted; public ArrayList<UUID> trusted;
/** /**
* List of denied players * List of denied players
*/ */
public ArrayList<UUID> denied; public ArrayList<UUID> denied;
/** /**
* External settings class * External settings class
*/ */
public PlotSettings settings; public PlotSettings settings;
/** /**
* Delete on next save cycle? * Delete on next save cycle?
*/ */
public boolean delete; public boolean delete;
/** /**
* 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
* *
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
* @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);
this.owner = owner; this.owner = owner;
this.deny_entry = this.owner == null; this.deny_entry = this.owner == null;
this.helpers = helpers; this.helpers = helpers;
this.denied = denied; this.denied = denied;
this.trusted = new ArrayList<UUID>(); this.trusted = new ArrayList<UUID>();
this.settings.setAlias(""); this.settings.setAlias("");
this.settings.setPosition(PlotHomePosition.DEFAULT); this.settings.setPosition(PlotHomePosition.DEFAULT);
this.delete = false; this.delete = false;
this.settings.setFlags(new Flag[0]); this.settings.setFlags(new Flag[0]);
this.world = world; this.world = world;
} }
/** /**
* Constructor for saved plots * Constructor for saved plots
* *
* @param id * @param id
* @param owner * @param owner
* @param plotBiome * @param plotBiome
* @param helpers * @param helpers
* @param denied * @param denied
* @param changeTime * @param changeTime
* @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, this.id = id;
PlotHomePosition position, Flag[] flags, String world, boolean[] merged) { this.settings = new PlotSettings(this);
this.id = id; this.settings.setBiome(plotBiome);
this.settings = new PlotSettings(this); this.owner = owner;
this.settings.setBiome(plotBiome); this.deny_entry = this.owner != null;
this.owner = owner; this.trusted = trusted;
this.deny_entry = this.owner != null; this.helpers = helpers;
this.trusted = trusted; this.denied = denied;
this.helpers = helpers; this.settings.setAlias(alias);
this.denied = denied; this.settings.setPosition(position);
this.settings.setAlias(alias); this.settings.setMerged(merged);
this.settings.setPosition(position); this.delete = false;
this.settings.setMerged(merged); if (flags != null) {
this.delete = false; this.settings.setFlags(flags);
if (flags != null) { }
this.settings.setFlags(flags); else {
} this.settings.setFlags(new Flag[0]);
else { }
this.settings.setFlags(new Flag[0]); this.world = world;
} }
this.world = world;
}
/** /**
* Check if the plot has a set owner * Check if the plot has a set owner
* *
* @return false if there is no owner * @return false if there is no owner
*/ */
public boolean hasOwner() { public boolean hasOwner() {
return this.owner != null; return this.owner != null;
} }
/** /**
* Set the owner * Set the owner
* *
* @param player * @param player
*/ */
public void setOwner(Player player) { public void setOwner(final Player player) {
this.owner = player.getUniqueId(); this.owner = player.getUniqueId();
} }
/** /**
* Check if the player is either the owner or on the helpers list * Check if the player is either the owner or on the helpers list
* *
* @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)));
}
/** /**
* Should the player be allowed to enter? * Should the player be allowed to enter?
* *
* @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()))); }
}
/** /**
* Get the UUID of the owner * Get the UUID of the owner
*/ */
public UUID getOwner() { public UUID getOwner() {
return this.owner; return this.owner;
} }
/** /**
* Get the plot ID * Get the plot ID
*/ */
public PlotId getId() { public PlotId getId() {
return this.id; return this.id;
} }
/** /**
* Get the plot World * Get the plot World
*/ */
public World getWorld() { public World getWorld() {
return Bukkit.getWorld(this.world); return Bukkit.getWorld(this.world);
} }
/** /**
* Get a clone of the plot * Get a clone of the plot
* *
* @return * @return
*/ */
@Override @Override
public Object clone() throws CloneNotSupportedException { public Object clone() throws CloneNotSupportedException {
try { try {
return super.clone(); return super.clone();
} }
catch (CloneNotSupportedException e) { catch (final CloneNotSupportedException e) {
return null; return null;
} }
} }
/** /**
* Deny someone (use DBFunc.addDenied() as well) * Deny someone (use DBFunc.addDenied() as well)
* *
* @param uuid * @param uuid
*/ */
public void addDenied(UUID uuid) { public void addDenied(final UUID uuid) {
this.denied.add(uuid); this.denied.add(uuid);
} }
/** /**
* Add someone as a helper (use DBFunc as well) * Add someone as a helper (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void addHelper(UUID uuid) { public void addHelper(final UUID uuid) {
this.helpers.add(uuid); this.helpers.add(uuid);
} }
/** /**
* Add someone as a trusted user (use DBFunc as well) * Add someone as a trusted user (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void addTrusted(UUID uuid) { public void addTrusted(final UUID uuid) {
this.trusted.add(uuid); this.trusted.add(uuid);
} }
/** /**
* Get plot display name * Get plot display name
* *
* @return alias if set, else id * @return alias if set, else id
*/ */
public String getDisplayName() { public String getDisplayName() {
if (this.settings.getAlias().length() > 1) { if (this.settings.getAlias().length() > 1) {
return this.settings.getAlias(); return this.settings.getAlias();
} }
return this.getId().x + ";" + this.getId().y; return this.getId().x + ";" + this.getId().y;
} }
/** /**
* Remove a denied player (use DBFunc as well) * Remove a denied player (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeDenied(UUID uuid) { public void removeDenied(final UUID uuid) {
this.denied.remove(uuid); this.denied.remove(uuid);
} }
/** /**
* Remove a helper (use DBFunc as well) * Remove a helper (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeHelper(UUID uuid) { public void removeHelper(final UUID uuid) {
this.helpers.remove(uuid); this.helpers.remove(uuid);
} }
/** /**
* Remove a trusted user (use DBFunc as well) * Remove a trusted user (use DBFunc as well)
* *
* @param uuid * @param uuid
*/ */
public void removeTrusted(UUID uuid) { public void removeTrusted(final UUID uuid) {
this.trusted.remove(uuid); this.trusted.remove(uuid);
} }
/** /**
* Clear a plot * Clear a plot
* *
* @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

@ -1,11 +1,11 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
public class PlotBlock { 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

@ -2,10 +2,10 @@ package com.intellectualcrafters.plot;
public class PlotComment { public class PlotComment {
public final String comment; public final String comment;
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = PlotHomePosition.java >> Generated by: Citymonstret at 2014-08-09 * >> File = PlotHomePosition.java >> Generated by: Citymonstret at 2014-08-09
* 01:44 * 01:44
*/ */
@ -13,25 +13,25 @@ package com.intellectualcrafters.plot;
* Created by Citymonstret on 2014-08-05. * Created by Citymonstret on 2014-08-05.
*/ */
public enum PlotHomePosition { public enum PlotHomePosition {
CENTER("Center", 'c'), CENTER("Center", 'c'),
DEFAULT("Default", 'd'); DEFAULT("Default", 'd');
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;
} }
if (string.equalsIgnoreCase(this.string)) { if (string.equalsIgnoreCase(this.string)) {
return true; return true;
} }
return false; return false;
} }
} }

View File

@ -1,54 +1,54 @@
package com.intellectualcrafters.plot; package com.intellectualcrafters.plot;
public class PlotId { public class PlotId {
/** /**
* x value * x value
*/ */
public Integer x; public Integer x;
/** /**
* y value * y value
*/ */
public Integer y; public Integer y;
/** /**
* PlotId class (PlotId x,y values do not correspond to Block locations) * PlotId class (PlotId x,y values do not correspond to Block locations)
* *
* @param x * @param x
* The plot x coordinate * The plot x coordinate
* @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;
} }
if (obj == null) { if (obj == null) {
return false; return false;
} }
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
public String toString() { public String toString() {
return this.x + ";" + this.y; return this.x + ";" + this.y;
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = (prime * result) + this.x; result = (prime * result) + this.x;
result = (prime * result) + this.y; result = (prime * result) + this.y;
return result; return result;
} }
} }

View File

@ -5,70 +5,69 @@ 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 {
/* /*
* Plot locations (methods with Abs in them will not need to consider mega * Plot locations (methods with Abs in them will not need to consider mega
* 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 setFloor(World world, PlotWorld plotworld, PlotId plotid, PlotBlock[] block); public abstract boolean setWall(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock block);
public abstract boolean setBiome(World world, Plot plot, Biome biome); public abstract boolean setFloor(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] block);
/* public abstract boolean setBiome(final World world, final Plot plot, final Biome biome);
* PLOT MERGING (return false if your generator does not support plot
* merging)
*/
public abstract boolean createRoadEast(PlotWorld plotworld, Plot plot);
public abstract boolean createRoadSouth(PlotWorld plotworld, Plot plot); /*
* PLOT MERGING (return false if your generator does not support plot
* merging)
*/
public abstract boolean createRoadEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot); public abstract boolean createRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot); public abstract boolean removeRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean startPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean startPlotUnlink(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds); public abstract boolean removeRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean finishPlotUnlink(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(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean finishPlotMerge(final World world, final PlotWorld plotworld, final 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,103 +14,85 @@ 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;
public PlotSelection(int width, World world, Plot plot) { private final Biome biome;
public PlotSelection(final int width, final World world, final Plot plot) {
this.width = width; this.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);
int index = 0; int index = 0;
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 = 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(), minX2 = bot2.getBlockX(), minZ2 = bot2.getBlockZ();
minZ = bot1.getBlockZ(),
maxZ = top1.getBlockZ(), final boolean canSetFast = PlotHelper.canSetFast;
minX2 = bot2.getBlockX(), for (int x = 0; x <= (maxX - minX); x++) {
minZ2 = bot2.getBlockZ(); for (int z = 0; z <= (maxZ - minZ); z++) {
boolean canSetFast = PlotHelper.canSetFast;
for (int x = 0; x <= maxX - minX; x++) {
for (int z = 0; z <= maxZ - minZ; z++) {
for (int y = 1; y <= world.getMaxHeight(); y++) { 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);
} }
@ -135,35 +111,26 @@ 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);
} }
int index = 0; int index = 0;
PlotBlock current; PlotBlock current;
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

@ -2,191 +2,187 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = PlotSettings.java >> Generated by: Citymonstret at 2014-08-09 01:44 * >> File = PlotSettings.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/ */
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
* *
* @author Citymonstret * @author Citymonstret
*/ */
public class PlotSettings { public class PlotSettings {
/** /**
* merged plots * merged plots
*/ */
private boolean[] merged = new boolean[] { false, false, false, false }; private boolean[] merged = new boolean[] { false, false, false, false };
/** /**
* plot alias * plot alias
*/ */
private String alias; private String alias;
/** /**
* plot biome * plot biome
*/ */
private Biome biome; private Biome biome;
private ArrayList<PlotComment> comments = null; private ArrayList<PlotComment> comments = null;
/** /**
* *
*/ */
private Set<Flag> flags; private Set<Flag> flags;
private PlotHomePosition position; private PlotHomePosition position;
/** /**
* Constructor * Constructor
* *
* @param plot * @param plot
*/ */
public PlotSettings(Plot plot) { public PlotSettings(final Plot plot) {
this.alias = ""; this.alias = "";
}
/**
* <b>Check if the plot is merged in a direction</b><br>
* 0 = North<br>
* 1 = East<br>
* 2 = South<br>
* 3 = West<br>
*
* @param direction
* @return boolean
*/
public boolean getMerged(int direction) {
return this.merged[direction];
}
/**
* Returns true if the plot is merged (i.e. if it's a mega plot)
*/
public boolean isMerged() {
return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]);
}
public boolean[] getMerged() {
return this.merged;
}
public void setMerged(boolean[] merged) {
this.merged = merged;
}
public void setMerged(int direction, boolean merged) {
this.merged[direction] = merged;
}
/**
* @param b
*/
public void setBiome(Biome b) {
this.biome = b;
}
/**
* @return
* @deprecated
*/
@Deprecated
public Biome getBiome() {
return this.biome;
}
/**
* @param alias
*/
public void setAlias(String alias) {
this.alias = alias;
}
/**
* @param flag
*/
public void addFlag(Flag flag) {
Flag hasFlag = getFlag(flag.getKey());
if (hasFlag != null) {
this.flags.remove(hasFlag);
}
this.flags.add(flag);
}
/**
* @param flags
*/
public void setFlags(Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags));
}
/**
* @return
*/
public Set<Flag> getFlags() {
return this.flags;
}
/**
* @param flag
* @return
*/
public Flag getFlag(String flag) {
for (Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) {
return myflag;
}
}
return null;
}
public PlotHomePosition getPosition() {
return this.position;
}
public void setPosition(PlotHomePosition position) {
this.position = position;
}
public String getAlias() {
return this.alias;
}
public String getJoinMessage() {
return "";
}
public String getLeaveMessage() {
return "";
}
public ArrayList<PlotComment> getComments(int tier) {
ArrayList<PlotComment> c = new ArrayList<PlotComment>();
for (PlotComment comment : this.comments) {
if (comment.tier == tier) {
c.add(comment);
}
}
return c;
}
public void setComments(ArrayList<PlotComment> comments) {
this.comments = comments;
} }
public void addComment(PlotComment comment) { /**
if (this.comments == null) { * <b>Check if the plot is merged in a direction</b><br>
* 0 = North<br>
* 1 = East<br>
* 2 = South<br>
* 3 = West<br>
*
* @param direction
* @return boolean
*/
public boolean getMerged(final int direction) {
return this.merged[direction];
}
/**
* Returns true if the plot is merged (i.e. if it's a mega plot)
*/
public boolean isMerged() {
return (this.merged[0] || this.merged[1] || this.merged[2] || this.merged[3]);
}
public boolean[] getMerged() {
return this.merged;
}
public void setMerged(final boolean[] merged) {
this.merged = merged;
}
public void setMerged(final int direction, final boolean merged) {
this.merged[direction] = merged;
}
/**
* @param b
*/
public void setBiome(final Biome b) {
this.biome = b;
}
/**
* @return
* @deprecated
*/
@Deprecated
public Biome getBiome() {
return this.biome;
}
/**
* @param alias
*/
public void setAlias(final String alias) {
this.alias = alias;
}
/**
* @param flag
*/
public void addFlag(final Flag flag) {
final Flag hasFlag = getFlag(flag.getKey());
if (hasFlag != null) {
this.flags.remove(hasFlag);
}
this.flags.add(flag);
}
/**
* @param flags
*/
public void setFlags(final Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags));
}
/**
* @return
*/
public Set<Flag> getFlags() {
return this.flags;
}
/**
* @param flag
* @return
*/
public Flag getFlag(final String flag) {
for (final Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) {
return myflag;
}
}
return null;
}
public PlotHomePosition getPosition() {
return this.position;
}
public void setPosition(final PlotHomePosition position) {
this.position = position;
}
public String getAlias() {
return this.alias;
}
public String getJoinMessage() {
return "";
}
public String getLeaveMessage() {
return "";
}
public ArrayList<PlotComment> getComments(final int tier) {
final ArrayList<PlotComment> c = new ArrayList<PlotComment>();
for (final PlotComment comment : this.comments) {
if (comment.tier == tier) {
c.add(comment);
}
}
return c;
}
public void setComments(final ArrayList<PlotComment> comments) {
this.comments = comments;
}
public void addComment(final PlotComment comment) {
if (this.comments == null) {
this.comments = new ArrayList<PlotComment>(); this.comments = new ArrayList<PlotComment>();
} }
this.comments.add(comment); this.comments.add(comment);
} }
} }

View File

@ -5,26 +5,26 @@ 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);
} }
public static enum PlotError { public static enum PlotError {
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;
} }
public String getHeader() { public String getHeader() {
return this.errorHeader; return this.errorHeader;
} }
@Override @Override
public String toString() { public String toString() {
return this.getHeader(); return this.getHeader();
} }
} }
} }

View File

@ -1,179 +1,247 @@
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;
/** /**
* *
* @author Jesse Boyd * @author Jesse Boyd
* *
*/ */
public abstract class PlotWorld { 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;
public boolean MOB_SPAWNING; public boolean MOB_SPAWNING;
public static boolean MOB_SPAWNING_DEFAULT = false; public static boolean MOB_SPAWNING_DEFAULT = false;
public Biome PLOT_BIOME; public Biome PLOT_BIOME;
public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST; public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST;
public boolean PLOT_CHAT; public boolean PLOT_CHAT;
public static boolean PLOT_CHAT_DEFAULT = false; public static boolean PLOT_CHAT_DEFAULT = false;
public boolean SCHEMATIC_CLAIM_SPECIFY = false; public boolean SCHEMATIC_CLAIM_SPECIFY = false;
public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false; public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false;
public boolean SCHEMATIC_ON_CLAIM; public boolean SCHEMATIC_ON_CLAIM;
public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false; public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false;
public String SCHEMATIC_FILE; public String SCHEMATIC_FILE;
public static String SCHEMATIC_FILE_DEFAULT = "null"; public static String SCHEMATIC_FILE_DEFAULT = "null";
public List<String> SCHEMATICS; public List<String> SCHEMATICS;
public static List<String> SCHEMATICS_DEFAULT = null; public static List<String> SCHEMATICS_DEFAULT = null;
public List<String> DEFAULT_FLAGS; public List<String> DEFAULT_FLAGS;
public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>(); public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>();
public boolean USE_ECONOMY; public boolean USE_ECONOMY;
public static boolean USE_ECONOMY_DEFAULT = false; public static boolean USE_ECONOMY_DEFAULT = false;
public double PLOT_PRICE; public double PLOT_PRICE;
public static double PLOT_PRICE_DEFAULT = 100; public static double PLOT_PRICE_DEFAULT = 100;
public double MERGE_PRICE; public double MERGE_PRICE;
public static double MERGE_PRICE_DEFAULT = 100; public static double MERGE_PRICE_DEFAULT = 100;
public double SELL_PRICE; public double SELL_PRICE;
public static double SELL_PRICE_DEFAULT = 75; public static double SELL_PRICE_DEFAULT = 75;
public boolean PVP; public boolean PVP;
public static boolean PVP_DEFAULT = false; public static boolean PVP_DEFAULT = false;
public boolean PVE; public boolean PVE;
public static boolean PVE_DEFAULT = false; public static boolean PVE_DEFAULT = false;
public boolean SPAWN_EGGS; public boolean SPAWN_EGGS;
public static boolean SPAWN_EGGS_DEFAULT = false; public static boolean SPAWN_EGGS_DEFAULT = false;
public boolean SPAWN_CUSTOM; public boolean SPAWN_CUSTOM;
public static boolean SPAWN_CUSTOM_DEFAULT = true; public static boolean SPAWN_CUSTOM_DEFAULT = true;
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) {
this.worldname = worldname;
}
public PlotWorld(String worldname) { /**
this.worldname = worldname; * When a world is created, the following method will be called for each
} *
* @param config
/** */
* When a world is created, the following method will be called for each public void loadDefaultConfiguration(final ConfigurationSection config) {
* this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
@param config this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
*/ this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome"));
public void loadDefaultConfiguration(ConfigurationSection config) this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim");
{ this.SCHEMATIC_FILE = config.getString("schematic.file");
this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning"); this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim");
this.AUTO_MERGE = config.getBoolean("plot.auto_merge"); this.SCHEMATICS = config.getStringList("schematic.schematics");
this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome")); this.USE_ECONOMY = config.getBoolean("economy.use");
this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim"); this.PLOT_PRICE = config.getDouble("economy.prices.claim");
this.SCHEMATIC_FILE = config.getString("schematic.file"); this.MERGE_PRICE = config.getDouble("economy.prices.merge");
this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim"); this.SELL_PRICE = config.getDouble("economy.prices.sell");
this.SCHEMATICS = config.getStringList("schematic.schematics"); this.PLOT_CHAT = config.getBoolean("chat.enabled");
this.USE_ECONOMY = config.getBoolean("economy.use"); this.DEFAULT_FLAGS = config.getStringList("flags.default");
this.PLOT_PRICE = config.getDouble("economy.prices.claim"); this.PVP = config.getBoolean("event.pvp");
this.MERGE_PRICE = config.getDouble("economy.prices.merge");
this.SELL_PRICE = config.getDouble("economy.prices.sell");
this.PLOT_CHAT = config.getBoolean("chat.enabled");
this.DEFAULT_FLAGS = config.getStringList("flags.default");
this.PVP = config.getBoolean("event.pvp");
this.PVE = config.getBoolean("event.pve"); this.PVE = config.getBoolean("event.pve");
this.SPAWN_EGGS = config.getBoolean("event.spawn.egg"); this.SPAWN_EGGS = config.getBoolean("event.spawn.egg");
this.SPAWN_CUSTOM = config.getBoolean("event.spawn.custom"); this.SPAWN_CUSTOM = config.getBoolean("event.spawn.custom");
this.SPAWN_BREEDING = config.getBoolean("event.spawn.breeding"); this.SPAWN_BREEDING = config.getBoolean("event.spawn.breeding");
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) {
HashMap<String, Object> options = new HashMap<String, Object>(); final 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);
options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString()); options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString());
options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT); options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT); options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT);
options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT); options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT);
options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT); options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT);
options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT); options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT);
options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT); options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT);
options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT); options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT);
options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT); options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT);
options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT); options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT);
options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT); options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT);
options.put("event.pvp", PlotWorld.PVP_DEFAULT); options.put("event.pvp", PlotWorld.PVP_DEFAULT);
options.put("event.pve", PlotWorld.PVE_DEFAULT); options.put("event.pve", PlotWorld.PVE_DEFAULT);
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)); }
} }
} }
}
public String worldname; public String worldname;
/** /**
* Used for the <b>/plot setup</b> command Return null if you do not want to * Used for the <b>/plot setup</b> command Return null if you do not want to
* support this feature * support this feature
* *
* @return ConfigurationNode[] * @return ConfigurationNode[]
*/ */
public abstract ConfigurationNode[] getSettingNodes(); public abstract ConfigurationNode[] getSettingNodes();
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = RUtils.java >> Generated by: Citymonstret at 2014-08-09 01:44 * >> File = RUtils.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/ */
@ -18,70 +18,70 @@ import org.bukkit.entity.Player;
*/ */
public class RUtils { public class RUtils {
public static long getTotalRam() { public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024; return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
} }
public static long getFreeRam() { public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024; return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
} }
public static long getRamPercentage() { public static long getRamPercentage() {
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);
} }
enum Direction { enum Direction {
SOUTH(0), SOUTH(0),
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;
} }
public int getInt() { public int getInt() {
return this.i; return this.i;
} }
} }
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;
case 1: case 1:
return Direction.EAST; return Direction.EAST;
case 2: case 2:
return Direction.NORTH; return Direction.NORTH;
case 3: case 3:
return Direction.WEST; return Direction.WEST;
default: default:
return null; return null;
} }
} }
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

@ -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,263 +12,342 @@ 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(); final int WIDTH = demensions.getX();
int LENGTH = demensions.getZ(); final int LENGTH = demensions.getZ();
int HEIGHT = demensions.getY(); final int HEIGHT = demensions.getY();
DataCollection[] blocks = schematic.getBlockCollection(); final DataCollection[] blocks = schematic.getBlockCollection();
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId()); final int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX() + 1, l1.getBlockZ() + 1);
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); final World world = location.getWorld();
World world = location.getWorld(); int y_offset;
if (HEIGHT == location.getWorld().getMaxHeight()) {
for (int x = 0; x < WIDTH; x++) { y_offset = 0;
for (int z = 0; z < LENGTH; z++) {
for (int y = 0; y < HEIGHT; y++) {
int index = y * WIDTH * LENGTH + z * WIDTH + x;
short id = blocks[index].getBlock();
byte data = blocks[index].getData();
Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset);
PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(block, plotblock);
}
}
} }
} else {
catch (Exception e) { y_offset = l1.getBlockY();
return false; }
}
return true; for (int x = 0; x < WIDTH; x++) {
} for (int z = 0; z < LENGTH; z++) {
for (int y = 0; y < HEIGHT; y++) {
final int index = (y * WIDTH * LENGTH) + (z * WIDTH) + x;
final DataCollection block = blocks[index];
final short id = block.getBlock();
final byte data = block.getData();
// if (block.tag != null) {
// WorldEditUtils.setNBT(world, id, data, l1.getBlockX()
// + x + x_offset, y + y_offset, l1.getBlockZ() + z +
// z_offset, block.tag);
// }
// else {
final Block bukkitBlock = world.getBlockAt(l1.getBlockX() + x + x_offset, y + y_offset, l1.getBlockZ() + z + z_offset);
final PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(bukkitBlock, plotblock);
// }
}
}
}
}
catch (final Exception e) {
return false;
}
return true;
}
/** /**
* Get a schematic * 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(); }
} }
} final File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
File file = if (!file.exists()) {
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
+ File.separator + name + ".schematic"); return null;
if (!file.exists()) { }
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null;
}
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
// AddBlocks index // AddBlocks index
blocks[index] = (short) (b[index] & 0xFF); blocks[index] = (short) (b[index] & 0xFF);
} }
else { else {
if ((index & 1) == 0) { if ((index & 1) == 0) {
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF)); blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF));
} }
else { else {
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF)); blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF));
} }
} }
} }
DataCollection[] collection = new DataCollection[b.length]; final DataCollection[] collection = new DataCollection[b.length];
for (int x = 0; x < b.length; x++) { 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) {
schematic = new Schematic(collection, dimension, file); // List<Tag> tileEntities = requireTag(tagMap, "TileEntities",
} // ListTag.class).getValue();
catch (Exception e) { //
e.printStackTrace(); // for (Tag blocktag : tileEntities) {
return null; // if (!(blocktag instanceof CompoundTag)) continue;
} // CompoundTag t = (CompoundTag) blocktag;
return schematic; //
} // 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);
}
catch (final Exception e) {
e.printStackTrace();
return null;
}
return schematic;
}
/** /**
* 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;
} }
public File getFile() { public File getFile() {
return this.file; return this.file;
} }
public Dimension getSchematicDimension() { public Dimension getSchematicDimension() {
return this.schematicDimension; return this.schematicDimension;
} }
public DataCollection[] getBlockCollection() { public DataCollection[] getBlockCollection() {
return this.blockCollection; return this.blockCollection;
} }
} }
/** /**
* 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;
} }
public int getX() { public int getX() {
return this.x; return this.x;
} }
public int getY() { public int getY() {
return this.y; return this.y;
} }
public int getZ() {
return this.z;
}
}
/**
* Saves a schematic to a file path
*
* @param tag
* to save
* @param path
* to save in
* @return true if succeeded
*/
public static boolean save(final CompoundTag tag, final String path) {
if (tag == null) {
PlotMain.sendConsoleSenderMessage("&cCannot save empty tag");
return false;
}
public int getZ() {
return this.z;
}
}
/**
* Saves a schematic to a file path
* @param tag to save
* @param path to save in
* @return true if succeeded
*/
public static boolean save(CompoundTag tag, String path) {
if (tag==null) {
PlotMain.sendConsoleSenderMessage("&cCannot save empty tag");
return false;
}
try { 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;
} }
return true; return true;
} }
/**
* Gets the schematic of a plot
* @param world to check
* @param id plot
* @return tag
*/
public static CompoundTag getCompoundTag(World world, PlotId id) {
if (!PlotMain.getPlots(world).containsKey(id)) { /**
return null; * Gets the schematic of a plot
// Plot is empty *
} * @param world
* to check
// loading chunks * @param id
final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1); * plot
* @return tag
*/
public static CompoundTag getCompoundTag(final World world, final PlotId id) {
if (!PlotMain.getPlots(world).containsKey(id)) {
return null;
// Plot is empty
}
// loading chunks
final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1);
final Location pos2 = PlotHelper.getPlotTopLoc(world, id); final Location pos2 = PlotHelper.getPlotTopLoc(world, id);
int i = 0; int i = 0;
int j = 0; int j = 0;
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
return null; return null;
}
} }
} }
} }
} catch (final Exception e) {
catch (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;
final Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z));
final int id2 = block.getTypeId();
Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z));
int id2 = block.getTypeId();
if (id2 > 255) { if (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
} }
} }
} }
@ -324,7 +392,7 @@ public class SchematicHandler {
schematic.put("Data", new ByteArrayTag("Data", blockData)); schematic.put("Data", new ByteArrayTag("Data", blockData));
schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>())); schematic.put("Entities", new ListTag("Entities", CompoundTag.class, new ArrayList<Tag>()));
schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, new ArrayList<Tag>())); schematic.put("TileEntities", new ListTag("TileEntities", CompoundTag.class, new ArrayList<Tag>()));
if (addBlocks != null) { if (addBlocks != null) {
schematic.put("AddBlocks", new ByteArrayTag("AddBlocks", addBlocks)); schematic.put("AddBlocks", new ByteArrayTag("AddBlocks", addBlocks));
} }
@ -334,51 +402,54 @@ 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;
this.block = block;
this.data = data;
}
public short getBlock() { public DataCollection(final short block, final byte data) {
return this.block; this.block = block;
} this.data = data;
}
public byte getData() { public short getBlock() {
return this.data; return this.block;
} }
}
public static boolean pastePart(World world, DataCollection[] blocks, Location l1, int x_offset, int z_offset, int i1, int i2, int WIDTH, int LENGTH) { public byte getData() {
return this.data;
}
}
public static boolean pastePart(final World world, final DataCollection[] blocks, final Location l1, final int x_offset, final int z_offset, final int i1, final int i2, final int WIDTH, final int LENGTH) {
boolean result = false; 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;
int r = i%(area);
int x = r%WIDTH; final int area = WIDTH * LENGTH;
int y = i/area; final int r = i % (area);
int z = r/WIDTH;
final int x = r % WIDTH;
if (y>256) { final int y = i / area;
final int z = r / WIDTH;
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

@ -13,38 +13,38 @@ import com.intellectualcrafters.plot.ReflectionUtils.RefMethod;
*/ */
public class SetBlockFast { public class SetBlockFast {
private static final RefClass classBlock = getRefClass("{nms}.Block"); private static final RefClass classBlock = getRefClass("{nms}.Block");
private static final RefClass classChunk = getRefClass("{nms}.Chunk"); private static final RefClass classChunk = getRefClass("{nms}.Chunk");
private static final RefClass classWorld = getRefClass("{nms}.World"); private static final RefClass classWorld = getRefClass("{nms}.World");
private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld"); private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private static RefMethod methodGetHandle; private static RefMethod methodGetHandle;
private static RefMethod methodGetChunkAt; private static RefMethod methodGetChunkAt;
private static RefMethod methodA; private static RefMethod methodA;
private static RefMethod methodGetById; private static RefMethod methodGetById;
public SetBlockFast() throws NoSuchMethodException { public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle"); methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class); methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class); methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Settings.java >> Generated by: Citymonstret at 2014-08-09 01:44 * >> File = Settings.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/ */
@ -15,118 +15,116 @@ package com.intellectualcrafters.plot;
* @author Empire92 * @author Empire92
*/ */
public class Settings { public class Settings {
public static boolean TITLES = true; public static boolean TITLES = true;
/** /**
* Schematic Save Path * Schematic Save Path
*/ */
public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics"; public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics";
/** /**
* Max allowed plots * Max allowed plots
*/ */
public static int MAX_PLOTS = 20; public static int MAX_PLOTS = 20;
/** /**
* WorldGuard region on claimed plots * WorldGuard region on claimed plots
*/ */
public static boolean WORLDGUARD = false; public static boolean WORLDGUARD = false;
/** /**
* metrics * metrics
*/ */
public static boolean METRICS = true; public static boolean METRICS = true;
/** /**
* plot specific resource pack * plot specific resource pack
*/ */
public static String PLOT_SPECIFIC_RESOURCE_PACK = ""; public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
/** /**
* Kill road mobs? * Kill road mobs?
*/ */
public static boolean KILL_ROAD_MOBS; public static boolean KILL_ROAD_MOBS;
/** /**
* Default kill road mobs: true * Default kill road mobs: true
*/ */
public static boolean KILL_ROAD_MOBS_DEFAULT = true; public static boolean KILL_ROAD_MOBS_DEFAULT = true;
/** /**
* mob pathfinding? * mob pathfinding?
*/ */
public static boolean MOB_PATHFINDING; public static boolean MOB_PATHFINDING;
/** /**
* Default mob pathfinding: true * Default mob pathfinding: true
*/ */
public static boolean MOB_PATHFINDING_DEFAULT = true; public static boolean MOB_PATHFINDING_DEFAULT = true;
/** /**
* Delete plots on ban? * Delete plots on ban?
*/ */
public static boolean DELETE_PLOTS_ON_BAN = false; public static boolean DELETE_PLOTS_ON_BAN = false;
/** /**
* Verbose? * Verbose?
*/ */
public static boolean DEBUG = true; public static boolean DEBUG = true;
/** /**
* Auto clear enabled * Auto clear enabled
*/ */
public static boolean AUTO_CLEAR = false; public static boolean AUTO_CLEAR = false;
/** /**
* Days until a plot gets cleared * Days until a plot gets cleared
*/ */
public static int AUTO_CLEAR_DAYS = 365; public static int AUTO_CLEAR_DAYS = 365;
/** /**
* API Location * API Location
*/ */
public static String API_URL = "http://www.intellectualsites.com/minecraft.php"; public static String API_URL = "http://www.intellectualsites.com/minecraft.php";
/** /**
* Use the custom API * Use the custom API
*/ */
public static boolean CUSTOM_API = true; public static boolean CUSTOM_API = true;
/**
/** * Database settings
* Database settings *
* * @author Citymonstret
* @author Citymonstret */
*/ public static class DB {
public static class DB {
/** /**
* MongoDB enabled? * MongoDB enabled?
*/ */
public static boolean USE_MONGO = false; /* public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo * TODO: Implement Mongo
* * @Brandon
* @Brandon */
*/
/** /**
* SQLite enabled? * SQLite enabled?
*/ */
public static boolean USE_SQLITE = false; public static boolean USE_SQLITE = false;
/** /**
* MySQL Enabled? * MySQL Enabled?
*/ */
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */ public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
/** /**
* SQLite Database name * SQLite Database name
*/ */
public static String SQLITE_DB = "storage"; public static String SQLITE_DB = "storage";
/** /**
* MySQL Host name * MySQL Host name
*/ */
public static String HOST_NAME = "localhost"; public static String HOST_NAME = "localhost";
/** /**
* MySQL Port * MySQL Port
*/ */
public static String PORT = "3306"; public static String PORT = "3306";
/** /**
* MySQL DB * MySQL DB
*/ */
public static String DATABASE = "plot_db"; public static String DATABASE = "plot_db";
/** /**
* MySQL User * MySQL User
*/ */
public static String USER = "root"; public static String USER = "root";
/** /**
* MySQL Password * MySQL Password
*/ */
public static String PASSWORD = "password"; public static String PASSWORD = "password";
/** /**
* MySQL Prefix * MySQL Prefix
*/ */
public static String PREFIX = ""; public static String PREFIX = "";
} }
} }

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

@ -17,410 +17,399 @@ import org.bukkit.entity.Player;
*/ */
@SuppressWarnings("unused") @SuppressWarnings("unused")
public class Title { public class Title {
/* Title packet */ /* Title packet */
private Class<?> packetTitle; private Class<?> packetTitle;
/* Title packet actions ENUM */ /* Title packet actions ENUM */
private Class<?> packetActions; private Class<?> packetActions;
/* Chat serializer */ /* Chat serializer */
private Class<?> nmsChatSerializer; private Class<?> nmsChatSerializer;
/* Title text and color */ /* Title text and color */
private String title = ""; private String title = "";
private ChatColor titleColor = ChatColor.WHITE; private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */ /* Subtitle text and color */
private String subtitle = ""; private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE; private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */ /* Title timings */
private int fadeInTime = -1; private int fadeInTime = -1;
private int stayTime = -1; private int stayTime = -1;
private int fadeOutTime = -1; private int fadeOutTime = -1;
private boolean ticks = false; private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES; private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES;
static { static {
CORRESPONDING_TYPES = new HashMap<>(); CORRESPONDING_TYPES = new HashMap<>();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title * Title
*/ */
public Title(String title) { public Title(final String title) {
this.title = title; this.title = title;
loadClasses(); loadClasses();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title text * Title text
* @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();
} }
/** /**
* Create a new 1.8 title * Create a new 1.8 title
* *
* @param title * @param title
* Title text * Title text
* @param subtitle * @param subtitle
* Subtitle text * Subtitle text
* @param fadeInTime * @param fadeInTime
* Fade in time * Fade in time
* @param stayTime * @param stayTime
* Stay on screen time * Stay on screen time
* @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;
this.stayTime = stayTime; this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime; this.fadeOutTime = fadeOutTime;
loadClasses(); loadClasses();
} }
/** /**
* Load spigot and NMS classes * Load spigot and NMS classes
*/ */
private void loadClasses() { private void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle"); this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action"); this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer"); this.nmsChatSerializer = getNMSClass("ChatSerializer");
} }
/** /**
* Set the title color * Set the title color
* *
* @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;
} }
/** /**
* Set the subtitle color * Set the subtitle color
* *
* @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;
} }
/** /**
* Set title fade in time * Set title fade in time
* *
* @param time * @param time
* Time * Time
*/ */
public void setFadeInTime(int time) { public void setFadeInTime(final int time) {
this.fadeInTime = time; this.fadeInTime = time;
} }
/** /**
* Set title fade out time * Set title fade out time
* *
* @param time * @param time
* Time * Time
*/ */
public void setFadeOutTime(int time) { public void setFadeOutTime(final int time) {
this.fadeOutTime = time; this.fadeOutTime = time;
} }
/** /**
* Set title stay time * Set title stay time
* *
* @param time * @param time
* Time * Time
*/ */
public void setStayTime(int time) { public void setStayTime(final int time) {
this.stayTime = time; this.stayTime = time;
} }
/** /**
* Set timings to ticks * Set timings to ticks
*/ */
public void setTimingsToTicks() { public void setTimingsToTicks() {
this.ticks = true; this.ticks = true;
} }
/** /**
* Set timings to seconds * Set timings to seconds
*/ */
public void setTimingsToSeconds() { public void setTimingsToSeconds() {
this.ticks = false; this.ticks = false;
} }
/** /**
* Send the title to a player * Send the title to a player
* *
* @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 // Send if set
* (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
* (this.ticks ? 1 : 20)); sendPacket.invoke(connection, packet);
// Send if set }
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
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:" sendPacket.invoke(connection, packet);
+ this.titleColor.name().toLowerCase() + "}"); if (!this.subtitle.equals("")) {
packet = // Send subtitle if present
this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized); serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
sendPacket.invoke(connection, packet); packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
if (!this.subtitle.equals("")) { sendPacket.invoke(connection, packet);
// Send subtitle if present }
serialized = }
getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" catch (final Exception e) {
+ ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" e.printStackTrace();
+ this.subtitleColor.name().toLowerCase() + "}"); }
packet = }
this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized); }
sendPacket.invoke(connection, packet);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/** /**
* 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);
} }
} }
/** /**
* Clear the title * Clear the 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();
} }
} }
} }
/** /**
* Reset the title settings * Reset the title settings
* *
* @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();
} }
} }
} }
/** /**
* Get the protocol version of the player * Get the protocol version of the player
* *
* @param player * @param player
* 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;
} }
/** /**
* Check if running spigot * Check if running spigot
* *
* @return Spigot * @return Spigot
*/ */
private boolean isSpigot() { private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot"); return Bukkit.getVersion().contains("Spigot");
} }
/** /**
* Get class by url * Get class by url
* *
* @param namespace * @param namespace
* 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;
} }
for (int i = 0; i < a.length; i++) { for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) { if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false; return false;
} }
} }
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;
} }
} }
return null; return null;
} }
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;
} }
} }
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;
} }
for (int i = 0; i < l1.length; i++) { for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) { if (l1[i] != l2[i]) {
equal = false; equal = false;
break; break;
} }
} }
return equal; return equal;
} }
} }

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,30 +25,35 @@ 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.
*/ */
public class UUIDHandler { 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();
/** /**
* Map containing names and UUID's * Map containing names and UUID's
*/ */
private static BiMap<StringWrapper, UUID> uuidMap = HashBiMap.create(new HashMap<StringWrapper, UUID>()); private static BiMap<StringWrapper, UUID> uuidMap = HashBiMap.create(new HashMap<StringWrapper, UUID>());
/** /**
* 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,222 +62,233 @@ 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
* @return uuid * to use as key
*/ * @return uuid
public static UUID getUUID(String name) { */
StringWrapper nameWrap = new StringWrapper(name); public static UUID getUUID(final String name) {
if (uuidMap.containsKey(nameWrap)) { final StringWrapper nameWrap = new StringWrapper(name);
return uuidMap.get(nameWrap); if (uuidMap.containsKey(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();
} }
} }
} }
else { else {
return getUuidOfflineMode(nameWrap); return getUuidOfflineMode(nameWrap);
} }
return null; return null;
} }
/** /**
* @param uuid to use as key * @param uuid
* @return name (cache) * to use as key
*/ * @return name (cache)
private static StringWrapper loopSearch(UUID uuid) { */
return uuidMap.inverse().get(uuid); private static StringWrapper loopSearch(final UUID uuid) {
} return uuidMap.inverse().get(uuid);
}
/** /**
* @param uuid to use as key * @param uuid
* @return Name * to use as key
*/ * @return Name
public static String getName(UUID uuid) { */
if (uuidExists(uuid)) { public static String getName(final UUID uuid) {
return loopSearch(uuid).value; if (uuidExists(uuid)) {
} return loopSearch(uuid).value;
String name; }
if ((name = getNameOnlinePlayer(uuid)) != null) { String name;
return name; if ((name = getNameOnlinePlayer(uuid)) != null) {
} return name;
if ((name = getNameOfflinePlayer(uuid)) != null) { }
return name; if ((name = getNameOfflinePlayer(uuid)) != null) {
} return name;
if (online) { }
if(!Settings.CUSTOM_API) { if (online) {
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();
} }
} }
} }
else { else {
return "unknown"; return "unknown";
} }
return ""; return "";
} }
/** /**
* @param name to use as key * @param name
* @return UUID (name hash) * to use as key
*/ * @return UUID (name hash)
private static UUID getUuidOfflineMode(StringWrapper name) { */
UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8)); private static UUID getUuidOfflineMode(final StringWrapper name) {
add(name, uuid); final UUID uuid = UUID.nameUUIDFromBytes(("OfflinePlayer:" + name).getBytes(Charsets.UTF_8));
return uuid; add(name, uuid);
} return uuid;
}
/** /**
* @param uuid to use as key * @param uuid
* @return String - name * to use as key
*/ * @return String - name
private static String getNameOnlinePlayer(UUID uuid) { */
Player player = Bukkit.getPlayer(uuid); private static String getNameOnlinePlayer(final UUID uuid) {
if (player == null || !player.isOnline()) { final Player player = Bukkit.getPlayer(uuid);
return null; if ((player == null) || !player.isOnline()) {
} return null;
String name = player.getName(); }
add(new StringWrapper(name), uuid); final String name = player.getName();
return name; add(new StringWrapper(name), uuid);
} return name;
}
/** /**
* @param uuid to use as key * @param uuid
* @return String - name * to use as key
*/ * @return String - name
private static String getNameOfflinePlayer(UUID uuid) { */
OfflinePlayer player = Bukkit.getOfflinePlayer(uuid); private static String getNameOfflinePlayer(final UUID uuid) {
if (player == null || !player.hasPlayedBefore()) { final OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
return null; if ((player == null) || !player.hasPlayedBefore()) {
} return null;
String name = player.getName(); }
add(new StringWrapper(name), uuid); final String name = player.getName();
return name; add(new StringWrapper(name), uuid);
} return name;
}
/** /**
* @param name to use as key * @param name
* @return UUID * to use as key
*/ * @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

@ -2,15 +2,15 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = PlotAPI.java >> Generated by: Citymonstret at 2014-08-09 01:44 * >> File = PlotAPI.java >> Generated by: Citymonstret at 2014-08-09 01:44
*/ */
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.
@ -29,39 +40,40 @@ import java.util.Set;
@SuppressWarnings({ "unused", "javadoc" }) @SuppressWarnings({ "unused", "javadoc" })
public class PlotAPI { public class PlotAPI {
private static PlotHelper plotHelper; private static PlotHelper plotHelper;
private static PlayerFunctions playerFunctions; private static PlayerFunctions playerFunctions;
private static FlagManager flagManager; private static FlagManager flagManager;
private static SchematicHandler schematicHandler; private static SchematicHandler schematicHandler;
private static C c; private static C c;
// Methods/fields in PlotMain class // Methods/fields in PlotMain class
// PlotMain.checkForExpiredPlots(); #Ignore // PlotMain.checkForExpiredPlots(); #Ignore
// PlotMain.killAllEntities(); #Ignore // PlotMain.killAllEntities(); #Ignore
// //
// PlotMain.createConfiguration(plotworld); // PlotMain.createConfiguration(plotworld);
// PlotMain.getPlots(player) // PlotMain.getPlots(player)
// PlotMain.getPlots(world) // PlotMain.getPlots(world)
// PlotMain.getPlots(world, player) // PlotMain.getPlots(world, player)
// PlotMain.getWorldPlots(world) // PlotMain.getWorldPlots(world)
// PlotMain.getPlotWorlds() // PlotMain.getPlotWorlds()
// PlotMain.isPlotWorld(world) // PlotMain.isPlotWorld(world)
// PlotMain.removePlot(world, id, callEvent) // PlotMain.removePlot(world, id, callEvent)
// PlotMain.teleportPlayer(player, from, plot) // PlotMain.teleportPlayer(player, from, plot)
// PlotMain.updatePlot(plot); // PlotMain.updatePlot(plot);
// To access plotMain stuff. // To access plotMain stuff.
private PlotMain plotMain; private final PlotMain plotMain;
// Reference // Reference
/** /**
* Admin Permission * Admin Permission
*/ */
public static final String ADMIN_PERMISSION = "plots.admin"; public static final String ADMIN_PERMISSION = "plots.admin";
/** /**
* 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);
} }
@ -112,375 +131,376 @@ public class PlotAPI {
return PlotMain.storage; return PlotMain.storage;
} }
/** /**
* 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
public PlotAPI(JavaPlugin plugin) { * Plugin used to access this method
this.plotMain = JavaPlugin.getPlugin(PlotMain.class); */
} public PlotAPI(final JavaPlugin plugin) {
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;
} }
/** /**
* PlotHelper class contains useful methods relating to plots. * PlotHelper class contains useful methods relating to plots.
* *
* @return PlotHelper * @return PlotHelper
*/ */
public PlotHelper getPlotHelper() { public PlotHelper getPlotHelper() {
return plotHelper; return plotHelper;
} }
/** /**
* PlayerFunctions class contains useful methods relating to players - Some * PlayerFunctions class contains useful methods relating to players - Some
* player/plot methods are here as well * player/plot methods are here as well
* *
* @return PlayerFunctions * @return PlayerFunctions
*/ */
public PlayerFunctions getPlayerFunctions() { public PlayerFunctions getPlayerFunctions() {
return playerFunctions; return playerFunctions;
} }
/** /**
* FlagManager class contains methods relating to plot flags * FlagManager class contains methods relating to plot flags
* *
* @return FlagManager * @return FlagManager
*/ */
public FlagManager getFlagManager() { public FlagManager getFlagManager() {
return flagManager; return flagManager;
} }
/** /**
* SchematicHandler class contains methods related to pasting schematics * SchematicHandler class contains methods related to pasting schematics
* *
* @return SchematicHandler * @return SchematicHandler
*/ */
public SchematicHandler getSchematicHandler() { public SchematicHandler getSchematicHandler() {
return schematicHandler; return schematicHandler;
} }
/** /**
* C class contains all the captions from the translations.yml file. * C class contains all the captions from the translations.yml file.
* *
* @return C * @return C
*/ */
public C getCaptions() { public C getCaptions() {
return c; return c;
} }
/** /**
* Get the plot manager for a world. - Most of these methods can be accessed * Get the plot manager for a world. - Most of these methods can be accessed
* through the PlotHelper * through the PlotHelper
* *
* @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);
} }
/** /**
* Get the plot manager for a world. - Contains useful low level methods for * Get the plot manager for a world. - Contains useful low level methods for
* plot merging, clearing, and tessellation * plot merging, clearing, and tessellation
* *
* @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);
} }
/** /**
* Get the settings for a world (settings bundled in PlotWorld class) - You * Get the settings for a world (settings bundled in PlotWorld class) - You
* will need to downcast for the specific settings a Generator has. e.g. * will need to downcast for the specific settings a Generator has. e.g.
* DefaultPlotWorld class implements PlotWorld * DefaultPlotWorld class implements PlotWorld
* *
* @param world * @param world
* (to get settings of) * (to get settings of)
* @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);
} }
/** /**
* Get the settings for a world (settings bundled in PlotWorld class) * Get the settings for a world (settings bundled in PlotWorld class)
* *
* @param world * @param world
* (to get settings of) * (to get settings of)
* @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);
} }
/** /**
* Send a message to a player. * Send a message to a player.
* *
* @param player * @param player
* @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);
} }
/** /**
* Send a message to a player. - Supports color codes * Send a message to a player. - Supports color codes
* *
* @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);
} }
/** /**
* Send a message to the console. - Supports color codes * Send a message to the console. - Supports color codes
* *
* @param msg * @param msg
*/ */
public void sendConsoleMessage(String msg) { public void sendConsoleMessage(final String msg) {
PlotMain.sendConsoleSenderMessage(msg); PlotMain.sendConsoleSenderMessage(msg);
} }
/** /**
* Send a message to the console * Send a message to the console
* *
* @param c * @param c
* (Caption) * (Caption)
*/ */
public void sendConsoleMessage(C c) { public void sendConsoleMessage(final C c) {
sendConsoleMessage(c.s()); sendConsoleMessage(c.s());
} }
/** /**
* Register a flag for use in plots * Register a flag for use in plots
* *
* @param flag * @param flag
*/ */
public void addFlag(AbstractFlag flag) { public void addFlag(final AbstractFlag flag) {
FlagManager.addFlag(flag); FlagManager.addFlag(flag);
} }
/** /**
* get all the currently registered flags * get all the currently registered flags
* *
* @return array of Flag[] * @return array of Flag[]
*/ */
public AbstractFlag[] getFlags() { public AbstractFlag[] getFlags() {
return FlagManager.getFlags().toArray(new AbstractFlag[0]); return FlagManager.getFlags().toArray(new AbstractFlag[0]);
} }
/** /**
* Get a plot based on the ID * Get a plot based on the ID
* *
* @param world * @param world
* @param x * @param x
* @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));
} }
/** /**
* Get a plot based on the location * Get a plot based on the location
* *
* @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);
} }
/** /**
* Get a plot based on the player location * Get a plot based on the player location
* *
* @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());
} }
/** /**
* Check whether or not a player has a plot * Check whether or not a player has a plot
* *
* @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);
} }
/** /**
* Get all plots for the player * Get all plots for the player
* *
* @param plr * @param plr
* to search for * to search for
* @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);
} }
} }
else { else {
if (plot.hasRights(plr)) { if (plot.hasRights(plr)) {
pPlots.add(plot); pPlots.add(plot);
} }
} }
} }
return (Plot[]) pPlots.toArray(); return (Plot[]) pPlots.toArray();
} }
/** /**
* Get all plots for the world * Get all plots for the world
* *
* @param world * @param world
* 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);
} }
/** /**
* Get all plot worlds * Get all plot worlds
* *
* @return World[] - array of plot worlds * @return World[] - array of plot worlds
*/ */
public String[] getPlotWorlds() { public String[] getPlotWorlds() {
return PlotMain.getPlotWorlds(); return PlotMain.getPlotWorlds();
} }
/** /**
* Get if plot world * Get if plot world
* *
* @param world * @param world
* (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);
} }
/** /**
* Get plot locations * Get plot locations
* *
* @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) }; }
}
/** /**
* Get home location * Get home location
* *
* @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);
} }
/** /**
* Get Bottom Location * Get Bottom Location
* *
* @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);
} }
/** /**
* Get Top Location * Get Top Location
* *
* @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);
} }
/** /**
* Check whether or not a player is in a plot * Check whether or not a player is in a plot
* *
* @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);
} }
/** /**
* Register a subcommand * Register a subcommand
* *
* @param c * @param c
*/ */
public void registerCommand(SubCommand c) { public void registerCommand(final SubCommand c) {
MainCommand.subCommands.add(c); MainCommand.subCommands.add(c);
} }
/** /**
* Get the plotMain class * Get the plotMain class
* *
* @return PlotMain Class * @return PlotMain Class
*/ */
public PlotMain getPlotMain() { public PlotMain getPlotMain() {
return this.plotMain; return this.plotMain;
} }
/** /**
* Get the player plot count * Get the player plot count
* *
* @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);
} }
/** /**
* Get a players plots * Get a players plots
* *
* @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);
} }
/** /**
* Get the allowed plot count for a player * Get the allowed plot count for a player
* *
* @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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Auto.java >> Generated by: Citymonstret at 2014-08-09 01:40 * >> File = Auto.java >> Generated by: Citymonstret at 2014-08-09 01:40
*/ */
package com.intellectualcrafters.plot.commands; package com.intellectualcrafters.plot.commands;
@ -24,126 +24,126 @@ import com.intellectualcrafters.plot.PlotWorld;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class Auto extends SubCommand { public class Auto extends SubCommand {
public Auto() { public Auto() {
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;
String schematic = ""; String schematic = "";
if (PlotMain.getPlotWorlds().length == 1) { if (PlotMain.getPlotWorlds().length == 1) {
world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]); world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]);
} }
else { else {
if (PlotMain.isPlotWorld(plr.getWorld())) { if (PlotMain.isPlotWorld(plr.getWorld())) {
world = plr.getWorld(); world = plr.getWorld();
} }
else { else {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false; return false;
} }
} }
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)) {
PlayerFunctions.sendMessage(plr, "&cError: size<=0"); PlayerFunctions.sendMessage(plr, "&cError: size<=0");
} }
if ((size_x > 4) || (size_z > 4)) { if ((size_x > 4) || (size_z > 4)) {
PlayerFunctions.sendMessage(plr, "&cError: size>4"); PlayerFunctions.sendMessage(plr, "&cError: size>4");
} }
if (args.length > 1) { if (args.length > 1) {
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)");
// return false; // return false;
} }
} }
else { else {
schematic = args[0]; schematic = args[0];
// PlayerFunctions.sendMessage(plr, C.NO_PERMISSION); // PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
// return false; // return false;
} }
} }
if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) { if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) {
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;
} }
economy.withdrawPlayer(plr, cost); economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); sendMessage(plr, C.REMOVED_BALANCE, cost + "");
} }
} }
if (!schematic.equals("")) { if (!schematic.equals("")) {
if (pWorld.SCHEMATIC_CLAIM_SPECIFY) { if (pWorld.SCHEMATIC_CLAIM_SPECIFY) {
if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) { if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) {
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 br = false; boolean br = false;
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));
} }
} }
Auto.lastPlot = getNextPlot(Auto.lastPlot, 1); Auto.lastPlot = getNextPlot(Auto.lastPlot, 1);
} }
} }
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,20 +151,20 @@ 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));
} }
} }
} }
} }
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) {
@ -194,19 +194,18 @@ public class Auto extends SubCommand {
return new PlotId(id.x + 1, id.y); return new PlotId(id.x + 1, id.y);
} }
} }
public boolean isUnowned(World world, PlotId pos1, PlotId pos2) { public boolean isUnowned(final World world, final PlotId pos1, final 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;
} }
} }
} }
} }
return true; return true;
} }
} }

View File

@ -2,121 +2,130 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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
*/ */
public class Claim extends SubCommand { public class Claim extends SubCommand {
public Claim() { public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true); super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true);
} }
@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];
} }
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;
} }
if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) { if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) {
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;
} }
economy.withdrawPlayer(plr, cost); economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); sendMessage(plr, C.REMOVED_BALANCE, cost + "");
} }
} }
if (!schematic.equals("")) { if (!schematic.equals("")) {
if (world.SCHEMATIC_CLAIM_SPECIFY) { if (world.SCHEMATIC_CLAIM_SPECIFY) {
if (!world.SCHEMATICS.contains(schematic.toLowerCase())) { if (!world.SCHEMATICS.contains(schematic.toLowerCase())) {
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;
} }
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);
PlotHelper.setSign(player, plot); PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED); PlayerFunctions.sendMessage(player, C.CLAIMED);
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;
if (schematic.equals("")) { if (schematic.equals("")) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
} }
else { else {
sch = SchematicHandler.getSchematic(schematic); sch = SchematicHandler.getSchematic(schematic);
if (sch == null) { if (sch == null) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE); sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
} }
} }
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);
} }
} }
} }
return event.isCancelled(); return event.isCancelled();
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -20,30 +20,29 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class Clear extends SubCommand { public class Clear extends SubCommand {
public Clear() { public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true); super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true);
// TODO console clear plot at location
}
@Override // TODO console clear plot at location
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) { }
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false; @Override
} public boolean execute(final Player plr, final String... args) {
Plot plot = PlayerFunctions.getCurrentPlot(plr); if (!PlayerFunctions.isInPlot(plr)) {
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) { PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); 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; }
} plot.clear(plr);
plot.clear(plr); return true;
return true; }
}
} }

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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Command.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Command.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -15,15 +15,15 @@ package com.intellectualcrafters.plot.commands;
*/ */
public enum Command { public enum Command {
// TODO new commands // TODO new commands
// (economy) // (economy)
// - /plot buy // - /plot buy
// - /plot sell <value> // - /plot sell <value>
// (Rating system) (ratings can be stored as the average, and number of // (Rating system) (ratings can be stored as the average, and number of
// ratings) // ratings)
// - /plot rate <number out of 10> // - /plot rate <number out of 10>
// - /plot list <some parameter to list the most popular, and highest rated // - /plot list <some parameter to list the most popular, and highest rated
// plots> // plots>
SWAP("swap"), SWAP("swap"),
/** /**
* *
@ -40,152 +40,152 @@ public enum Command {
/** /**
* *
*/ */
TRUSTED("trusted", "trust"), TRUSTED("trusted", "trust"),
/** /**
* *
*/ */
PASTE("paste"), PASTE("paste"),
CLIPBOARD("clipboard", "cboard"), CLIPBOARD("clipboard", "cboard"),
COPY("copy"), COPY("copy"),
/** /**
* *
*/ */
KICK("kick", "k"), KICK("kick", "k"),
/** /**
* *
*/ */
HELPERS("helpers", "hp"), HELPERS("helpers", "hp"),
/** /**
* *
*/ */
DENIED("denied", "dn"), DENIED("denied", "dn"),
/** /**
* *
*/ */
CLAIM("claim", "c"), CLAIM("claim", "c"),
/** /**
* *
*/ */
MERGE("merge", "m"), MERGE("merge", "m"),
/** /**
* *
*/ */
UNLINK("unlink", "u"), UNLINK("unlink", "u"),
/** /**
* *
*/ */
CLEAR("clear", "clear", new CommandPermission("plots.clear")), CLEAR("clear", "clear", new CommandPermission("plots.clear")),
/** /**
* *
*/ */
DELETE("delete", "d", new CommandPermission("plots.delete")), DELETE("delete", "d", new CommandPermission("plots.delete")),
/** /**
* *
*/ */
DEBUG("debug", "database", new CommandPermission("plots.admin")), DEBUG("debug", "database", new CommandPermission("plots.admin")),
/** /**
* *
*/ */
INTERFACE("interface", "int", new CommandPermission("plots.interface")), INTERFACE("interface", "int", new CommandPermission("plots.interface")),
/** /**
* *
*/ */
HOME("home", "h"), HOME("home", "h"),
/** /**
* *
*/ */
INFO("info", "i"), INFO("info", "i"),
/** /**
* *
*/ */
LIST("list", "l"), LIST("list", "l"),
/** /**
* *
*/ */
SET("set", "s"), SET("set", "s"),
/** /**
* *
*/ */
PURGE("purge"), PURGE("purge"),
/** /**
* *
*/ */
SETUP("setup"), SETUP("setup"),
/** /**
* *
*/ */
TP("tp", "tp"); TP("tp", "tp");
/** /**
* *
*/ */
private String command; private String command;
/** /**
* *
*/ */
private String alias; private String alias;
/** /**
* *
*/ */
private CommandPermission permission; private CommandPermission permission;
/** /**
* @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);
} }
/** /**
* @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;
} }
/** /**
* @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);
} }
/** /**
* @param Command * @param 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;
} }
/** /**
* @return * @return
*/ */
public String getCommand() { public String getCommand() {
return this.command; return this.command;
} }
/** /**
* @return * @return
*/ */
public String getAlias() { public String getAlias() {
return this.alias; return this.alias;
} }
/** /**
* @return * @return
*/ */
public CommandPermission getPermission() { public CommandPermission getPermission() {
return this.permission; return this.permission;
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = CommandPermission.java >> Generated by: Citymonstret at 2014-08-09 * >> File = CommandPermission.java >> Generated by: Citymonstret at 2014-08-09
* 01:41 * 01:41
*/ */
@ -20,23 +20,23 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class CommandPermission { public class CommandPermission {
/** /**
* *
*/ */
public String permission; public String permission;
/** /**
* @param permission * @param permission
*/ */
public CommandPermission(String permission) { public CommandPermission(final String permission) {
this.permission = permission.toLowerCase(); this.permission = permission.toLowerCase();
} }
/** /**
* @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

@ -2,62 +2,65 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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.
*/ */
public class Comment extends SubCommand { public class Comment extends SubCommand {
public Comment() { public Comment() {
super(Command.COMMENT, "Comment on a plot", "comment", CommandCategory.ACTIONS, true); super(Command.COMMENT, "Comment on a plot", "comment", CommandCategory.ACTIONS, true);
} }
@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;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
List<String> recipients = Arrays.asList(new String[] {"admin", "owner", "helper", "trusted", "everyone" }); if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
if (args.length==2 && recipients.contains(args[0].toLowerCase())) { return false;
}
if (PlotMain.hasPermission(plr, "plots.comment."+args[0].toLowerCase())) {
String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " "); final List<String> recipients = Arrays.asList(new String[] { "admin", "owner", "helper", "trusted", "everyone" });
PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase()));
plot.settings.addComment(comment); if ((args.length == 2) && recipients.contains(args[0].toLowerCase())) {
DBFunc.setComment(plr.getWorld().getName(), plot, comment); if (PlotMain.hasPermission(plr, "plots.comment." + args[0].toLowerCase())) {
final String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " ");
final PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase()));
return true; plot.settings.addComment(comment);
}
else { DBFunc.setComment(plr.getWorld().getName(), plot, comment);
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment."+args[0].toLowerCase());
return false; return true;
} }
} else {
PlayerFunctions.sendMessage(plr, C.COMMENT_SYNTAX); PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment." + args[0].toLowerCase());
return false;
}
}
PlayerFunctions.sendMessage(plr, C.COMMENT_SYNTAX);
return false; return false;
} }
} }

View File

@ -2,50 +2,55 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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.
*/ */
public class Copy extends SubCommand { public class Copy extends SubCommand {
public Copy() { public Copy() {
super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true); super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true);
} }
@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; }
} if (plot.settings.isMerged()) {
if (plot.settings.isMerged()) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED); PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
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,
return true; // new PlotId(plot.getId().x + 1, plot.getId().y)));
} return true;
}
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Debug.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Debug.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -31,91 +31,91 @@ import com.intellectualcrafters.plot.RUtils;
*/ */
public class Debug extends SubCommand { public class Debug extends SubCommand {
// private extends SubCommand^Implements {Command, Information} from // private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\ // >>\\S.txt6\\
public Debug() { public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false); super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false);
{ {
/** /**
* This. * This.
*/ */
} }
} }
@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());
return true; return true;
} }
StringBuilder information; StringBuilder information;
String header, line, section; String header, line, section;
/** /**
* {$notnull || compile:: \\Debug:Captions\\} * {$notnull || compile:: \\Debug:Captions\\}
*/ */
{ {
information = new StringBuilder(); information = new StringBuilder();
header = C.DEUBG_HEADER.s(); header = C.DEUBG_HEADER.s();
line = C.DEBUG_LINE.s(); line = C.DEBUG_LINE.s();
section = C.DEBUG_SECTION.s(); section = C.DEBUG_SECTION.s();
} }
/** /**
* {||direct:: load: debug::I>Captions::trsl} \\ if(missing) * {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* set(default) -> this->(){} \\ echo line->line(Compiler.cpp -> * set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* lineCompiler); when finished: now = this(); * lineCompiler); when finished: now = this();
* now(getter)->setter(this())->{ "string" = getter(this); * now(getter)->setter(this())->{ "string" = getter(this);
* setter(string) = getter(this->setter); } when ^ finished compile; * setter(string) = getter(this->setter); } when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.| ||run test * if(^compile failed -> |this->failed.|tests->failed.| ||run test
* {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);
information.append(getSection(section, "Lag / TPS")); information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS())); information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%")); information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%"));
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%")); information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%"));
information.append(getSection(section, "PlotWorld")); information.append(getSection(section, "PlotWorld"));
information.append(getLine(line, "Plot Worlds", worlds)); information.append(getLine(line, "Plot Worlds", worlds));
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)));
information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world))); information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world)));
} }
information.append(getSection(section, "RAM")); information.append(getSection(section, "RAM"));
information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB")); information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB"));
information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB")); information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB"));
information.append(getSection(section, "Messages")); information.append(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", C.values().length)); information.append(getLine(line, "Total Messages", C.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg")); information.append(getLine(line, "View all captions", "/plot debug msg"));
} }
/** /**
* {function:: SEND_MESSAGE |local player -> plr|local string -> * {function:: SEND_MESSAGE |local player -> plr|local string ->
* information.toString())} * information.toString())}
*/ */
{ {
PlayerFunctions.sendMessage(plr, information.toString()); PlayerFunctions.sendMessage(plr, information.toString());
} }
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -11,8 +11,6 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList; import java.util.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;
@ -42,141 +39,141 @@ import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
*/ */
public class DebugClaimTest extends SubCommand { public class DebugClaimTest extends SubCommand {
public DebugClaimTest() { public DebugClaimTest() {
super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false); super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false);
} }
@Override @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;
} }
PlotId min, max;
try {
String[] split1 = args[1].split(";");
String[] split2 = args[2].split(";");
min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]));
max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1]));
}
catch (Exception e) {
PlayerFunctions.sendMessage(plr, "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X,Y are the plot coords\nThe conversion will only check the plots in the selected area.");
return false;
}
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while...");
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)");
PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world);
ArrayList<Plot> plots = new ArrayList<Plot>();
for (PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) { PlotId min, max;
Plot plot = PlotHelper.getPlot(world, id);
boolean contains = PlotMain.getPlots(world).containsKey(plot.id); try {
final String[] split1 = args[1].split(";");
final String[] split2 = args[2].split(";");
min = new PlotId(Integer.parseInt(split1[0]), Integer.parseInt(split1[1]));
max = new PlotId(Integer.parseInt(split2[0]), Integer.parseInt(split2[1]));
}
catch (final Exception e) {
PlayerFunctions.sendMessage(plr, "&cInvalid min/max values. &7The values are to Plot IDs in the format &cX;Y &7where X,Y are the plot coords\nThe conversion will only check the plots in the selected area.");
return false;
}
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Beginning sign to plot conversion. This may take a while...");
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: Found an excess of 250,000 chunks. Limiting search radius... (~3.8 min)");
final PlotManager manager = PlotMain.getPlotManager(world);
final PlotWorld plotworld = PlotMain.getWorldSettings(world);
final ArrayList<Plot> plots = new ArrayList<Plot>();
for (final PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) {
final Plot plot = PlotHelper.getPlot(world, id);
final boolean contains = PlotMain.getPlots(world).containsKey(plot.id);
if (contains) { 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);
} }
} }
} }
} }
} }
} }
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);
} }
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!"); PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
} }
else { else {
PlayerFunctions.sendMessage(plr, "No plots were found for the given search."); PlayerFunctions.sendMessage(plr, "No plots were found for the given search.");
} }
} }
else { else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
} }
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);
PlotHelper.setSign(player, plot); PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED); PlayerFunctions.sendMessage(player, C.CLAIMED);
if (teleport) { if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot); PlotMain.teleportPlayer(player, player.getLocation(), plot);
} }
plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS)); plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS));
} }
return event.isCancelled(); return event.isCancelled();
} }
} }

View File

@ -2,70 +2,46 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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
*/ */
public class DebugLoadTest extends SubCommand { public class DebugLoadTest extends SubCommand {
public DebugLoadTest() { public DebugLoadTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false); super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false);
} }
@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===");
} }
} }
else { else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
} }
return true; return true;
} }
} }

View File

@ -2,62 +2,41 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Claim.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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
*/ */
public class DebugSaveTest extends SubCommand { public class DebugSaveTest extends SubCommand {
public DebugSaveTest() { public DebugSaveTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false); super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false);
} }
@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);
} }
else { else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused."); PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
} }
return true; return true;
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Delete.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Delete.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -15,7 +15,6 @@ import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C; import com.intellectualcrafters.plot.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;
@ -25,46 +24,45 @@ import com.intellectualcrafters.plot.database.DBFunc;
*/ */
public class Delete extends SubCommand { public class Delete extends SubCommand {
public Delete() { public Delete() {
super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true); super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true);
} }
@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; }
} final PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld()); if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) { final double c = pWorld.SELL_PRICE;
double c = pWorld.SELL_PRICE; if (c > 0d) {
if (c > 0d) { final Economy economy = PlotMain.economy;
Economy economy = PlotMain.economy; economy.depositPlayer(plr, c);
economy.depositPlayer(plr, c); sendMessage(plr, C.ADDED_BALANCE, c + "");
sendMessage(plr, C.ADDED_BALANCE, c + ""); }
} }
} final boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
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;
} }
} }
else { else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied."); PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
} }
return true; return true;
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Denied.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Denied.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -26,35 +26,35 @@ import com.intellectualcrafters.plot.events.PlayerPlotDeniedEvent;
@SuppressWarnings("deprecated") @SuppressWarnings("deprecated")
public class Denied extends SubCommand { public class Denied extends SubCommand {
public Denied() { public Denied() {
super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true); super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true);
} }
@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;
} }
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.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;
} }
if (args[0].equalsIgnoreCase("add")) { if (args[0].equalsIgnoreCase("add")) {
UUID uuid; UUID uuid;
if (args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone; uuid = DBFunc.everyone;
} }
else { else {
uuid = UUIDHandler.getUUID(args[1]); uuid = UUIDHandler.getUUID(args[1]);
} }
if (!plot.denied.contains(uuid)) { if (!plot.denied.contains(uuid)) {
if (plot.owner == uuid) { if (plot.owner == uuid) {
PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER); PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER);
return false; return false;
@ -69,59 +69,58 @@ 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 {
PlayerFunctions.sendMessage(plr, C.ALREADY_ADDED); PlayerFunctions.sendMessage(plr, C.ALREADY_ADDED);
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());
} }
} }
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("*")) { final UUID uuid = DBFunc.everyone;
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; }
} 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])); PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED); return true;
return true; }
} /*
/* * if (!hasBeenOnServer(args[1])) {
* if (!hasBeenOnServer(args[1])) { * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); * return true; } UUID uuid = null; if
* return true; } UUID uuid = null; if * (Bukkit.getPlayer(args[1])!=null) { uuid =
* (Bukkit.getPlayer(args[1])!=null) { uuid = * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if * (!plot.denied.contains(uuid)) {
* (!plot.denied.contains(uuid)) { * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return * 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; } */
*/ final UUID uuid = UUIDHandler.getUUID(args[1]);
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])); final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false);
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); }
} else {
else { PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT); return true;
return true; }
} return true;
return true; }
}
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Help.java >> Generated by: Citymonstret at 2014-08-11 17:32 * >> File = Help.java >> Generated by: Citymonstret at 2014-08-11 17:32
*/ */
@ -14,12 +14,12 @@ import org.bukkit.entity.Player;
* Created by Citymonstret on 2014-08-11. * Created by Citymonstret on 2014-08-11.
*/ */
public class Help extends SubCommand { public class Help extends SubCommand {
public Help() { public Help() {
super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false); super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false);
} }
@Override @Override
public boolean execute(Player plr, String... args) { public boolean execute(final Player plr, final String... args) {
return false; return false;
} }
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Helpers.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Helpers.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -23,34 +23,34 @@ import com.intellectualcrafters.plot.events.PlayerPlotHelperEvent;
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public class Helpers extends SubCommand { public class Helpers extends SubCommand {
public Helpers() { public Helpers() {
super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true); super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true);
} }
@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;
} }
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.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;
} }
if (args[0].equalsIgnoreCase("add")) { if (args[0].equalsIgnoreCase("add")) {
UUID uuid; UUID uuid;
if (args[1].equalsIgnoreCase("*")) { if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone; uuid = DBFunc.everyone;
} }
else { else {
uuid = UUIDHandler.getUUID(args[1]); uuid = UUIDHandler.getUUID(args[1]);
} }
if (!plot.helpers.contains(uuid)) { if (!plot.helpers.contains(uuid)) {
if (plot.owner == uuid) { if (plot.owner == uuid) {
PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER); PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER);
return false; return false;
@ -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 {
@ -74,44 +74,43 @@ 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("*")) { final UUID uuid = DBFunc.everyone;
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; }
} 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])); PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED); return true;
return true; }
} /*
/* * if (!hasBeenOnServer(args[1])) {
* if (!hasBeenOnServer(args[1])) { * PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON); * return true; } UUID uuid = null; if
* return true; } UUID uuid = null; if * (Bukkit.getPlayer(args[1]) != null) { uuid =
* (Bukkit.getPlayer(args[1]) != null) { uuid = * Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid = * Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid == * null) { PlayerFunctions.sendMessage(plr,
* null) { PlayerFunctions.sendMessage(plr, * C.PLAYER_HAS_NOT_BEEN_ON); return true; } if
* C.PLAYER_HAS_NOT_BEEN_ON); return true; } if * (!plot.helpers.contains(uuid)) {
* (!plot.helpers.contains(uuid)) { * PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return * true; }
* true; } */
*/ final UUID uuid = UUIDHandler.getUUID(args[1]);
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])); final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false);
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); }
} else {
else { PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT); return true;
return true; }
} return true;
return true; }
}
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Home.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Home.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -20,60 +20,59 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class Home extends SubCommand { public class Home extends SubCommand {
public Home() { public Home() {
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;
} }
} }
return null; return null;
} }
@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" }; }
} int id = 0;
int id = 0; try {
try { id = Integer.parseInt(args[0]);
id = Integer.parseInt(args[0]); }
} catch (final Exception e) {
catch (Exception e) { Plot temp;
Plot temp; if ((temp = isAlias(args[0])) != null) {
if ((temp = isAlias(args[0])) != null) { if (temp.hasOwner()) {
if (temp.hasOwner()) { if (temp.getOwner().equals(plr.getUniqueId())) {
if (temp.getOwner().equals(plr.getUniqueId())) { PlotMain.teleportPlayer(plr, plr.getLocation(), temp);
PlotMain.teleportPlayer(plr, plr.getLocation(), temp); return true;
return true; }
} }
} PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT);
PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT); return false;
return false; }
} PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); return true;
return true; }
} if ((id > (plots.length)) || (id < 1)) {
if ((id > (plots.length)) || (id < 1)) { PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER); return false;
return false; }
} PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]);
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]); return true;
return true; }
} else {
else { PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
PlayerFunctions.sendMessage(plr, C.NO_PLOTS); return true;
return true; }
} }
}
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Clear.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -13,109 +13,112 @@ import java.util.Arrays;
import java.util.List; import java.util.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.
*/ */
public class Inbox extends SubCommand { public class Inbox extends SubCommand {
public Inbox() { public Inbox() {
super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true); super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true);
} }
@Override @Override
public boolean execute(final Player plr, final 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;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false; return false;
} }
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
Integer tier = null; if (!plot.hasOwner()) {
UUID uuid = plr.getUniqueId(); PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
if (PlotMain.hasPermission(plr, "plots.admin")) { return false;
tier = 0; }
}
else if (plot.owner == uuid) { Integer tier = null;
tier = 1; final UUID uuid = plr.getUniqueId();
} if (PlotMain.hasPermission(plr, "plots.admin")) {
else if (plot.helpers.contains(uuid)) { tier = 0;
}
else if (plot.owner == uuid) {
tier = 1;
}
else if (plot.helpers.contains(uuid)) {
tier = 2; tier = 2;
} }
else if (plot.trusted.contains(uuid)) { else if (plot.trusted.contains(uuid)) {
tier = 3; tier = 3;
} }
else { else {
tier = 4; tier = 4;
} }
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "admin":
if (tier<=0) {
tier = 0;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "owner":
if (tier<=1) {
tier = 1;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "helper":
if (tier<=2) {
tier = 2;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "trusted":
if (tier<=3) {
tier = 3;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "everyone":
if (tier<=4) {
tier = 4;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "default":
PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] {"admin", "owner", "helper", "trusted", "everyone" }, tier, 4));
return false;
}
}
final String world = plr.getWorld().getName();
final int tier2 = tier;
Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() { if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "admin":
if (tier <= 0) {
tier = 0;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "owner":
if (tier <= 1) {
tier = 1;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "helper":
if (tier <= 2) {
tier = 2;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "trusted":
if (tier <= 3) {
tier = 3;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "everyone":
if (tier <= 4) {
tier = 4;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
case "default":
PlayerFunctions.sendMessage(plr, C.INVALID_INBOX, Arrays.copyOfRange(new String[] { "admin", "owner", "helper", "trusted", "everyone" }, tier, 4));
return false;
}
}
final String world = plr.getWorld().getName();
final int tier2 = tier;
Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() {
@Override @Override
public void run() { public void run() {
ArrayList<PlotComment> comments = plot.settings.getComments(tier2); ArrayList<PlotComment> comments = plot.settings.getComments(tier2);
@ -123,49 +126,49 @@ public class Inbox extends SubCommand {
comments = DBFunc.getCommenst(world, plot, tier2); comments = DBFunc.getCommenst(world, plot, tier2);
plot.settings.setComments(comments); plot.settings.setComments(comments);
} }
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());
} }
} }
}); });
return true; return true;
} }
} }

View File

@ -2,169 +2,111 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Info.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Info.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
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
*/ */
public class Info extends SubCommand { public class Info extends SubCommand {
public Info() { public Info() {
super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false); super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false);
} }
@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);
return false; return false;
} }
plot = PlayerFunctions.getCurrentPlot(player); plot = PlayerFunctions.getCurrentPlot(player);
}
else {
if (args.length<2) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld==null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD);
return false;
}
try {
String[] split = args[1].split(";");
PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id);
if (plot==null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID);
return false;
}
world = Bukkit.getWorld(args[0]);
if (args.length==3) {
args = new String[] {args[2]};
}
else {
args = new String[0];
}
}
catch (Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
}
boolean hasOwner = plot.hasOwner();
boolean containsEveryone;
boolean trustedEveryone;
// Wildcard player {added}
{
if (plot.helpers == null) {
containsEveryone = false;
}
else {
containsEveryone = plot.helpers.contains(DBFunc.everyone);
}
if (plot.trusted == null) {
trustedEveryone = false;
}
else {
trustedEveryone = plot.trusted.contains(DBFunc.everyone);
}
}
// Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) {
PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y));
return true;
}
String owner = "none";
if (plot.owner != null) {
owner = Bukkit.getOfflinePlayer(plot.owner).getName();
}
if (owner == null) {
owner = plot.owner.toString();
}
String info = C.PLOT_INFO.s();
if (args.length==1) {
info = getCaption(args[0].toLowerCase());
if (info==null) {
PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating");
return false;
}
}
info = format(info, world, plot, player);
PlayerFunctions.sendMessage(player, info);
return true;
}
private String getCaption(String string) {
switch (string) {
case "helpers":
return C.PLOT_INFO_HELPERS.s();
case "alias":
return C.PLOT_INFO_ALIAS.s();
case "biome":
return C.PLOT_INFO_BIOME.s();
case "denied":
return C.PLOT_INFO_DENIED.s();
case "flags":
return C.PLOT_INFO_FLAGS.s();
case "id":
return C.PLOT_INFO_ID.s();
case "size":
return C.PLOT_INFO_SIZE.s();
case "trusted":
return C.PLOT_INFO_TRUSTED.s();
case "owner":
return C.PLOT_INFO_OWNER.s();
case "rating":
return C.PLOT_INFO_RATING.s();
default:
return null;
} }
} else {
if (args.length < 2) {
private String format(String info, World world, Plot plot, Player player) { PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
PlotId id = plot.id; }
PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id; final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size(); if (plotworld == null) {
String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none"; PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD);
String biome = getBiomeAt(plot).toString(); return false;
String helpers = getPlayerList(plot.helpers); }
String trusted = getPlayerList(plot.trusted); try {
String denied = getPlayerList(plot.denied); final String[] split = args[1].split(";");
String rating = String.format("%.1f", DBFunc.getRatings(plot)); final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
String flags = "&3"+ (StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), "&7, &3") : "none"); plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id);
boolean build = player==null ? true : plot.hasRights(player); if (plot == null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID);
return false;
}
world = Bukkit.getWorld(args[0]);
if (args.length == 3) {
args = new String[] { args[2] };
}
else {
args = new String[0];
}
}
catch (final Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
}
final boolean hasOwner = plot.hasOwner();
boolean containsEveryone;
boolean trustedEveryone;
// Wildcard player {added}
{
if (plot.helpers == null) {
containsEveryone = false;
}
else {
containsEveryone = plot.helpers.contains(DBFunc.everyone);
}
if (plot.trusted == null) {
trustedEveryone = false;
}
else {
trustedEveryone = plot.trusted.contains(DBFunc.everyone);
}
}
// Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) {
PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y));
return true;
}
String owner = "none"; String owner = "none";
if (plot.owner != null) { if (plot.owner != null) {
owner = Bukkit.getOfflinePlayer(plot.owner).getName(); owner = Bukkit.getOfflinePlayer(plot.owner).getName();
@ -172,11 +114,75 @@ public class Info extends SubCommand {
if (owner == null) { if (owner == null) {
owner = plot.owner.toString(); owner = plot.owner.toString();
} }
String info = C.PLOT_INFO.s();
if (args.length == 1) {
info = getCaption(args[0].toLowerCase());
if (info == null) {
PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating");
return false;
}
}
info = format(info, world, plot, player);
PlayerFunctions.sendMessage(player, info);
return true;
}
private String getCaption(final String string) {
switch (string) {
case "helpers":
return C.PLOT_INFO_HELPERS.s();
case "alias":
return C.PLOT_INFO_ALIAS.s();
case "biome":
return C.PLOT_INFO_BIOME.s();
case "denied":
return C.PLOT_INFO_DENIED.s();
case "flags":
return C.PLOT_INFO_FLAGS.s();
case "id":
return C.PLOT_INFO_ID.s();
case "size":
return C.PLOT_INFO_SIZE.s();
case "trusted":
return C.PLOT_INFO_TRUSTED.s();
case "owner":
return C.PLOT_INFO_OWNER.s();
case "rating":
return C.PLOT_INFO_RATING.s();
default:
return null;
}
}
private String format(String info, final World world, final Plot plot, final Player player) {
final PlotId id = plot.id;
final PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id;
final int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size();
final String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none";
final String biome = getBiomeAt(plot).toString();
final String helpers = getPlayerList(plot.helpers);
final String trusted = getPlayerList(plot.trusted);
final String denied = getPlayerList(plot.denied);
final String rating = String.format("%.1f", DBFunc.getRatings(plot));
final String flags = "&3" + (StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), "&7, &3") : "none");
final boolean build = player == null ? true : plot.hasRights(player);
String owner = "none";
if (plot.owner != null) {
owner = Bukkit.getOfflinePlayer(plot.owner).getName();
}
if (owner == null) {
owner = plot.owner.toString();
}
info = info.replaceAll("%alias%", alias); info = info.replaceAll("%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,47 +190,46 @@ 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(",", ""));
} }
else { else {
list.append(c.replace("%user%", getPlayerName(l.get(x)))); list.append(c.replace("%user%", getPlayerName(l.get(x))));
} }
} }
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";
} }
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) { if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
return "everyone"; return "everyone";
} }
/* /*
* OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName() * OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName()
* == null) { return "unknown"; } return plr.getName(); * == null) { return "unknown"; } return plr.getName();
*/ */
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Inventory.java >> Generated by: Citymonstret at 2014-08-10 13:57 * >> File = Inventory.java >> Generated by: Citymonstret at 2014-08-10 13:57
*/ */
@ -19,42 +19,41 @@ import org.bukkit.inventory.meta.ItemMeta;
public class Inventory extends SubCommand { public class Inventory extends SubCommand {
public Inventory() { public Inventory() {
super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true); super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true);
} }
@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);
return true; return true;
} }
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()); add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description); add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage); }
} });
}); }
} stack.setItemMeta(meta);
stack.setItemMeta(meta); return stack;
return stack; }
}
} }

View File

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Kick.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Kick.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -21,38 +21,35 @@ import com.intellectualcrafters.plot.PlotMain;
*/ */
public class Kick extends SubCommand { public class Kick extends SubCommand {
public Kick() { public Kick() {
super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true); super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true);
} }
@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; }
} if (args.length != 1) {
if (args.length != 1) { PlayerFunctions.sendMessage(plr, "&c/plot kick <player>");
PlayerFunctions.sendMessage(plr, "&c/plot kick <player>"); return false;
return false; }
} if (Bukkit.getPlayer(args[0]) == null) {
if (Bukkit.getPlayer(args[0]) == null) { 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; }
} final Player player = Bukkit.getPlayer(args[0]);
Player player = Bukkit.getPlayer(args[0]); if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) {
if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
|| (PlayerFunctions.getCurrentPlot(player) == null) return false;
|| !PlayerFunctions.getCurrentPlot(player).equals(plot)) { }
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0])); player.teleport(player.getWorld().getSpawnLocation());
return false; return true;
} }
player.teleport(player.getWorld().getSpawnLocation());
return true;
}
} }

View File

@ -2,16 +2,15 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = MainCommand.java >> Generated by: Citymonstret at 2014-08-09 01:42 * >> File = MainCommand.java >> Generated by: Citymonstret at 2014-08-09 01:42
*/ */
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,173 +32,170 @@ 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>() {
{ {
addAll(Arrays.asList(_subCommands)); addAll(Arrays.asList(_subCommands));
} }
}; };
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) { final StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder(); builder.append(C.HELP_INFO.s());
builder.append(C.HELP_INFO.s()); for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
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; }
} final String cat = args[1];
String cat = args[1]; SubCommand.CommandCategory cato = null;
SubCommand.CommandCategory cato = null; for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (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) { final StringBuilder builder = new StringBuilder();
StringBuilder builder = new StringBuilder(); builder.append(C.HELP_INFO.s());
builder.append(C.HELP_INFO.s()); for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) { builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
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; }
} final StringBuilder help = new StringBuilder();
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 {
PlayerFunctions.sendMessage(null, C.IS_CONSOLE); PlayerFunctions.sendMessage(null, C.IS_CONSOLE);
return false; return false;
} }
} }
else { else {
return no_permission(player, command.permission.permission.toLowerCase()); return no_permission(player, command.permission.permission.toLowerCase());
} }
} }
} }
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,29 +205,31 @@ 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)));
} }
} }
if (help.size() < 2) { if (help.size() < 2) {
help.add(t(C.NO_COMMANDS.s())); help.add(t(C.NO_COMMANDS.s()));
} }
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;
}
if(strings.length < 1) { final Player player = (Player) commandSender;
if (strings.length==0 || "plots".startsWith(s)) {
return Arrays.asList(new String[] {"plots"}); if (strings.length < 1) {
if ((strings.length == 0) || "plots".startsWith(s)) {
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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Merge.java >> Generated by: Citymonstret at 2014-08-09 01:41 * >> File = Merge.java >> Generated by: Citymonstret at 2014-08-09 01:41
*/ */
@ -32,129 +32,123 @@ import com.intellectualcrafters.plot.events.PlotMergeEvent;
*/ */
public class Merge extends SubCommand { public class Merge extends SubCommand {
public static String[] values = new String[] { "north", "east", "south", "west" }; public static String[] values = new String[] { "north", "east", "south", "west" };
public static String[] aliases = new String[] { "n", "e", "s", "w" }; public static String[] aliases = new String[] { "n", "e", "s", "w" };
public Merge() { public Merge() {
super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true); super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true);
} }
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:
case 4: case 4:
return "SOUTH"; return "SOUTH";
case -1: case -1:
case 3: case 3:
return "EAST"; return "EAST";
case -2: case -2:
case 2: case 2:
return "NORTH"; return "NORTH";
case -3: case -3:
case 1: case 1:
return "WEST"; return "WEST";
default: default:
return ""; return "";
} }
} }
@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;
} }
if (!plot.getOwner().equals(plr.getUniqueId())) { if (!plot.getOwner().equals(plr.getUniqueId())) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS); PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
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; }
} int direction = -1;
int direction = -1; for (int i = 0; i < values.length; i++) {
for (int i = 0; i < values.length; i++) { if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) {
if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) { direction = i;
direction = i; break;
break; }
} }
} if (direction == -1) {
if (direction == -1) { PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s())); return false;
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw()))); }
return false; final World world = plr.getWorld();
} final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
World world = plr.getWorld(); final PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id; ArrayList<PlotId> plots;
PlotId top = PlayerFunctions.getTopPlot(world, plot).id; switch (direction) {
ArrayList<PlotId> plots; case 0: // north = -y
switch (direction) { plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
case 0: // north = -y break;
plots = case 1: // east = +x
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y)); plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
break; break;
case 1: // east = +x 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 + 1, top.y)); break;
break; case 3: // west = -x
case 2: // south = +y plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
plots = break;
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1)); default:
break; return false;
case 3: // west = -x }
plots = for (final PlotId myid : plots) {
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y)); final Plot myplot = PlotMain.getPlots(world).get(myid);
break; if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) {
default: PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false; return false;
} }
for (PlotId myid : plots) { }
Plot myplot = PlotMain.getPlots(world).get(myid);
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) {
PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false;
}
}
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;
} }
economy.withdrawPlayer(plr, cost); economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + ""); sendMessage(plr, C.REMOVED_BALANCE, cost + "");
} }
} }
PlotMergeEvent event = new PlotMergeEvent(world, plot, plots); final PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
Bukkit.getServer().getPluginManager().callEvent(event); Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) { if (event.isCancelled()) {
event.setCancelled(true); event.setCancelled(true);
PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled"); PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled");
return false; return false;
} }
PlayerFunctions.sendMessage(plr, "&cPlots have been merged"); PlayerFunctions.sendMessage(plr, "&cPlots have been merged");
PlotHelper.mergePlots(world, plots); PlotHelper.mergePlots(world, plots);
if (PlotHelper.canSetFast) { if (PlotHelper.canSetFast) {
SetBlockFast.update(plr); SetBlockFast.update(plr);
} }
return true; return true;
} }
} }

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);
@ -38,4 +41,4 @@ public class MusicSubcommand extends SubCommand {
player.openInventory(inventory); player.openInventory(inventory);
return true; return true;
} }
} }

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

@ -2,7 +2,7 @@
* Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute * Copyright (c) IntellectualCrafters - 2014. You are not allowed to distribute
* and/or monetize any of our intellectual property. IntellectualCrafters is not * and/or monetize any of our intellectual property. IntellectualCrafters is not
* affiliated with Mojang AB. Minecraft is a trademark of Mojang AB. * affiliated with Mojang AB. Minecraft is a trademark of Mojang AB.
* *
* >> File = Purge.java >> Generated by: Citymonstret at 2014-08-09 01:42 * >> File = Purge.java >> Generated by: Citymonstret at 2014-08-09 01:42
*/ */
@ -22,61 +22,61 @@ import com.intellectualcrafters.plot.database.DBFunc;
*/ */
public class Purge extends SubCommand { public class Purge extends SubCommand {
public Purge() { public Purge() {
super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false); super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false);
} }
@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;
} }
if (!PlotMain.isPlotWorld(world)) { if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD); PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false; return false;
} }
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);
} }
} }
PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX); PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX);
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;
} }
PlotMain.removePlotWorld(args[0]); PlotMain.removePlotWorld(args[0]);
DBFunc.purge(args[0]); DBFunc.purge(args[0]);
PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS)); PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS));
return true; return true;
} }
else { else {
PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o"); PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o");
return false; return false;
} }
} }
} }

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