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

View File

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

View File

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

View File

@ -1,10 +1,10 @@
package com.intellectualcrafters.jnbt;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.HashMap;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
/**
* Helps create compound tags.
*/
@ -22,9 +22,10 @@ public class CompoundTagBuilder {
/**
* Create a new instance and use the given map (which will be modified).
*
* @param value the value
* @param value
* the value
*/
CompoundTagBuilder(Map<String, Tag> value) {
CompoundTagBuilder(final Map<String, Tag> value) {
checkNotNull(value);
this.entries = value;
}
@ -32,14 +33,16 @@ public class CompoundTagBuilder {
/**
* Put the given key and tag into the compound tag.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder put(String key, Tag value) {
public CompoundTagBuilder put(final String key, final Tag value) {
checkNotNull(key);
checkNotNull(value);
entries.put(key, value);
this.entries.put(key, value);
return this;
}
@ -47,47 +50,52 @@ public class CompoundTagBuilder {
* Put the given key and value into the compound tag as a
* {@code ByteArrayTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putByteArray(String key, byte[] value) {
public CompoundTagBuilder putByteArray(final String key, final byte[] value) {
return put(key, new ByteArrayTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ByteTag}.
* Put the given key and value into the compound tag as a {@code ByteTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putByte(String key, byte value) {
public CompoundTagBuilder putByte(final String key, final byte value) {
return put(key, new ByteTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code DoubleTag}.
* Put the given key and value into the compound tag as a {@code DoubleTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putDouble(String key, double value) {
public CompoundTagBuilder putDouble(final String key, final double value) {
return put(key, new DoubleTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code FloatTag}.
* Put the given key and value into the compound tag as a {@code FloatTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putFloat(String key, float value) {
public CompoundTagBuilder putFloat(final String key, final float value) {
return put(key, new FloatTag(key, value));
}
@ -95,70 +103,78 @@ public class CompoundTagBuilder {
* Put the given key and value into the compound tag as a
* {@code IntArrayTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putIntArray(String key, int[] value) {
public CompoundTagBuilder putIntArray(final String key, final int[] value) {
return put(key, new IntArrayTag(key, value));
}
/**
* Put the given key and value into the compound tag as an {@code IntTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putInt(String key, int value) {
public CompoundTagBuilder putInt(final String key, final int value) {
return put(key, new IntTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code LongTag}.
* Put the given key and value into the compound tag as a {@code LongTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putLong(String key, long value) {
public CompoundTagBuilder putLong(final String key, final long value) {
return put(key, new LongTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code ShortTag}.
* Put the given key and value into the compound tag as a {@code ShortTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putShort(String key, short value) {
public CompoundTagBuilder putShort(final String key, final short value) {
return put(key, new ShortTag(key, value));
}
/**
* Put the given key and value into the compound tag as a
* {@code StringTag}.
* Put the given key and value into the compound tag as a {@code StringTag}.
*
* @param key they key
* @param value the value
* @param key
* they key
* @param value
* the value
* @return this object
*/
public CompoundTagBuilder putString(String key, String value) {
public CompoundTagBuilder putString(final String key, final String value) {
return put(key, new StringTag(key, value));
}
/**
* Put all the entries from the given map into this map.
*
* @param value the map of tags
* @param value
* the map of tags
* @return this object
*/
public CompoundTagBuilder putAll(Map<String, ? extends Tag> value) {
public CompoundTagBuilder putAll(final Map<String, ? extends Tag> 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());
}
return this;
@ -170,17 +186,18 @@ public class CompoundTagBuilder {
* @return the new compound tag
*/
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.
*
* @param name the name of the tag
* @param name
* the name of the tag
* @return the created compound tag
*/
public CompoundTag build(String name) {
return new CompoundTag(name, new HashMap<String, Tag>(entries));
public CompoundTag build(final String name) {
return new CompoundTag(name, new HashMap<String, Tag>(this.entries));
}
/**

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -9,10 +9,7 @@ public final class NBTConstants {
public static final Charset CHARSET = Charset.forName("UTF-8");
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2,
TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6,
TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9,
TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
public static final int TYPE_END = 0, TYPE_BYTE = 1, TYPE_SHORT = 2, TYPE_INT = 3, TYPE_LONG = 4, TYPE_FLOAT = 5, TYPE_DOUBLE = 6, TYPE_BYTE_ARRAY = 7, TYPE_STRING = 8, TYPE_LIST = 9, TYPE_COMPOUND = 10, TYPE_INT_ARRAY = 11;
/**
* Default private constructor.
@ -24,38 +21,40 @@ public final class NBTConstants {
/**
* Convert a type ID to its corresponding {@link Tag} class.
*
* @param id type ID
* @param id
* type ID
* @return tag class
* @throws IllegalArgumentException thrown if the tag ID is not valid
* @throws IllegalArgumentException
* thrown if the tag ID is not valid
*/
public static Class<? extends Tag> getClassFromType(int id) {
public static Class<? extends Tag> getClassFromType(final int id) {
switch (id) {
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
return ByteTag.class;
case TYPE_SHORT:
return ShortTag.class;
case TYPE_INT:
return IntTag.class;
case TYPE_LONG:
return LongTag.class;
case TYPE_FLOAT:
return FloatTag.class;
case TYPE_DOUBLE:
return DoubleTag.class;
case TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case TYPE_STRING:
return StringTag.class;
case TYPE_LIST:
return ListTag.class;
case TYPE_COMPOUND:
return CompoundTag.class;
case TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Unknown tag type ID of " + id);
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
return ByteTag.class;
case TYPE_SHORT:
return ShortTag.class;
case TYPE_INT:
return IntTag.class;
case TYPE_LONG:
return LongTag.class;
case TYPE_FLOAT:
return FloatTag.class;
case TYPE_DOUBLE:
return DoubleTag.class;
case TYPE_BYTE_ARRAY:
return ByteArrayTag.class;
case TYPE_STRING:
return StringTag.class;
case TYPE_LIST:
return ListTag.class;
case TYPE_COMPOUND:
return CompoundTag.class;
case TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Unknown tag type ID of " + id);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,29 @@
package com.intellectualcrafters.jnbt;
import org.bukkit.World;
import com.sk89q.jnbt.CompoundTag;
import com.sk89q.worldedit.LocalWorld;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldedit.WorldEditException;
import com.sk89q.worldedit.blocks.BaseBlock;
import com.sk89q.worldedit.bukkit.BukkitUtil;
public class WorldEditUtils {
public static void setNBT(final World world, final short id, final byte data, final int x, final int y, final int z, final com.intellectualcrafters.jnbt.CompoundTag tag) {
// final LocalWorld bukkitWorld = BukkitUtil.getLocalWorld(world);
// I need to somehow convert our CompoundTag to WorldEdit's
// final BaseBlock block = new BaseBlock(5, 5, (CompoundTag) tag);
// final Vector vector = new Vector(x, y, z);
// try {
// bukkitWorld.setBlock(vector, block);
// }
// catch (final WorldEditException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

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

View File

@ -1,4 +1,5 @@
package com.intellectualcrafters.json;
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
@ -7,7 +8,7 @@ package com.intellectualcrafters.json;
*/
public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0;
private Throwable cause;
private Throwable cause;
/**
* Constructs a JSONException with an explanatory message.
@ -15,15 +16,17 @@ public class JSONException extends RuntimeException {
* @param message
* Detail about the reason for the exception.
*/
public JSONException(String message) {
public JSONException(final String message) {
super(message);
}
/**
* Constructs a new JSONException with the specified cause.
* @param cause The cause.
*
* @param cause
* The cause.
*/
public JSONException(Throwable cause) {
public JSONException(final Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
@ -33,7 +36,7 @@ public class JSONException extends RuntimeException {
* or unknown.
*
* @return the cause of this exception or null if the cause is nonexistent
* or unknown.
* or unknown.
*/
@Override
public Throwable getCause() {

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -32,11 +32,11 @@ package com.intellectualcrafters.json;
* than 3 bytes. Every byte contributes 7 bits to the character. ASCII is
* unmodified.
*
* Kim UTF-8
* one byte U+007F U+007F
* two bytes U+3FFF U+07FF
* three bytes U+10FFF U+FFFF
* four bytes U+10FFFF
* Kim UTF-8
* one byte U+007F U+007F
* two bytes U+3FFF U+07FF
* three bytes U+10FFF U+FFFF
* four bytes U+10FFFF
*
* Characters in the ranges U+0800..U+3FFF and U+10000..U+10FFFF will be one
* byte smaller when encoded in Kim compared to UTF-8.
@ -65,23 +65,23 @@ public class Kim {
/**
* The byte array containing the kim's content.
*/
private byte[] bytes = null;
private byte[] bytes = null;
/**
* The kim's hashcode, conforming to Java's hashcode conventions.
*/
private int hashcode = 0;
private int hashcode = 0;
/**
* The number of bytes in the kim. The number of bytes can be as much as
* three times the number of characters.
*/
public int length = 0;
public int length = 0;
/**
* The memoization of toString().
*/
private String string = null;
private String string = null;
/**
* Make a kim from a portion of a byte array.
@ -93,10 +93,11 @@ public class Kim {
* @param thru
* The index of the last byte plus one.
*/
public Kim(byte[] bytes, int from, int thru) {
public Kim(final byte[] bytes, final int from, final int thru) {
// As the bytes are copied into the new kim, a hashcode is computed using a
// modified Fletcher code.
// As the bytes are copied into the new kim, a hashcode is computed
// using a
// modified Fletcher code.
int sum = 1;
int value;
@ -105,7 +106,7 @@ public class Kim {
if (this.length > 0) {
this.bytes = new byte[this.length];
for (int at = 0; at < this.length; at += 1) {
value = (int) bytes[at + from] & 0xFF;
value = bytes[at + from] & 0xFF;
sum += value;
this.hashcode += sum;
this.bytes[at] = (byte) value;
@ -122,7 +123,7 @@ public class Kim {
* @param length
* The number of bytes.
*/
public Kim(byte[] bytes, int length) {
public Kim(final byte[] bytes, final int length) {
this(bytes, 0, length);
}
@ -137,7 +138,7 @@ public class Kim {
* @param thru
* The point at which to stop taking bytes.
*/
public Kim(Kim kim, int from, int thru) {
public Kim(final Kim kim, final int from, final int thru) {
this(kim.bytes, from, thru);
}
@ -149,26 +150,28 @@ public class Kim {
* @throws JSONException
* if surrogate pair mismatch.
*/
public Kim(String string) throws JSONException {
int stringLength = string.length();
public Kim(final String string) throws JSONException {
final int stringLength = string.length();
this.hashcode = 0;
this.length = 0;
// First pass: Determine the length of the kim, allowing for the UTF-16
// to UTF-32 conversion, and then the UTF-32 to Kim conversion.
// First pass: Determine the length of the kim, allowing for the UTF-16
// to UTF-32 conversion, and then the UTF-32 to Kim conversion.
if (stringLength > 0) {
for (int i = 0; i < stringLength; i += 1) {
int c = string.charAt(i);
final int c = string.charAt(i);
if (c <= 0x7F) {
this.length += 1;
} else if (c <= 0x3FFF) {
}
else if (c <= 0x3FFF) {
this.length += 2;
} else {
if (c >= 0xD800 && c <= 0xDFFF) {
}
else {
if ((c >= 0xD800) && (c <= 0xDFFF)) {
i += 1;
int d = string.charAt(i);
if (c > 0xDBFF || d < 0xDC00 || d > 0xDFFF) {
final int d = string.charAt(i);
if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) {
throw new JSONException("Bad UTF16");
}
}
@ -176,49 +179,51 @@ public class Kim {
}
}
// Second pass: Allocate a byte array and fill that array with the conversion
// while computing the hashcode.
// Second pass: Allocate a byte array and fill that array with the
// conversion
// while computing the hashcode.
this.bytes = new byte[length];
this.bytes = new byte[this.length];
int at = 0;
int b;
int sum = 1;
for (int i = 0; i < stringLength; i += 1) {
int character = string.charAt(i);
if (character <= 0x7F) {
bytes[at] = (byte) character;
this.bytes[at] = (byte) character;
sum += character;
this.hashcode += sum;
at += 1;
} else if (character <= 0x3FFF) {
}
else if (character <= 0x3FFF) {
b = 0x80 | (character >>> 7);
bytes[at] = (byte) b;
this.bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
at += 1;
b = character & 0x7F;
bytes[at] = (byte) b;
this.bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
at += 1;
} else {
if (character >= 0xD800 && character <= 0xDBFF) {
}
else {
if ((character >= 0xD800) && (character <= 0xDBFF)) {
i += 1;
character = (((character & 0x3FF) << 10) | (string
.charAt(i) & 0x3FF)) + 65536;
character = (((character & 0x3FF) << 10) | (string.charAt(i) & 0x3FF)) + 65536;
}
b = 0x80 | (character >>> 14);
bytes[at] = (byte) b;
this.bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
at += 1;
b = 0x80 | ((character >>> 7) & 0xFF);
bytes[at] = (byte) b;
this.bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
at += 1;
b = character & 0x7F;
bytes[at] = (byte) b;
this.bytes[at] = (byte) b;
sum += b;
this.hashcode += sum;
at += 1;
@ -239,23 +244,23 @@ public class Kim {
* @throws JSONException
* if at does not point to a valid character.
*/
public int characterAt(int at) throws JSONException {
int c = get(at);
public int characterAt(final int at) throws JSONException {
final int c = get(at);
if ((c & 0x80) == 0) {
return c;
}
int character;
int c1 = get(at + 1);
final int c1 = get(at + 1);
if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
if (character > 0x7F) {
return character;
}
} else {
int c2 = get(at + 2);
}
else {
final int c2 = get(at + 2);
character = ((c & 0x7F) << 14) | ((c1 & 0x7F) << 7) | c2;
if ((c2 & 0x80) == 0 && character > 0x3FFF && character <= 0x10FFFF
&& (character < 0xD800 || character > 0xDFFF)) {
if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) {
return character;
}
}
@ -272,8 +277,8 @@ public class Kim {
* @throws JSONException
* if the character is not representable in a kim.
*/
public static int characterSize(int character) throws JSONException {
if (character < 0 || character > 0x10FFFF) {
public static int characterSize(final int character) throws JSONException {
if ((character < 0) || (character > 0x10FFFF)) {
throw new JSONException("Bad character " + character);
}
return character <= 0x7F ? 1 : character <= 0x3FFF ? 2 : 3;
@ -288,7 +293,7 @@ public class Kim {
* The position within the byte array to take the byes.
* @return The position immediately after the copy.
*/
public int copy(byte[] bytes, int at) {
public int copy(final byte[] bytes, final int at) {
System.arraycopy(this.bytes, 0, bytes, at, this.length);
return at + this.length;
}
@ -302,11 +307,12 @@ public class Kim {
* @returns true if this and obj are both kim objects containing identical
* byte sequences.
*/
public boolean equals(Object obj) {
@Override
public boolean equals(final Object obj) {
if (!(obj instanceof Kim)) {
return false;
}
Kim that = (Kim) obj;
final Kim that = (Kim) obj;
if (this == that) {
return true;
}
@ -318,22 +324,24 @@ public class Kim {
/**
* Get a byte from a kim.
*
* @param at
* The position of the byte. The first byte is at 0.
* @return The byte.
* @throws JSONException
* if there is no byte at that position.
*/
public int get(int at) throws JSONException {
if (at < 0 || at > this.length) {
public int get(final int at) throws JSONException {
if ((at < 0) || (at > this.length)) {
throw new JSONException("Bad character at " + at);
}
return ((int) this.bytes[at]) & 0xFF;
return (this.bytes[at]) & 0xFF;
}
/**
* Returns a hash code value for the kim.
*/
@Override
public int hashCode() {
return this.hashcode;
}
@ -347,17 +355,19 @@ public class Kim {
* @throws JSONException
* if the kim is not valid.
*/
@Override
public String toString() throws JSONException {
if (this.string == null) {
int c;
int length = 0;
char chars[] = new char[this.length];
final char chars[] = new char[this.length];
for (int at = 0; at < this.length; at += characterSize(c)) {
c = this.characterAt(at);
if (c < 0x10000) {
chars[length] = (char) c;
length += 1;
} else {
}
else {
chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10));
length += 1;
chars[length] = (char) (0xDC00 | (c & 0x03FF));

View File

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

View File

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

View File

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

View File

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

View File

@ -40,7 +40,7 @@ public enum C {
NOT_CONSOLE("&cFor safety reasons, this command can only be executed by console."),
IS_CONSOLE("&cThis command can only be executed by a player."),
/*
Clipboard
* Clipboard
*/
CLIPBOARD_SET("&cThe current plot is now copied to your clipboard, use &6/plot paste&c to paste it"),
PASTED("&cThe plot selection was successfully pasted. It has been cleared from your clipboard."),
@ -150,8 +150,8 @@ public enum C {
*/
INVALID_PLAYER("&cPlayer not found: &6%player%."),
/*
*
*/
*
*/
COMMAND_WENT_WRONG("&cSomething went wrong when executing that command..."),
/*
* purge
@ -327,10 +327,7 @@ public enum C {
HELP_CATEGORY("&6Current Category&c: &l%category%"),
HELP_INFO("&6You need to specify a help category"),
HELP_INFO_ITEM("&6/plots help %category% &c- &6%category_desc%"),
HELP_PAGE(
"&c>> &6%usage% &c[&6%alias%&c]\n" +
"&c>> &6%desc%\n"
),
HELP_PAGE("&c>> &6%usage% &c[&6%alias%&c]\n" + "&c>> &6%desc%\n"),
HELP_ITEM_SEPARATOR("&c%lines"),
HELP_HEADER("&c(Page &6%cur&c/&6%max&c) &6Help for Plots"),
/*
@ -344,77 +341,78 @@ public enum C {
/**
* Default
*/
private String d;
/**
* Translated
*/
private String s;
private String d;
/**
* Translated
*/
private String s;
/**
* Constructor for custom strings.
*/
@SuppressWarnings("unused")
C() {
/*
* use setCustomString();
*/
}
/**
* Constructor for custom strings.
*/
@SuppressWarnings("unused")
C() {
/*
* use setCustomString();
*/
}
/**
* Constructor
*
* @param d
* default
*/
C(String d) {
this.d = d;
if (PlotMain.translations == null) {
this.s = d;
}
else {
this.s = PlotMain.translations.getString(this.toString());
}
if (this.s == null) {
this.s = "";
}
}
/**
* Constructor
*
* @param d
* default
*/
C(final String d) {
this.d = d;
if (PlotMain.translations == null) {
this.s = d;
}
else {
this.s = PlotMain.translations.getString(this.toString());
}
if (this.s == null) {
this.s = "";
}
}
public static class Potato {
}
/**
* Get the default string
*
* @return default
*/
@SuppressWarnings("unused")
public String d() {
return this.d;
}
/**
* Get translated if exists
*
* @return translated if exists else default
*/
public String s() {
if(PlotMain.translations != null){
String t = PlotMain.translations.getString(this.toString());
if (t!=null) {
/**
* Get the default string
*
* @return default
*/
@SuppressWarnings("unused")
public String d() {
return this.d;
}
/**
* Get translated if exists
*
* @return translated if exists else default
*/
public String s() {
if (PlotMain.translations != null) {
final String t = PlotMain.translations.getString(this.toString());
if (t != null) {
this.s = t;
}
}
if (this.s.length() < 1) {
return "";
}
return this.s.replace("\\n", "\n");
}
if (this.s.length() < 1) {
return "";
}
return this.s.replace("\\n", "\n");
}
/**
* @return translated and color decoded
*/
public String translated() {
return ChatColor.translateAlternateColorCodes('&', this.s());
}
/**
* @return translated and color decoded
*/
public String translated() {
return ChatColor.translateAlternateColorCodes('&', this.s());
}
}

View File

@ -3,265 +3,266 @@ package com.intellectualcrafters.plot;
import java.util.ArrayList;
import java.util.List;
import org.bukkit.Bukkit;
import org.bukkit.block.Biome;
public class Configuration {
public static final SettingValue STRING = new SettingValue("STRING") {
@Override
public boolean validateValue(String string) {
return true;
}
public static final SettingValue STRING = new SettingValue("STRING") {
@Override
public boolean validateValue(final String string) {
return true;
}
@Override
public Object parseString(String string) {
return string;
}
};
@Override
public Object parseString(final String string) {
return string;
}
};
public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") {
@Override
public boolean validateValue(String string) {
return true;
}
public static final SettingValue STRINGLIST = new SettingValue("STRINGLIST") {
@Override
public boolean validateValue(final String string) {
return true;
}
@Override
public Object parseString(String string) {
return string.split(",");
}
};
@Override
public Object parseString(final String string) {
return string.split(",");
}
};
public static final SettingValue INTEGER = new SettingValue("INTEGER") {
@Override
public boolean validateValue(String string) {
try {
Integer.parseInt(string);
return true;
}
catch (Exception e) {
return false;
}
}
public static final SettingValue INTEGER = new SettingValue("INTEGER") {
@Override
public boolean validateValue(final String string) {
try {
Integer.parseInt(string);
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(String string) {
return Integer.parseInt(string);
}
};
@Override
public Object parseString(final String string) {
return Integer.parseInt(string);
}
};
public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") {
@Override
public boolean validateValue(String string) {
try {
Boolean.parseBoolean(string);
return true;
}
catch (Exception e) {
return false;
}
}
public static final SettingValue BOOLEAN = new SettingValue("BOOLEAN") {
@Override
public boolean validateValue(final String string) {
try {
Boolean.parseBoolean(string);
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(String string) {
return Boolean.parseBoolean(string);
}
};
@Override
public Object parseString(final String string) {
return Boolean.parseBoolean(string);
}
};
public static final SettingValue DOUBLE = new SettingValue("DOUBLE") {
@Override
public boolean validateValue(String string) {
try {
Double.parseDouble(string);
return true;
}
catch (Exception e) {
return false;
}
}
public static final SettingValue DOUBLE = new SettingValue("DOUBLE") {
@Override
public boolean validateValue(final String string) {
try {
Double.parseDouble(string);
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(String string) {
return Double.parseDouble(string);
}
};
@Override
public Object parseString(final String string) {
return Double.parseDouble(string);
}
};
public static final SettingValue BIOME = new SettingValue("BIOME") {
@Override
public boolean validateValue(String string) {
try {
Biome.valueOf(string.toUpperCase());
return true;
}
catch (Exception e) {
return false;
}
}
public static final SettingValue BIOME = new SettingValue("BIOME") {
@Override
public boolean validateValue(final String string) {
try {
Biome.valueOf(string.toUpperCase());
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(String string) {
for (Biome biome : Biome.values()) {
if (biome.name().equals(string.toUpperCase())) {
return biome;
}
}
return Biome.FOREST;
}
@Override
public Object parseString(final String string) {
for (final Biome biome : Biome.values()) {
if (biome.name().equals(string.toUpperCase())) {
return biome;
}
}
return Biome.FOREST;
}
@Override
public Object parseObject(Object object) {
return ((Biome) object).toString();
}
};
@Override
public Object parseObject(final Object object) {
return ((Biome) object).toString();
}
};
public static final SettingValue BLOCK = new SettingValue("BLOCK") {
@Override
public boolean validateValue(String string) {
try {
if (string.contains(":")) {
String[] split = string.split(":");
Short.parseShort(split[0]);
Short.parseShort(split[1]);
}
else {
Short.parseShort(string);
}
return true;
}
catch (Exception e) {
return false;
}
}
public static final SettingValue BLOCK = new SettingValue("BLOCK") {
@Override
public boolean validateValue(final String string) {
try {
if (string.contains(":")) {
final String[] split = string.split(":");
Short.parseShort(split[0]);
Short.parseShort(split[1]);
}
else {
Short.parseShort(string);
}
return true;
}
catch (final Exception e) {
return false;
}
}
@Override
public Object parseString(String string) {
if (string.contains(":")) {
String[] split = string.split(":");
return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
}
else {
return new PlotBlock(Short.parseShort(string), (byte) 0);
}
}
@Override
public Object parseString(final String string) {
if (string.contains(":")) {
final String[] split = string.split(":");
return new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
}
else {
return new PlotBlock(Short.parseShort(string), (byte) 0);
}
}
@Override
public Object parseObject(Object object) {
return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data;
}
};
@Override
public Object parseObject(final Object object) {
return ((PlotBlock) object).id + ":" + ((PlotBlock) object).data;
}
};
public static int gcd(int a, int b) {
if (b==0) return a;
return gcd(b,a%b);
}
private static int gcd(int[] a)
{
int result = a[0];
for(int i = 1; i < a.length; i++)
result = gcd(result, a[i]);
return result;
}
public static int gcd(final int a, final int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") {
@Override
public boolean validateValue(String string) {
try {
for (String block : string.split(",")) {
if (block.contains("%")) {
String[] split = block.split("%");
Integer.parseInt(split[0]);
block = split[1];
}
if (block.contains(":")) {
String[] split = block.split(":");
Short.parseShort(split[0]);
Short.parseShort(split[1]);
}
else {
Short.parseShort(block);
}
}
return true;
}
catch (Exception e) {
return false;
}
}
private static int gcd(final int[] a) {
int result = a[0];
for (int i = 1; i < a.length; i++) {
result = gcd(result, a[i]);
}
return result;
}
@Override
public Object parseString(String string) {
String[] blocks = string.split(",");
ArrayList<PlotBlock> parsedvalues = new ArrayList<PlotBlock>();
public static final SettingValue BLOCKLIST = new SettingValue("BLOCKLIST") {
@Override
public boolean validateValue(final String string) {
try {
for (String block : string.split(",")) {
if (block.contains("%")) {
final String[] split = block.split("%");
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>();
PlotBlock[] values = new PlotBlock[blocks.length];
int[] counts = new int[blocks.length];
int min = 100;
for (int i = 0; i < blocks.length; i++) {
if (blocks[i].contains("%")) {
String[] split = blocks[i].split("%");
blocks[i] = split[1];
int value = Integer.parseInt(split[0]);
counts[i] = value;
if (value<min) {
final PlotBlock[] values = new PlotBlock[blocks.length];
final int[] counts = new int[blocks.length];
int min = 100;
for (int i = 0; i < blocks.length; i++) {
if (blocks[i].contains("%")) {
final String[] split = blocks[i].split("%");
blocks[i] = split[1];
final int value = Integer.parseInt(split[0]);
counts[i] = value;
if (value < min) {
min = value;
}
}
else {
counts[i] = 1;
if (1<min) {
min = 1;
}
}
if (blocks[i].contains(":")) {
String[] split = blocks[i].split(":");
values[i] = new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
}
else {
values[i] = new PlotBlock(Short.parseShort(blocks[i]), (byte) 0);
}
}
int gcd = gcd(counts);
for (int i = 0; i < counts.length; i++) {
int num = counts[i];
for (int j = 0; j<num/gcd; j++) {
parsedvalues.add(values[i]);
}
}
}
else {
counts[i] = 1;
if (1 < min) {
min = 1;
}
}
if (blocks[i].contains(":")) {
final String[] split = blocks[i].split(":");
values[i] = new PlotBlock(Short.parseShort(split[0]), Byte.parseByte(split[1]));
}
else {
values[i] = new PlotBlock(Short.parseShort(blocks[i]), (byte) 0);
}
}
final int gcd = gcd(counts);
for (int i = 0; i < counts.length; i++) {
final int num = counts[i];
for (int j = 0; j < (num / gcd); j++) {
parsedvalues.add(values[i]);
}
}
return parsedvalues.toArray(new PlotBlock[0]);
}
return parsedvalues.toArray(new PlotBlock[0]);
}
@Override
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
public Object parseObject(final Object object) {
final List<String> list = new ArrayList<String>();
for (final PlotBlock block : (PlotBlock[]) object) {
list.add((block.id + ":" + (block.data)));
}
return list;
}
};
/**
* Create your own SettingValue object to make the management of plotworld
* configuration easier
*/
public static abstract class SettingValue {
private String type;
/**
* Create your own SettingValue object to make the management of plotworld
* configuration easier
*/
public static abstract class SettingValue {
private final String type;
public SettingValue(String type) {
this.type = type;
}
public SettingValue(final String type) {
this.type = type;
}
public String getType() {
return this.type;
}
public String getType() {
return this.type;
}
public Object parseObject(Object object) {
return object;
}
public Object parseObject(final Object object) {
return object;
}
public abstract Object parseString(String string);
public abstract Object parseString(final String string);
public abstract boolean validateValue(String string);
}
public abstract boolean validateValue(final String string);
}
}

View File

@ -1,70 +1,70 @@
package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.Configuration.SettingValue;
import org.apache.commons.lang.StringUtils;
import java.util.Arrays;
import org.apache.commons.lang.StringUtils;
import com.intellectualcrafters.plot.Configuration.SettingValue;
public class ConfigurationNode {
private String constant;
private Object default_value;
private String description;
private Object value;
private SettingValue type;
private final String constant;
private final Object default_value;
private final String description;
private Object value;
private final SettingValue type;
public ConfigurationNode(String constant, Object default_value, String description, SettingValue type,
boolean required) {
this.constant = constant;
this.default_value = default_value;
this.description = description;
this.value = default_value;
this.type = type;
}
public ConfigurationNode(final String constant, final Object default_value, final String description, final SettingValue type, final boolean required) {
this.constant = constant;
this.default_value = default_value;
this.description = description;
this.value = default_value;
this.type = type;
}
public SettingValue getType() {
return this.type;
}
public SettingValue getType() {
return this.type;
}
public boolean isValid(String string) {
try {
Object result = this.type.parseString(string);
if (result == null) {
return false;
}
return true;
}
catch (Exception e) {
return false;
}
}
public boolean isValid(final String string) {
try {
final Object result = this.type.parseString(string);
if (result == null) {
return false;
}
return true;
}
catch (final Exception e) {
return false;
}
}
public boolean setValue(String string) {
if (!this.type.validateValue(string)) {
return false;
}
this.value = this.type.parseString(string);
return true;
}
public boolean setValue(final String string) {
if (!this.type.validateValue(string)) {
return false;
}
this.value = this.type.parseString(string);
return true;
}
public Object getValue() {
if (this.value instanceof String[]) {
return Arrays.asList((String[]) this.value);
}
return this.value;
}
public Object getValue() {
if (this.value instanceof String[]) {
return Arrays.asList((String[]) this.value);
}
return this.value;
}
public String getConstant() {
return this.constant;
}
public String getConstant() {
return this.constant;
}
public Object getDefaultValue() {
if (this.default_value instanceof String[]) {
return StringUtils.join((String[]) this.default_value, ",");
}
return this.default_value;
}
public Object getDefaultValue() {
if (this.default_value instanceof String[]) {
return StringUtils.join((String[]) this.default_value, ",");
}
return this.default_value;
}
public String getDescription() {
return this.description;
}
public String getDescription() {
return this.description;
}
}

View File

@ -7,95 +7,95 @@ import org.bukkit.ChatColor;
*/
public class ConsoleColors {
static enum ConsoleColor {
RESET("\u001B[0m"),
BLACK("\u001B[30m"),
RED("\u001B[31m"),
GREEN("\u001B[32m"),
YELLOW("\u001B[33m"),
BLUE("\u001B[34m"),
PURPLE("\u001B[35m"),
CYAN("\u001B[36m"),
WHITE("\u001B[37m"),
BOLD("\033[1m"),
UNDERLINE("\033[0m"),
ITALIC("\033[3m");
static enum ConsoleColor {
RESET("\u001B[0m"),
BLACK("\u001B[30m"),
RED("\u001B[31m"),
GREEN("\u001B[32m"),
YELLOW("\u001B[33m"),
BLUE("\u001B[34m"),
PURPLE("\u001B[35m"),
CYAN("\u001B[36m"),
WHITE("\u001B[37m"),
BOLD("\033[1m"),
UNDERLINE("\033[0m"),
ITALIC("\033[3m");
private String win;
private String lin;
private final String win;
private final String lin;
ConsoleColor(String lin) {
this.lin = lin;
this.win = this.win;
}
ConsoleColor(final String lin) {
this.lin = lin;
this.win = this.win;
}
public String getWin() {
return this.win;
}
public String getWin() {
return this.win;
}
public String getLin() {
return this.lin;
}
}
public String getLin() {
return this.lin;
}
}
/*
* public static final String ANSI_RESET = "\u001B[0m"; public static final
* String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED =
* "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m";
* public static final String ANSI_YELLOW = "\u001B[33m"; public static
* final String ANSI_BLUE = "\u001B[34m"; public static final String
* ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN =
* "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m";
* public static final String ANSI_BOLD = "\033[1m"; public static final
* String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC
* = "\033[3m]";
*/
/*
* public static final String ANSI_RESET = "\u001B[0m"; public static final
* String ANSI_BLACK = "\u001B[30m"; public static final String ANSI_RED =
* "\u001B[31m"; public static final String ANSI_GREEN = "\u001B[32m";
* public static final String ANSI_YELLOW = "\u001B[33m"; public static
* final String ANSI_BLUE = "\u001B[34m"; public static final String
* ANSI_PURPLE = "\u001B[35m"; public static final String ANSI_CYAN =
* "\u001B[36m"; public static final String ANSI_WHITE = "\u001B[37m";
* public static final String ANSI_BOLD = "\033[1m"; public static final
* String ANSI_UNDERLINE = "\033[0m"; public static final String ANSI_ITALIC
* = "\033[3m]";
*/
public static String fromString(String input) {
input =
input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH)).replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET));
return input + "\u001B[0m";
}
public static String fromString(String input) {
input = input.replaceAll("&0", fromChatColor(ChatColor.BLACK)).replaceAll("&1", fromChatColor(ChatColor.DARK_BLUE)).replaceAll("&2", fromChatColor(ChatColor.DARK_GREEN)).replaceAll("&3", fromChatColor(ChatColor.DARK_AQUA)).replaceAll("&4", fromChatColor(ChatColor.DARK_RED)).replaceAll("&5", fromChatColor(ChatColor.DARK_PURPLE)).replaceAll("&6", fromChatColor(ChatColor.GOLD)).replaceAll("&7", fromChatColor(ChatColor.GRAY)).replaceAll("&8", fromChatColor(ChatColor.DARK_GRAY)).replaceAll("&9", fromChatColor(ChatColor.BLUE)).replaceAll("&a", fromChatColor(ChatColor.GREEN)).replaceAll("&b", fromChatColor(ChatColor.AQUA)).replaceAll("&c", fromChatColor(ChatColor.RED)).replaceAll("&d", fromChatColor(ChatColor.LIGHT_PURPLE)).replaceAll("&e", fromChatColor(ChatColor.YELLOW)).replaceAll("&f", fromChatColor(ChatColor.WHITE)).replaceAll("&k", fromChatColor(ChatColor.MAGIC)).replaceAll("&l", fromChatColor(ChatColor.BOLD)).replaceAll("&m", fromChatColor(ChatColor.STRIKETHROUGH))
.replaceAll("&n", fromChatColor(ChatColor.UNDERLINE)).replaceAll("&o", fromChatColor(ChatColor.ITALIC)).replaceAll("&r", fromChatColor(ChatColor.RESET));
return input + "\u001B[0m";
}
public static String fromChatColor(ChatColor color) {
return chatColor(color).getLin();
}
public static String fromChatColor(final ChatColor color) {
return chatColor(color).getLin();
}
public static ConsoleColor chatColor(ChatColor color) {
switch (color) {
case RESET:
return ConsoleColor.RESET;
case GRAY:
case DARK_GRAY:
return ConsoleColor.WHITE;
case BLACK:
return ConsoleColor.BLACK;
case DARK_RED:
case RED:
return ConsoleColor.RED;
case GOLD:
case YELLOW:
return ConsoleColor.YELLOW;
case DARK_GREEN:
case GREEN:
return ConsoleColor.GREEN;
case AQUA:
case DARK_AQUA:
return ConsoleColor.CYAN;
case LIGHT_PURPLE:
case DARK_PURPLE:
return ConsoleColor.PURPLE;
case BLUE:
case DARK_BLUE:
return ConsoleColor.BLUE;
case UNDERLINE:
return ConsoleColor.UNDERLINE;
case ITALIC:
return ConsoleColor.ITALIC;
case BOLD:
return ConsoleColor.BOLD;
default:
return ConsoleColor.RESET;
}
}
public static ConsoleColor chatColor(final ChatColor color) {
switch (color) {
case RESET:
return ConsoleColor.RESET;
case GRAY:
case DARK_GRAY:
return ConsoleColor.WHITE;
case BLACK:
return ConsoleColor.BLACK;
case DARK_RED:
case RED:
return ConsoleColor.RED;
case GOLD:
case YELLOW:
return ConsoleColor.YELLOW;
case DARK_GREEN:
case GREEN:
return ConsoleColor.GREEN;
case AQUA:
case DARK_AQUA:
return ConsoleColor.CYAN;
case LIGHT_PURPLE:
case DARK_PURPLE:
return ConsoleColor.PURPLE;
case BLUE:
case DARK_BLUE:
return ConsoleColor.BLUE;
case UNDERLINE:
return ConsoleColor.UNDERLINE;
case ITALIC:
return ConsoleColor.ITALIC;
case BOLD:
return ConsoleColor.BOLD;
default:
return ConsoleColor.RESET;
}
}
}

View File

@ -3,94 +3,93 @@ package com.intellectualcrafters.plot;
import org.apache.commons.lang.StringUtils;
public class Flag {
private AbstractFlag key;
private String value;
private final AbstractFlag key;
private final String value;
/**
* Flag object used to store basic information for a Plot. Flags are a
* key/value pair. For a flag to be usable by a player, you need to register
* it with PlotSquared.
*
* @param key
* AbstractFlag
* @param value
* Value must be alphanumerical (can have spaces) and be <= 48
* characters
* @throws IllegalArgumentException
* if you provide inadequate inputs
*/
public Flag(AbstractFlag key, String value) {
char[] allowedCharacters = new char[] {
'[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§'
};
/**
* Flag object used to store basic information for a Plot. Flags are a
* key/value pair. For a flag to be usable by a player, you need to register
* it with PlotSquared.
*
* @param key
* AbstractFlag
* @param value
* Value must be alphanumerical (can have spaces) and be <= 48
* characters
* @throws IllegalArgumentException
* if you provide inadequate inputs
*/
public Flag(final AbstractFlag key, final String value) {
final char[] allowedCharacters = new char[] { '[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§' };
String tempValue = value;
for(char c : allowedCharacters)
for (final char c : allowedCharacters) {
tempValue = tempValue.replace(c, 'c');
if (!StringUtils.isAlphanumericSpace(tempValue)) {
throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)");
}
if (value.length() > 48) {
throw new IllegalArgumentException("Value must be <= 48 characters");
}
this.key = key;
this.value = key.parseValue(value);
if (this.value==null) {
throw new IllegalArgumentException(key.getValueDesc());
}
}
}
if (!StringUtils.isAlphanumericSpace(tempValue)) {
throw new IllegalArgumentException("Flag must be alphanumerical (colours and some special characters are allowed)");
}
if (value.length() > 48) {
throw new IllegalArgumentException("Value must be <= 48 characters");
}
this.key = key;
this.value = key.parseValue(value);
if (this.value == null) {
throw new IllegalArgumentException(key.getValueDesc());
}
}
/**
* Get the AbstractFlag used in creating the flag
*
* @return AbstractFlag
*/
public AbstractFlag getAbstractFlag() {
return this.key;
}
/**
* Get the AbstractFlag used in creating the flag
*
* @return AbstractFlag
*/
public AbstractFlag getAbstractFlag() {
return this.key;
}
/**
* Get the key for the AbstractFlag
*
* @return String
*/
public String getKey() {
return this.key.getKey();
}
/**
* Get the key for the AbstractFlag
*
* @return String
*/
public String getKey() {
return this.key.getKey();
}
/**
* Get the value
*
* @return String
*/
public String getValue() {
return this.value;
}
/**
* Get the value
*
* @return String
*/
public String getValue() {
return this.value;
}
@Override
public String toString() {
if (this.value.equals("")) {
return this.key.getKey();
}
return this.key + ":" + this.value;
}
@Override
public String toString() {
if (this.value.equals("")) {
return this.key.getKey();
}
return this.key + ":" + this.value;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value));
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value));
}
@Override
public int hashCode() {
return this.key.getKey().hashCode();
}
@Override
public int hashCode() {
return this.key.getKey().hashCode();
}
}

View File

@ -1,146 +1,151 @@
package com.intellectualcrafters.plot;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.bukkit.entity.Player;
public class FlagManager {
// TODO add some flags
// - Plot clear interval
// - Mob cap
// - customized plot composition
// - greeting / leaving message
// OR in the flag command, allow users to set worldguard flags.
// TODO add some flags
// - Plot clear interval
// - Mob cap
// - customized plot composition
// - greeting / leaving message
// OR in the flag command, allow users to set worldguard flags.
private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>();
private static ArrayList<AbstractFlag> flags = new ArrayList<AbstractFlag>();
/**
* Register an AbstractFlag with PlotSquared
*
* @param flag
* @return
*/
public static boolean addFlag(AbstractFlag flag) {
if (getFlag(flag.getKey()) != null) {
return false;
}
return flags.add(flag);
}
/**
* Register an AbstractFlag with PlotSquared
*
* @param flag
* @return
*/
public static boolean addFlag(final AbstractFlag flag) {
if (getFlag(flag.getKey()) != null) {
return false;
}
return flags.add(flag);
}
public static Flag[] removeFlag(Flag[] flags, String r) {
Flag[] f = new Flag[flags.length - 1];
public static Flag[] removeFlag(final Flag[] flags, final String r) {
final Flag[] f = new Flag[flags.length - 1];
int index = 0;
for(Flag flag : flags) {
if(!flag.getKey().equals(r))
for (final Flag flag : flags) {
if (!flag.getKey().equals(r)) {
f[index++] = flag;
}
}
return f;
}
public static Flag[] removeFlag(Set<Flag> flags, String r) {
Flag[] flagArray = new Flag[flags.size() - 1];
public static Flag[] removeFlag(final Set<Flag> flags, final String r) {
final Flag[] flagArray = new Flag[flags.size() - 1];
int index = 0;
for(Flag flag : flags) {
if(!flag.getKey().equals(r))
for (final Flag flag : flags) {
if (!flag.getKey().equals(r)) {
flagArray[index++] = flag;
}
}
return flagArray;
}
/**
* Get a list of registered AbstractFlag objects
*
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getFlags() {
return flags;
}
/**
* Get a list of registered AbstractFlag objects
*
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getFlags() {
return flags;
}
/**
* Get a list of registerd AbstragFlag objects based on player permissions
* @param player with permissions
*
* @param player
* with permissions
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getFlags(Player player) {
List<AbstractFlag> returnFlags = new ArrayList<>();
for(AbstractFlag flag : flags) {
if(player.hasPermission("plots.set." + flag.getKey().toLowerCase()))
public static List<AbstractFlag> getFlags(final Player player) {
final List<AbstractFlag> returnFlags = new ArrayList<>();
for (final AbstractFlag flag : flags) {
if (player.hasPermission("plots.set." + flag.getKey().toLowerCase())) {
returnFlags.add(flag);
}
}
return returnFlags;
}
/**
* Get an AbstractFlag by a string Returns null if flag does not exist
*
* @param string
* @return AbstractFlag
*/
public static AbstractFlag getFlag(String string) {
for (AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) {
return flag;
}
}
return null;
}
/**
* Get an AbstractFlag by a string Returns null if flag does not exist
*
* @param string
* @return AbstractFlag
*/
public static AbstractFlag getFlag(final String string) {
for (final AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) {
return flag;
}
}
return null;
}
/**
* Get an AbstractFlag by a string
*
* @param string
* @param create
* If to create the flag if it does not exist
* @return AbstractFlag
*/
public static AbstractFlag getFlag(String string, boolean create) {
if ((getFlag(string) == null) && create) {
AbstractFlag flag = new AbstractFlag(string);
addFlag(flag);
return flag;
}
return getFlag(string);
}
/**
* Get an AbstractFlag by a string
*
* @param string
* @param create
* If to create the flag if it does not exist
* @return AbstractFlag
*/
public static AbstractFlag getFlag(final String string, final boolean create) {
if ((getFlag(string) == null) && create) {
final AbstractFlag flag = new AbstractFlag(string);
addFlag(flag);
return flag;
}
return getFlag(string);
}
/**
* Remove a registered AbstractFlag
*
* @param flag
* @return boolean Result of operation
*/
public static boolean removeFlag(AbstractFlag flag) {
return flags.remove(flag);
}
/**
* Remove a registered AbstractFlag
*
* @param flag
* @return boolean Result of operation
*/
public static boolean removeFlag(final AbstractFlag flag) {
return flags.remove(flag);
}
public static Flag[] parseFlags(List<String> flagstrings) {
Flag[] flags = new Flag[flagstrings.size()];
for (int i = 0; i < flagstrings.size(); i++) {
String[] split = flagstrings.get(i).split(";");
if (split.length == 1) {
flags[i] = new Flag(getFlag(split[0], true), "");
}
else {
flags[i] = new Flag(getFlag(split[0], true), split[1]);
}
}
return flags;
}
public static Flag[] parseFlags(final List<String> flagstrings) {
final Flag[] flags = new Flag[flagstrings.size()];
for (int i = 0; i < flagstrings.size(); i++) {
final String[] split = flagstrings.get(i).split(";");
if (split.length == 1) {
flags[i] = new Flag(getFlag(split[0], true), "");
}
else {
flags[i] = new Flag(getFlag(split[0], true), split[1]);
}
}
return flags;
}
/**
* Get the flags for a plot
*
* @param plot
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getPlotFlags(Plot plot) {
Set<Flag> plotFlags = plot.settings.getFlags();
List<AbstractFlag> flags = new ArrayList<>();
for (Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag());
}
return flags;
}
/**
* Get the flags for a plot
*
* @param plot
* @return List (AbstractFlag)
*/
public static List<AbstractFlag> getPlotFlags(final Plot plot) {
final Set<Flag> plotFlags = plot.settings.getFlags();
final List<AbstractFlag> flags = new ArrayList<>();
for (final Flag flag : plotFlags) {
flags.add(flag.getAbstractFlag());
}
return flags;
}
}

View File

@ -17,110 +17,108 @@ import org.bukkit.Location;
*/
public class LSetCube {
/**
* Base locations
*/
private Location l1, l2;
/**
* Base locations
*/
private Location l1, l2;
/**
* Constructor
*
* @param l1
* @param l2
*/
public LSetCube(Location l1, Location l2) {
this.l1 = l1;
this.l1 = l2;
}
/**
* Constructor
*
* @param l1
* @param l2
*/
public LSetCube(final Location l1, final Location l2) {
this.l1 = l1;
this.l1 = l2;
}
/**
* Secondary constructor
*
* @param l1
* @param size
*/
public LSetCube(Location l1, int size) {
this.l1 = l1;
this.l2 = l1.clone().add(size, size, size);
}
/**
* Secondary constructor
*
* @param l1
* @param size
*/
public LSetCube(final Location l1, final int size) {
this.l1 = l1;
this.l2 = l1.clone().add(size, size, size);
}
/**
* Returns the absolute min. of the cube
*
* @return abs. min
*/
public Location minLoc() {
int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z);
}
/**
* Returns the absolute min. of the cube
*
* @return abs. min
*/
public Location minLoc() {
final int x = Math.min(this.l1.getBlockX(), this.l2.getBlockX());
final int y = Math.min(this.l1.getBlockY(), this.l2.getBlockY());
final int z = Math.min(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z);
}
/**
* Returns the absolute max. of the cube
*
* @return abs. max
*/
public Location maxLoc() {
int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX());
int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY());
int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z);
}
/**
* Returns the absolute max. of the cube
*
* @return abs. max
*/
public Location maxLoc() {
final int x = Math.max(this.l1.getBlockX(), this.l2.getBlockX());
final int y = Math.max(this.l1.getBlockY(), this.l2.getBlockY());
final int z = Math.max(this.l1.getBlockZ(), this.l2.getBlockZ());
return new Location(this.l1.getWorld(), x, y, z);
}
/**
* Creates a LCycler for the cube.
*
* @return new lcycler
*/
public LCycler getCycler() {
return new LCycler(this);
}
/**
* Creates a LCycler for the cube.
*
* @return new lcycler
*/
public LCycler getCycler() {
return new LCycler(this);
}
/**
* @author Citymonstret
*/
protected class LCycler {
/**
*
*/
private Location min;
/**
*
*/
private Location max;
/**
*
*/
private Location current;
/**
* @author Citymonstret
*/
protected class LCycler {
/**
*
*/
private final Location min;
/**
*
*/
private final Location max;
/**
*
*/
private Location current;
/**
* @param cube
*/
public LCycler(LSetCube cube) {
this.min = cube.minLoc();
this.max = cube.maxLoc();
this.current = this.min;
}
/**
* @param cube
*/
public LCycler(final LSetCube cube) {
this.min = cube.minLoc();
this.max = cube.maxLoc();
this.current = this.min;
}
/**
* @return
*/
public boolean hasNext() {
return ((this.current.getBlockX() + 1) <= this.max.getBlockX())
&& ((this.current.getBlockY() + 1) <= this.max.getBlockY())
&& ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
}
/**
* @return
*/
public boolean hasNext() {
return ((this.current.getBlockX() + 1) <= this.max.getBlockX()) && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
}
/**
* @return
*/
public Location getNext() {
if (!hasNext()) {
return null;
}
this.current = this.current.add(1, 1, 1);
return this.current;
}
}
/**
* @return
*/
public Location getNext() {
if (!hasNext()) {
return null;
}
this.current = this.current.add(1, 1, 1);
return this.current;
}
}
}

View File

@ -15,79 +15,79 @@ package com.intellectualcrafters.plot;
*/
public class Lag implements Runnable {
/**
* Tick count
*/
public static int TC = 0;
/**
* Ticks
*/
public static long[] T = new long[600];
/**
* something :_:
*/
@SuppressWarnings("unused")
public static long LT = 0L;
/**
* Tick count
*/
public static int TC = 0;
/**
* Ticks
*/
public static long[] T = new long[600];
/**
* something :_:
*/
@SuppressWarnings("unused")
public static long LT = 0L;
/**
* Get the server TPS
*
* @return server tick per second
*/
public static double getTPS() {
return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100));
}
/**
* Get the server TPS
*
* @return server tick per second
*/
public static double getTPS() {
return Math.round(getTPS(100)) > 20.0D ? 20.0D : Math.round(getTPS(100));
}
/**
* Return the tick per second (measured in $ticks)
*
* @param ticks
* Ticks
* @return ticks per second
*/
public static double getTPS(int ticks) {
if (TC < ticks) {
return 20.0D;
}
int t = (TC - 1 - ticks) % T.length;
long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D);
}
/**
* Return the tick per second (measured in $ticks)
*
* @param ticks
* Ticks
* @return ticks per second
*/
public static double getTPS(final int ticks) {
if (TC < ticks) {
return 20.0D;
}
final int t = (TC - 1 - ticks) % T.length;
final long e = System.currentTimeMillis() - T[t];
return ticks / (e / 1000.0D);
}
/**
* Get number of ticks since
*
* @param tI
* Ticks <
* @return number of ticks since $tI
*/
@SuppressWarnings("unused")
public static long getElapsed(int tI) {
long t = T[tI % T.length];
return System.currentTimeMillis() - t;
}
/**
* Get number of ticks since
*
* @param tI
* Ticks <
* @return number of ticks since $tI
*/
@SuppressWarnings("unused")
public static long getElapsed(final int tI) {
final long t = T[tI % T.length];
return System.currentTimeMillis() - t;
}
@Override
public void run() {
T[TC % T.length] = System.currentTimeMillis();
TC++;
}
@Override
public void run() {
T[TC % T.length] = System.currentTimeMillis();
TC++;
}
/**
* Get lag percentage
*
* @return lag percentage
*/
public static double getPercentage() {
return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D);
}
/**
* Get lag percentage
*
* @return lag percentage
*/
public static double getPercentage() {
return Math.round((1.0D - (Lag.getTPS() / 20.0D)) * 100.0D);
}
/**
* Get TPS percentage (of 20)
*
* @return TPS percentage
*/
public static double getFullPercentage() {
return getTPS() * 5.0D;
}
/**
* Get TPS percentage (of 20)
*
* @return TPS percentage
*/
public static double getFullPercentage() {
return getTPS() * 5.0D;
}
}

View File

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

View File

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

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

View File

@ -8,14 +8,15 @@
package com.intellectualcrafters.plot;
import com.intellectualcrafters.plot.database.DBFunc;
import java.util.ArrayList;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.UUID;
import com.intellectualcrafters.plot.database.DBFunc;
/**
* The plot class
@ -25,262 +26,255 @@ import java.util.UUID;
@SuppressWarnings("javadoc")
public class Plot implements Cloneable {
/**
* plot ID
*/
public PlotId id;
/**
* plot world
*/
public String world;
/**
* plot owner
*/
public UUID owner;
/**
* Deny Entry
*/
public boolean deny_entry;
/**
* List of helpers (with plot permissions)
*/
public ArrayList<UUID> helpers;
/**
* List of trusted users (with plot permissions)
*/
public ArrayList<UUID> trusted;
/**
* List of denied players
*/
public ArrayList<UUID> denied;
/**
* External settings class
*/
public PlotSettings settings;
/**
* Delete on next save cycle?
*/
public boolean delete;
/**
* Has the plot changed since the last save cycle?
*/
public boolean hasChanged = false;
public boolean countsTowardsMax = true ;
/**
* plot ID
*/
public PlotId id;
/**
* plot world
*/
public String world;
/**
* plot owner
*/
public UUID owner;
/**
* Deny Entry
*/
public boolean deny_entry;
/**
* List of helpers (with plot permissions)
*/
public ArrayList<UUID> helpers;
/**
* List of trusted users (with plot permissions)
*/
public ArrayList<UUID> trusted;
/**
* List of denied players
*/
public ArrayList<UUID> denied;
/**
* External settings class
*/
public PlotSettings settings;
/**
* Delete on next save cycle?
*/
public boolean delete;
/**
* Has the plot changed since the last save cycle?
*/
public boolean hasChanged = false;
public boolean countsTowardsMax = true;
/**
* Primary constructor
*
* @param id
* @param owner
* @param plotBiome
* @param helpers
* @param denied
*/
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner == null;
this.helpers = helpers;
this.denied = denied;
this.trusted = new ArrayList<UUID>();
this.settings.setAlias("");
this.settings.setPosition(PlotHomePosition.DEFAULT);
this.delete = false;
this.settings.setFlags(new Flag[0]);
this.world = world;
}
/**
* Primary constructor
*
* @param id
* @param owner
* @param plotBiome
* @param helpers
* @param denied
*/
public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList<UUID> helpers, final ArrayList<UUID> denied, final String world) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner == null;
this.helpers = helpers;
this.denied = denied;
this.trusted = new ArrayList<UUID>();
this.settings.setAlias("");
this.settings.setPosition(PlotHomePosition.DEFAULT);
this.delete = false;
this.settings.setFlags(new Flag[0]);
this.world = world;
}
/**
* Constructor for saved plots
*
* @param id
* @param owner
* @param plotBiome
* @param helpers
* @param denied
* @param changeTime
* @param time
* @param merged
*/
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> trusted,
ArrayList<UUID> denied, String alias,
PlotHomePosition position, Flag[] flags, String world, boolean[] merged) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner != null;
this.trusted = trusted;
this.helpers = helpers;
this.denied = denied;
this.settings.setAlias(alias);
this.settings.setPosition(position);
this.settings.setMerged(merged);
this.delete = false;
if (flags != null) {
this.settings.setFlags(flags);
}
else {
this.settings.setFlags(new Flag[0]);
}
this.world = world;
}
/**
* Constructor for saved plots
*
* @param id
* @param owner
* @param plotBiome
* @param helpers
* @param denied
* @param changeTime
* @param time
* @param merged
*/
public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList<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) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
this.owner = owner;
this.deny_entry = this.owner != null;
this.trusted = trusted;
this.helpers = helpers;
this.denied = denied;
this.settings.setAlias(alias);
this.settings.setPosition(position);
this.settings.setMerged(merged);
this.delete = false;
if (flags != null) {
this.settings.setFlags(flags);
}
else {
this.settings.setFlags(new Flag[0]);
}
this.world = world;
}
/**
* Check if the plot has a set owner
*
* @return false if there is no owner
*/
public boolean hasOwner() {
return this.owner != null;
}
/**
* Check if the plot has a set owner
*
* @return false if there is no owner
*/
public boolean hasOwner() {
return this.owner != null;
}
/**
* Set the owner
*
* @param player
*/
public void setOwner(Player player) {
this.owner = player.getUniqueId();
}
/**
* Set the owner
*
* @param player
*/
public void setOwner(final Player player) {
this.owner = player.getUniqueId();
}
/**
* Check if the player is either the owner or on the helpers list
*
* @param player
* @return true if the player is added as a helper or is the owner
*/
public boolean hasRights(Player player) {
return PlotMain.hasPermission(player, "plots.admin")
|| ((this.helpers != null) && this.helpers.contains(DBFunc.everyone))
|| ((this.helpers != null) && this.helpers.contains(player.getUniqueId()))
|| ((this.owner != null) && this.owner.equals(player.getUniqueId()))
|| ((this.owner != null) && (this.trusted != null) && (Bukkit.getPlayer(this.owner) != null) && (this.trusted.contains(player.getUniqueId()) || this.trusted.contains(DBFunc.everyone)));
}
/**
* Check if the player is either the owner or on the helpers list
*
* @param player
* @return true if the player is added as a helper or is the owner
*/
public boolean hasRights(final Player player) {
return PlotMain.hasPermission(player, "plots.admin") || ((this.helpers != null) && this.helpers.contains(DBFunc.everyone)) || ((this.helpers != null) && this.helpers.contains(player.getUniqueId())) || ((this.owner != null) && this.owner.equals(player.getUniqueId())) || ((this.owner != null) && (this.trusted != null) && (Bukkit.getPlayer(this.owner) != null) && (this.trusted.contains(player.getUniqueId()) || this.trusted.contains(DBFunc.everyone)));
}
/**
* Should the player be allowed to enter?
*
* @param player
* @return false if the player is allowed to enter
*/
public boolean deny_entry(Player player) {
return (this.denied != null)
&& ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
}
/**
* Should the player be allowed to enter?
*
* @param player
* @return false if the player is allowed to enter
*/
public boolean deny_entry(final Player player) {
return (this.denied != null) && ((this.denied.contains(DBFunc.everyone) && !this.hasRights(player)) || (!this.hasRights(player) && this.denied.contains(player.getUniqueId())));
}
/**
* Get the UUID of the owner
*/
public UUID getOwner() {
return this.owner;
}
/**
* Get the UUID of the owner
*/
public UUID getOwner() {
return this.owner;
}
/**
* Get the plot ID
*/
public PlotId getId() {
return this.id;
}
/**
* Get the plot ID
*/
public PlotId getId() {
return this.id;
}
/**
* Get the plot World
*/
public World getWorld() {
return Bukkit.getWorld(this.world);
}
/**
* Get the plot World
*/
public World getWorld() {
return Bukkit.getWorld(this.world);
}
/**
* Get a clone of the plot
*
* @return
*/
@Override
public Object clone() throws CloneNotSupportedException {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
return null;
}
}
/**
* Get a clone of the plot
*
* @return
*/
@Override
public Object clone() throws CloneNotSupportedException {
try {
return super.clone();
}
catch (final CloneNotSupportedException e) {
return null;
}
}
/**
* Deny someone (use DBFunc.addDenied() as well)
*
* @param uuid
*/
public void addDenied(UUID uuid) {
this.denied.add(uuid);
}
/**
* Deny someone (use DBFunc.addDenied() as well)
*
* @param uuid
*/
public void addDenied(final UUID uuid) {
this.denied.add(uuid);
}
/**
* Add someone as a helper (use DBFunc as well)
*
* @param uuid
*/
public void addHelper(UUID uuid) {
this.helpers.add(uuid);
}
/**
* Add someone as a helper (use DBFunc as well)
*
* @param uuid
*/
public void addHelper(final UUID uuid) {
this.helpers.add(uuid);
}
/**
* Add someone as a trusted user (use DBFunc as well)
*
* @param uuid
*/
public void addTrusted(UUID uuid) {
this.trusted.add(uuid);
}
/**
* Add someone as a trusted user (use DBFunc as well)
*
* @param uuid
*/
public void addTrusted(final UUID uuid) {
this.trusted.add(uuid);
}
/**
* Get plot display name
*
* @return alias if set, else id
*/
public String getDisplayName() {
if (this.settings.getAlias().length() > 1) {
return this.settings.getAlias();
}
return this.getId().x + ";" + this.getId().y;
}
/**
* Get plot display name
*
* @return alias if set, else id
*/
public String getDisplayName() {
if (this.settings.getAlias().length() > 1) {
return this.settings.getAlias();
}
return this.getId().x + ";" + this.getId().y;
}
/**
* Remove a denied player (use DBFunc as well)
*
* @param uuid
*/
public void removeDenied(UUID uuid) {
this.denied.remove(uuid);
}
/**
* Remove a denied player (use DBFunc as well)
*
* @param uuid
*/
public void removeDenied(final UUID uuid) {
this.denied.remove(uuid);
}
/**
* Remove a helper (use DBFunc as well)
*
* @param uuid
*/
public void removeHelper(UUID uuid) {
this.helpers.remove(uuid);
}
/**
* Remove a helper (use DBFunc as well)
*
* @param uuid
*/
public void removeHelper(final UUID uuid) {
this.helpers.remove(uuid);
}
/**
* Remove a trusted user (use DBFunc as well)
*
* @param uuid
*/
public void removeTrusted(UUID uuid) {
this.trusted.remove(uuid);
}
/**
* Remove a trusted user (use DBFunc as well)
*
* @param uuid
*/
public void removeTrusted(final UUID uuid) {
this.trusted.remove(uuid);
}
/**
* Clear a plot
*
* @param plr
* initiator
*/
public void clear(Player plr) {
PlotHelper.clear(plr, this);
}
/**
* Clear a plot
*
* @param plr
* initiator
*/
public void clear(final Player plr) {
PlotHelper.clear(plr, this);
}
}

View File

@ -1,11 +1,11 @@
package com.intellectualcrafters.plot;
public class PlotBlock {
public short id;
public byte data;
public short id;
public byte data;
public PlotBlock(short id, byte data) {
this.id = id;
this.data = data;
}
public PlotBlock(final short id, final byte data) {
this.id = id;
this.data = data;
}
}

View File

@ -2,10 +2,10 @@ package com.intellectualcrafters.plot;
public class PlotComment {
public final String comment;
public final int tier;
public final int tier;
public final String senderName;
public PlotComment(String comment, String senderName, int tier) {
public PlotComment(final String comment, final String senderName, final int tier) {
this.comment = comment;
this.tier = tier;
this.senderName = senderName;

View File

@ -4,11 +4,11 @@ import org.bukkit.generator.ChunkGenerator;
public abstract class PlotGenerator extends ChunkGenerator {
public PlotGenerator(String world) {
PlotMain.loadWorld(world, this);
}
public PlotGenerator(final String world) {
PlotMain.loadWorld(world, this);
}
public abstract PlotWorld getNewPlotWorld(String world);
public abstract PlotWorld getNewPlotWorld(final String world);
public abstract PlotManager getPlotManager();
public abstract PlotManager getPlotManager();
}

View File

@ -13,25 +13,25 @@ package com.intellectualcrafters.plot;
* Created by Citymonstret on 2014-08-05.
*/
public enum PlotHomePosition {
CENTER("Center", 'c'),
DEFAULT("Default", 'd');
CENTER("Center", 'c'),
DEFAULT("Default", 'd');
private String string;
private char ch;
private String string;
private char ch;
PlotHomePosition(String string, char ch) {
this.string = string;
this.ch = ch;
}
PlotHomePosition(final String string, final char ch) {
this.string = string;
this.ch = ch;
}
public boolean isMatching(String string) {
if ((string.length() < 2) && (string.charAt(0) == this.ch)) {
return true;
}
if (string.equalsIgnoreCase(this.string)) {
return true;
}
return false;
}
public boolean isMatching(final String string) {
if ((string.length() < 2) && (string.charAt(0) == this.ch)) {
return true;
}
if (string.equalsIgnoreCase(this.string)) {
return true;
}
return false;
}
}

View File

@ -1,54 +1,54 @@
package com.intellectualcrafters.plot;
public class PlotId {
/**
* x value
*/
public Integer x;
/**
* y value
*/
public Integer y;
/**
* x value
*/
public Integer x;
/**
* y value
*/
public Integer y;
/**
* PlotId class (PlotId x,y values do not correspond to Block locations)
*
* @param x
* The plot x coordinate
* @param y
* The plot y coordinate
*/
public PlotId(int x, int y) {
this.x = x;
this.y = y;
}
/**
* PlotId class (PlotId x,y values do not correspond to Block locations)
*
* @param x
* The plot x coordinate
* @param y
* The plot y coordinate
*/
public PlotId(final int x, final int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
PlotId other = (PlotId) obj;
return (((int) this.x == (int) other.x) && ((int) this.y == (int) other.y));
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final PlotId other = (PlotId) obj;
return ((this.x == other.x) && (this.y == other.y));
}
@Override
public String toString() {
return this.x + ";" + this.y;
}
@Override
public String toString() {
return this.x + ";" + this.y;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + this.x;
result = (prime * result) + this.y;
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = (prime * result) + this.x;
result = (prime * result) + this.y;
return result;
}
}

View File

@ -5,70 +5,69 @@ import java.util.ArrayList;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
public abstract class PlotManager {
/*
* Plot locations (methods with Abs in them will not need to consider mega
* plots)
*/
/*
* Plot locations (methods with Abs in them will not need to consider mega
* plots)
*/
public abstract PlotId getPlotIdAbs(PlotWorld plotworld, Location loc);
public abstract PlotId getPlotIdAbs(final PlotWorld plotworld, final Location loc);
public abstract PlotId getPlotId(PlotWorld plotworld, Location loc);
public abstract PlotId getPlotId(final PlotWorld plotworld, final Location loc);
public abstract boolean isInPlotAbs(PlotWorld plotworld, Location loc, PlotId plotid);
public abstract boolean isInPlotAbs(final PlotWorld plotworld, final Location loc, final PlotId plotid);
// If you have a circular plot, just return the corner if it were a square
public abstract Location getPlotBottomLocAbs(PlotWorld plotworld, PlotId plotid);
// If you have a circular plot, just return the corner if it were a square
public abstract Location getPlotBottomLocAbs(final PlotWorld plotworld, final PlotId plotid);
// the same applies here
public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid);
// the same applies here
public abstract Location getPlotTopLocAbs(final PlotWorld plotworld, final PlotId plotid);
/*
* Plot clearing (return false if you do not support some method)
*/
/*
* Plot clearing (return false if you do not support some method)
*/
public abstract boolean clearPlot(World world, Plot plot);
public abstract boolean clearPlot(final World world, final Plot plot);
public abstract Location getSignLoc(World world, PlotWorld plotworld, Plot plot);
public abstract Location getSignLoc(final World world, final PlotWorld plotworld, final Plot plot);
/*
* Plot set functions (return false if you do not support the specific set
* method)
*/
/*
* Plot set functions (return false if you do not support the specific set
* method)
*/
public abstract boolean setWallFilling(World world, PlotWorld plotworld, PlotId plotid, PlotBlock block);
public abstract boolean setWallFilling(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock block);
public abstract boolean setWall(World world, PlotWorld plotworld, PlotId plotid, PlotBlock block);
public abstract boolean setWall(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock block);
public abstract boolean setFloor(World world, PlotWorld plotworld, PlotId plotid, PlotBlock[] block);
public abstract boolean setFloor(final World world, final PlotWorld plotworld, final PlotId plotid, final PlotBlock[] block);
public abstract boolean setBiome(World world, Plot plot, Biome biome);
public abstract boolean setBiome(final World world, final Plot plot, final Biome biome);
/*
* PLOT MERGING (return false if your generator does not support plot
* merging)
*/
public abstract boolean createRoadEast(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 createRoadSouth(PlotWorld plotworld, Plot plot);
public abstract boolean createRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean createRoadSouthEast(PlotWorld plotworld, Plot plot);
public abstract boolean createRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadEast(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouth(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadSouth(final PlotWorld plotworld, final Plot plot);
public abstract boolean removeRoadSouthEast(PlotWorld plotworld, Plot plot);
public abstract boolean removeRoadSouthEast(final PlotWorld plotworld, final Plot plot);
public abstract boolean startPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean startPlotMerge(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean startPlotUnlink(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean startPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean finishPlotMerge(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean finishPlotMerge(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
public abstract boolean finishPlotUnlink(World world, PlotWorld plotworld, ArrayList<PlotId> plotIds);
public abstract boolean finishPlotUnlink(final World world, final PlotWorld plotworld, final ArrayList<PlotId> plotIds);
}

View File

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

View File

@ -8,185 +8,181 @@
package com.intellectualcrafters.plot;
import org.bukkit.block.Biome;
import com.intellectualcrafters.plot.database.DBFunc;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import org.bukkit.block.Biome;
/**
* plot settings
*
* @author Citymonstret
*/
public class PlotSettings {
/**
* merged plots
*/
private boolean[] merged = new boolean[] { false, false, false, false };
/**
* plot alias
*/
private String alias;
/**
* plot biome
*/
private Biome biome;
/**
* merged plots
*/
private boolean[] merged = new boolean[] { false, false, false, false };
/**
* plot alias
*/
private String alias;
/**
* plot biome
*/
private Biome biome;
private ArrayList<PlotComment> comments = null;
/**
*
*/
private Set<Flag> flags;
private ArrayList<PlotComment> comments = null;
/**
*
*/
private Set<Flag> flags;
private PlotHomePosition position;
private PlotHomePosition position;
/**
* Constructor
*
* @param plot
*/
public PlotSettings(Plot plot) {
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;
/**
* Constructor
*
* @param plot
*/
public PlotSettings(final Plot plot) {
this.alias = "";
}
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.add(comment);
}
}
}

View File

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

View File

@ -1,15 +1,97 @@
package com.intellectualcrafters.plot;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.configuration.ConfigurationSection;
import static org.bukkit.Material.ACACIA_STAIRS;
import static org.bukkit.Material.BEACON;
import static org.bukkit.Material.BEDROCK;
import static org.bukkit.Material.BIRCH_WOOD_STAIRS;
import static org.bukkit.Material.BOOKSHELF;
import static org.bukkit.Material.BREWING_STAND;
import static org.bukkit.Material.BRICK;
import static org.bukkit.Material.BRICK_STAIRS;
import static org.bukkit.Material.BURNING_FURNACE;
import static org.bukkit.Material.CAKE_BLOCK;
import static org.bukkit.Material.CAULDRON;
import static org.bukkit.Material.CLAY;
import static org.bukkit.Material.CLAY_BRICK;
import static org.bukkit.Material.COAL_BLOCK;
import static org.bukkit.Material.COAL_ORE;
import static org.bukkit.Material.COBBLESTONE;
import static org.bukkit.Material.COBBLESTONE_STAIRS;
import static org.bukkit.Material.COBBLE_WALL;
import static org.bukkit.Material.COMMAND;
import static org.bukkit.Material.DARK_OAK_STAIRS;
import static org.bukkit.Material.DAYLIGHT_DETECTOR;
import static org.bukkit.Material.DIAMOND_BLOCK;
import static org.bukkit.Material.DIAMOND_ORE;
import static org.bukkit.Material.DIRT;
import static org.bukkit.Material.DISPENSER;
import static org.bukkit.Material.DROPPER;
import static org.bukkit.Material.EMERALD_BLOCK;
import static org.bukkit.Material.EMERALD_ORE;
import static org.bukkit.Material.ENCHANTMENT_TABLE;
import static org.bukkit.Material.ENDER_PORTAL_FRAME;
import static org.bukkit.Material.ENDER_STONE;
import static org.bukkit.Material.FURNACE;
import static org.bukkit.Material.GLASS;
import static org.bukkit.Material.GLOWSTONE;
import static org.bukkit.Material.GOLD_BLOCK;
import static org.bukkit.Material.GOLD_ORE;
import static org.bukkit.Material.GRASS;
import static org.bukkit.Material.GRAVEL;
import static org.bukkit.Material.HARD_CLAY;
import static org.bukkit.Material.HAY_BLOCK;
import static org.bukkit.Material.HUGE_MUSHROOM_1;
import static org.bukkit.Material.HUGE_MUSHROOM_2;
import static org.bukkit.Material.IRON_BLOCK;
import static org.bukkit.Material.IRON_ORE;
import static org.bukkit.Material.JACK_O_LANTERN;
import static org.bukkit.Material.JUKEBOX;
import static org.bukkit.Material.JUNGLE_WOOD_STAIRS;
import static org.bukkit.Material.LAPIS_BLOCK;
import static org.bukkit.Material.LAPIS_ORE;
import static org.bukkit.Material.LEAVES;
import static org.bukkit.Material.LEAVES_2;
import static org.bukkit.Material.LOG;
import static org.bukkit.Material.LOG_2;
import static org.bukkit.Material.MELON_BLOCK;
import static org.bukkit.Material.MOB_SPAWNER;
import static org.bukkit.Material.MOSSY_COBBLESTONE;
import static org.bukkit.Material.MYCEL;
import static org.bukkit.Material.NETHERRACK;
import static org.bukkit.Material.NETHER_BRICK;
import static org.bukkit.Material.NETHER_BRICK_STAIRS;
import static org.bukkit.Material.NOTE_BLOCK;
import static org.bukkit.Material.OBSIDIAN;
import static org.bukkit.Material.PACKED_ICE;
import static org.bukkit.Material.PUMPKIN;
import static org.bukkit.Material.QUARTZ_BLOCK;
import static org.bukkit.Material.QUARTZ_ORE;
import static org.bukkit.Material.QUARTZ_STAIRS;
import static org.bukkit.Material.REDSTONE_BLOCK;
import static org.bukkit.Material.SAND;
import static org.bukkit.Material.SANDSTONE;
import static org.bukkit.Material.SANDSTONE_STAIRS;
import static org.bukkit.Material.SMOOTH_BRICK;
import static org.bukkit.Material.SMOOTH_STAIRS;
import static org.bukkit.Material.SNOW_BLOCK;
import static org.bukkit.Material.SOUL_SAND;
import static org.bukkit.Material.SPONGE;
import static org.bukkit.Material.SPRUCE_WOOD_STAIRS;
import static org.bukkit.Material.STONE;
import static org.bukkit.Material.WOOD;
import static org.bukkit.Material.WOOD_STAIRS;
import static org.bukkit.Material.WOOL;
import static org.bukkit.Material.WORKBENCH;
import static org.bukkit.Material.getMaterial;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import static org.bukkit.Material.*;
import org.bukkit.Material;
import org.bukkit.block.Biome;
import org.bukkit.configuration.ConfigurationSection;
/**
*
@ -18,162 +100,148 @@ import static org.bukkit.Material.*;
*/
public abstract class PlotWorld {
// TODO make this configurable
// make non static and static_default_valu + add config option
@SuppressWarnings("deprecation")
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, SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK,
SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44),
getMaterial(126) }));
// TODO make this configurable
// make non static and static_default_valu + add config option
@SuppressWarnings("deprecation")
public static ArrayList<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,
SANDSTONE_STAIRS, SMOOTH_BRICK, SMOOTH_STAIRS, SNOW_BLOCK, SOUL_SAND, SPONGE, SPRUCE_WOOD_STAIRS, STONE, WOOD, WOOD_STAIRS, WORKBENCH, WOOL, getMaterial(44), getMaterial(126) }));
public boolean AUTO_MERGE;
public static boolean AUTO_MERGE_DEFAULT = false;
public boolean AUTO_MERGE;
public static boolean AUTO_MERGE_DEFAULT = false;
public boolean MOB_SPAWNING;
public static boolean MOB_SPAWNING_DEFAULT = false;
public boolean MOB_SPAWNING;
public static boolean MOB_SPAWNING_DEFAULT = false;
public Biome PLOT_BIOME;
public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST;
public Biome PLOT_BIOME;
public static Biome PLOT_BIOME_DEFAULT = Biome.FOREST;
public boolean PLOT_CHAT;
public static boolean PLOT_CHAT_DEFAULT = false;
public boolean PLOT_CHAT;
public static boolean PLOT_CHAT_DEFAULT = false;
public boolean SCHEMATIC_CLAIM_SPECIFY = false;
public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false;
public boolean SCHEMATIC_CLAIM_SPECIFY = false;
public static boolean SCHEMATIC_CLAIM_SPECIFY_DEFAULT = false;
public boolean SCHEMATIC_ON_CLAIM;
public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false;
public boolean SCHEMATIC_ON_CLAIM;
public static boolean SCHEMATIC_ON_CLAIM_DEFAULT = false;
public String SCHEMATIC_FILE;
public static String SCHEMATIC_FILE_DEFAULT = "null";
public String SCHEMATIC_FILE;
public static String SCHEMATIC_FILE_DEFAULT = "null";
public List<String> SCHEMATICS;
public static List<String> SCHEMATICS_DEFAULT = null;
public List<String> SCHEMATICS;
public static List<String> SCHEMATICS_DEFAULT = null;
public List<String> DEFAULT_FLAGS;
public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>();
public List<String> DEFAULT_FLAGS;
public static List<String> DEFAULT_FLAGS_DEFAULT = new ArrayList<String>();
public boolean USE_ECONOMY;
public static boolean USE_ECONOMY_DEFAULT = false;
public boolean USE_ECONOMY;
public static boolean USE_ECONOMY_DEFAULT = false;
public double PLOT_PRICE;
public static double PLOT_PRICE_DEFAULT = 100;
public double PLOT_PRICE;
public static double PLOT_PRICE_DEFAULT = 100;
public double MERGE_PRICE;
public static double MERGE_PRICE_DEFAULT = 100;
public double MERGE_PRICE;
public static double MERGE_PRICE_DEFAULT = 100;
public double SELL_PRICE;
public static double SELL_PRICE_DEFAULT = 75;
public double SELL_PRICE;
public static double SELL_PRICE_DEFAULT = 75;
public boolean PVP;
public static boolean PVP_DEFAULT = false;
public boolean PVP;
public static boolean PVP_DEFAULT = false;
public boolean PVE;
public static boolean PVE_DEFAULT = false;
public boolean PVE;
public static boolean PVE_DEFAULT = false;
public boolean SPAWN_EGGS;
public static boolean SPAWN_EGGS_DEFAULT = false;
public boolean SPAWN_EGGS;
public static boolean SPAWN_EGGS_DEFAULT = false;
public boolean SPAWN_CUSTOM;
public static boolean SPAWN_CUSTOM_DEFAULT = true;
public boolean SPAWN_CUSTOM;
public static boolean SPAWN_CUSTOM_DEFAULT = true;
public boolean SPAWN_BREEDING;
public static boolean SPAWN_BREEDING_DEFAULT = false;
public boolean SPAWN_BREEDING;
public static boolean SPAWN_BREEDING_DEFAULT = false;
public PlotWorld(final String worldname) {
this.worldname = worldname;
}
public PlotWorld(String worldname) {
this.worldname = worldname;
}
/**
* When a world is created, the following method will be called for each
*
@param config
*/
public void loadDefaultConfiguration(ConfigurationSection config)
{
this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome"));
this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim");
this.SCHEMATIC_FILE = config.getString("schematic.file");
this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim");
this.SCHEMATICS = config.getStringList("schematic.schematics");
this.USE_ECONOMY = config.getBoolean("economy.use");
this.PLOT_PRICE = config.getDouble("economy.prices.claim");
this.MERGE_PRICE = config.getDouble("economy.prices.merge");
this.SELL_PRICE = config.getDouble("economy.prices.sell");
this.PLOT_CHAT = config.getBoolean("chat.enabled");
this.DEFAULT_FLAGS = config.getStringList("flags.default");
this.PVP = config.getBoolean("event.pvp");
/**
* When a world is created, the following method will be called for each
*
* @param config
*/
public void loadDefaultConfiguration(final ConfigurationSection config) {
this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome"));
this.SCHEMATIC_ON_CLAIM = config.getBoolean("schematic.on_claim");
this.SCHEMATIC_FILE = config.getString("schematic.file");
this.SCHEMATIC_CLAIM_SPECIFY = config.getBoolean("schematic.specify_on_claim");
this.SCHEMATICS = config.getStringList("schematic.schematics");
this.USE_ECONOMY = config.getBoolean("economy.use");
this.PLOT_PRICE = config.getDouble("economy.prices.claim");
this.MERGE_PRICE = config.getDouble("economy.prices.merge");
this.SELL_PRICE = config.getDouble("economy.prices.sell");
this.PLOT_CHAT = config.getBoolean("chat.enabled");
this.DEFAULT_FLAGS = config.getStringList("flags.default");
this.PVP = config.getBoolean("event.pvp");
this.PVE = config.getBoolean("event.pve");
this.SPAWN_EGGS = config.getBoolean("event.spawn.egg");
this.SPAWN_CUSTOM = config.getBoolean("event.spawn.custom");
this.SPAWN_BREEDING = config.getBoolean("event.spawn.breeding");
loadConfiguration(config);
}
}
public abstract void loadConfiguration(ConfigurationSection config);
public abstract void loadConfiguration(final ConfigurationSection config);
/**
* Saving core plotworld settings
* @param config
*/
public void saveConfiguration(ConfigurationSection config)
{
HashMap<String, Object> options = new HashMap<String, Object>();
/**
* Saving core plotworld settings
*
* @param config
*/
public void saveConfiguration(final ConfigurationSection config) {
final HashMap<String, Object> options = new HashMap<String, Object>();
options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT);
options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT);
options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString());
options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT);
options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT);
options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT);
options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT);
options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT);
options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT);
options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT);
options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT);
options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT);
options.put("natural_mob_spawning", PlotWorld.MOB_SPAWNING_DEFAULT);
options.put("plot.auto_merge", PlotWorld.AUTO_MERGE_DEFAULT);
options.put("plot.biome", PlotWorld.PLOT_BIOME_DEFAULT.toString());
options.put("schematic.on_claim", PlotWorld.SCHEMATIC_ON_CLAIM_DEFAULT);
options.put("schematic.file", PlotWorld.SCHEMATIC_FILE_DEFAULT);
options.put("schematic.specify_on_claim", PlotWorld.SCHEMATIC_CLAIM_SPECIFY_DEFAULT);
options.put("schematic.schematics", PlotWorld.SCHEMATICS_DEFAULT);
options.put("economy.use", PlotWorld.USE_ECONOMY_DEFAULT);
options.put("economy.prices.claim", PlotWorld.PLOT_PRICE_DEFAULT);
options.put("economy.prices.merge", PlotWorld.MERGE_PRICE_DEFAULT);
options.put("economy.prices.sell", PlotWorld.SELL_PRICE_DEFAULT);
options.put("chat.enabled", PlotWorld.PLOT_CHAT_DEFAULT);
options.put("flags.default", PlotWorld.DEFAULT_FLAGS_DEFAULT);
options.put("event.pvp", PlotWorld.PVP_DEFAULT);
options.put("event.pve", PlotWorld.PVE_DEFAULT);
options.put("event.spawn.egg", PlotWorld.SPAWN_EGGS_DEFAULT);
options.put("event.spawn.custom", PlotWorld.SPAWN_CUSTOM_DEFAULT);
options.put("event.spawn.breeding", PlotWorld.SPAWN_BREEDING_DEFAULT);
ConfigurationNode[] settings = getSettingNodes();
final ConfigurationNode[] settings = getSettingNodes();
/*
* Saving generator specific settings
*/
for (ConfigurationNode setting : settings)
{
options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue()));
}
/*
* Saving generator specific settings
*/
for (final ConfigurationNode setting : settings) {
options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue()));
}
for (String option : options.keySet())
{
if (!config.contains(option)) {
config.set(option, options.get(option));
}
}
}
for (final String option : options.keySet()) {
if (!config.contains(option)) {
config.set(option, options.get(option));
}
}
}
public String worldname;
public String worldname;
/**
* Used for the <b>/plot setup</b> command Return null if you do not want to
* support this feature
*
* @return ConfigurationNode[]
*/
public abstract ConfigurationNode[] getSettingNodes();
/**
* Used for the <b>/plot setup</b> command Return null if you do not want to
* support this feature
*
* @return ConfigurationNode[]
*/
public abstract ConfigurationNode[] getSettingNodes();
}

View File

@ -18,70 +18,70 @@ import org.bukkit.entity.Player;
*/
public class RUtils {
public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
}
public static long getTotalRam() {
return (Runtime.getRuntime().maxMemory() / 1024) / 1024;
}
public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
}
public static long getFreeRam() {
return (Runtime.getRuntime().freeMemory() / 1024) / 1024;
}
public static long getRamPercentage() {
return (getFreeRam() / getTotalRam()) * 100;
}
public static long getRamPercentage() {
return (getFreeRam() / getTotalRam()) * 100;
}
public static String formatTime(double sec) {
double h = sec / 3600;
double m = (sec % 3600) / 60;
double s = sec % 60;
String string = C.TIME_FORMAT.s();
public static String formatTime(final double sec) {
final double h = sec / 3600;
final double m = (sec % 3600) / 60;
final double s = sec % 60;
final String string = C.TIME_FORMAT.s();
String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second");
return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h);
}
final String s_h = (int) h + " " + ((int) h != 1 ? "hours" : "hour");
final String s_m = (int) m + " " + ((int) m != 1 ? "minutes" : "minute");
final String s_s = (int) s + " " + ((int) s != 1 ? "seconds" : "second");
return string.replaceAll("%sec%", s_s).replaceAll("%min%", s_m).replaceAll("%hours%", s_h);
}
enum Direction {
SOUTH(0),
EAST(1),
NORTH(2),
WEST(3);
private int i;
enum Direction {
SOUTH(0),
EAST(1),
NORTH(2),
WEST(3);
private final int i;
Direction(int i) {
this.i = i;
}
Direction(final int i) {
this.i = i;
}
public int getInt() {
return this.i;
}
}
public int getInt() {
return this.i;
}
}
public void forceTexture(Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
}
public void forceTexture(final Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
}
public Direction getDirection(Location l) {
double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D;
int i = (int) d;
int x = d < i ? i - 1 : i;
switch (x) {
case 0:
return Direction.SOUTH;
case 1:
return Direction.EAST;
case 2:
return Direction.NORTH;
case 3:
return Direction.WEST;
default:
return null;
}
}
public Direction getDirection(final Location l) {
final double d = ((l.getYaw() * 4.0F) / 360.0F) + 0.5D;
final int i = (int) d;
final int x = d < i ? i - 1 : i;
switch (x) {
case 0:
return Direction.SOUTH;
case 1:
return Direction.EAST;
case 2:
return Direction.NORTH;
case 3:
return Direction.WEST;
default:
return null;
}
}
public boolean compareDirections(Location l1, Location l2) {
return getDirection(l1) == getDirection(l2);
}
public boolean compareDirections(final Location l1, final Location l2) {
return getDirection(l1) == getDirection(l2);
}
}

View File

@ -1,14 +1,5 @@
package com.intellectualcrafters.plot;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.jnbt.*;
import com.intellectualcrafters.plot.SchematicHandler.DataCollection;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
@ -21,263 +12,342 @@ import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.plugin.java.JavaPlugin;
import com.intellectualcrafters.jnbt.ByteArrayTag;
import com.intellectualcrafters.jnbt.CompoundTag;
import com.intellectualcrafters.jnbt.IntTag;
import com.intellectualcrafters.jnbt.ListTag;
import com.intellectualcrafters.jnbt.NBTInputStream;
import com.intellectualcrafters.jnbt.NBTOutputStream;
import com.intellectualcrafters.jnbt.ShortTag;
import com.intellectualcrafters.jnbt.StringTag;
import com.intellectualcrafters.jnbt.Tag;
/**
* Schematic Handler
*
* @author Citymonstret
* @author Empire92
*/
@SuppressWarnings({"all"})
@SuppressWarnings({ "all" })
public class SchematicHandler {
/**
* Paste a schematic
* @param location origin
* @param schematic schematic to paste
* @param plot plot to paste in
*
* @param location
* origin
* @param schematic
* schematic to paste
* @param plot
* plot to paste in
* @return true if succeeded
*/
public static boolean paste(Location location, Schematic schematic, Plot plot, int x_offset, int z_offset) {
if (schematic == null) {
PlotMain.sendConsoleSenderMessage("Schematic == null :|");
return false;
}
try {
Dimension demensions = schematic.getSchematicDimension();
public static boolean paste(final Location location, final Schematic schematic, final Plot plot, final int x_offset, final int z_offset) {
if (schematic == null) {
PlotMain.sendConsoleSenderMessage("Schematic == null :|");
return false;
}
try {
final Dimension demensions = schematic.getSchematicDimension();
int WIDTH = demensions.getX();
int LENGTH = demensions.getZ();
int HEIGHT = demensions.getY();
final int WIDTH = demensions.getX();
final int LENGTH = demensions.getZ();
final int HEIGHT = demensions.getY();
DataCollection[] blocks = schematic.getBlockCollection();
final DataCollection[] blocks = schematic.getBlockCollection();
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
final int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX() + 1, l1.getBlockZ() + 1);
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
l1 = l1.add(1, sy - 1, 1);
int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX()+1, l1.getBlockZ()+1);
final World world = location.getWorld();
l1 = l1.add(1, sy-1, 1);
World world = location.getWorld();
for (int x = 0; x < WIDTH; x++) {
for (int z = 0; z < LENGTH; z++) {
for (int y = 0; y < HEIGHT; y++) {
int index = y * WIDTH * LENGTH + z * WIDTH + x;
short id = blocks[index].getBlock();
byte data = blocks[index].getData();
Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset);
PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(block, plotblock);
}
}
int y_offset;
if (HEIGHT == location.getWorld().getMaxHeight()) {
y_offset = 0;
}
}
catch (Exception e) {
return false;
}
return true;
}
else {
y_offset = l1.getBlockY();
}
for (int x = 0; x < WIDTH; x++) {
for (int z = 0; z < LENGTH; z++) {
for (int y = 0; y < HEIGHT; y++) {
final int index = (y * WIDTH * LENGTH) + (z * WIDTH) + x;
final DataCollection block = blocks[index];
final short id = block.getBlock();
final byte data = block.getData();
// if (block.tag != null) {
// WorldEditUtils.setNBT(world, id, data, l1.getBlockX()
// + x + x_offset, y + y_offset, l1.getBlockZ() + z +
// z_offset, block.tag);
// }
// else {
final Block bukkitBlock = world.getBlockAt(l1.getBlockX() + x + x_offset, y + y_offset, l1.getBlockZ() + z + z_offset);
final PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(bukkitBlock, plotblock);
// }
}
}
}
}
catch (final Exception e) {
return false;
}
return true;
}
/**
* Get a schematic
* @param name to check
*
* @param name
* to check
* @return schematic if found, else null
*/
public static Schematic getSchematic(String name) {
{
File parent =
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if (!parent.exists()) {
parent.mkdir();
}
}
File file =
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics"
+ File.separator + name + ".schematic");
if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null;
}
public static Schematic getSchematic(final String name) {
{
final File parent = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
if (!parent.exists()) {
parent.mkdir();
}
}
final File file = new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics" + File.separator + name + ".schematic");
if (!file.exists()) {
PlotMain.sendConsoleSenderMessage(file.toString() + " doesn't exist");
return null;
}
Schematic schematic;
try {
InputStream iStream = new FileInputStream(file);
NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream));
CompoundTag tag = (CompoundTag) stream.readTag();
stream.close();
Map<String, Tag> tagMap = tag.getValue();
Schematic schematic;
try {
final InputStream iStream = new FileInputStream(file);
final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream));
final CompoundTag tag = (CompoundTag) stream.readTag();
stream.close();
final Map<String, Tag> tagMap = tag.getValue();
byte[] addId = new byte[0];
if (tagMap.containsKey("AddBlocks")) {
addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue();
}
short width = ShortTag.class.cast(tagMap.get("Width")).getValue();
short length = ShortTag.class.cast(tagMap.get("Length")).getValue();
short height = ShortTag.class.cast(tagMap.get("Height")).getValue();
byte[] addId = new byte[0];
if (tagMap.containsKey("AddBlocks")) {
addId = ByteArrayTag.class.cast(tagMap.get("AddBlocks")).getValue();
}
final short width = ShortTag.class.cast(tagMap.get("Width")).getValue();
final short length = ShortTag.class.cast(tagMap.get("Length")).getValue();
final short height = ShortTag.class.cast(tagMap.get("Height")).getValue();
byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue();
byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue();
short[] blocks = new short[b.length];
final byte[] b = ByteArrayTag.class.cast(tagMap.get("Blocks")).getValue();
final byte[] d = ByteArrayTag.class.cast(tagMap.get("Data")).getValue();
final short[] blocks = new short[b.length];
Dimension dimension = new Dimension(width, height, length);
final Dimension dimension = new Dimension(width, height, length);
for (int index = 0; index < b.length; index++) {
if ((index >> 1) >= addId.length) { // No corresponding
// AddBlocks index
blocks[index] = (short) (b[index] & 0xFF);
}
else {
if ((index & 1) == 0) {
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF));
}
else {
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF));
}
}
}
for (int index = 0; index < b.length; index++) {
if ((index >> 1) >= addId.length) { // No corresponding
// AddBlocks index
blocks[index] = (short) (b[index] & 0xFF);
}
else {
if ((index & 1) == 0) {
blocks[index] = (short) (((addId[index >> 1] & 0x0F) << 8) + (b[index] & 0xFF));
}
else {
blocks[index] = (short) (((addId[index >> 1] & 0xF0) << 4) + (b[index] & 0xFF));
}
}
}
DataCollection[] collection = new DataCollection[b.length];
final DataCollection[] collection = new DataCollection[b.length];
for (int x = 0; x < b.length; x++) {
collection[x] = new DataCollection(blocks[x], d[x]);
}
schematic = new Schematic(collection, dimension, file);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
return schematic;
}
for (int x = 0; x < b.length; x++) {
collection[x] = new DataCollection(blocks[x], d[x]);
}
// if (PlotMain.worldEdit!=null) {
// List<Tag> tileEntities = requireTag(tagMap, "TileEntities",
// ListTag.class).getValue();
//
// for (Tag blocktag : tileEntities) {
// if (!(blocktag instanceof CompoundTag)) continue;
// CompoundTag t = (CompoundTag) blocktag;
//
// int x = 0;
// int y = 0;
// int z = 0;
//
// Map<String, Tag> values = new HashMap<String, Tag>();
//
// for (Map.Entry<String, Tag> entry : t.getValue().entrySet()) {
// if (entry.getKey().equals("x")) {
// if (entry.getValue() instanceof IntTag) {
// x = ((IntTag) entry.getValue()).getValue();
// }
// } else if (entry.getKey().equals("y")) {
// if (entry.getValue() instanceof IntTag) {
// y = ((IntTag) entry.getValue()).getValue();
// }
// } else if (entry.getKey().equals("z")) {
// if (entry.getValue() instanceof IntTag) {
// z = ((IntTag) entry.getValue()).getValue();
// }
// }
//
// values.put(entry.getKey(), entry.getValue());
// }
//
// int index = y * width * length + z * height + x;
// collection[index].tag = new CompoundTag("", values);
// }
// }
schematic = new Schematic(collection, dimension, file);
}
catch (final Exception e) {
e.printStackTrace();
return null;
}
return schematic;
}
/**
* Schematic Class
*
* @author Citymonstret
*/
public static class Schematic {
private DataCollection[] blockCollection;
private Dimension schematicDimension;
private File file;
public static class Schematic {
private final DataCollection[] blockCollection;
private final Dimension schematicDimension;
private final File file;
public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) {
this.blockCollection = blockCollection;
this.schematicDimension = schematicDimension;
this.file = file;
}
public Schematic(final DataCollection[] blockCollection, final Dimension schematicDimension, final File file) {
this.blockCollection = blockCollection;
this.schematicDimension = schematicDimension;
this.file = file;
}
public File getFile() {
return this.file;
}
public File getFile() {
return this.file;
}
public Dimension getSchematicDimension() {
return this.schematicDimension;
}
public Dimension getSchematicDimension() {
return this.schematicDimension;
}
public DataCollection[] getBlockCollection() {
return this.blockCollection;
}
}
public DataCollection[] getBlockCollection() {
return this.blockCollection;
}
}
/**
* Schematic Dimensions
*
* @author Citymonstret
*/
public static class Dimension {
private int x;
private int y;
private int z;
public static class Dimension {
private final int x;
private final int y;
private final int z;
public Dimension(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
public Dimension(final int x, final int y, final int z) {
this.x = x;
this.y = y;
this.z = z;
}
public int getX() {
return this.x;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
public int getY() {
return this.y;
}
public int getZ() {
return this.z;
}
}
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) {
/**
* 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;
}
if (tag == null) {
PlotMain.sendConsoleSenderMessage("&cCannot save empty tag");
return false;
}
try {
OutputStream stream = new FileOutputStream(path);
NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream));
final OutputStream stream = new FileOutputStream(path);
final NBTOutputStream output = new NBTOutputStream(new GZIPOutputStream(stream));
output.writeTag(tag);
output.close();
stream.close();
} catch (IOException e) {
}
catch (final IOException e) {
e.printStackTrace();
return false;
}
return true;
}
}
/**
* Gets the schematic of a plot
* @param world to check
* @param id plot
* @return tag
*/
public static CompoundTag getCompoundTag(World world, PlotId id) {
/**
* Gets the schematic of a plot
*
* @param world
* to check
* @param id
* plot
* @return tag
*/
public static CompoundTag getCompoundTag(final World world, final PlotId id) {
if (!PlotMain.getPlots(world).containsKey(id)) {
return null;
// Plot is empty
}
if (!PlotMain.getPlots(world).containsKey(id)) {
return null;
// Plot is empty
}
// loading chunks
final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1);
// loading chunks
final Location pos1 = PlotHelper.getPlotBottomLoc(world, id).add(1, 0, 1);
final Location pos2 = PlotHelper.getPlotTopLoc(world, id);
int i = 0;
int j = 0;
try {
for (i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) {
for (j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) {
Chunk chunk = world.getChunkAt(i, j);
boolean result = chunk.load(false);
if (!result) {
for (i = (pos1.getBlockX() / 16) * 16; i < (16 + ((pos2.getBlockX() / 16) * 16)); i += 16) {
for (j = (pos1.getBlockZ() / 16) * 16; j < (16 + ((pos2.getBlockZ() / 16) * 16)); j += 16) {
final Chunk chunk = world.getChunkAt(i, j);
final boolean result = chunk.load(false);
if (!result) {
// Plot is not even generated
// Plot is not even generated
return null;
return null;
}
}
}
}
}
catch (Exception e) {
PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at "+(i/16)+", "+(j/16));
catch (final Exception e) {
PlotMain.sendConsoleSenderMessage("&7 - Cannot save: corrupt chunk at " + (i / 16) + ", " + (j / 16));
return null;
}
int width = pos2.getBlockX()-pos1.getBlockX()+1;
int height = 256;
int length = pos2.getBlockZ()-pos1.getBlockZ()+1;
final int width = (pos2.getBlockX() - pos1.getBlockX()) + 1;
final int height = 256;
final int length = (pos2.getBlockZ() - pos1.getBlockZ()) + 1;
HashMap<String, Tag> schematic = new HashMap<>();
final HashMap<String, Tag> schematic = new HashMap<>();
schematic.put("Width", new ShortTag("Width", (short) width));
schematic.put("Length", new ShortTag("Length", (short) length));
schematic.put("Height", new ShortTag("Height", (short) height));
@ -288,35 +358,33 @@ public class SchematicHandler {
schematic.put("WEOffsetX", new IntTag("WEOffsetX", 0));
schematic.put("WEOffsetY", new IntTag("WEOffsetY", 0));
schematic.put("WEOffsetZ", new IntTag("WEOffsetZ", 0));
byte[] blocks = new byte[width * height * length];
final byte[] blocks = new byte[width * height * length];
byte[] addBlocks = null;
byte[] blockData = new byte[width * height * length];
final byte[] blockData = new byte[width * height * length];
for (int x = 0; x < width; x++) {
for (int z = 0; z < length; z++) {
for (int y = 0; y < height; y++) {
int index = y * width * length + z * width + x;
final int index = (y * width * length) + (z * width) + x;
Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z));
final Block block = world.getBlockAt(new Location(world, pos1.getBlockX() + x, y, pos1.getBlockZ() + z));
int id2 = block.getTypeId();
final int id2 = block.getTypeId();
if (id2 > 255) {
if (addBlocks == null) {
addBlocks = new byte[(blocks.length >> 1) + 1];
}
addBlocks[index >> 1] = (byte) (((index & 1) == 0) ?
addBlocks[index >> 1] & 0xF0 | (id2 >> 8) & 0xF
: addBlocks[index >> 1] & 0xF | ((id2 >> 8) & 0xF) << 4);
addBlocks[index >> 1] = (byte) (((index & 1) == 0) ? (addBlocks[index >> 1] & 0xF0) | ((id2 >> 8) & 0xF) : (addBlocks[index >> 1] & 0xF) | (((id2 >> 8) & 0xF) << 4));
}
blocks[index] = (byte) id2;
blockData[index] = block.getData();
// We need worldedit to save tileentity data or entities
// - it uses NMS and CB internal code, which changes every update
// - it uses NMS and CB internal code, which changes every
// update
}
}
}
@ -334,51 +402,54 @@ public class SchematicHandler {
/**
* Schematic Data Collection
*
* @author Citymonstret
*/
public static class DataCollection {
private short block;
private byte data;
public static class DataCollection {
private final short block;
private final byte data;
public DataCollection(short block, byte data) {
this.block = block;
this.data = data;
}
// public CompoundTag tag;
public short getBlock() {
return this.block;
}
public DataCollection(final short block, final byte data) {
this.block = block;
this.data = data;
}
public byte getData() {
return this.data;
}
}
public short getBlock() {
return this.block;
}
public static boolean pastePart(World world, DataCollection[] blocks, Location l1, int x_offset, int z_offset, int i1, int i2, int WIDTH, int LENGTH) {
public byte getData() {
return this.data;
}
}
public static boolean pastePart(final World world, final DataCollection[] blocks, final Location l1, final int x_offset, final int z_offset, final int i1, final int i2, final int WIDTH, final int LENGTH) {
boolean result = false;
for (int i = i1; i<=i2 ;i++) {
short id = blocks[i].getBlock();
byte data = blocks[i].getData();
if (id==0) {
continue;
}
for (int i = i1; i <= i2; i++) {
final short id = blocks[i].getBlock();
final byte data = blocks[i].getData();
if (id == 0) {
continue;
}
int area = WIDTH*LENGTH;
int r = i%(area);
final int area = WIDTH * LENGTH;
final int r = i % (area);
int x = r%WIDTH;
int y = i/area;
int z = r/WIDTH;
final int x = r % WIDTH;
final int y = i / area;
final int z = r / WIDTH;
if (y>256) {
if (y > 256) {
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) {
result = true;
}

View File

@ -13,38 +13,38 @@ import com.intellectualcrafters.plot.ReflectionUtils.RefMethod;
*/
public class SetBlockFast {
private static final RefClass classBlock = getRefClass("{nms}.Block");
private static final RefClass classChunk = getRefClass("{nms}.Chunk");
private static final RefClass classWorld = getRefClass("{nms}.World");
private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private static final RefClass classBlock = getRefClass("{nms}.Block");
private static final RefClass classChunk = getRefClass("{nms}.Chunk");
private static final RefClass classWorld = getRefClass("{nms}.World");
private static final RefClass classCraftWorld = getRefClass("{cb}.CraftWorld");
private static RefMethod methodGetHandle;
private static RefMethod methodGetChunkAt;
private static RefMethod methodA;
private static RefMethod methodGetById;
private static RefMethod methodGetHandle;
private static RefMethod methodGetChunkAt;
private static RefMethod methodA;
private static RefMethod methodGetById;
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
}
public SetBlockFast() throws NoSuchMethodException {
methodGetHandle = classCraftWorld.getMethod("getHandle");
methodGetChunkAt = classWorld.getMethod("getChunkAt", int.class, int.class);
methodA = classChunk.getMethod("a", int.class, int.class, int.class, classBlock, int.class);
methodGetById = classBlock.getMethod("getById", int.class);
}
public static boolean set(org.bukkit.World world, int x, int y, int z, int blockId, byte data) throws NoSuchMethodException {
public static boolean set(final org.bukkit.World world, final int x, final int y, final int z, final int blockId, final byte data) throws NoSuchMethodException {
Object w = methodGetHandle.of(world).call();
Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
return true;
}
final Object w = methodGetHandle.of(world).call();
final Object chunk = methodGetChunkAt.of(w).call(x >> 4, z >> 4);
final Object block = methodGetById.of(null).call(blockId);
methodA.of(chunk).call(x & 0x0f, y, z & 0x0f, block, data);
return true;
}
public static void update(org.bukkit.entity.Player player) {
int distance = Bukkit.getViewDistance() + 1;
for (int cx = -distance; cx < distance; cx++) {
for (int cz = -distance; cz < distance; cz++) {
player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz);
}
}
}
public static void update(final org.bukkit.entity.Player player) {
final int distance = Bukkit.getViewDistance() + 1;
for (int cx = -distance; cx < distance; cx++) {
for (int cz = -distance; cz < distance; cz++) {
player.getWorld().refreshChunk(player.getLocation().getChunk().getX() + cx, player.getLocation().getChunk().getZ() + cz);
}
}
}
}

View File

@ -15,118 +15,116 @@ package com.intellectualcrafters.plot;
* @author Empire92
*/
public class Settings {
public static boolean TITLES = true;
public static boolean TITLES = true;
/**
* Schematic Save Path
*/
public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics";
public static String SCHEMATIC_SAVE_PATH = "/var/www/schematics";
/**
* Max allowed plots
*/
public static int MAX_PLOTS = 20;
/**
* WorldGuard region on claimed plots
*/
public static boolean WORLDGUARD = false;
/**
* metrics
*/
public static boolean METRICS = true;
/**
* plot specific resource pack
*/
public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
/**
* Kill road mobs?
*/
public static boolean KILL_ROAD_MOBS;
/**
* Default kill road mobs: true
*/
public static boolean KILL_ROAD_MOBS_DEFAULT = true;
/**
* mob pathfinding?
*/
public static boolean MOB_PATHFINDING;
/**
* Default mob pathfinding: true
*/
public static boolean MOB_PATHFINDING_DEFAULT = true;
public static int MAX_PLOTS = 20;
/**
* WorldGuard region on claimed plots
*/
public static boolean WORLDGUARD = false;
/**
* metrics
*/
public static boolean METRICS = true;
/**
* plot specific resource pack
*/
public static String PLOT_SPECIFIC_RESOURCE_PACK = "";
/**
* Kill road mobs?
*/
public static boolean KILL_ROAD_MOBS;
/**
* Default kill road mobs: true
*/
public static boolean KILL_ROAD_MOBS_DEFAULT = true;
/**
* mob pathfinding?
*/
public static boolean MOB_PATHFINDING;
/**
* Default mob pathfinding: true
*/
public static boolean MOB_PATHFINDING_DEFAULT = true;
/**
* Delete plots on ban?
*/
public static boolean DELETE_PLOTS_ON_BAN = false;
public static boolean DELETE_PLOTS_ON_BAN = false;
/**
* Verbose?
*/
public static boolean DEBUG = true;
public static boolean DEBUG = true;
/**
* Auto clear enabled
*/
public static boolean AUTO_CLEAR = false;
public static boolean AUTO_CLEAR = false;
/**
* Days until a plot gets cleared
*/
public static int AUTO_CLEAR_DAYS = 365;
public static int AUTO_CLEAR_DAYS = 365;
/**
* API Location
*/
public static String API_URL = "http://www.intellectualsites.com/minecraft.php";
public static String API_URL = "http://www.intellectualsites.com/minecraft.php";
/**
* Use the custom API
*/
public static boolean CUSTOM_API = true;
public static boolean CUSTOM_API = true;
/**
* Database settings
*
* @author Citymonstret
*/
public static class DB {
/**
* Database settings
*
* @author Citymonstret
*/
public static class DB {
/**
* MongoDB enabled?
*/
public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo
*
* @Brandon
*/
public static boolean USE_MONGO = false; /*
* TODO: Implement Mongo
* @Brandon
*/
/**
* SQLite enabled?
*/
public static boolean USE_SQLITE = false;
public static boolean USE_SQLITE = false;
/**
* MySQL Enabled?
*/
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
public static boolean USE_MYSQL = true; /* NOTE: Fixed connector */
/**
* SQLite Database name
*/
public static String SQLITE_DB = "storage";
public static String SQLITE_DB = "storage";
/**
* MySQL Host name
*/
public static String HOST_NAME = "localhost";
public static String HOST_NAME = "localhost";
/**
* MySQL Port
*/
public static String PORT = "3306";
public static String PORT = "3306";
/**
* MySQL DB
*/
public static String DATABASE = "plot_db";
public static String DATABASE = "plot_db";
/**
* MySQL User
*/
public static String USER = "root";
public static String USER = "root";
/**
* MySQL Password
*/
public static String PASSWORD = "password";
public static String PASSWORD = "password";
/**
* MySQL Prefix
*/
public static String PREFIX = "";
}
public static String PREFIX = "";
}
}

View File

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

View File

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

View File

@ -17,410 +17,399 @@ import org.bukkit.entity.Player;
*/
@SuppressWarnings("unused")
public class Title {
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
private Class<?> packetActions;
/* Chat serializer */
private Class<?> nmsChatSerializer;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
/* Title packet */
private Class<?> packetTitle;
/* Title packet actions ENUM */
private Class<?> packetActions;
/* Chat serializer */
private Class<?> nmsChatSerializer;
/* Title text and color */
private String title = "";
private ChatColor titleColor = ChatColor.WHITE;
/* Subtitle text and color */
private String subtitle = "";
private ChatColor subtitleColor = ChatColor.WHITE;
/* Title timings */
private int fadeInTime = -1;
private int stayTime = -1;
private int fadeOutTime = -1;
private boolean ticks = false;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES;
private static final Map<Class<?>, Class<?>> CORRESPONDING_TYPES;
static {
CORRESPONDING_TYPES = new HashMap<>();
}
static {
CORRESPONDING_TYPES = new HashMap<>();
}
/**
* Create a new 1.8 title
*
* @param title
* Title
*/
public Title(String title) {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title
*/
public Title(final String title) {
this.title = title;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
*/
public Title(String title, String subtitle) {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
*/
public Title(final String title, final String subtitle) {
this.title = title;
this.subtitle = subtitle;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @param fadeInTime
* Fade in time
* @param stayTime
* Stay on screen time
* @param fadeOutTime
* Fade out time
*/
public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
/**
* Create a new 1.8 title
*
* @param title
* Title text
* @param subtitle
* Subtitle text
* @param fadeInTime
* Fade in time
* @param stayTime
* Stay on screen time
* @param fadeOutTime
* Fade out time
*/
public Title(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
this.stayTime = stayTime;
this.fadeOutTime = fadeOutTime;
loadClasses();
}
/**
* Load spigot and NMS classes
*/
private void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Load spigot and NMS classes
*/
private void loadClasses() {
this.packetTitle = getClass("org.spigotmc.ProtocolInjector$PacketTitle");
this.packetActions = getClass("org.spigotmc.ProtocolInjector$PacketTitle$Action");
this.nmsChatSerializer = getNMSClass("ChatSerializer");
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(ChatColor color) {
this.titleColor = color;
}
/**
* Set the title color
*
* @param color
* Chat color
*/
public void setTitleColor(final ChatColor color) {
this.titleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(ChatColor color) {
this.subtitleColor = color;
}
/**
* Set the subtitle color
*
* @param color
* Chat color
*/
public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(int time) {
this.fadeInTime = time;
}
/**
* Set title fade in time
*
* @param time
* Time
*/
public void setFadeInTime(final int time) {
this.fadeInTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(int time) {
this.fadeOutTime = time;
}
/**
* Set title fade out time
*
* @param time
* Time
*/
public void setFadeOutTime(final int time) {
this.fadeOutTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(int time) {
this.stayTime = time;
}
/**
* Set title stay time
*
* @param time
* Time
*/
public void setStayTime(final int time) {
this.stayTime = time;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to ticks
*/
public void setTimingsToTicks() {
this.ticks = true;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Set timings to seconds
*/
public void setTimingsToSeconds() {
this.ticks = false;
}
/**
* Send the title to a player
*
* @param player
* Player
*/
public void send(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet =
this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime
* (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime
* (this.ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
/**
* Send the title to a player
*
* @param player
* Player
*/
public void send(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot() && (this.packetTitle != null)) {
// First reset previous settings
resetTitle(player);
try {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions, Integer.TYPE, Integer.TYPE, Integer.TYPE).newInstance(actions[2], this.fadeInTime * (this.ticks ? 1 : 20), this.stayTime * (this.ticks ? 1 : 20), this.fadeOutTime * (this.ticks ? 1 : 20));
// Send if set
if ((this.fadeInTime != -1) && (this.fadeOutTime != -1) && (this.stayTime != -1)) {
sendPacket.invoke(connection, packet);
}
// Send title
Object serialized =
getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\""
+ ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:"
+ this.titleColor.name().toLowerCase() + "}");
packet =
this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.subtitle.equals("")) {
// Send subtitle if present
serialized =
getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\""
+ ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:"
+ this.subtitleColor.name().toLowerCase() + "}");
packet =
this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// Send title
Object serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.title) + "\",color:" + this.titleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[0], serialized);
sendPacket.invoke(connection, packet);
if (!this.subtitle.equals("")) {
// Send subtitle if present
serialized = getMethod(this.nmsChatSerializer, "a", String.class).invoke(null, "{text:\"" + ChatColor.translateAlternateColorCodes('&', this.subtitle) + "\",color:" + this.subtitleColor.name().toLowerCase() + "}");
packet = this.packetTitle.getConstructor(this.packetActions, getNMSClass("IChatBaseComponent")).newInstance(actions[1], serialized);
sendPacket.invoke(connection, packet);
}
}
catch (final Exception e) {
e.printStackTrace();
}
}
}
/**
* Broadcast the title to all players
*/
public void broadcast() {
for (Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Broadcast the title to all players
*/
public void broadcast() {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
/**
* Clear the title
*
* @param player
* Player
*/
public void clearTitle(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Clear the title
*
* @param player
* Player
*/
public void clearTitle(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[3]);
sendPacket.invoke(connection, packet);
}
catch (final Exception e) {
e.printStackTrace();
}
}
}
/**
* Reset the title settings
*
* @param player
* Player
*/
public void resetTitle(Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object[] actions = this.packetActions.getEnumConstants();
Method sendPacket = getMethod(connection.getClass(), "sendPacket");
Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* Reset the title settings
*
* @param player
* Player
*/
public void resetTitle(final Player player) {
if ((getProtocolVersion(player) >= 47) && isSpigot()) {
try {
// Send timings first
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object[] actions = this.packetActions.getEnumConstants();
final Method sendPacket = getMethod(connection.getClass(), "sendPacket");
final Object packet = this.packetTitle.getConstructor(this.packetActions).newInstance(actions[4]);
sendPacket.invoke(connection, packet);
}
catch (final Exception e) {
e.printStackTrace();
}
}
}
/**
* Get the protocol version of the player
*
* @param player
* Player
* @return Protocol version
*/
private int getProtocolVersion(Player player) {
int version = 0;
try {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
/**
* Get the protocol version of the player
*
* @param player
* Player
* @return Protocol version
*/
private int getProtocolVersion(final Player player) {
int version = 0;
try {
final Object handle = getHandle(player);
final Object connection = getField(handle.getClass(), "playerConnection").get(handle);
final Object networkManager = getValue("networkManager", connection);
version = (Integer) getMethod("getVersion", networkManager.getClass()).invoke(networkManager);
return version;
}
catch (Exception ex) {
// ex.printStackTrace(); <-- spammy console
}
return version;
}
return version;
}
catch (final Exception ex) {
// ex.printStackTrace(); <-- spammy console
}
return version;
}
/**
* Check if running spigot
*
* @return Spigot
*/
private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot");
}
/**
* Check if running spigot
*
* @return Spigot
*/
private boolean isSpigot() {
return Bukkit.getVersion().contains("Spigot");
}
/**
* Get class by url
*
* @param namespace
* Namespace url
* @return Class
*/
private Class<?> getClass(String namespace) {
try {
return Class.forName(namespace);
}
catch (Exception e) {
return null;
}
}
/**
* Get class by url
*
* @param namespace
* Namespace url
* @return Class
*/
private Class<?> getClass(final String namespace) {
try {
return Class.forName(namespace);
}
catch (final Exception e) {
return null;
}
}
private Field getField(String name, Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name);
}
private Field getField(final String name, final Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj) throws Exception {
Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Object getValue(final String name, final Object obj) throws Exception {
final Field f = getField(name, obj.getClass());
f.setAccessible(true);
return f.get(obj);
}
private Class<?> getPrimitiveType(Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?> getPrimitiveType(final Class<?> clazz) {
return CORRESPONDING_TYPES.containsKey(clazz) ? CORRESPONDING_TYPES.get(clazz) : clazz;
}
private Class<?>[] toPrimitiveTypeArray(Class<?>[] classes) {
int a = classes != null ? classes.length : 0;
Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private Class<?>[] toPrimitiveTypeArray(final Class<?>[] classes) {
final int a = classes != null ? classes.length : 0;
final Class<?>[] types = new Class<?>[a];
for (int i = 0; i < a; i++) {
types[i] = getPrimitiveType(classes[i]);
}
return types;
}
private static boolean equalsTypeArray(Class<?>[] a, Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (!a[i].equals(o[i]) && !a[i].isAssignableFrom(o[i])) {
return false;
}
}
return true;
}
private Object getHandle(Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Object getHandle(final Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(String name, Class<?> clazz, Class<?>... paramTypes) {
Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (Method m : clazz.getMethods()) {
Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private Method getMethod(final String name, final Class<?> clazz, final Class<?>... paramTypes) {
final Class<?>[] t = toPrimitiveTypeArray(paramTypes);
for (final Method m : clazz.getMethods()) {
final Class<?>[] types = toPrimitiveTypeArray(m.getParameterTypes());
if (m.getName().equals(name) && equalsTypeArray(types, t)) {
return m;
}
}
return null;
}
private String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + ".";
}
private String getVersion() {
final String name = Bukkit.getServer().getClass().getPackage().getName();
return name.substring(name.lastIndexOf('.') + 1) + ".";
}
private Class<?> getNMSClass(String className) {
String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
}
catch (Exception e) {
e.printStackTrace();
}
return clazz;
}
private Class<?> getNMSClass(final String className) {
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
}
catch (final Exception e) {
e.printStackTrace();
}
return clazz;
}
private Field getField(Class<?> clazz, String name) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
private Field getField(final Class<?> clazz, final String name) {
try {
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private Method getMethod(final Class<?> clazz, final String name, final Class<?>... args) {
for (final Method m : clazz.getMethods()) {
if (m.getName().equals(name) && ((args.length == 0) || ClassListEqual(args, m.getParameterTypes()))) {
m.setAccessible(true);
return m;
}
}
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) {
return false;
}
for (int i = 0; i < l1.length; i++) {
if (l1[i] != l2[i]) {
equal = false;
break;
}
}
return equal;
}
}

View File

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

View File

@ -8,9 +8,9 @@
package com.intellectualcrafters.plot.api;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.commands.SubCommand;
import java.util.ArrayList;
import java.util.Set;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
@ -18,8 +18,19 @@ import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
import java.util.ArrayList;
import java.util.Set;
import com.intellectualcrafters.plot.AbstractFlag;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.commands.MainCommand;
import com.intellectualcrafters.plot.commands.SubCommand;
/**
* The plotMain api class.
@ -29,39 +40,40 @@ import java.util.Set;
@SuppressWarnings({ "unused", "javadoc" })
public class PlotAPI {
private static PlotHelper plotHelper;
private static PlayerFunctions playerFunctions;
private static FlagManager flagManager;
private static SchematicHandler schematicHandler;
private static C c;
private static PlotHelper plotHelper;
private static PlayerFunctions playerFunctions;
private static FlagManager flagManager;
private static SchematicHandler schematicHandler;
private static C c;
// Methods/fields in PlotMain class
// Methods/fields in PlotMain class
// PlotMain.checkForExpiredPlots(); #Ignore
// PlotMain.killAllEntities(); #Ignore
//
// PlotMain.createConfiguration(plotworld);
// PlotMain.getPlots(player)
// PlotMain.getPlots(world)
// PlotMain.getPlots(world, player)
// PlotMain.getWorldPlots(world)
// PlotMain.getPlotWorlds()
// PlotMain.isPlotWorld(world)
// PlotMain.removePlot(world, id, callEvent)
// PlotMain.teleportPlayer(player, from, plot)
// PlotMain.updatePlot(plot);
// PlotMain.checkForExpiredPlots(); #Ignore
// PlotMain.killAllEntities(); #Ignore
//
// PlotMain.createConfiguration(plotworld);
// PlotMain.getPlots(player)
// PlotMain.getPlots(world)
// PlotMain.getPlots(world, player)
// PlotMain.getWorldPlots(world)
// PlotMain.getPlotWorlds()
// PlotMain.isPlotWorld(world)
// PlotMain.removePlot(world, id, callEvent)
// PlotMain.teleportPlayer(player, from, plot)
// PlotMain.updatePlot(plot);
// To access plotMain stuff.
private PlotMain plotMain;
// To access plotMain stuff.
private final PlotMain plotMain;
// Reference
// Reference
/**
* Admin Permission
*/
public static final String ADMIN_PERMISSION = "plots.admin";
public static final String ADMIN_PERMISSION = "plots.admin";
/**
* Get all plots
*
* @return all plots
*/
public Set<Plot> getAllPlots() {
@ -70,21 +82,28 @@ public class PlotAPI {
/**
* Return all plots for a player
*
* @param player
* @return all plots that a player owns
*/
public Set<Plot> getPlayerPlots(Player player) {
public Set<Plot> getPlayerPlots(final Player player) {
return PlotMain.getPlots(player);
}
/**
* Add a plotoworld
* @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String, com.intellectualcrafters.plot.PlotWorld, com.intellectualcrafters.plot.PlotManager)
* @param world World Name
* @param plotWorld Plot World Object
* @param manager World Manager
*
* @see com.intellectualcrafters.plot.PlotMain#addPlotWorld(String,
* com.intellectualcrafters.plot.PlotWorld,
* com.intellectualcrafters.plot.PlotManager)
* @param world
* World Name
* @param plotWorld
* Plot World Object
* @param manager
* World Manager
*/
public void addPlotWorld(String world, PlotWorld plotWorld, PlotManager manager) {
public void addPlotWorld(final String world, final PlotWorld plotWorld, final PlotManager manager) {
PlotMain.addPlotWorld(world, plotWorld, manager);
}
@ -112,375 +131,376 @@ public class PlotAPI {
return PlotMain.storage;
}
/**
* Constructor. Insert any Plugin.
* (Optimally the plugin that is accessing the method)
* @param plugin Plugin used to access this method
*/
public PlotAPI(JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
}
/**
* Constructor. Insert any Plugin.
* (Optimally the plugin that is accessing the method)
*
* @param plugin
* Plugin used to access this method
*/
public PlotAPI(final JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
}
/**
* Get the main class for this plugin <br>
* - Contains a lot of fields and methods - not very well organized
* <br>
* Only use this if you really need it
* @return PlotMain PlotSquared Main Class
*/
public PlotMain getMain() {
return plotMain;
}
/**
* Get the main class for this plugin <br>
* - Contains a lot of fields and methods - not very well organized <br>
* Only use this if you really need it
*
* @return PlotMain PlotSquared Main Class
*/
public PlotMain getMain() {
return this.plotMain;
}
/**
* PlotHelper class contains useful methods relating to plots.
*
* @return PlotHelper
*/
public PlotHelper getPlotHelper() {
return plotHelper;
}
/**
* PlotHelper class contains useful methods relating to plots.
*
* @return PlotHelper
*/
public PlotHelper getPlotHelper() {
return plotHelper;
}
/**
* PlayerFunctions class contains useful methods relating to players - Some
* player/plot methods are here as well
*
* @return PlayerFunctions
*/
public PlayerFunctions getPlayerFunctions() {
return playerFunctions;
}
/**
* PlayerFunctions class contains useful methods relating to players - Some
* player/plot methods are here as well
*
* @return PlayerFunctions
*/
public PlayerFunctions getPlayerFunctions() {
return playerFunctions;
}
/**
* FlagManager class contains methods relating to plot flags
*
* @return FlagManager
*/
public FlagManager getFlagManager() {
return flagManager;
}
/**
* FlagManager class contains methods relating to plot flags
*
* @return FlagManager
*/
public FlagManager getFlagManager() {
return flagManager;
}
/**
* SchematicHandler class contains methods related to pasting schematics
*
* @return SchematicHandler
*/
public SchematicHandler getSchematicHandler() {
return schematicHandler;
}
/**
* SchematicHandler class contains methods related to pasting schematics
*
* @return SchematicHandler
*/
public SchematicHandler getSchematicHandler() {
return schematicHandler;
}
/**
* C class contains all the captions from the translations.yml file.
*
* @return C
*/
public C getCaptions() {
return c;
}
/**
* C class contains all the captions from the translations.yml file.
*
* @return C
*/
public C getCaptions() {
return c;
}
/**
* Get the plot manager for a world. - Most of these methods can be accessed
* through the PlotHelper
*
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(World world) {
return PlotMain.getPlotManager(world);
}
/**
* Get the plot manager for a world. - Most of these methods can be accessed
* through the PlotHelper
*
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(final World world) {
return PlotMain.getPlotManager(world);
}
/**
* Get the plot manager for a world. - Contains useful low level methods for
* plot merging, clearing, and tessellation
*
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(String world) {
return PlotMain.getPlotManager(world);
}
/**
* Get the plot manager for a world. - Contains useful low level methods for
* plot merging, clearing, and tessellation
*
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(final String world) {
return PlotMain.getPlotManager(world);
}
/**
* Get the settings for a world (settings bundled in PlotWorld class) - You
* will need to downcast for the specific settings a Generator has. e.g.
* DefaultPlotWorld class implements PlotWorld
*
* @param world
* (to get settings of)
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(World world) {
return PlotMain.getWorldSettings(world);
}
/**
* Get the settings for a world (settings bundled in PlotWorld class) - You
* will need to downcast for the specific settings a Generator has. e.g.
* DefaultPlotWorld class implements PlotWorld
*
* @param world
* (to get settings of)
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(final World world) {
return PlotMain.getWorldSettings(world);
}
/**
* Get the settings for a world (settings bundled in PlotWorld class)
*
* @param world
* (to get settings of)
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(String world) {
return PlotMain.getWorldSettings(world);
}
/**
* Get the settings for a world (settings bundled in PlotWorld class)
*
* @param world
* (to get settings of)
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(final String world) {
return PlotMain.getWorldSettings(world);
}
/**
* Send a message to a player.
*
* @param player
* @param c
* (Caption)
*/
public void sendMessage(Player player, C c) {
PlayerFunctions.sendMessage(player, c);
}
/**
* Send a message to a player.
*
* @param player
* @param c
* (Caption)
*/
public void sendMessage(final Player player, final C c) {
PlayerFunctions.sendMessage(player, c);
}
/**
* Send a message to a player. - Supports color codes
*
* @param player
* @param string
*/
public void sendMessage(Player player, String string) {
PlayerFunctions.sendMessage(player, string);
}
/**
* Send a message to a player. - Supports color codes
*
* @param player
* @param string
*/
public void sendMessage(final Player player, final String string) {
PlayerFunctions.sendMessage(player, string);
}
/**
* Send a message to the console. - Supports color codes
*
* @param msg
*/
public void sendConsoleMessage(String msg) {
PlotMain.sendConsoleSenderMessage(msg);
}
/**
* Send a message to the console. - Supports color codes
*
* @param msg
*/
public void sendConsoleMessage(final String msg) {
PlotMain.sendConsoleSenderMessage(msg);
}
/**
* Send a message to the console
*
* @param c
* (Caption)
*/
public void sendConsoleMessage(C c) {
sendConsoleMessage(c.s());
}
/**
* Send a message to the console
*
* @param c
* (Caption)
*/
public void sendConsoleMessage(final C c) {
sendConsoleMessage(c.s());
}
/**
* Register a flag for use in plots
*
* @param flag
*/
public void addFlag(AbstractFlag flag) {
FlagManager.addFlag(flag);
}
/**
* Register a flag for use in plots
*
* @param flag
*/
public void addFlag(final AbstractFlag flag) {
FlagManager.addFlag(flag);
}
/**
* get all the currently registered flags
*
* @return array of Flag[]
*/
public AbstractFlag[] getFlags() {
return FlagManager.getFlags().toArray(new AbstractFlag[0]);
}
/**
* get all the currently registered flags
*
* @return array of Flag[]
*/
public AbstractFlag[] getFlags() {
return FlagManager.getFlags().toArray(new AbstractFlag[0]);
}
/**
* Get a plot based on the ID
*
* @param world
* @param x
* @param z
* @return plot, null if ID is wrong
*/
public Plot getPlot(World world, int x, int z) {
return PlotHelper.getPlot(world, new PlotId(x, z));
}
/**
* Get a plot based on the ID
*
* @param world
* @param x
* @param z
* @return plot, null if ID is wrong
*/
public Plot getPlot(final World world, final int x, final int z) {
return PlotHelper.getPlot(world, new PlotId(x, z));
}
/**
* Get a plot based on the location
*
* @param l
* @return plot if found, otherwise it creates a temporary plot-
*/
public Plot getPlot(Location l) {
return PlotHelper.getCurrentPlot(l);
}
/**
* Get a plot based on the location
*
* @param l
* @return plot if found, otherwise it creates a temporary plot-
*/
public Plot getPlot(final Location l) {
return PlotHelper.getCurrentPlot(l);
}
/**
* Get a plot based on the player location
*
* @param player
* @return plot if found, otherwise it creates a temporary plot
*/
public Plot getPlot(Player player) {
return this.getPlot(player.getLocation());
}
/**
* Get a plot based on the player location
*
* @param player
* @return plot if found, otherwise it creates a temporary plot
*/
public Plot getPlot(final Player player) {
return this.getPlot(player.getLocation());
}
/**
* Check whether or not a player has a plot
*
* @param player
* @return true if player has a plot, false if not.
*/
public boolean hasPlot(World world, Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
}
/**
* Check whether or not a player has a plot
*
* @param player
* @return true if player has a plot, false if not.
*/
public boolean hasPlot(final World world, final Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
}
/**
* Get all plots for the player
*
* @param plr
* to search for
* @param just_owner
* should we just search for owner? Or with rights?
*/
public Plot[] getPlots(World world, Player plr, boolean just_owner) {
ArrayList<Plot> pPlots = new ArrayList<>();
for (Plot plot : PlotMain.getPlots(world).values()) {
if (just_owner) {
if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) {
pPlots.add(plot);
}
}
else {
if (plot.hasRights(plr)) {
pPlots.add(plot);
}
}
}
return (Plot[]) pPlots.toArray();
}
/**
* Get all plots for the player
*
* @param plr
* to search for
* @param just_owner
* should we just search for owner? Or with rights?
*/
public Plot[] getPlots(final World world, final Player plr, final boolean just_owner) {
final ArrayList<Plot> pPlots = new ArrayList<>();
for (final Plot plot : PlotMain.getPlots(world).values()) {
if (just_owner) {
if ((plot.owner != null) && (plot.owner == plr.getUniqueId())) {
pPlots.add(plot);
}
}
else {
if (plot.hasRights(plr)) {
pPlots.add(plot);
}
}
}
return (Plot[]) pPlots.toArray();
}
/**
* Get all plots for the world
*
* @param world
* to get plots of
* @return Plot[] - array of plot objects in world
*/
public Plot[] getPlots(World world) {
return PlotMain.getWorldPlots(world);
}
/**
* Get all plots for the world
*
* @param world
* to get plots of
* @return Plot[] - array of plot objects in world
*/
public Plot[] getPlots(final World world) {
return PlotMain.getWorldPlots(world);
}
/**
* Get all plot worlds
*
* @return World[] - array of plot worlds
*/
public String[] getPlotWorlds() {
return PlotMain.getPlotWorlds();
}
/**
* Get all plot worlds
*
* @return World[] - array of plot worlds
*/
public String[] getPlotWorlds() {
return PlotMain.getPlotWorlds();
}
/**
* Get if plot world
*
* @param world
* (to check if plot world)
* @return boolean (if plot world or not)
*/
public boolean isPlotWorld(World world) {
return PlotMain.isPlotWorld(world);
}
/**
* Get if plot world
*
* @param world
* (to check if plot world)
* @return boolean (if plot world or not)
*/
public boolean isPlotWorld(final World world) {
return PlotMain.isPlotWorld(world);
}
/**
* Get plot locations
*
* @param p
* @return [0] = bottomLc, [1] = topLoc, [2] = home
*/
public Location[] getLocations(Plot p) {
World world = Bukkit.getWorld(p.world);
return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id),
PlotHelper.getPlotHome(world, p.id) };
}
/**
* Get plot locations
*
* @param p
* @return [0] = bottomLc, [1] = topLoc, [2] = home
*/
public Location[] getLocations(final Plot p) {
final World world = Bukkit.getWorld(p.world);
return new Location[] { PlotHelper.getPlotBottomLoc(world, p.id), PlotHelper.getPlotTopLoc(world, p.id), PlotHelper.getPlotHome(world, p.id) };
}
/**
* Get home location
*
* @param p
* @return plot bottom location
*/
public Location getHomeLocation(Plot p) {
return PlotHelper.getPlotHome(p.getWorld(), p.id);
}
/**
* Get home location
*
* @param p
* @return plot bottom location
*/
public Location getHomeLocation(final Plot p) {
return PlotHelper.getPlotHome(p.getWorld(), p.id);
}
/**
* Get Bottom Location
*
* @param p
* @return plot bottom location
*/
public Location getBottomLocation(Plot p) {
World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotBottomLoc(world, p.id);
}
/**
* Get Bottom Location
*
* @param p
* @return plot bottom location
*/
public Location getBottomLocation(final Plot p) {
final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotBottomLoc(world, p.id);
}
/**
* Get Top Location
*
* @param p
* @return plot top location
*/
public Location getTopLocation(Plot p) {
World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotTopLoc(world, p.id);
}
/**
* Get Top Location
*
* @param p
* @return plot top location
*/
public Location getTopLocation(final Plot p) {
final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotTopLoc(world, p.id);
}
/**
* Check whether or not a player is in a plot
*
* @param player
* @return true if the player is in a plot, false if not-
*/
public boolean isInPlot(Player player) {
return PlayerFunctions.isInPlot(player);
}
/**
* Check whether or not a player is in a plot
*
* @param player
* @return true if the player is in a plot, false if not-
*/
public boolean isInPlot(final Player player) {
return PlayerFunctions.isInPlot(player);
}
/**
* Register a subcommand
*
* @param c
*/
public void registerCommand(SubCommand c) {
MainCommand.subCommands.add(c);
}
/**
* Register a subcommand
*
* @param c
*/
public void registerCommand(final SubCommand c) {
MainCommand.subCommands.add(c);
}
/**
* Get the plotMain class
*
* @return PlotMain Class
*/
public PlotMain getPlotMain() {
return this.plotMain;
}
/**
* Get the plotMain class
*
* @return PlotMain Class
*/
public PlotMain getPlotMain() {
return this.plotMain;
}
/**
* Get the player plot count
*
* @param player
* @return
*/
public int getPlayerPlotCount(World world, Player player) {
return PlayerFunctions.getPlayerPlotCount(world, player);
}
/**
* Get the player plot count
*
* @param player
* @return
*/
public int getPlayerPlotCount(final World world, final Player player) {
return PlayerFunctions.getPlayerPlotCount(world, player);
}
/**
* Get a players plots
*
* @param player
* @return a set containing the players plots
*/
public Set<Plot> getPlayerPlots(World world, Player player) {
return PlayerFunctions.getPlayerPlots(world, player);
}
/**
* Get a players plots
*
* @param player
* @return a set containing the players plots
*/
public Set<Plot> getPlayerPlots(final World world, final Player player) {
return PlayerFunctions.getPlayerPlots(world, player);
}
/**
* Get the allowed plot count for a player
*
* @param player
* @return the number of allowed plots
*/
public int getAllowedPlots(Player player) {
return PlayerFunctions.getAllowedPlots(player);
}
/**
* Get the allowed plot count for a player
*
* @param player
* @return the number of allowed plots
*/
public int getAllowedPlots(final Player player) {
return PlayerFunctions.getAllowedPlots(player);
}
}

View File

@ -24,126 +24,126 @@ import com.intellectualcrafters.plot.PlotWorld;
@SuppressWarnings("deprecation")
public class Auto extends SubCommand {
public Auto() {
super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true);
}
public Auto() {
super("auto", "plots.auto", "Claim the nearest plot", "auto", "a", CommandCategory.CLAIMING, true);
}
public static PlotId lastPlot = new PlotId(0,0);
public static PlotId lastPlot = new PlotId(0, 0);
// TODO auto claim a mega plot with schematic
@Override
public boolean execute(Player plr, String... args) {
World world;
int size_x = 1;
int size_z = 1;
String schematic = "";
if (PlotMain.getPlotWorlds().length == 1) {
world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]);
}
else {
if (PlotMain.isPlotWorld(plr.getWorld())) {
world = plr.getWorld();
}
else {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false;
}
}
if (args.length > 0) {
if (PlotMain.hasPermission(plr, "plots.auto.mega")) {
try {
String[] split = args[0].split(",");
size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) {
PlayerFunctions.sendMessage(plr, "&cError: size<=0");
}
if ((size_x > 4) || (size_z > 4)) {
PlayerFunctions.sendMessage(plr, "&cError: size>4");
}
if (args.length > 1) {
schematic = args[1];
}
}
catch (Exception e) {
schematic = args[0];
// PlayerFunctions.sendMessage(plr,
// "&cError: Invalid size (X,Y)");
// return false;
}
}
else {
schematic = args[0];
// PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
// return false;
}
}
if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return false;
}
PlotWorld pWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double cost = pWorld.PLOT_PRICE;
cost = (size_x * size_z) * cost;
if (cost > 0d) {
Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (!schematic.equals("")) {
if (pWorld.SCHEMATIC_CLAIM_SPECIFY) {
if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true;
}
}
}
boolean br = false;
if ((size_x == 1) && (size_z == 1)) {
while (!br) {
Plot plot = PlotHelper.getPlot(world, Auto.lastPlot);
if (plot==null || plot.owner == null) {
// TODO auto claim a mega plot with schematic
@Override
public boolean execute(final Player plr, final String... args) {
World world;
int size_x = 1;
int size_z = 1;
String schematic = "";
if (PlotMain.getPlotWorlds().length == 1) {
world = Bukkit.getWorld(PlotMain.getPlotWorlds()[0]);
}
else {
if (PlotMain.isPlotWorld(plr.getWorld())) {
world = plr.getWorld();
}
else {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT_WORLD);
return false;
}
}
if (args.length > 0) {
if (PlotMain.hasPermission(plr, "plots.auto.mega")) {
try {
final String[] split = args[0].split(",");
size_x = Integer.parseInt(split[0]);
size_z = Integer.parseInt(split[1]);
if ((size_x < 1) || (size_z < 1)) {
PlayerFunctions.sendMessage(plr, "&cError: size<=0");
}
if ((size_x > 4) || (size_z > 4)) {
PlayerFunctions.sendMessage(plr, "&cError: size>4");
}
if (args.length > 1) {
schematic = args[1];
}
}
catch (final Exception e) {
schematic = args[0];
// PlayerFunctions.sendMessage(plr,
// "&cError: Invalid size (X,Y)");
// return false;
}
}
else {
schematic = args[0];
// PlayerFunctions.sendMessage(plr, C.NO_PERMISSION);
// return false;
}
}
if (PlayerFunctions.getPlayerPlotCount(world, plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return false;
}
final PlotWorld pWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double cost = pWorld.PLOT_PRICE;
cost = (size_x * size_z) * cost;
if (cost > 0d) {
final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (!schematic.equals("")) {
if (pWorld.SCHEMATIC_CLAIM_SPECIFY) {
if (pWorld.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true;
}
}
}
boolean br = false;
if ((size_x == 1) && (size_z == 1)) {
while (!br) {
Plot plot = PlotHelper.getPlot(world, Auto.lastPlot);
if ((plot == null) || (plot.owner == null)) {
plot = PlotHelper.getPlot(world, Auto.lastPlot);
Claim.claimPlot(plr, plot, true);
br = true;
PlotWorld pw = PlotMain.getWorldSettings(world);
Plot plot2 = PlotMain.getPlots(world).get(plot.id);
if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) {
final PlotWorld pw = PlotMain.getWorldSettings(world);
final Plot plot2 = PlotMain.getPlots(world).get(plot.id);
if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS));
}
}
Auto.lastPlot = getNextPlot(Auto.lastPlot, 1);
}
}
else {
boolean claimed = true;
while (!br) {
PlotId start = getNextPlot(Auto.lastPlot, 1);
}
}
else {
final boolean claimed = true;
while (!br) {
final PlotId start = getNextPlot(Auto.lastPlot, 1);
//FIXME: Wtf is going on here?
if (claimed) {
if (PlotMain.getPlots(world).get(start) == null || PlotMain.getPlots(world).get(start).owner == null) {
Auto.lastPlot = start;
continue;
}
}
// FIXME: Wtf is going on here?
if (claimed) {
if ((PlotMain.getPlots(world).get(start) == null) || (PlotMain.getPlots(world).get(start).owner == null)) {
Auto.lastPlot = start;
continue;
}
}
PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1);
final PlotId end = new PlotId((start.x + size_x) - 1, (start.y + size_z) - 1);
if (isUnowned(world, start, end)) {
for (int i = start.x; i <= end.x; i++) {
for (int j = start.y; j <= end.y; j++) {
Plot plot = PlotHelper.getPlot(world, new PlotId(i, j));
boolean teleport = ((i == end.x) && (j == end.y));
final Plot plot = PlotHelper.getPlot(world, new PlotId(i, j));
final boolean teleport = ((i == end.x) && (j == end.y));
Claim.claimPlot(plr, plot, teleport);
}
}
@ -151,20 +151,20 @@ public class Auto extends SubCommand {
return false;
}
br = true;
PlotWorld pw = PlotMain.getWorldSettings(world);
Plot plot2 = PlotMain.getPlots(world).get(start);
if (pw.DEFAULT_FLAGS != null && pw.DEFAULT_FLAGS.size() > 0) {
final PlotWorld pw = PlotMain.getWorldSettings(world);
final Plot plot2 = PlotMain.getPlots(world).get(start);
if ((pw.DEFAULT_FLAGS != null) && (pw.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(pw.DEFAULT_FLAGS));
}
}
}
}
return true;
}
}
}
return true;
}
public static PlotId getNextPlot(PlotId id, int step) {
int absX = Math.abs(id.x);
int absY = Math.abs(id.y);
public static PlotId getNextPlot(final PlotId id, final int step) {
final int absX = Math.abs(id.x);
final int absY = Math.abs(id.y);
if (absX > absY) {
if (id.x > 0) {
return new PlotId(id.x, id.y + 1);
@ -173,7 +173,7 @@ public class Auto extends SubCommand {
return new PlotId(id.x, id.y - 1);
}
}
else if (absY > absX ){
else if (absY > absX) {
if (id.y > 0) {
return new PlotId(id.x - 1, id.y);
}
@ -182,10 +182,10 @@ public class Auto extends SubCommand {
}
}
else {
if (id.x.equals(id.y) && id.x > 0) {
if (id.x.equals(id.y) && (id.x > 0)) {
return new PlotId(id.x, id.y + step);
}
if (id.x==absX) {
if (id.x == absX) {
return new PlotId(id.x, id.y + 1);
}
if (id.y == absY) {
@ -195,18 +195,17 @@ public class Auto extends SubCommand {
}
}
public boolean isUnowned(World world, PlotId pos1, PlotId pos2) {
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
PlotId id = new PlotId(x, y);
if (PlotMain.getPlots(world).get(id) != null) {
if (PlotMain.getPlots(world).get(id).owner != null) {
return false;
}
}
}
}
return true;
}
public boolean isUnowned(final World world, final PlotId pos1, final PlotId pos2) {
for (int x = pos1.x; x <= pos2.x; x++) {
for (int y = pos1.y; y <= pos2.y; y++) {
final PlotId id = new PlotId(x, y);
if (PlotMain.getPlots(world).get(id) != null) {
if (PlotMain.getPlots(world).get(id).owner != null) {
return false;
}
}
}
}
return true;
}
}

View File

@ -8,115 +8,124 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
import com.intellectualcrafters.plot.generator.DefaultPlotWorld;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
import com.intellectualcrafters.plot.generator.DefaultPlotWorld;
/**
* @author Citymonstret
*/
public class Claim extends SubCommand {
public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true);
}
public Claim() {
super(Command.CLAIM, "Claim the current plot you're standing on.", "claim", CommandCategory.CLAIMING, true);
}
@Override
public boolean execute(Player plr, String... args) {
String schematic = "";
if (args.length >= 1) {
schematic = args[0];
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
return false;
}
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && world.USE_ECONOMY) {
double cost = world.PLOT_PRICE;
if (cost > 0d) {
Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (!schematic.equals("")) {
if (world.SCHEMATIC_CLAIM_SPECIFY) {
if (!world.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
if (!PlotMain.hasPermission(plr,"plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true;
}
}
}
boolean result = claimPlot(plr, plot, false, schematic);
if (result) {
PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED);
return false;
}
return true;
}
@Override
public boolean execute(final Player plr, final String... args) {
String schematic = "";
if (args.length >= 1) {
schematic = args[0];
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
if (PlayerFunctions.getPlayerPlotCount(plr.getWorld(), plr) >= PlayerFunctions.getAllowedPlots(plr)) {
PlayerFunctions.sendMessage(plr, C.CANT_CLAIM_MORE_PLOTS);
return true;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.PLOT_IS_CLAIMED);
return false;
}
final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && world.USE_ECONOMY) {
final double cost = world.PLOT_PRICE;
if (cost > 0d) {
final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_PLOT, "" + cost);
return true;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
if (!schematic.equals("")) {
if (world.SCHEMATIC_CLAIM_SPECIFY) {
if (!world.SCHEMATICS.contains(schematic.toLowerCase())) {
sendMessage(plr, C.SCHEMATIC_INVALID, "non-existent: " + schematic);
return true;
}
if (!PlotMain.hasPermission(plr, "plots.claim." + schematic) && !plr.hasPermission("plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_SCHEMATIC_PERMISSION, schematic);
return true;
}
}
}
final boolean result = claimPlot(plr, plot, false, schematic);
if (result) {
PlayerFunctions.sendMessage(plr, C.PLOT_NOT_CLAIMED);
return false;
}
return true;
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
return claimPlot(player, plot, teleport, "");
}
public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, "");
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) {
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED);
if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot);
}
PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) {
final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED);
if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot);
}
final PlotWorld world = PlotMain.getWorldSettings(plot.getWorld());
Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id);
final Plot plot2 = PlotMain.getPlots(player.getWorld()).get(plot.id);
if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler.Schematic sch;
if (schematic.equals("")) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
}
else {
sch = SchematicHandler.getSchematic(schematic);
if (sch == null) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
}
}
SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0);
}
if (world.DEFAULT_FLAGS != null && world.DEFAULT_FLAGS.size() > 0) {
plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS));
}
if (world.SCHEMATIC_ON_CLAIM) {
SchematicHandler.Schematic sch;
if (schematic.equals("")) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
}
else {
sch = SchematicHandler.getSchematic(schematic);
if (sch == null) {
sch = SchematicHandler.getSchematic(world.SCHEMATIC_FILE);
}
}
SchematicHandler.paste(player.getLocation(), sch, plot2, 0, 0);
}
if ((world.DEFAULT_FLAGS != null) && (world.DEFAULT_FLAGS.size() > 0)) {
plot2.settings.setFlags(FlagManager.parseFlags(world.DEFAULT_FLAGS));
}
if (world instanceof DefaultPlotWorld) {
DefaultPlotWorld pW = (DefaultPlotWorld) world;
if(pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) {
final DefaultPlotWorld pW = (DefaultPlotWorld) world;
if (pW.CLAIMED_WALL_BLOCK != pW.WALL_BLOCK) {
PlotMain.getPlotManager(plot.getWorld()).setWall(plot.getWorld(), world, plot.getId(), pW.CLAIMED_WALL_BLOCK);
}
}
}
return event.isCancelled();
}
}
return event.isCancelled();
}
}

View File

@ -20,30 +20,29 @@ import com.intellectualcrafters.plot.PlotMain;
*/
public class Clear extends SubCommand {
public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true);
public Clear() {
super(Command.CLEAR, "Clear a plot", "clear", CommandCategory.ACTIONS, true);
// TODO console clear plot at location
// TODO console clear plot at location
}
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
plot.clear(plr);
return true;
}
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
plot.clear(plr);
return true;
}
}

View File

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

View File

@ -15,15 +15,15 @@ package com.intellectualcrafters.plot.commands;
*/
public enum Command {
// TODO new commands
// (economy)
// - /plot buy
// - /plot sell <value>
// (Rating system) (ratings can be stored as the average, and number of
// ratings)
// - /plot rate <number out of 10>
// - /plot list <some parameter to list the most popular, and highest rated
// plots>
// TODO new commands
// (economy)
// - /plot buy
// - /plot sell <value>
// (Rating system) (ratings can be stored as the average, and number of
// ratings)
// - /plot rate <number out of 10>
// - /plot list <some parameter to list the most popular, and highest rated
// plots>
SWAP("swap"),
/**
*
@ -40,152 +40,152 @@ public enum Command {
/**
*
*/
TRUSTED("trusted", "trust"),
/**
*
*/
TRUSTED("trusted", "trust"),
/**
*
*/
PASTE("paste"),
CLIPBOARD("clipboard", "cboard"),
COPY("copy"),
/**
*
*/
KICK("kick", "k"),
/**
*
*/
HELPERS("helpers", "hp"),
/**
*
*/
DENIED("denied", "dn"),
/**
*
*/
CLAIM("claim", "c"),
/**
*
*/
MERGE("merge", "m"),
/**
*
*/
UNLINK("unlink", "u"),
/**
*
*/
CLEAR("clear", "clear", new CommandPermission("plots.clear")),
/**
*
*/
DELETE("delete", "d", new CommandPermission("plots.delete")),
/**
*
*/
DEBUG("debug", "database", new CommandPermission("plots.admin")),
/**
*
*/
COPY("copy"),
/**
*
*/
KICK("kick", "k"),
/**
*
*/
HELPERS("helpers", "hp"),
/**
*
*/
DENIED("denied", "dn"),
/**
*
*/
CLAIM("claim", "c"),
/**
*
*/
MERGE("merge", "m"),
/**
*
*/
UNLINK("unlink", "u"),
/**
*
*/
CLEAR("clear", "clear", new CommandPermission("plots.clear")),
/**
*
*/
DELETE("delete", "d", new CommandPermission("plots.delete")),
/**
*
*/
DEBUG("debug", "database", new CommandPermission("plots.admin")),
/**
*
*/
INTERFACE("interface", "int", new CommandPermission("plots.interface")),
/**
*
*/
HOME("home", "h"),
/**
*
*/
INFO("info", "i"),
/**
*
*/
LIST("list", "l"),
/**
*
*/
SET("set", "s"),
/**
*
*/
PURGE("purge"),
/**
*
*/
SETUP("setup"),
/**
*
*/
TP("tp", "tp");
/**
*
*/
private String command;
/**
*
*/
private String alias;
/**
*
*/
private CommandPermission permission;
HOME("home", "h"),
/**
*
*/
INFO("info", "i"),
/**
*
*/
LIST("list", "l"),
/**
*
*/
SET("set", "s"),
/**
*
*/
PURGE("purge"),
/**
*
*/
SETUP("setup"),
/**
*
*/
TP("tp", "tp");
/**
*
*/
private String command;
/**
*
*/
private String alias;
/**
*
*/
private CommandPermission permission;
/**
* @param command
*/
Command(String command) {
this.command = command;
this.alias = command;
this.permission = new CommandPermission("plots." + command);
}
/**
* @param command
*/
Command(final String command) {
this.command = command;
this.alias = command;
this.permission = new CommandPermission("plots." + command);
}
/**
* @param command
* @param permission
*/
Command(String command, CommandPermission permission) {
this.command = command;
this.permission = permission;
this.alias = command;
}
/**
* @param command
* @param permission
*/
Command(final String command, final CommandPermission permission) {
this.command = command;
this.permission = permission;
this.alias = command;
}
/**
* @param command
* @param alias
*/
Command(String command, String alias) {
this.command = command;
this.alias = alias;
this.permission = new CommandPermission("plots." + command);
}
/**
* @param command
* @param alias
*/
Command(final String command, final String alias) {
this.command = command;
this.alias = alias;
this.permission = new CommandPermission("plots." + command);
}
/**
* @param Command
* @param alias
* @param permission
*/
Command(String command, String alias, CommandPermission permission) {
this.command = command;
this.alias = alias;
this.permission = permission;
}
/**
* @param Command
* @param alias
* @param permission
*/
Command(final String command, final String alias, final CommandPermission permission) {
this.command = command;
this.alias = alias;
this.permission = permission;
}
/**
* @return
*/
public String getCommand() {
return this.command;
}
/**
* @return
*/
public String getCommand() {
return this.command;
}
/**
* @return
*/
public String getAlias() {
return this.alias;
}
/**
* @return
*/
public String getAlias() {
return this.alias;
}
/**
* @return
*/
public CommandPermission getPermission() {
return this.permission;
}
/**
* @return
*/
public CommandPermission getPermission() {
return this.permission;
}
}

View File

@ -20,23 +20,23 @@ import com.intellectualcrafters.plot.PlotMain;
*/
public class CommandPermission {
/**
*
*/
public String permission;
/**
*
*/
public String permission;
/**
* @param permission
*/
public CommandPermission(String permission) {
this.permission = permission.toLowerCase();
}
/**
* @param permission
*/
public CommandPermission(final String permission) {
this.permission = permission.toLowerCase();
}
/**
* @param player
* @return
*/
public boolean hasPermission(Player player) {
return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin");
}
/**
* @param player
* @return
*/
public boolean hasPermission(final Player player) {
return PlotMain.hasPermission(player, this.permission) || PlotMain.hasPermission(player, "plots.admin");
}
}

View File

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

View File

@ -8,44 +8,49 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotSelection;
/**
* Created by Citymonstret on 2014-08-01.
*/
public class Copy extends SubCommand {
public Copy() {
super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true);
}
public Copy() {
super(Command.COPY, "Copy a plot", "copy", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (plot.settings.isMerged()) {
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (plot.settings.isMerged()) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
assert plot != null;
int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX());
PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot);
if(PlotSelection.currentSelection.containsKey(plr.getName())) {
final int size = (PlotHelper.getPlotTopLocAbs(plr.getWorld(), plot.getId()).getBlockX() - PlotHelper.getPlotBottomLocAbs(plr.getWorld(), plot.getId()).getBlockX());
final PlotSelection selection = new PlotSelection(size, plr.getWorld(), plot);
if (PlotSelection.currentSelection.containsKey(plr.getName())) {
PlotSelection.currentSelection.remove(plr.getName());
}
PlotSelection.currentSelection.put(plr.getName(), selection);
sendMessage(plr, C.CLIPBOARD_SET);
//section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs, new PlotId(plot.getId().x + 1, plot.getId().y)));
return true;
}
// section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs,
// new PlotId(plot.getId().x + 1, plot.getId().y)));
return true;
}
}

View File

@ -31,91 +31,91 @@ import com.intellectualcrafters.plot.RUtils;
*/
public class Debug extends SubCommand {
// private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\
public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false);
{
/**
* This.
*/
}
}
// private extends SubCommand^Implements {Command, Information} from
// >>\\S.txt6\\
public Debug() {
super(Command.DEBUG, "Show debug information", "debug [msg]", CommandCategory.DEBUG, false);
{
/**
* This.
*/
}
}
@Override
public boolean execute(Player plr, String... args) {
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
StringBuilder msg = new StringBuilder();
for (C c : C.values()) {
msg.append(c.s() + "\n");
}
PlayerFunctions.sendMessage(plr, msg.toString());
return true;
}
StringBuilder information;
String header, line, section;
/**
* {$notnull || compile:: \\Debug:Captions\\}
*/
{
information = new StringBuilder();
header = C.DEUBG_HEADER.s();
line = C.DEBUG_LINE.s();
section = C.DEBUG_SECTION.s();
}
/**
* {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* lineCompiler); when finished: now = this();
* now(getter)->setter(this())->{ "string" = getter(this);
* setter(string) = getter(this->setter); } when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.| ||run test
* {this->test}|on fail(action(){return FAILED})|
*/
{
StringBuilder worlds = new StringBuilder("");
for (String world : PlotMain.getPlotWorlds()) {
worlds.append(world + " ");
}
information.append(header);
information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%"));
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%"));
information.append(getSection(section, "PlotWorld"));
information.append(getLine(line, "Plot Worlds", worlds));
information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size()));
// information.append(getLine(line, "PlotWorld Size",
// PlotHelper.getWorldFolderSize() + "MB"));
for (String worldname : PlotMain.getPlotWorlds()) {
World world = Bukkit.getWorld(worldname);
information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world)));
information.append(getLine(line, " - Entities", PlotHelper.getEntities(world)));
information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world)));
information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world)));
}
information.append(getSection(section, "RAM"));
information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB"));
information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB"));
information.append(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", C.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg"));
}
/**
* {function:: SEND_MESSAGE |local player -> plr|local string ->
* information.toString())}
*/
{
PlayerFunctions.sendMessage(plr, information.toString());
}
return true;
}
@Override
public boolean execute(final Player plr, final String... args) {
if ((args.length > 0) && args[0].equalsIgnoreCase("msg")) {
final StringBuilder msg = new StringBuilder();
for (final C c : C.values()) {
msg.append(c.s() + "\n");
}
PlayerFunctions.sendMessage(plr, msg.toString());
return true;
}
StringBuilder information;
String header, line, section;
/**
* {$notnull || compile:: \\Debug:Captions\\}
*/
{
information = new StringBuilder();
header = C.DEUBG_HEADER.s();
line = C.DEBUG_LINE.s();
section = C.DEBUG_SECTION.s();
}
/**
* {||direct:: load: debug::I>Captions::trsl} \\ if(missing)
* set(default) -> this->(){} \\ echo line->line(Compiler.cpp ->
* lineCompiler); when finished: now = this();
* now(getter)->setter(this())->{ "string" = getter(this);
* setter(string) = getter(this->setter); } when ^ finished compile;
* if(^compile failed -> |this->failed.|tests->failed.| ||run test
* {this->test}|on fail(action(){return FAILED})|
*/
{
final StringBuilder worlds = new StringBuilder("");
for (final String world : PlotMain.getPlotWorlds()) {
worlds.append(world + " ");
}
information.append(header);
information.append(getSection(section, "Lag / TPS"));
information.append(getLine(line, "Ticks Per Second", Lag.getTPS()));
information.append(getLine(line, "Lag Percentage", (int) Lag.getPercentage() + "%"));
information.append(getLine(line, "TPS Percentage", (int) Lag.getFullPercentage() + "%"));
information.append(getSection(section, "PlotWorld"));
information.append(getLine(line, "Plot Worlds", worlds));
information.append(getLine(line, "Owned Plots", PlotMain.getPlots().size()));
// information.append(getLine(line, "PlotWorld Size",
// PlotHelper.getWorldFolderSize() + "MB"));
for (final String worldname : PlotMain.getPlotWorlds()) {
final World world = Bukkit.getWorld(worldname);
information.append(getLine(line, "World: " + world + " size", PlotHelper.getWorldFolderSize(world)));
information.append(getLine(line, " - Entities", PlotHelper.getEntities(world)));
information.append(getLine(line, " - Loaded Tile Entities", PlotHelper.getTileEntities(world)));
information.append(getLine(line, " - Loaded Chunks", PlotHelper.getLoadedChunks(world)));
}
information.append(getSection(section, "RAM"));
information.append(getLine(line, "Free Ram", RUtils.getFreeRam() + "MB"));
information.append(getLine(line, "Total Ram", RUtils.getTotalRam() + "MB"));
information.append(getSection(section, "Messages"));
information.append(getLine(line, "Total Messages", C.values().length));
information.append(getLine(line, "View all captions", "/plot debug msg"));
}
/**
* {function:: SEND_MESSAGE |local player -> plr|local string ->
* information.toString())}
*/
{
PlayerFunctions.sendMessage(plr, information.toString());
}
return true;
}
private String getSection(String line, String val) {
return line.replaceAll("%val%", val) + "\n";
}
private String getSection(final String line, final String val) {
return line.replaceAll("%val%", val) + "\n";
}
private String getLine(String line, String var, Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
}
private String getLine(final String line, final String var, final Object val) {
return line.replaceAll("%var%", var).replaceAll("%val%", "" + val) + "\n";
}
}

View File

@ -11,8 +11,6 @@ package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.UUID;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
@ -31,7 +29,6 @@ import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.StringWrapper;
import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc;
@ -42,141 +39,141 @@ import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
*/
public class DebugClaimTest extends SubCommand {
public DebugClaimTest() {
super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false);
}
public DebugClaimTest() {
super(Command.DEBUGCLAIMTEST, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. Execution time may vary", "claim", CommandCategory.DEBUG, false);
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
if (args.length<3) {
PlayerFunctions.sendMessage(plr, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}");
return false;
}
World world = Bukkit.getWorld(args[0]);
if (world==null || !PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, "&cInvalid plot world!");
return false;
}
@Override
public boolean execute(final Player plr, final String... args) {
if (plr == null) {
if (args.length < 3) {
PlayerFunctions.sendMessage(plr, "If you accidentally delete your database, this command will attempt to restore all plots based on the data from the plot signs. \n\n&cMissing world arg /plot debugclaimtest {world} {PlotId min} {PlotId max}");
return false;
}
final World world = Bukkit.getWorld(args[0]);
if ((world == null) || !PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, "&cInvalid plot world!");
return false;
}
PlotId min, max;
PlotId min, max;
try {
String[] split1 = args[1].split(";");
String[] split2 = args[2].split(";");
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 (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)");
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)");
PlotManager manager = PlotMain.getPlotManager(world);
PlotWorld plotworld = PlotMain.getWorldSettings(world);
final PlotManager manager = PlotMain.getPlotManager(world);
final PlotWorld plotworld = PlotMain.getWorldSettings(world);
ArrayList<Plot> plots = new ArrayList<Plot>();
final ArrayList<Plot> plots = new ArrayList<Plot>();
for (PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) {
Plot plot = PlotHelper.getPlot(world, id);
boolean contains = PlotMain.getPlots(world).containsKey(plot.id);
for (final PlotId id : PlayerFunctions.getPlotSelectionIds(world, min, max)) {
final Plot plot = PlotHelper.getPlot(world, id);
final boolean contains = PlotMain.getPlots(world).containsKey(plot.id);
if (contains) {
PlayerFunctions.sendMessage(plr, " - &cDB Already contains: "+plot.id);
PlayerFunctions.sendMessage(plr, " - &cDB Already contains: " + plot.id);
continue;
}
Location loc = manager.getSignLoc(world, plotworld, plot);
final Location loc = manager.getSignLoc(world, plotworld, plot);
Chunk chunk = world.getChunkAt(loc);
final Chunk chunk = world.getChunkAt(loc);
if (!chunk.isLoaded()) {
boolean result = chunk.load(false);
final boolean result = chunk.load(false);
if (!result) {
continue;
}
}
Block block = world.getBlockAt(loc);
if (block!=null) {
final Block block = world.getBlockAt(loc);
if (block != null) {
if (block.getState() instanceof Sign) {
Sign sign = (Sign) block.getState();
if (sign!=null) {
final Sign sign = (Sign) block.getState();
if (sign != null) {
String line = sign.getLine(2);
if (line!=null && line.length() > 2) {
if ((line != null) && (line.length() > 2)) {
line = line.substring(2);
BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
final BiMap<StringWrapper, UUID> map = UUIDHandler.getUuidMap();
UUID uuid = (map.get(new StringWrapper(line)));
if (uuid==null) {
for (StringWrapper string : map.keySet()) {
if (uuid == null) {
for (final StringWrapper string : map.keySet()) {
if (string.value.toLowerCase().startsWith(line.toLowerCase())) {
uuid = map.get(string);
break;
}
}
}
if (uuid==null) {
if (uuid == null) {
uuid = UUIDHandler.getUUID(line);
}
if (uuid!=null) {
PlayerFunctions.sendMessage(plr, " - &aFound plot: "+plot.id+" : "+line);
if (uuid != null) {
PlayerFunctions.sendMessage(plr, " - &aFound plot: " + plot.id + " : " + line);
plot.owner = uuid;
plot.hasChanged = true;
plots.add(plot);
}
else {
PlayerFunctions.sendMessage(plr, " - &cInvalid playername: "+plot.id+" : "+line);
PlayerFunctions.sendMessage(plr, " - &cInvalid playername: " + plot.id + " : " + line);
}
}
}
}
}
}
}
if (plots.size()>0) {
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '"+plots.size()+"' plots!");
DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots);
if (plots.size() > 0) {
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '" + plots.size() + "' plots!");
DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots);
for (Plot plot : plots) {
PlotMain.updatePlot(plot);
}
for (final Plot plot : plots) {
PlotMain.updatePlot(plot);
}
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Complete!");
}
else {
PlayerFunctions.sendMessage(plr, "No plots were found for the given search.");
}
}
else {
PlayerFunctions.sendMessage(plr, "No plots were found for the given search.");
}
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
return true;
}
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
return claimPlot(player, plot, teleport, "");
}
public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, "");
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) {
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED);
if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot);
}
plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS));
}
return event.isCancelled();
}
public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport, final String schematic) {
final PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
Bukkit.getPluginManager().callEvent(event);
if (!event.isCancelled()) {
PlotHelper.createPlot(player, plot);
PlotHelper.setSign(player, plot);
PlayerFunctions.sendMessage(player, C.CLAIMED);
if (teleport) {
PlotMain.teleportPlayer(player, player.getLocation(), plot);
}
plot.settings.setFlags(FlagManager.parseFlags(PlotMain.getWorldSettings(player.getWorld()).DEFAULT_FLAGS));
}
return event.isCancelled();
}
}

View File

@ -9,63 +9,39 @@
package com.intellectualcrafters.plot.commands;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.StringWrapper;
import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
import com.worldcretornica.plotme.PlayerList;
/**
* @author Citymonstret
*/
public class DebugLoadTest extends SubCommand {
public DebugLoadTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false);
}
public DebugLoadTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the reload of all plots in the DB", "claim", CommandCategory.DEBUG, false);
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
try {
Field fPlots = PlotMain.class.getDeclaredField("plots");
fPlots.setAccessible(true);
fPlots.set(null, DBFunc.getPlots());
}
catch (Exception e) {
PlotMain.sendConsoleSenderMessage("&3===FAILED&3===");
e.printStackTrace();
PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE===");
}
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
@Override
public boolean execute(final Player plr, final String... args) {
if (plr == null) {
try {
final Field fPlots = PlotMain.class.getDeclaredField("plots");
fPlots.setAccessible(true);
fPlots.set(null, DBFunc.getPlots());
}
catch (final Exception e) {
PlotMain.sendConsoleSenderMessage("&3===FAILED&3===");
e.printStackTrace();
PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE===");
}
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
return true;
}
}
}

View File

@ -9,55 +9,34 @@
package com.intellectualcrafters.plot.commands;
import java.util.ArrayList;
import java.util.Set;
import java.util.UUID;
import net.milkbowl.vault.economy.Economy;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.block.Sign;
import org.bukkit.entity.Player;
import com.google.common.collect.BiMap;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.FlagManager;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotManager;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.SchematicHandler;
import com.intellectualcrafters.plot.StringWrapper;
import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc;
import com.intellectualcrafters.plot.events.PlayerClaimPlotEvent;
/**
* @author Citymonstret
*/
public class DebugSaveTest extends SubCommand {
public DebugSaveTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false);
}
public DebugSaveTest() {
super(Command.DEBUGCLAIMTEST, "This debug command will force the recreation of all plots in the DB", "claim", CommandCategory.DEBUG, false);
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotMain.getPlots());
DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots);
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
@Override
public boolean execute(final Player plr, final String... args) {
if (plr == null) {
final ArrayList<Plot> plots = new ArrayList<Plot>();
plots.addAll(PlotMain.getPlots());
DBFunc.createPlots(plots);
DBFunc.createAllSettingsAndHelpers(plots);
}
else {
PlayerFunctions.sendMessage(plr, "This debug command can only be executed by console as it has been deemed unsafe if abused.");
}
return true;
}
}
}

View File

@ -15,7 +15,6 @@ import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.database.DBFunc;
@ -25,46 +24,45 @@ import com.intellectualcrafters.plot.database.DBFunc;
*/
public class Delete extends SubCommand {
public Delete() {
super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true);
}
public Delete() {
super(Command.DELETE, "Delete a plot", "delete", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double c = pWorld.SELL_PRICE;
if (c > 0d) {
Economy economy = PlotMain.economy;
economy.depositPlayer(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
}
boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
if (result) {
plot.clear(plr);
DBFunc.delete(plr.getWorld().getName(), plot);
if (Math.abs(plot.id.x)<=Math.abs(Auto.lastPlot.x) && Math.abs(plot.id.y)<=Math.abs(Auto.lastPlot.y)) {
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))) && !PlotMain.hasPermission(plr, "plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
final PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
final double c = pWorld.SELL_PRICE;
if (c > 0d) {
final Economy economy = PlotMain.economy;
economy.depositPlayer(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
}
final boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
if (result) {
plot.clear(plr);
DBFunc.delete(plr.getWorld().getName(), plot);
if ((Math.abs(plot.id.x) <= Math.abs(Auto.lastPlot.x)) && (Math.abs(plot.id.y) <= Math.abs(Auto.lastPlot.y))) {
Auto.lastPlot = plot.id;
}
}
else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
}
return true;
}
}
else {
PlayerFunctions.sendMessage(plr, "Plot clearing has been denied.");
}
return true;
}
}

View File

@ -26,35 +26,35 @@ import com.intellectualcrafters.plot.events.PlayerPlotDeniedEvent;
@SuppressWarnings("deprecated")
public class Denied extends SubCommand {
public Denied() {
super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true);
}
public Denied() {
super(Command.DENIED, "Manage plot helpers", "denied {add|remove} {player}", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(Player plr, String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true;
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true;
}
if (args[0].equalsIgnoreCase("add")) {
UUID uuid;
if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone;
@Override
public boolean execute(final Player plr, final String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true;
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true;
}
if (args[0].equalsIgnoreCase("add")) {
UUID uuid;
if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone;
}
else {
uuid = UUIDHandler.getUUID(args[1]);
}
if (!plot.denied.contains(uuid)) {
}
else {
uuid = UUIDHandler.getUUID(args[1]);
}
if (!plot.denied.contains(uuid)) {
if (plot.owner == uuid) {
PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER);
return false;
@ -69,59 +69,58 @@ public class Denied extends SubCommand {
}
plot.addDenied(uuid);
DBFunc.setDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true);
final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, true);
Bukkit.getPluginManager().callEvent(event);
}
else {
PlayerFunctions.sendMessage(plr, C.ALREADY_ADDED);
return false;
}
if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) {
Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid)));
if (pl!=null && pl.id.equals(plot.id)) {
PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED);
Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation());
}
}
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
if (!uuid.equals(DBFunc.everyone) && (Bukkit.getPlayer(uuid) != null) && Bukkit.getPlayer(uuid).isOnline()) {
final Plot pl = PlayerFunctions.getCurrentPlot(Bukkit.getPlayer((uuid)));
if ((pl != null) && pl.id.equals(plot.id)) {
PlayerFunctions.sendMessage(Bukkit.getPlayer(uuid), C.YOU_BE_DENIED);
Bukkit.getPlayer(uuid).teleport(Bukkit.getPlayer(uuid).getWorld().getSpawnLocation());
}
}
PlayerFunctions.sendMessage(plr, C.DENIED_ADDED);
return true;
}
else
if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone;
if (!plot.denied.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true;
}
plot.removeDenied(uuid);
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
return true;
}
/*
* if (!hasBeenOnServer(args[1])) {
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* return true; } UUID uuid = null; if
* (Bukkit.getPlayer(args[1])!=null) { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if
* (!plot.denied.contains(uuid)) {
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* true; } if (uuid == null) { PlayerFunctions.sendMessage(plr,
* C.PLAYER_HAS_NOT_BEEN_ON); return true; }
*/
UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeDenied(uuid);
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
}
else {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true;
}
return true;
}
}
else if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) {
final UUID uuid = DBFunc.everyone;
if (!plot.denied.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true;
}
plot.removeDenied(uuid);
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
return true;
}
/*
* if (!hasBeenOnServer(args[1])) {
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* return true; } UUID uuid = null; if
* (Bukkit.getPlayer(args[1])!=null) { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if
* (!plot.denied.contains(uuid)) {
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* true; } if (uuid == null) { PlayerFunctions.sendMessage(plr,
* C.PLAYER_HAS_NOT_BEEN_ON); return true; }
*/
final UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeDenied(uuid);
DBFunc.removeDenied(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
final PlayerPlotDeniedEvent event = new PlayerPlotDeniedEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.DENIED_REMOVED);
}
else {
PlayerFunctions.sendMessage(plr, C.DENIED_NEED_ARGUMENT);
return true;
}
return true;
}
}

View File

@ -14,12 +14,12 @@ import org.bukkit.entity.Player;
* Created by Citymonstret on 2014-08-11.
*/
public class Help extends SubCommand {
public Help() {
super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false);
}
public Help() {
super("help", "", "Get this help menu", "help", "he", SubCommand.CommandCategory.INFO, false);
}
@Override
public boolean execute(Player plr, String... args) {
return false;
}
@Override
public boolean execute(final Player plr, final String... args) {
return false;
}
}

View File

@ -23,34 +23,34 @@ import com.intellectualcrafters.plot.events.PlayerPlotHelperEvent;
@SuppressWarnings("deprecation")
public class Helpers extends SubCommand {
public Helpers() {
super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true);
}
public Helpers() {
super(Command.HELPERS, "Manage plot helpers", "helpers {add|remove} {player}", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(Player plr, String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true;
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true;
}
if (args[0].equalsIgnoreCase("add")) {
UUID uuid;
if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone;
}
else {
uuid = UUIDHandler.getUUID(args[1]);
}
if (!plot.helpers.contains(uuid)) {
@Override
public boolean execute(final Player plr, final String... args) {
if (args.length < 2) {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true;
}
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot.owner == null) || !plot.hasRights(plr)) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return true;
}
if (args[0].equalsIgnoreCase("add")) {
UUID uuid;
if (args[1].equalsIgnoreCase("*")) {
uuid = DBFunc.everyone;
}
else {
uuid = UUIDHandler.getUUID(args[1]);
}
if (!plot.helpers.contains(uuid)) {
if (plot.owner == uuid) {
PlayerFunctions.sendMessage(plr, C.ALREADY_OWNER);
return false;
@ -65,7 +65,7 @@ public class Helpers extends SubCommand {
}
plot.addHelper(uuid);
DBFunc.setHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true);
final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, true);
Bukkit.getPluginManager().callEvent(event);
}
else {
@ -74,44 +74,43 @@ public class Helpers extends SubCommand {
}
PlayerFunctions.sendMessage(plr, C.HELPER_ADDED);
return true;
}
else
if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) {
UUID uuid = DBFunc.everyone;
if (!plot.helpers.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true;
}
plot.removeHelper(uuid);
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
return true;
}
/*
* if (!hasBeenOnServer(args[1])) {
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* return true; } UUID uuid = null; if
* (Bukkit.getPlayer(args[1]) != null) { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
* null) { PlayerFunctions.sendMessage(plr,
* C.PLAYER_HAS_NOT_BEEN_ON); return true; } if
* (!plot.helpers.contains(uuid)) {
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* true; }
*/
UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeHelper(uuid);
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
}
else {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true;
}
return true;
}
}
else if (args[0].equalsIgnoreCase("remove")) {
if (args[1].equalsIgnoreCase("*")) {
final UUID uuid = DBFunc.everyone;
if (!plot.helpers.contains(uuid)) {
PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED);
return true;
}
plot.removeHelper(uuid);
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
return true;
}
/*
* if (!hasBeenOnServer(args[1])) {
* PlayerFunctions.sendMessage(plr, C.PLAYER_HAS_NOT_BEEN_ON);
* return true; } UUID uuid = null; if
* (Bukkit.getPlayer(args[1]) != null) { uuid =
* Bukkit.getPlayer(args[1]).getUniqueId(); } else { uuid =
* Bukkit.getOfflinePlayer(args[1]).getUniqueId(); } if (uuid ==
* null) { PlayerFunctions.sendMessage(plr,
* C.PLAYER_HAS_NOT_BEEN_ON); return true; } if
* (!plot.helpers.contains(uuid)) {
* PlayerFunctions.sendMessage(plr, C.WAS_NOT_ADDED); return
* true; }
*/
final UUID uuid = UUIDHandler.getUUID(args[1]);
plot.removeHelper(uuid);
DBFunc.removeHelper(plr.getWorld().getName(), plot, Bukkit.getOfflinePlayer(args[1]));
final PlayerPlotHelperEvent event = new PlayerPlotHelperEvent(plr, plot, uuid, false);
Bukkit.getPluginManager().callEvent(event);
PlayerFunctions.sendMessage(plr, C.HELPER_REMOVED);
}
else {
PlayerFunctions.sendMessage(plr, C.HELPER_NEED_ARGUMENT);
return true;
}
return true;
}
}

View File

@ -20,60 +20,59 @@ import com.intellectualcrafters.plot.PlotMain;
*/
public class Home extends SubCommand {
public Home() {
super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true);
}
public Home() {
super(Command.HOME, "Go to your plot", "home {id|alias}", CommandCategory.TELEPORT, true);
}
private Plot isAlias(String a) {
for (Plot p : PlotMain.getPlots()) {
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p;
}
}
return null;
}
private Plot isAlias(final String a) {
for (final Plot p : PlotMain.getPlots()) {
if ((p.settings.getAlias().length() > 0) && p.settings.getAlias().equalsIgnoreCase(a)) {
return p;
}
}
return null;
}
@Override
public boolean execute(Player plr, String... args) {
Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]);
if (plots.length == 1) {
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]);
return true;
}
else
if (plots.length > 1) {
if (args.length < 1) {
args = new String[] { "1" };
}
int id = 0;
try {
id = Integer.parseInt(args[0]);
}
catch (Exception e) {
Plot temp;
if ((temp = isAlias(args[0])) != null) {
if (temp.hasOwner()) {
if (temp.getOwner().equals(plr.getUniqueId())) {
PlotMain.teleportPlayer(plr, plr.getLocation(), temp);
return true;
}
}
PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT);
return false;
}
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return true;
}
if ((id > (plots.length)) || (id < 1)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return false;
}
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]);
return true;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
return true;
}
}
@Override
public boolean execute(final Player plr, String... args) {
final Plot[] plots = PlotMain.getPlots(plr).toArray(new Plot[0]);
if (plots.length == 1) {
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[0]);
return true;
}
else if (plots.length > 1) {
if (args.length < 1) {
args = new String[] { "1" };
}
int id = 0;
try {
id = Integer.parseInt(args[0]);
}
catch (final Exception e) {
Plot temp;
if ((temp = isAlias(args[0])) != null) {
if (temp.hasOwner()) {
if (temp.getOwner().equals(plr.getUniqueId())) {
PlotMain.teleportPlayer(plr, plr.getLocation(), temp);
return true;
}
}
PlayerFunctions.sendMessage(plr, C.NOT_YOUR_PLOT);
return false;
}
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return true;
}
if ((id > (plots.length)) || (id < 1)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_NUMBER);
return false;
}
PlotMain.teleportPlayer(plr, plr.getLocation(), plots[id - 1]);
return true;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PLOTS);
return true;
}
}
}

View File

@ -13,109 +13,112 @@ import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.database.DBFunc;
import org.apache.commons.lang.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotComment;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.database.DBFunc;
/**
* Created by Citymonstret on 2014-08-01.
*/
public class Inbox extends SubCommand {
public Inbox() {
super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true);
}
public Inbox() {
super(Command.INBOX, "Review a the comments for a plot", "comment", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return false;
}
Integer tier = null;
UUID uuid = plr.getUniqueId();
if (PlotMain.hasPermission(plr, "plots.admin")) {
tier = 0;
}
else if (plot.owner == uuid) {
tier = 1;
}
else if (plot.helpers.contains(uuid)) {
Integer tier = null;
final UUID uuid = plr.getUniqueId();
if (PlotMain.hasPermission(plr, "plots.admin")) {
tier = 0;
}
else if (plot.owner == uuid) {
tier = 1;
}
else if (plot.helpers.contains(uuid)) {
tier = 2;
}
else if (plot.trusted.contains(uuid)) {
else if (plot.trusted.contains(uuid)) {
tier = 3;
}
else {
tier = 4;
}
else {
tier = 4;
}
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "admin":
if (tier<=0) {
tier = 0;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERM_INBOX);
return false;
}
break;
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;
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;
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;
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;
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));
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;
final String world = plr.getWorld().getName();
final int tier2 = tier;
Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() {
Bukkit.getScheduler().runTaskAsynchronously(PlotMain.getMain(), new Runnable() {
@Override
public void run() {
ArrayList<PlotComment> comments = plot.settings.getComments(tier2);
@ -125,47 +128,47 @@ public class Inbox extends SubCommand {
}
if (args.length == 2) {
String[] split = args[1].toLowerCase().split(":");
final String[] split = args[1].toLowerCase().split(":");
if (!split[0].equals("clear")) {
PlayerFunctions.sendMessage(plr, "&c/plot inbox [tier] [clear][:#]");
return;
}
if (split.length > 1) {
try {
int index = Integer.parseInt(split[1]);
PlotComment comment = comments.get(index-1);
final int index = Integer.parseInt(split[1]);
final PlotComment comment = comments.get(index - 1);
DBFunc.removeComment(world, plot, comment);
PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "1 comment");
return;
}
catch (Exception e) {
catch (final Exception e) {
PlayerFunctions.sendMessage(plr, "&cInvalid index:\n/plot inbox [tier] [clear][:#]");
return;
}
}
for (PlotComment comment : comments) {
for (final PlotComment comment : comments) {
DBFunc.removeComment(world, plot, comment);
}
PlayerFunctions.sendMessage(plr, C.COMMENT_REMOVED, "all comments in that category");
return;
}
else {
final List<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;
StringBuilder message = new StringBuilder();
final StringBuilder message = new StringBuilder();
String prefix = "";
for (PlotComment comment : comments) {
message.append(prefix + "["+count+"]&6[&c" + recipients.get(tier2) + "&6] &7"+comment.senderName+"&f: "+comment.comment);
for (final PlotComment comment : comments) {
message.append(prefix + "[" + count + "]&6[&c" + recipients.get(tier2) + "&6] &7" + comment.senderName + "&f: " + comment.comment);
prefix = "\n";
count++;
}
if (comments.size()==0) {
if (comments.size() == 0) {
message.append("&cNo messages.");
}
PlayerFunctions.sendMessage(plr, message.toString());
}
}
});
return true;
}
});
return true;
}
}

View File

@ -8,162 +8,168 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.*;
import com.intellectualcrafters.plot.database.DBFunc;
import java.util.ArrayList;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.World;
import org.bukkit.block.Biome;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.UUID;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.Plot;
import com.intellectualcrafters.plot.PlotHelper;
import com.intellectualcrafters.plot.PlotId;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.PlotWorld;
import com.intellectualcrafters.plot.UUIDHandler;
import com.intellectualcrafters.plot.database.DBFunc;
/**
* @author Citymonstret
*/
public class Info extends SubCommand {
public Info() {
super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false);
}
public Info() {
super(Command.INFO, "Display plot info", "info", CommandCategory.INFO, false);
}
@Override
public boolean execute(Player player, String... args) {
World world;
Plot plot;
if (player!=null) {
world = player.getWorld();
if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
return false;
}
plot = PlayerFunctions.getCurrentPlot(player);
}
else {
if (args.length<2) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld==null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD);
return false;
}
try {
String[] split = args[1].split(";");
PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id);
if (plot==null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID);
return false;
}
world = Bukkit.getWorld(args[0]);
if (args.length==3) {
args = new String[] {args[2]};
}
else {
args = new String[0];
}
}
catch (Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
}
boolean hasOwner = plot.hasOwner();
boolean containsEveryone;
boolean trustedEveryone;
// Wildcard player {added}
{
if (plot.helpers == null) {
containsEveryone = false;
}
else {
containsEveryone = plot.helpers.contains(DBFunc.everyone);
}
if (plot.trusted == null) {
trustedEveryone = false;
}
else {
trustedEveryone = plot.trusted.contains(DBFunc.everyone);
}
}
// Unclaimed?
if (!hasOwner && !containsEveryone && !trustedEveryone) {
PlayerFunctions.sendMessage(player, C.PLOT_INFO_UNCLAIMED, (plot.id.x + ";" + plot.id.y));
return true;
}
String owner = "none";
if (plot.owner != null) {
owner = Bukkit.getOfflinePlayer(plot.owner).getName();
}
if (owner == null) {
owner = plot.owner.toString();
}
String info = C.PLOT_INFO.s();
if (args.length==1) {
info = getCaption(args[0].toLowerCase());
if (info==null) {
PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating");
return false;
}
}
info = format(info, world, plot, player);
PlayerFunctions.sendMessage(player, info);
return true;
}
private String getCaption(String string) {
switch (string) {
case "helpers":
return C.PLOT_INFO_HELPERS.s();
case "alias":
return C.PLOT_INFO_ALIAS.s();
case "biome":
return C.PLOT_INFO_BIOME.s();
case "denied":
return C.PLOT_INFO_DENIED.s();
case "flags":
return C.PLOT_INFO_FLAGS.s();
case "id":
return C.PLOT_INFO_ID.s();
case "size":
return C.PLOT_INFO_SIZE.s();
case "trusted":
return C.PLOT_INFO_TRUSTED.s();
case "owner":
return C.PLOT_INFO_OWNER.s();
case "rating":
return C.PLOT_INFO_RATING.s();
default:
return null;
@Override
public boolean execute(final Player player, String... args) {
World world;
Plot plot;
if (player != null) {
world = player.getWorld();
if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
return false;
}
plot = PlayerFunctions.getCurrentPlot(player);
}
else {
if (args.length < 2) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld == null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_WORLD);
return false;
}
try {
final String[] split = args[1].split(";");
final PlotId id = new PlotId(Integer.parseInt(split[0]), Integer.parseInt(split[1]));
plot = PlotHelper.getPlot(Bukkit.getWorld(plotworld.worldname), id);
if (plot == null) {
PlayerFunctions.sendMessage(player, C.NOT_VALID_PLOT_ID);
return false;
}
world = Bukkit.getWorld(args[0]);
if (args.length == 3) {
args = new String[] { args[2] };
}
else {
args = new String[0];
}
}
catch (final Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
}
}
private String format(String info, World world, Plot plot, Player player) {
final boolean hasOwner = plot.hasOwner();
boolean containsEveryone;
boolean trustedEveryone;
PlotId id = plot.id;
PlotId id2 = PlayerFunctions.getTopPlot(world, plot).id;
int num = PlayerFunctions.getPlotSelectionIds(world, id, id2).size();
String alias = plot.settings.getAlias().length() > 0 ? plot.settings.getAlias() : "none";
String biome = getBiomeAt(plot).toString();
String helpers = getPlayerList(plot.helpers);
String trusted = getPlayerList(plot.trusted);
String denied = getPlayerList(plot.denied);
String rating = String.format("%.1f", DBFunc.getRatings(plot));
String flags = "&3"+ (StringUtils.join(plot.settings.getFlags(), "").length() > 0 ? StringUtils.join(plot.settings.getFlags(), "&7, &3") : "none");
boolean build = player==null ? true : plot.hasRights(player);
// 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(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) {
@ -176,7 +182,7 @@ public class Info extends SubCommand {
info = info.replaceAll("%alias%", alias);
info = info.replaceAll("%id%", id.toString());
info = info.replaceAll("%id2%", id2.toString());
info = info.replaceAll("%num%", num+"");
info = info.replaceAll("%num%", num + "");
info = info.replaceAll("%biome%", biome);
info = info.replaceAll("%owner%", owner);
info = info.replaceAll("%helpers%", helpers);
@ -184,47 +190,46 @@ public class Info extends SubCommand {
info = info.replaceAll("%denied%", denied);
info = info.replaceAll("%rating%", rating);
info = info.replaceAll("%flags%", flags);
info = info.replaceAll("%build%", build+"");
info = info.replaceAll("%build%", build + "");
info = info.replaceAll("%desc%", "No description set.");
return info;
}
}
private String getPlayerList(ArrayList<UUID> l) {
if ((l == null) || (l.size() < 1)) {
return " none";
}
String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
}
else {
list.append(c.replace("%user%", getPlayerName(l.get(x))));
}
}
return list.toString();
}
private String getPlayerList(final ArrayList<UUID> l) {
if ((l == null) || (l.size() < 1)) {
return " none";
}
final String c = C.PLOT_USER_LIST.s();
final StringBuilder list = new StringBuilder();
for (int x = 0; x < l.size(); x++) {
if ((x + 1) == l.size()) {
list.append(c.replace("%user%", getPlayerName(l.get(x))).replace(",", ""));
}
else {
list.append(c.replace("%user%", getPlayerName(l.get(x))));
}
}
return list.toString();
}
private String getPlayerName(UUID uuid) {
if (uuid == null) {
return "unknown";
}
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
return "everyone";
}
/*
* OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName()
* == null) { return "unknown"; } return plr.getName();
*/
return UUIDHandler.getName(uuid);
}
private String getPlayerName(final UUID uuid) {
if (uuid == null) {
return "unknown";
}
if (uuid.equals(DBFunc.everyone) || uuid.toString().equalsIgnoreCase(DBFunc.everyone.toString())) {
return "everyone";
}
/*
* OfflinePlayer plr = Bukkit.getOfflinePlayer(uuid); if (plr.getName()
* == null) { return "unknown"; } return plr.getName();
*/
return UUIDHandler.getName(uuid);
}
private Biome getBiomeAt(Plot plot) {
World w = Bukkit.getWorld(plot.world);
Location bl = PlotHelper.getPlotTopLoc(w, plot.id);
return bl.getBlock().getBiome();
}
private Biome getBiomeAt(final Plot plot) {
final World w = Bukkit.getWorld(plot.world);
final Location bl = PlotHelper.getPlotTopLoc(w, plot.id);
return bl.getBlock().getBiome();
}
}

View File

@ -19,42 +19,41 @@ import org.bukkit.inventory.meta.ItemMeta;
public class Inventory extends SubCommand {
public Inventory() {
super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true);
}
public Inventory() {
super("inventory", "plots.inventory", "Open a command inventory", "inventory", "inv", CommandCategory.INFO, true);
}
@Override
public boolean execute(final Player plr, String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) {
if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd);
}
}
int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for (SubCommand cmd : cmds) {
inventory.addItem(getItem(cmd));
}
plr.openInventory(inventory);
return true;
}
@Override
public boolean execute(final Player plr, final String... args) {
final ArrayList<SubCommand> cmds = new ArrayList<>();
for (final SubCommand cmd : MainCommand.subCommands) {
if (cmd.permission.hasPermission(plr)) {
cmds.add(cmd);
}
}
final int size = 9 * (int) Math.ceil(cmds.size() / 9.0);
final org.bukkit.inventory.Inventory inventory = Bukkit.createInventory(null, size, "PlotSquared Commands");
for (final SubCommand cmd : cmds) {
inventory.addItem(getItem(cmd));
}
plr.openInventory(inventory);
return true;
}
private ItemStack getItem(final SubCommand cmd) {
ItemStack stack = new ItemStack(Material.COMMAND);
ItemMeta meta = stack.getItemMeta();
{
meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias
+ ChatColor.DARK_GRAY + "]");
meta.setLore(new ArrayList<String>() {
{
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
}
});
}
stack.setItemMeta(meta);
return stack;
}
private ItemStack getItem(final SubCommand cmd) {
final ItemStack stack = new ItemStack(Material.COMMAND);
final ItemMeta meta = stack.getItemMeta();
{
meta.setDisplayName(ChatColor.GREEN + cmd.cmd + ChatColor.DARK_GRAY + " [" + ChatColor.GREEN + cmd.alias + ChatColor.DARK_GRAY + "]");
meta.setLore(new ArrayList<String>() {
{
add(ChatColor.RED + "Category: " + ChatColor.GOLD + cmd.category.toString());
add(ChatColor.RED + "Description: " + ChatColor.GOLD + cmd.description);
add(ChatColor.RED + "Usage: " + ChatColor.GOLD + "/plot " + cmd.usage);
}
});
}
stack.setItemMeta(meta);
return stack;
}
}

View File

@ -21,38 +21,35 @@ import com.intellectualcrafters.plot.PlotMain;
*/
public class Kick extends SubCommand {
public Kick() {
super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true);
}
public Kick() {
super(Command.KICK, "Kick a player from your plot", "kick", CommandCategory.ACTIONS, true);
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (args.length != 1) {
PlayerFunctions.sendMessage(plr, "&c/plot kick <player>");
return false;
}
if (Bukkit.getPlayer(args[0]) == null) {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false;
}
Player player = Bukkit.getPlayer(args[0]);
if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player)
|| (PlayerFunctions.getCurrentPlot(player) == null)
|| !PlayerFunctions.getCurrentPlot(player).equals(plot)) {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false;
}
player.teleport(player.getWorld().getSpawnLocation());
return true;
}
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, "You're not in a plot.");
return false;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (args.length != 1) {
PlayerFunctions.sendMessage(plr, "&c/plot kick <player>");
return false;
}
if (Bukkit.getPlayer(args[0]) == null) {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false;
}
final Player player = Bukkit.getPlayer(args[0]);
if (!player.getWorld().equals(plr.getWorld()) || !PlayerFunctions.isInPlot(player) || (PlayerFunctions.getCurrentPlot(player) == null) || !PlayerFunctions.getCurrentPlot(player).equals(plot)) {
PlayerFunctions.sendMessage(plr, C.INVALID_PLAYER.s().replaceAll("%player%", args[0]));
return false;
}
player.teleport(player.getWorld().getSpawnLocation());
return true;
}
}

View File

@ -8,10 +8,9 @@
package com.intellectualcrafters.plot.commands;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.StringComparsion;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
@ -21,9 +20,10 @@ import org.bukkit.command.TabCompleter;
import org.bukkit.entity.Player;
import org.bukkit.util.ChatPaginator;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.intellectualcrafters.plot.C;
import com.intellectualcrafters.plot.PlayerFunctions;
import com.intellectualcrafters.plot.PlotMain;
import com.intellectualcrafters.plot.StringComparsion;
/**
* PlotMain command class
@ -32,173 +32,170 @@ import java.util.List;
*/
public class MainCommand implements CommandExecutor, TabCompleter {
private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Paste(), new Copy(), new Clipboard(), new Auto(), new Home(), new Visit(),
new TP(), new Set(), new Clear(), new Delete(), new SetOwner(), new Denied(), new Helpers(), new Trusted(),
new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Purge(),
new Reload(), new Merge(), new Unlink(), new Kick(), new Setup(), new DebugClaimTest(), new Inbox(), new Comment(), new Swap(), new MusicSubcommand() };
private static SubCommand[] _subCommands = new SubCommand[] { new Claim(), new Paste(), new Copy(), new Clipboard(), new Auto(), new Home(), new Visit(), new TP(), new Set(), new Clear(), new Delete(), new SetOwner(), new Denied(), new Helpers(), new Trusted(), new Info(), new list(), new Help(), new Debug(), new Schematic(), new plugin(), new Inventory(), new Purge(), new Reload(), new Merge(), new Unlink(), new Kick(), new Setup(), new DebugClaimTest(), new Inbox(), new Comment(), new Swap(), new MusicSubcommand() };
public static ArrayList<SubCommand> subCommands = new ArrayList<SubCommand>() {
{
addAll(Arrays.asList(_subCommands));
}
};
public static ArrayList<SubCommand> subCommands = new ArrayList<SubCommand>() {
{
addAll(Arrays.asList(_subCommands));
}
};
public static boolean no_permission(Player player, String permission) {
PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission);
return false;
}
public static boolean no_permission(final Player player, final String permission) {
PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission);
return false;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (sender instanceof Player) ? (Player) sender : null;
@Override
public boolean onCommand(final CommandSender sender, final Command cmd, final String commandLabel, final String[] args) {
final Player player = (sender instanceof Player) ? (Player) sender : null;
if (!PlotMain.hasPermission(player, "plots.use"))
return no_permission(player, "plots.use");
if (!PlotMain.hasPermission(player, "plots.use")) {
return no_permission(player, "plots.use");
}
if ((args.length < 1)
|| ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
if (args.length < 2) {
StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
String cat = args[1];
SubCommand.CommandCategory cato = null;
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
if (cat.equalsIgnoreCase(category.toString())) {
cato = category;
break;
}
}
if (cato == null) {
StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
StringBuilder help = new StringBuilder();
if ((args.length < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
if (args.length < 2) {
final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
final String cat = args[1];
SubCommand.CommandCategory cato = null;
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
if (cat.equalsIgnoreCase(category.toString())) {
cato = category;
break;
}
}
if (cato == null) {
final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
final StringBuilder help = new StringBuilder();
int page = 0;
boolean digit = true;
for(char c : args[2].toCharArray())
if(!Character.isDigit(c)) {
for (final char c : args[2].toCharArray()) {
if (!Character.isDigit(c)) {
digit = false;
break;
}
if(digit) {
}
if (digit) {
page = Integer.parseInt(args[2]);
if(--page < 0) page = 0;
if (--page < 0) {
page = 0;
}
}
for(String string : helpMenu(player, cato, page))
for (final String string : helpMenu(player, cato, page)) {
help.append(string).append("\n");
}
PlayerFunctions.sendMessage(player, help.toString());
return true;
}
else {
for (SubCommand command : subCommands) {
if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) {
String[] arguments = new String[args.length - 1];
PlayerFunctions.sendMessage(player, help.toString());
return true;
}
else {
for (final SubCommand command : subCommands) {
if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) {
final String[] arguments = new String[args.length - 1];
System.arraycopy(args, 1, arguments, 0, args.length - 1);
if (command.permission.hasPermission(player)) {
if (player!=null || !command.isPlayer ) {
return command.execute(player, arguments);
}
else {
PlayerFunctions.sendMessage(null, C.IS_CONSOLE);
return false;
}
}
else {
return no_permission(player, command.permission.permission.toLowerCase());
}
}
}
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND);
if (command.permission.hasPermission(player)) {
if ((player != null) || !command.isPlayer) {
return command.execute(player, arguments);
}
else {
PlayerFunctions.sendMessage(null, C.IS_CONSOLE);
return false;
}
}
else {
return no_permission(player, command.permission.permission.toLowerCase());
}
}
}
PlayerFunctions.sendMessage(player, C.NOT_VALID_SUBCOMMAND);
String[] commands = new String[subCommands.size()];
for(int x = 0; x < subCommands.size(); x++)
final String[] commands = new String[subCommands.size()];
for (int x = 0; x < subCommands.size(); x++) {
commands[x] = subCommands.get(x).cmd;
}
PlayerFunctions.sendMessage(player, C.DID_YOU_MEAN, new StringComparsion(args[0], commands).getBestMatch());
}
return false;
}
}
return false;
}
public static List<SubCommand> getCommands(SubCommand.CommandCategory category, Player player) {
List<SubCommand> cmds = new ArrayList<>();
for(SubCommand c : subCommands)
if(c.category == category && c.permission.hasPermission(player))
public static List<SubCommand> getCommands(final SubCommand.CommandCategory category, final Player player) {
final List<SubCommand> cmds = new ArrayList<>();
for (final SubCommand c : subCommands) {
if ((c.category == category) && c.permission.hasPermission(player)) {
cmds.add(c);
}
}
return cmds;
}
/*
// Current page
int page = 0;
//is a page specified? else use 0
if(args.length > 1) {
try {
page = Integer.parseInt(args[1]);
} catch(Exception e) {
page = 0;
}
}
//Get the total pages
int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size()) / 100));
if(page > totalPages)
page = totalPages;
//Only display 12!
int max = (page * 12) + 12;
if(max > PlotMain.getPlotsSorted().size())
max = PlotMain.getPlotsSorted().size();
StringBuilder string = new StringBuilder();
string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 + "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") + "\n");
Plot p;
//This might work xD
for (int x = (page * 12); x < max; x++) {
* // Current page
* int page = 0;
* //is a page specified? else use 0
* if(args.length > 1) {
* try {
* page = Integer.parseInt(args[1]);
* } catch(Exception e) {
* page = 0;
* }
* }
* //Get the total pages
* int totalPages = ((int) Math.ceil(12 * (PlotMain.getPlotsSorted().size())
* / 100));
* if(page > totalPages)
* page = totalPages;
* //Only display 12!
* int max = (page * 12) + 12;
* if(max > PlotMain.getPlotsSorted().size())
* max = PlotMain.getPlotsSorted().size();
* StringBuilder string = new StringBuilder();
* string.append(C.PLOT_LIST_HEADER_PAGED.s().replaceAll("%cur", page + 1 +
* "").replaceAll("%max", totalPages + 1 + "").replaceAll("%word%", "all") +
* "\n");
* Plot p;
* //This might work xD
* for (int x = (page * 12); x < max; x++) {
*/
public static ArrayList<String> helpMenu(Player player, final SubCommand.CommandCategory category, int page) {
List<SubCommand> commands = getCommands(category, player);
//final int totalPages = ((int) Math.ceil(12 * (commands.size()) / 100));
int perPage = 5;
int totalPages = (int) Math.ceil(commands.size() / perPage);
if(page > totalPages)
public static ArrayList<String> helpMenu(final Player player, final SubCommand.CommandCategory category, int page) {
final List<SubCommand> commands = getCommands(category, player);
// final int totalPages = ((int) Math.ceil(12 * (commands.size()) /
// 100));
final int perPage = 5;
final int totalPages = (int) Math.ceil(commands.size() / perPage);
if (page > totalPages) {
page = totalPages;
}
int max = (page * perPage) + perPage;
if(max > commands.size())
if (max > commands.size()) {
max = commands.size();
ArrayList<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()))
));
}
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()))));
SubCommand cmd;
String lines = "";
for(int x = 0; x < ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH * 0.75; x++) {
for (int x = 0; x < (ChatPaginator.GUARANTEED_NO_WRAP_CHAT_PAGE_WIDTH * 0.75); x++) {
lines += "-";
}
int start = page * perPage;
for(int x = start; x < max; x++) {
final int start = page * perPage;
for (int x = start; x < max; x++) {
cmd = subCommands.get(x);
String s = t(C.HELP_PAGE.s());
s = s.replaceAll("%alias%", cmd.alias);
@ -208,29 +205,31 @@ public class MainCommand implements CommandExecutor, TabCompleter {
help.add(s);
if(x != start && x != max - 1) {
if ((x != start) && (x != (max - 1))) {
help.add(t(C.HELP_ITEM_SEPARATOR.s().replaceAll("%lines", lines)));
}
}
if (help.size() < 2) {
help.add(t(C.NO_COMMANDS.s()));
}
return help;
}
if (help.size() < 2) {
help.add(t(C.NO_COMMANDS.s()));
}
return help;
}
private static String t(String s) {
return ChatColor.translateAlternateColorCodes('&', s);
}
private static String t(final String s) {
return ChatColor.translateAlternateColorCodes('&', s);
}
@Override
public List<String> onTabComplete(CommandSender commandSender, Command command, String s, String[] strings) {
if(!(commandSender instanceof Player)) return null;
Player player = (Player) commandSender;
public List<String> onTabComplete(final CommandSender commandSender, final Command command, final String s, final String[] strings) {
if (!(commandSender instanceof Player)) {
return null;
}
final Player player = (Player) commandSender;
if(strings.length < 1) {
if (strings.length==0 || "plots".startsWith(s)) {
return Arrays.asList(new String[] {"plots"});
if (strings.length < 1) {
if ((strings.length == 0) || "plots".startsWith(s)) {
return Arrays.asList(new String[] { "plots" });
}
}
if (strings.length > 1) {
@ -239,9 +238,9 @@ public class MainCommand implements CommandExecutor, TabCompleter {
if (!command.getLabel().equalsIgnoreCase("plots")) {
return null;
}
List<String> tabOptions = new ArrayList<String>();
String arg = strings[0].toLowerCase();
for (SubCommand cmd : subCommands) {
final List<String> tabOptions = new ArrayList<String>();
final String arg = strings[0].toLowerCase();
for (final SubCommand cmd : subCommands) {
if (cmd.permission.hasPermission(player)) {
if (cmd.cmd.startsWith(arg)) {
tabOptions.add(cmd.cmd);
@ -251,7 +250,7 @@ public class MainCommand implements CommandExecutor, TabCompleter {
}
}
}
if(tabOptions.size()>0) {
if (tabOptions.size() > 0) {
return tabOptions;
}
return null;

View File

@ -32,129 +32,123 @@ import com.intellectualcrafters.plot.events.PlotMergeEvent;
*/
public class Merge extends SubCommand {
public static String[] values = new String[] { "north", "east", "south", "west" };
public static String[] aliases = new String[] { "n", "e", "s", "w" };
public static String[] values = new String[] { "north", "east", "south", "west" };
public static String[] aliases = new String[] { "n", "e", "s", "w" };
public Merge() {
super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true);
}
public Merge() {
super(Command.MERGE, "Merge the plot you are standing on with another plot.", "merge", CommandCategory.ACTIONS, true);
}
public static String direction(float yaw) {
yaw = yaw / 90;
int i = Math.round(yaw);
switch (i) {
case -4:
case 0:
case 4:
return "SOUTH";
case -1:
case 3:
return "EAST";
case -2:
case 2:
return "NORTH";
case -3:
case 1:
return "WEST";
default:
return "";
}
}
public static String direction(float yaw) {
yaw = yaw / 90;
final int i = Math.round(yaw);
switch (i) {
case -4:
case 0:
case 4:
return "SOUTH";
case -1:
case 3:
return "EAST";
case -2:
case 2:
return "NORTH";
case -3:
case 1:
return "WEST";
default:
return "";
}
}
@Override
public boolean execute(Player plr, String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot == null) || !plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (!plot.getOwner().equals(plr.getUniqueId())) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s()
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false;
}
int direction = -1;
for (int i = 0; i < values.length; i++) {
if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) {
direction = i;
break;
}
}
if (direction == -1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s()
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false;
}
World world = plr.getWorld();
PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
ArrayList<PlotId> plots;
switch (direction) {
case 0: // north = -y
plots =
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
break;
case 1: // east = +x
plots =
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
break;
case 2: // south = +y
plots =
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
break;
case 3: // west = -x
plots =
PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
break;
default:
return false;
}
for (PlotId myid : plots) {
Plot myplot = PlotMain.getPlots(world).get(myid);
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) {
PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false;
}
}
@Override
public boolean execute(final Player plr, final String... args) {
if (!PlayerFunctions.isInPlot(plr)) {
PlayerFunctions.sendMessage(plr, C.NOT_IN_PLOT);
return true;
}
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot == null) || !plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (!plot.getOwner().equals(plr.getUniqueId())) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}
if (args.length < 1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false;
}
int direction = -1;
for (int i = 0; i < values.length; i++) {
if (args[0].equalsIgnoreCase(values[i]) || args[0].equalsIgnoreCase(aliases[i])) {
direction = i;
break;
}
}
if (direction == -1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.DIRECTION.s().replaceAll("%dir%", direction(plr.getLocation().getYaw())));
return false;
}
final World world = plr.getWorld();
final PlotId bot = PlayerFunctions.getBottomPlot(world, plot).id;
final PlotId top = PlayerFunctions.getTopPlot(world, plot).id;
ArrayList<PlotId> plots;
switch (direction) {
case 0: // north = -y
plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y - 1), new PlotId(top.x, top.y));
break;
case 1: // east = +x
plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x + 1, top.y));
break;
case 2: // south = +y
plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x, bot.y), new PlotId(top.x, top.y + 1));
break;
case 3: // west = -x
plots = PlayerFunctions.getMaxPlotSelectionIds(plr.getWorld(), new PlotId(bot.x - 1, bot.y), new PlotId(top.x, top.y));
break;
default:
return false;
}
for (final PlotId myid : plots) {
final Plot myplot = PlotMain.getPlots(world).get(myid);
if ((myplot == null) || !myplot.hasOwner() || !(myplot.getOwner().equals(plr.getUniqueId()))) {
PlayerFunctions.sendMessage(plr, C.NO_PERM_MERGE.s().replaceAll("%plot%", myid.toString()));
return false;
}
}
PlotWorld plotWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost;
if (cost > 0d) {
Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
final PlotWorld plotWorld = PlotMain.getWorldSettings(world);
if (PlotMain.useEconomy && plotWorld.USE_ECONOMY) {
double cost = plotWorld.MERGE_PRICE;
cost = plots.size() * cost;
if (cost > 0d) {
final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false;
}
economy.withdrawPlayer(plr, cost);
sendMessage(plr, C.REMOVED_BALANCE, cost + "");
}
}
PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
final PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
event.setCancelled(true);
PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled");
return false;
}
PlayerFunctions.sendMessage(plr, "&cPlots have been merged");
PlotHelper.mergePlots(world, plots);
if (PlotHelper.canSetFast) {
SetBlockFast.update(plr);
}
return true;
}
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {
event.setCancelled(true);
PlayerFunctions.sendMessage(plr, "&cMerge has been cancelled");
return false;
}
PlayerFunctions.sendMessage(plr, "&cPlots have been merged");
PlotHelper.mergePlots(world, plots);
if (PlotHelper.canSetFast) {
SetBlockFast.update(plr);
}
return true;
}
}

View File

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

View File

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

View File

@ -22,61 +22,61 @@ import com.intellectualcrafters.plot.database.DBFunc;
*/
public class Purge extends SubCommand {
public Purge() {
super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false);
}
public Purge() {
super("purge", "plots.admin", "Purge all plots for a world", "purge", "", CommandCategory.DEBUG, false);
}
@Override
public boolean execute(Player plr, String... args) {
if (args.length!=2) {
if (args.length==1) {
try {
String[] split = args[0].split(";");
String world = split[0];
PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
@Override
public boolean execute(final Player plr, final String... args) {
if (args.length != 2) {
if (args.length == 1) {
try {
final String[] split = args[0].split(";");
final String world = split[0];
final PlotId id = new PlotId(Integer.parseInt(split[1]), Integer.parseInt(split[2]));
System.out.print("VALID ID");
System.out.print("VALID ID");
if (plr!=null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false;
}
if (plr != null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false;
}
if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false;
}
PlotMain.getPlots(world).remove(id);
DBFunc.purge(world, id);
PlayerFunctions.sendMessage(plr, "&aPurge of '"+args[0]+"' was successful!");
return true;
}
catch (Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID);
}
}
PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX);
return false;
}
if (args[1].equals("-o")) {
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld == null) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false;
}
if (plr!=null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false;
}
PlotMain.removePlotWorld(args[0]);
DBFunc.purge(args[0]);
PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS));
return true;
}
else {
PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o");
return false;
}
}
if (!PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false;
}
PlotMain.getPlots(world).remove(id);
DBFunc.purge(world, id);
PlayerFunctions.sendMessage(plr, "&aPurge of '" + args[0] + "' was successful!");
return true;
}
catch (final Exception e) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_ID);
}
}
PlayerFunctions.sendMessage(plr, C.PURGE_SYNTAX);
return false;
}
if (args[1].equals("-o")) {
final PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld == null) {
PlayerFunctions.sendMessage(plr, C.NOT_VALID_PLOT_WORLD);
return false;
}
if (plr != null) {
PlayerFunctions.sendMessage(plr, (C.NOT_CONSOLE));
return false;
}
PlotMain.removePlotWorld(args[0]);
DBFunc.purge(args[0]);
PlayerFunctions.sendMessage(plr, (C.PURGE_SUCCESS));
return true;
}
else {
PlayerFunctions.sendMessage(plr, "This is a dangerous command, if you are sure, use /plot purge {world} -o");
return false;
}
}
}

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