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.
@ -18,10 +19,12 @@ public final class ListTag extends Tag {
/**
* 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,12 +1,12 @@
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.
*/
@ -18,9 +18,10 @@ public class ListTagBuilder {
/**
* 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,11 +21,13 @@ 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;

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,50 +77,54 @@ 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 {
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());
return new ByteTag(name, this.is.readByte());
case NBTConstants.TYPE_SHORT:
return new ShortTag(name, is.readShort());
return new ShortTag(name, this.is.readShort());
case NBTConstants.TYPE_INT:
return new IntTag(name, is.readInt());
return new IntTag(name, this.is.readInt());
case NBTConstants.TYPE_LONG:
return new LongTag(name, is.readLong());
return new LongTag(name, this.is.readLong());
case NBTConstants.TYPE_FLOAT:
return new FloatTag(name, is.readFloat());
return new FloatTag(name, this.is.readFloat());
case NBTConstants.TYPE_DOUBLE:
return new DoubleTag(name, is.readDouble());
return new DoubleTag(name, this.is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
int length = this.is.readInt();
byte[] bytes = new byte[length];
is.readFully(bytes);
this.is.readFully(bytes);
return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING:
length = is.readShort();
length = this.is.readShort();
bytes = new byte[length];
is.readFully(bytes);
this.is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
int childType = is.readByte();
length = is.readInt();
final int childType = this.is.readByte();
length = this.is.readInt();
List<Tag> tagList = new ArrayList<Tag>();
final List<Tag> tagList = new ArrayList<Tag>();
for (int i = 0; i < length; ++i) {
Tag tag = readTagPayload(childType, "", depth + 1);
final Tag tag = readTagPayload(childType, "", depth + 1);
if (tag instanceof EndTag) {
throw new IOException("TAG_End not permitted in a list.");
}
@ -121,22 +133,23 @@ public final class NBTInputStream implements Closeable {
return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
Map<String, Tag> tagMap = new HashMap<String, Tag>();
final Map<String, Tag> tagMap = new HashMap<String, Tag>();
while (true) {
Tag tag = readTag(depth + 1);
final Tag tag = readTag(depth + 1);
if (tag instanceof EndTag) {
break;
} else {
}
else {
tagMap.put(tag.getName(), tag);
}
}
return new CompoundTag(name, tagMap);
case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt();
int[] data = new int[length];
length = this.is.readInt();
final int[] data = new int[length];
for (int i = 0; i < length; i++) {
data[i] = is.readInt();
data[i] = this.is.readInt();
}
return new IntArrayTag(name, data);
default:
@ -146,7 +159,7 @@ public final class NBTInputStream implements Closeable {
@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,8 +73,8 @@ 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);
@ -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,86 +17,113 @@ 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;
@ -123,25 +150,27 @@ public final class NBTUtils {
case NBTConstants.TYPE_INT_ARRAY:
return IntArrayTag.class;
default:
throw new IllegalArgumentException("Invalid tag type : " + type
+ ".");
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,17 +49,21 @@ 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;
@ -71,7 +76,7 @@ public class CDL {
if (c == q) {
break;
}
if (c == 0 || c == '\n' || c == '\r') {
if ((c == 0) || (c == '\n') || (c == '\r')) {
throw x.syntaxError("Missing close quote '" + q + "'.");
}
sb.append(c);
@ -88,17 +93,18 @@ public class CDL {
/**
* 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,16 +126,19 @@ 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
*
* @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 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);
public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException {
final JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null;
}
@ -138,31 +146,32 @@ public class CDL {
* Produce a comma delimited text row from a JSONArray. Values containing
* 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.
*
* @param string
* The source string.
* @return The escaped result.
*/
public static String escape(String string) {
public static String escape(final String string) {
char c;
String s = string.trim();
int length = s.length();
StringBuilder sb = new StringBuilder(length);
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.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
public static JSONObject toJSONObject(final String string) throws JSONException {
String name;
JSONObject jo = new JSONObject();
final JSONObject jo = new JSONObject();
Object value;
JSONTokener x = new JSONTokener(string);
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
*/
@ -42,15 +43,17 @@ public class CookieList {
* To add a cookie to a cooklist,
* cookielistJSONObject.put(cookieJSONObject.getString("name"),
* cookieJSONObject.getString("value"));
* @param string A cookie list string
*
* @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 {
public static String toString(final JSONObject jo) throws JSONException {
boolean b = false;
Iterator<String> keys = jo.keys();
final Iterator<String> keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
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.
* @throws JSONException
*/
public static JSONObject toJSONObject(String string) throws JSONException {
JSONObject jo = new JSONObject();
HTTPTokener x = new HTTPTokener(string);
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
* @throws JSONException
* if the object does not contain enough
* information.
*/
public static String toString(JSONObject jo) throws JSONException {
Iterator<String> keys = jo.keys();
public static String toString(final JSONObject jo) throws JSONException {
final Iterator<String> keys = jo.keys();
String string;
StringBuilder sb = new StringBuilder();
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,7 +110,8 @@ public class JSONArray {
if (x.nextClean() == ',') {
x.back();
this.myArrayList.add(JSONObject.NULL);
} else {
}
else {
x.back();
this.myArrayList.add(x.nextValue());
}
@ -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.
*
@ -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;
}

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,18 +38,18 @@ 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
*
* @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 {
private static Object parse(final XMLTokener x, final boolean arrayForm, final JSONArray ja) throws JSONException {
String attribute;
char c;
String closeTag = null;
@ -60,11 +59,11 @@ public class JSONML {
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);
}
} else if (token == XML.QUEST) {
while (i > 0);
}
}
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 {
public static String toString(final JSONArray ja) throws JSONException {
int i;
JSONObject jo;
String key;
Iterator<String> keys;
int length;
Object object;
StringBuilder sb = new StringBuilder();
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,12 +410,14 @@ 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();
public static String toString(final JSONObject jo) throws JSONException {
final StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
String key;
@ -404,7 +427,7 @@ public class JSONML {
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,33 +8,34 @@ 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
*/
@ -45,19 +46,17 @@ public class JSONTokener {
private long index;
private long line;
private char previous;
private Reader reader;
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
*
* @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,49 +168,52 @@ 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.
* @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.
*/
public String next(int n) throws JSONException {
public String next(final int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
final char[] chars = new char[n];
int pos = 0;
while (pos < n) {
@ -222,36 +226,38 @@ public class JSONTokener {
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.
*/
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>.
*
* @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.
* @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) {
@ -278,7 +284,7 @@ public class JSONTokener {
sb.append('\r');
break;
case 'u':
sb.append((char)Integer.parseInt(this.next(4), 16));
sb.append((char) Integer.parseInt(this.next(4), 16));
break;
case '"':
case '\'':
@ -299,18 +305,19 @@ public class JSONTokener {
}
}
/**
* Get the text up but not including the specified character or the
* end of line, whichever comes first.
* @param delimiter A delimiter character.
*
* @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.
*/
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.
* @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
*/
@ -92,7 +97,7 @@ public class JSONWriter {
/**
* 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
* @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
* @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
* @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

@ -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,19 +64,22 @@ 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;");
@ -102,32 +106,37 @@ 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 {
private static boolean parse(final XMLTokener x, final JSONObject context, final String name) throws JSONException {
char c;
int i;
JSONObject jsonobject = null;
@ -135,19 +144,19 @@ public class XML {
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,41 +369,45 @@ 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.
*
* @param object
* A JSONObject.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object) throws JSONException {
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.
*
* @param object
* A JSONObject.
* @param tagName
* The optional name of the enclosing tag.
* @return A string.
* @throws JSONException
*/
public static String toString(Object object, String tagName)
throws JSONException {
StringBuilder sb = new StringBuilder();
public static String toString(Object object, final String tagName) throws JSONException {
final StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
JSONObject jo;
@ -389,7 +418,7 @@ public class XML {
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,38 +1,40 @@
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
/**
* 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;
@ -48,21 +50,25 @@ public class XMLTokener extends JSONTokener {
/**
* 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();
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
@ -93,7 +97,8 @@ public class XMLTokener extends JSONTokener {
StringBuilder sb;
do {
c = next();
} while (Character.isWhitespace(c));
}
while (Character.isWhitespace(c));
if (c == 0) {
return null;
}
@ -102,52 +107,59 @@ 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.
*
* @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.
* @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
* 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
* @throws JSONException
* If a string is not properly closed or if the XML
* is badly structured.
*/
public Object nextMeta() throws JSONException {
@ -155,7 +167,8 @@ public class XMLTokener extends JSONTokener {
char q;
do {
c = next();
} while (Character.isWhitespace(c));
}
while (Character.isWhitespace(c));
switch (c) {
case 0:
throw syntaxError("Misshaped meta tag");
@ -206,14 +219,15 @@ public class XMLTokener extends JSONTokener {
}
}
/**
* Get the next XML Token. These tokens are found inside of angle
* 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,7 +235,8 @@ 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");
@ -238,7 +253,7 @@ public class XMLTokener extends JSONTokener {
case '?':
return XML.QUEST;
// Quoted string
// Quoted string
case '"':
case '\'':
@ -254,13 +269,14 @@ public class XMLTokener extends JSONTokener {
}
if (c == '&') {
sb.append(nextEntity(c));
} else {
}
else {
sb.append(c);
}
}
default:
// Name
// Name
sb = new StringBuilder();
for (;;) {
@ -290,21 +306,23 @@ public class XMLTokener extends JSONTokener {
}
}
/**
* 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

@ -16,7 +16,7 @@ public class AbstractFlag {
* The key must be alphabetical characters and <= 16 characters
* in length
*/
public AbstractFlag(String key) {
public AbstractFlag(final String key) {
if (!StringUtils.isAlpha(key.replaceAll("_", "").replaceAll("-", ""))) {
throw new IllegalArgumentException("Flag must be alphabetic characters");
}
@ -26,7 +26,7 @@ public class AbstractFlag {
this.key = key.toLowerCase();
}
public String parseValue(String value) {
public String parseValue(final String value) {
return value;
}
@ -34,7 +34,6 @@ public class AbstractFlag {
return "Flag value must be alphanumeric";
}
/**
* AbstractFlag key
*
@ -50,11 +49,17 @@ public class AbstractFlag {
}
@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;
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,5 +1,6 @@
package com.intellectualcrafters.plot;
public class BlockWrapper {
public int x;
public int y;
@ -7,7 +8,7 @@ public class BlockWrapper {
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."),
@ -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"),
/*
@ -366,7 +363,7 @@ public enum C {
* @param d
* default
*/
C(String d) {
C(final String d) {
this.d = d;
if (PlotMain.translations == null) {
this.s = d;
@ -382,6 +379,7 @@ public enum C {
public static class Potato {
}
/**
* Get the default string
*
@ -398,9 +396,9 @@ public enum C {
* @return translated if exists else default
*/
public String s() {
if(PlotMain.translations != null){
String t = PlotMain.translations.getString(this.toString());
if (t!=null) {
if (PlotMain.translations != null) {
final String t = PlotMain.translations.getString(this.toString());
if (t != null) {
this.s = t;
}
}

View File

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

View File

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

View File

@ -3,8 +3,8 @@ 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
@ -19,13 +19,12 @@ public class Flag {
* @throws IllegalArgumentException
* if you provide inadequate inputs
*/
public Flag(AbstractFlag key, String value) {
char[] allowedCharacters = new char[] {
'[', ']', '(', ')', ',', '_', '-', '.', ',', '?', '!', '&', '§'
};
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)");
}
@ -34,7 +33,7 @@ public class Flag {
}
this.key = key;
this.value = key.parseValue(value);
if (this.value==null) {
if (this.value == null) {
throw new IllegalArgumentException(key.getValueDesc());
}
}
@ -75,7 +74,7 @@ public class Flag {
}
@Override
public boolean equals(Object obj) {
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
@ -85,7 +84,7 @@ public class Flag {
if (getClass() != obj.getClass()) {
return false;
}
Flag other = (Flag) obj;
final Flag other = (Flag) obj;
return (this.key.getKey().equals(other.key.getKey()) && this.value.equals(other.value));
}

View File

@ -1,11 +1,11 @@
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
@ -23,30 +23,32 @@ public class FlagManager {
* @param flag
* @return
*/
public static boolean addFlag(AbstractFlag flag) {
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;
}
@ -61,15 +63,18 @@ public class FlagManager {
/**
* 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;
}
@ -79,8 +84,8 @@ public class FlagManager {
* @param string
* @return AbstractFlag
*/
public static AbstractFlag getFlag(String string) {
for (AbstractFlag flag : flags) {
public static AbstractFlag getFlag(final String string) {
for (final AbstractFlag flag : flags) {
if (flag.getKey().equalsIgnoreCase(string)) {
return flag;
}
@ -96,9 +101,9 @@ public class FlagManager {
* If to create the flag if it does not exist
* @return AbstractFlag
*/
public static AbstractFlag getFlag(String string, boolean create) {
public static AbstractFlag getFlag(final String string, final boolean create) {
if ((getFlag(string) == null) && create) {
AbstractFlag flag = new AbstractFlag(string);
final AbstractFlag flag = new AbstractFlag(string);
addFlag(flag);
return flag;
}
@ -111,14 +116,14 @@ public class FlagManager {
* @param flag
* @return boolean Result of operation
*/
public static boolean removeFlag(AbstractFlag flag) {
public static boolean removeFlag(final AbstractFlag flag) {
return flags.remove(flag);
}
public static Flag[] parseFlags(List<String> flagstrings) {
Flag[] flags = new Flag[flagstrings.size()];
public static Flag[] parseFlags(final List<String> flagstrings) {
final Flag[] flags = new Flag[flagstrings.size()];
for (int i = 0; i < flagstrings.size(); i++) {
String[] split = flagstrings.get(i).split(";");
final String[] split = flagstrings.get(i).split(";");
if (split.length == 1) {
flags[i] = new Flag(getFlag(split[0], true), "");
}
@ -135,10 +140,10 @@ public class FlagManager {
* @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) {
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

@ -28,7 +28,7 @@ public class LSetCube {
* @param l1
* @param l2
*/
public LSetCube(Location l1, Location l2) {
public LSetCube(final Location l1, final Location l2) {
this.l1 = l1;
this.l1 = l2;
}
@ -39,7 +39,7 @@ public class LSetCube {
* @param l1
* @param size
*/
public LSetCube(Location l1, int size) {
public LSetCube(final Location l1, final int size) {
this.l1 = l1;
this.l2 = l1.clone().add(size, size, size);
}
@ -50,9 +50,9 @@ public class LSetCube {
* @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());
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);
}
@ -62,9 +62,9 @@ public class LSetCube {
* @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());
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);
}
@ -84,11 +84,11 @@ public class LSetCube {
/**
*
*/
private Location min;
private final Location min;
/**
*
*/
private Location max;
private final Location max;
/**
*
*/
@ -97,7 +97,7 @@ public class LSetCube {
/**
* @param cube
*/
public LCycler(LSetCube cube) {
public LCycler(final LSetCube cube) {
this.min = cube.minLoc();
this.max = cube.maxLoc();
this.current = this.min;
@ -107,9 +107,7 @@ public class LSetCube {
* @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 ((this.current.getBlockX() + 1) <= this.max.getBlockX()) && ((this.current.getBlockY() + 1) <= this.max.getBlockY()) && ((this.current.getBlockZ() + 1) <= this.max.getBlockZ());
}
/**

View File

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

View File

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

View File

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

View File

@ -20,7 +20,7 @@ import com.sk89q.worldedit.regions.CuboidRegion;
public class PWE {
@SuppressWarnings("deprecation")
public static void setMask(Player p, Location l) {
public static void setMask(final Player p, final Location l) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) {
@ -30,14 +30,12 @@ public class PWE {
s = PlotMain.worldEdit.getSession(p);
}
PlotId id = PlayerFunctions.getPlot(l);
final PlotId id = PlayerFunctions.getPlot(l);
if (id != null) {
Plot plot = PlotMain.getPlots(l.getWorld()).get(id);
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());
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);
@ -46,41 +44,41 @@ public class PWE {
}
else {
World w = p.getWorld();
final World w = p.getWorld();
Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
Location tloc = PlotHelper.getPlotTopLoc(w, plot.id);
final Location bloc = PlotHelper.getPlotBottomLoc(w, plot.id);
final 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());
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());
LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld();
final LocalWorld lw = PlotMain.worldEdit.wrapPlayer(p).getWorld();
CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
RegionMask mask = new RegionMask(region);
final CuboidRegion region = new CuboidRegion(lw, bvec, tvec);
final 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);
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 (Exception e) {
catch (final Exception e) {
// throw new
// PlotSquaredException(PlotSquaredException.PlotError.MISSING_DEPENDENCY,
// "WorldEdit == Null?");
}
}
public static boolean noMask(LocalSession s) {
public static boolean noMask(final LocalSession s) {
return s.getMask() == null;
}
public static void setNoMask(Player p) {
public static void setNoMask(final Player p) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) {
@ -89,21 +87,21 @@ public class PWE {
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);
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 (Exception e) {
catch (final Exception e) {
}
}
public static void removeMask(Player p, LocalSession s) {
Mask mask = null;
public static void removeMask(final Player p, final LocalSession s) {
final Mask mask = null;
s.setMask(mask);
}
public static void removeMask(Player p) {
public static void removeMask(final Player p) {
try {
LocalSession s;
if (PlotMain.worldEdit == null) {
@ -114,7 +112,7 @@ public class PWE {
}
removeMask(p, s);
}
catch (Exception e) {
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.
*
@ -28,7 +36,7 @@ public class PlayerFunctions {
* player
* @return
*/
public static boolean isInPlot(Player player) {
public static boolean isInPlot(final Player player) {
return getCurrentPlot(player) != null;
}
@ -37,15 +45,15 @@ public class PlayerFunctions {
* plot
* @return
*/
public static boolean hasExpired(Plot plot) {
OfflinePlayer player = Bukkit.getOfflinePlayer(plot.owner);
long lp = player.getLastPlayed();
long cu = System.currentTimeMillis();
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,10 +62,10 @@ 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) {
pos1 = getBottomPlot(world, plot1).id;
@ -67,7 +75,7 @@ public class PlayerFunctions {
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,17 +84,17 @@ public class PlayerFunctions {
return myplots;
}
public static Plot getBottomPlot(World world, Plot plot) {
public static Plot getBottomPlot(final World world, final Plot plot) {
if (plot.settings.getMerged(0)) {
Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y - 1));
if (p==null) {
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);
}
if (plot.settings.getMerged(3)) {
Plot p = PlotMain.getPlots(world).get(new PlotId(plot.id.x - 1, plot.id.y));
if (p==null) {
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);
@ -94,7 +102,7 @@ public class PlayerFunctions {
return plot;
}
public static Plot getTopPlot(World world, Plot plot) {
public static Plot getTopPlot(final World world, final Plot plot) {
if (plot.settings.getMerged(2)) {
return getTopPlot(world, PlotMain.getPlots(world).get(new PlotId(plot.id.x, plot.id.y + 1)));
}
@ -105,52 +113,54 @@ public class PlayerFunctions {
}
/**
* Returns the plot at a location (mega plots are not considered, all plots are treated as small plots)
* Returns the plot at a location (mega plots are not considered, all plots
* are treated as small plots)
*
* @param loc
* @return
*/
public static PlotId getPlotAbs(Location loc) {
String world = loc.getWorld().getName();
PlotManager manager = PlotMain.getPlotManager(world);
public static PlotId getPlotAbs(final Location loc) {
final String world = loc.getWorld().getName();
final PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) {
return null;
}
PlotWorld plotworld = PlotMain.getWorldSettings(world);
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);
public static PlotId getPlot(final Location loc) {
final String world = loc.getWorld().getName();
final PlotManager manager = PlotMain.getPlotManager(world);
if (manager == null) {
return null;
}
PlotWorld plotworld = PlotMain.getWorldSettings(world);
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(Player player) {
public static Plot getCurrentPlot(final Player player) {
if (!PlotMain.isPlotWorld(player.getWorld())) {
return null;
}
PlotId id = getPlot(player.getLocation());
World world = player.getWorld();
final PlotId id = getPlot(player.getLocation());
final World world = player.getWorld();
if (id == null) {
return null;
}
HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
final HashMap<PlotId, Plot> plots = PlotMain.getPlots(world);
if (plots != null) {
if (plots.containsKey(id)) {
return plots.get(id);
@ -162,22 +172,24 @@ public class PlayerFunctions {
/**
* Updates a given plot with another instance
*
* @deprecated
*
* @param plot
*/
@Deprecated
public static void set(Plot plot) {
public static void set(final Plot plot) {
PlotMain.updatePlot(plot);
}
/**
* 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);
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>();
}
@ -186,13 +198,14 @@ public class PlayerFunctions {
/**
* Get the number of plots for a player
*
* @param plr
* @return
*/
public static int getPlayerPlotCount(World world, Player plr) {
UUID uuid = plr.getUniqueId();
public static int getPlayerPlotCount(final World world, final Player plr) {
final UUID uuid = plr.getUniqueId();
int count = 0;
for (Plot plot: PlotMain.getPlots(world).values()) {
for (final Plot plot : PlotMain.getPlots(world).values()) {
if (plot.hasOwner() && plot.owner.equals(uuid) && plot.countsTowardsMax) {
count++;
}
@ -202,11 +215,12 @@ public class PlayerFunctions {
/**
* Get the maximum number of plots a player is allowed
*
* @param p
* @return
*/
@SuppressWarnings("SuspiciousNameCombination")
public static int getAllowedPlots(Player p) {
public static int getAllowedPlots(final Player p) {
return PlotMain.hasPermissionRange(p, "plots.plot", Settings.MAX_PLOTS);
}
@ -226,7 +240,7 @@ public class PlayerFunctions {
* @param msg
* Was used to wrap the chat client length (Packets out--)
*/
public static void sendMessageWrapped(Player plr, String msg) {
public static void sendMessageWrapped(final Player plr, final String msg) {
plr.sendMessage(msg);
}
@ -238,12 +252,12 @@ public class PlayerFunctions {
* @param msg
* Message to send
*/
public static void sendMessage(Player plr, String msg) {
public static void sendMessage(final Player plr, final String msg) {
if ((msg.length() == 0) || msg.equalsIgnoreCase("")) {
return;
}
if (plr==null) {
if (plr == null) {
PlotMain.sendConsoleSenderMessage(C.PREFIX.s() + msg);
return;
}
@ -259,9 +273,9 @@ public class PlayerFunctions {
* @param c
* Caption to send
*/
public static void sendMessage(Player plr, C c, String... args) {
public static void sendMessage(final Player plr, final C c, final String... args) {
if (plr==null) {
if (plr == null) {
PlotMain.sendConsoleSenderMessage(c);
return;
}
@ -271,7 +285,7 @@ public class PlayerFunctions {
}
String msg = c.s();
if ((args != null) && (args.length > 0)) {
for (String str : args) {
for (final String str : args) {
msg = msg.replaceFirst("%s", str);
}
}

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
@ -65,7 +66,7 @@ public class Plot implements Cloneable {
* Has the plot changed since the last save cycle?
*/
public boolean hasChanged = false;
public boolean countsTowardsMax = true ;
public boolean countsTowardsMax = true;
/**
* Primary constructor
@ -76,7 +77,7 @@ public class Plot implements Cloneable {
* @param helpers
* @param denied
*/
public Plot(PlotId id, UUID owner, Biome plotBiome, ArrayList<UUID> helpers, ArrayList<UUID> denied, String world) {
public Plot(final PlotId id, final UUID owner, final Biome plotBiome, final ArrayList<UUID> helpers, final ArrayList<UUID> denied, final String world) {
this.id = id;
this.settings = new PlotSettings(this);
this.settings.setBiome(plotBiome);
@ -104,9 +105,7 @@ public class Plot implements Cloneable {
* @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) {
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);
@ -142,7 +141,7 @@ public class Plot implements Cloneable {
*
* @param player
*/
public void setOwner(Player player) {
public void setOwner(final Player player) {
this.owner = player.getUniqueId();
}
@ -152,12 +151,8 @@ public class Plot implements Cloneable {
* @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)));
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)));
}
/**
@ -166,9 +161,8 @@ public class Plot implements Cloneable {
* @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())));
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())));
}
/**
@ -202,7 +196,7 @@ public class Plot implements Cloneable {
try {
return super.clone();
}
catch (CloneNotSupportedException e) {
catch (final CloneNotSupportedException e) {
return null;
}
}
@ -212,7 +206,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void addDenied(UUID uuid) {
public void addDenied(final UUID uuid) {
this.denied.add(uuid);
}
@ -221,7 +215,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void addHelper(UUID uuid) {
public void addHelper(final UUID uuid) {
this.helpers.add(uuid);
}
@ -230,7 +224,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void addTrusted(UUID uuid) {
public void addTrusted(final UUID uuid) {
this.trusted.add(uuid);
}
@ -251,7 +245,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void removeDenied(UUID uuid) {
public void removeDenied(final UUID uuid) {
this.denied.remove(uuid);
}
@ -260,7 +254,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void removeHelper(UUID uuid) {
public void removeHelper(final UUID uuid) {
this.helpers.remove(uuid);
}
@ -269,7 +263,7 @@ public class Plot implements Cloneable {
*
* @param uuid
*/
public void removeTrusted(UUID uuid) {
public void removeTrusted(final UUID uuid) {
this.trusted.remove(uuid);
}
@ -279,7 +273,7 @@ public class Plot implements Cloneable {
* @param plr
* initiator
*/
public void clear(Player plr) {
public void clear(final Player plr) {
PlotHelper.clear(plr, this);
}

View File

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

View File

@ -5,7 +5,7 @@ public class PlotComment {
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) {
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();
}

View File

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

View File

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

View File

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

View File

@ -5,7 +5,6 @@ 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 {
@ -14,61 +13,61 @@ public abstract class PlotManager {
* 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);
public abstract Location getPlotBottomLocAbs(final PlotWorld plotworld, final PlotId plotid);
// the same applies here
public abstract Location getPlotTopLocAbs(PlotWorld plotworld, PlotId plotid);
public abstract Location getPlotTopLocAbs(final PlotWorld plotworld, final PlotId plotid);
/*
* Plot clearing (return false if you do not support some method)
*/
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)
*/
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);
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,15 +8,13 @@
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
*
@ -49,7 +47,7 @@ public class PlotSettings {
*
* @param plot
*/
public PlotSettings(Plot plot) {
public PlotSettings(final Plot plot) {
this.alias = "";
}
@ -63,7 +61,7 @@ public class PlotSettings {
* @param direction
* @return boolean
*/
public boolean getMerged(int direction) {
public boolean getMerged(final int direction) {
return this.merged[direction];
}
@ -78,22 +76,21 @@ public class PlotSettings {
return this.merged;
}
public void setMerged(boolean[] merged) {
public void setMerged(final boolean[] merged) {
this.merged = merged;
}
public void setMerged(int direction, boolean merged) {
public void setMerged(final int direction, final boolean merged) {
this.merged[direction] = merged;
}
/**
* @param b
*/
public void setBiome(Biome b) {
public void setBiome(final Biome b) {
this.biome = b;
}
/**
* @return
* @deprecated
@ -103,20 +100,18 @@ public class PlotSettings {
return this.biome;
}
/**
* @param alias
*/
public void setAlias(String alias) {
public void setAlias(final String alias) {
this.alias = alias;
}
/**
* @param flag
*/
public void addFlag(Flag flag) {
Flag hasFlag = getFlag(flag.getKey());
public void addFlag(final Flag flag) {
final Flag hasFlag = getFlag(flag.getKey());
if (hasFlag != null) {
this.flags.remove(hasFlag);
}
@ -126,7 +121,7 @@ public class PlotSettings {
/**
* @param flags
*/
public void setFlags(Flag[] flags) {
public void setFlags(final Flag[] flags) {
this.flags = new HashSet<Flag>(Arrays.asList(flags));
}
@ -141,8 +136,8 @@ public class PlotSettings {
* @param flag
* @return
*/
public Flag getFlag(String flag) {
for (Flag myflag : this.flags) {
public Flag getFlag(final String flag) {
for (final Flag myflag : this.flags) {
if (myflag.getKey().equals(flag)) {
return myflag;
}
@ -154,7 +149,7 @@ public class PlotSettings {
return this.position;
}
public void setPosition(PlotHomePosition position) {
public void setPosition(final PlotHomePosition position) {
this.position = position;
}
@ -169,9 +164,10 @@ public class PlotSettings {
public String getLeaveMessage() {
return "";
}
public ArrayList<PlotComment> getComments(int tier) {
ArrayList<PlotComment> c = new ArrayList<PlotComment>();
for (PlotComment comment : this.comments) {
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);
}
@ -179,11 +175,11 @@ public class PlotSettings {
return c;
}
public void setComments(ArrayList<PlotComment> comments) {
public void setComments(final ArrayList<PlotComment> comments) {
this.comments = comments;
}
public void addComment(PlotComment comment) {
public void addComment(final PlotComment comment) {
if (this.comments == null) {
this.comments = new ArrayList<PlotComment>();
}

View File

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

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;
/**
*
@ -21,18 +103,8 @@ 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) }));
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;
@ -88,18 +160,16 @@ public abstract class PlotWorld {
public boolean SPAWN_BREEDING;
public static boolean SPAWN_BREEDING_DEFAULT = false;
public PlotWorld(String worldname) {
public PlotWorld(final String worldname) {
this.worldname = worldname;
}
/**
* When a world is created, the following method will be called for each
*
@param config
* @param config
*/
public void loadDefaultConfiguration(ConfigurationSection config)
{
public void loadDefaultConfiguration(final ConfigurationSection config) {
this.MOB_SPAWNING = config.getBoolean("natural_mob_spawning");
this.AUTO_MERGE = config.getBoolean("plot.auto_merge");
this.PLOT_BIOME = (Biome) Configuration.BIOME.parseString(config.getString("plot.biome"));
@ -121,15 +191,15 @@ public abstract class PlotWorld {
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>();
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);
@ -149,18 +219,16 @@ public abstract class PlotWorld {
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)
{
for (final ConfigurationNode setting : settings) {
options.put(setting.getConstant(), setting.getType().parseObject(setting.getValue()));
}
for (String option : options.keySet())
{
for (final String option : options.keySet()) {
if (!config.contains(option)) {
config.set(option, options.get(option));
}

View File

@ -30,15 +30,15 @@ public class RUtils {
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");
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);
}
@ -47,9 +47,9 @@ public class RUtils {
EAST(1),
NORTH(2),
WEST(3);
private int i;
private final int i;
Direction(int i) {
Direction(final int i) {
this.i = i;
}
@ -58,14 +58,14 @@ public class RUtils {
}
}
public void forceTexture(Player p) {
public void forceTexture(final Player p) {
p.setResourcePack(Settings.PLOT_SPECIFIC_RESOURCE_PACK);
}
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;
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;
@ -80,7 +80,7 @@ public class RUtils {
}
}
public boolean compareDirections(Location l1, Location l2) {
public boolean compareDirections(final Location l1, final Location l2) {
return getDirection(l1) == getDirection(l2);
}

View File

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

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,62 +12,98 @@ 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) {
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 {
Dimension demensions = schematic.getSchematicDimension();
int WIDTH = demensions.getX();
int LENGTH = demensions.getZ();
int HEIGHT = demensions.getY();
DataCollection[] blocks = schematic.getBlockCollection();
final Dimension demensions = schematic.getSchematicDimension();
final int WIDTH = demensions.getX();
final int LENGTH = demensions.getZ();
final int HEIGHT = demensions.getY();
final DataCollection[] blocks = schematic.getBlockCollection();
Location l1 = PlotHelper.getPlotBottomLoc(plot.getWorld(), plot.getId());
int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX()+1, l1.getBlockZ()+1);
final int sy = location.getWorld().getHighestBlockYAt(l1.getBlockX() + 1, l1.getBlockZ() + 1);
l1 = l1.add(1, sy-1, 1);
l1 = l1.add(1, sy - 1, 1);
World world = location.getWorld();
final World world = location.getWorld();
int y_offset;
if (HEIGHT == location.getWorld().getMaxHeight()) {
y_offset = 0;
}
else {
y_offset = l1.getBlockY();
}
for (int x = 0; x < WIDTH; x++) {
for (int 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;
short id = blocks[index].getBlock();
byte data = blocks[index].getData();
final DataCollection block = blocks[index];
Block block = world.getBlockAt(l1.getBlockX()+x+x_offset, l1.getBlockY()+y, l1.getBlockZ()+z+z_offset);
final short id = block.getBlock();
final byte data = block.getData();
PlotBlock plotblock = new PlotBlock(id, data);
// if (block.tag != null) {
// WorldEditUtils.setNBT(world, id, data, l1.getBlockX()
// + x + x_offset, y + y_offset, l1.getBlockZ() + z +
// z_offset, block.tag);
// }
// else {
final Block bukkitBlock = world.getBlockAt(l1.getBlockX() + x + x_offset, y + y_offset, l1.getBlockZ() + z + z_offset);
PlotHelper.setBlock(block, plotblock);
final PlotBlock plotblock = new PlotBlock(id, data);
PlotHelper.setBlock(bukkitBlock, plotblock);
// }
}
}
}
}
catch (Exception e) {
catch (final Exception e) {
return false;
}
return true;
@ -84,20 +111,19 @@ public class SchematicHandler {
/**
* Get a schematic
* @param name to check
*
* @param name
* to check
* @return schematic if found, else null
*/
public static Schematic getSchematic(String name) {
public static Schematic getSchematic(final String name) {
{
File parent =
new File(JavaPlugin.getPlugin(PlotMain.class).getDataFolder() + File.separator + "schematics");
final 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");
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;
@ -105,25 +131,25 @@ public class SchematicHandler {
Schematic schematic;
try {
InputStream iStream = new FileInputStream(file);
NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream));
CompoundTag tag = (CompoundTag) stream.readTag();
final InputStream iStream = new FileInputStream(file);
final NBTInputStream stream = new NBTInputStream(new GZIPInputStream(iStream));
final CompoundTag tag = (CompoundTag) stream.readTag();
stream.close();
Map<String, Tag> tagMap = tag.getValue();
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();
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
@ -140,15 +166,50 @@ public class SchematicHandler {
}
}
DataCollection[] collection = new DataCollection[b.length];
final DataCollection[] collection = new DataCollection[b.length];
for (int x = 0; x < b.length; x++) {
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 (Exception e) {
catch (final Exception e) {
e.printStackTrace();
return null;
}
@ -157,14 +218,15 @@ public class SchematicHandler {
/**
* Schematic Class
*
* @author Citymonstret
*/
public static class Schematic {
private DataCollection[] blockCollection;
private Dimension schematicDimension;
private File file;
private final DataCollection[] blockCollection;
private final Dimension schematicDimension;
private final File file;
public Schematic(DataCollection[] blockCollection, Dimension schematicDimension, File file) {
public Schematic(final DataCollection[] blockCollection, final Dimension schematicDimension, final File file) {
this.blockCollection = blockCollection;
this.schematicDimension = schematicDimension;
this.file = file;
@ -185,14 +247,15 @@ public class SchematicHandler {
/**
* Schematic Dimensions
*
* @author Citymonstret
*/
public static class Dimension {
private int x;
private int y;
private int z;
private final int x;
private final int y;
private final int z;
public Dimension(int x, int y, int z) {
public Dimension(final int x, final int y, final int z) {
this.x = x;
this.y = y;
this.z = z;
@ -213,24 +276,28 @@ public class SchematicHandler {
/**
* Saves a schematic to a file path
* @param tag to save
* @param path to save in
*
* @param tag
* to save
* @param path
* to save in
* @return true if succeeded
*/
public static boolean save(CompoundTag tag, String path) {
public static boolean save(final CompoundTag tag, final String path) {
if (tag==null) {
if (tag == null) {
PlotMain.sendConsoleSenderMessage("&cCannot save empty tag");
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;
}
@ -239,11 +306,14 @@ public class SchematicHandler {
/**
* Gets the schematic of a plot
* @param world to check
* @param id plot
*
* @param world
* to check
* @param id
* plot
* @return tag
*/
public static CompoundTag getCompoundTag(World world, PlotId id) {
public static CompoundTag getCompoundTag(final World world, final PlotId id) {
if (!PlotMain.getPlots(world).containsKey(id)) {
return null;
@ -258,8 +328,8 @@ public class SchematicHandler {
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);
final Chunk chunk = world.getChunkAt(i, j);
final boolean result = chunk.load(false);
if (!result) {
// Plot is not even generated
@ -269,15 +339,15 @@ public class SchematicHandler {
}
}
}
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,13 +402,16 @@ public class SchematicHandler {
/**
* Schematic Data Collection
*
* @author Citymonstret
*/
public static class DataCollection {
private short block;
private byte data;
private final short block;
private final byte data;
public DataCollection(short block, byte data) {
// public CompoundTag tag;
public DataCollection(final short block, final byte data) {
this.block = block;
this.data = data;
}
@ -354,31 +425,31 @@ public class SchematicHandler {
}
}
public static boolean pastePart(World world, DataCollection[] blocks, Location l1, int x_offset, int z_offset, int i1, int i2, int WIDTH, int LENGTH) {
public static boolean pastePart(final World world, final DataCollection[] blocks, final Location l1, final int x_offset, final int z_offset, final int i1, final int i2, final int WIDTH, final int LENGTH) {
boolean result = false;
for (int i = i1; i<=i2 ;i++) {
short id = blocks[i].getBlock();
byte data = blocks[i].getData();
if (id==0) {
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

@ -30,17 +30,17 @@ public class SetBlockFast {
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);
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;
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

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

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

@ -47,7 +47,7 @@ public class Title {
* @param title
* Title
*/
public Title(String title) {
public Title(final String title) {
this.title = title;
loadClasses();
}
@ -60,7 +60,7 @@ public class Title {
* @param subtitle
* Subtitle text
*/
public Title(String title, String subtitle) {
public Title(final String title, final String subtitle) {
this.title = title;
this.subtitle = subtitle;
loadClasses();
@ -80,7 +80,7 @@ public class Title {
* @param fadeOutTime
* Fade out time
*/
public Title(String title, String subtitle, int fadeInTime, int stayTime, int fadeOutTime) {
public Title(final String title, final String subtitle, final int fadeInTime, final int stayTime, final int fadeOutTime) {
this.title = title;
this.subtitle = subtitle;
this.fadeInTime = fadeInTime;
@ -104,7 +104,7 @@ public class Title {
* @param color
* Chat color
*/
public void setTitleColor(ChatColor color) {
public void setTitleColor(final ChatColor color) {
this.titleColor = color;
}
@ -114,7 +114,7 @@ public class Title {
* @param color
* Chat color
*/
public void setSubtitleColor(ChatColor color) {
public void setSubtitleColor(final ChatColor color) {
this.subtitleColor = color;
}
@ -124,7 +124,7 @@ public class Title {
* @param time
* Time
*/
public void setFadeInTime(int time) {
public void setFadeInTime(final int time) {
this.fadeInTime = time;
}
@ -134,7 +134,7 @@ public class Title {
* @param time
* Time
*/
public void setFadeOutTime(int time) {
public void setFadeOutTime(final int time) {
this.fadeOutTime = time;
}
@ -144,7 +144,7 @@ public class Title {
* @param time
* Time
*/
public void setStayTime(int time) {
public void setStayTime(final int time) {
this.stayTime = time;
}
@ -168,45 +168,34 @@ public class Title {
* @param player
* Player
*/
public void send(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
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));
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);
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);
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) {
catch (final Exception e) {
e.printStackTrace();
}
}
@ -216,7 +205,7 @@ public class Title {
* Broadcast the title to all players
*/
public void broadcast() {
for (Player p : Bukkit.getOnlinePlayers()) {
for (final Player p : Bukkit.getOnlinePlayers()) {
send(p);
}
}
@ -227,18 +216,18 @@ public class Title {
* @param player
* Player
*/
public void clearTitle(Player player) {
public void clearTitle(final 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]);
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 (Exception e) {
catch (final Exception e) {
e.printStackTrace();
}
}
@ -250,18 +239,18 @@ public class Title {
* @param player
* Player
*/
public void resetTitle(Player player) {
public void resetTitle(final 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]);
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 (Exception e) {
catch (final Exception e) {
e.printStackTrace();
}
}
@ -274,17 +263,17 @@ public class Title {
* Player
* @return Protocol version
*/
private int getProtocolVersion(Player player) {
private int getProtocolVersion(final Player player) {
int version = 0;
try {
Object handle = getHandle(player);
Object connection = getField(handle.getClass(), "playerConnection").get(handle);
Object networkManager = getValue("networkManager", connection);
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) {
catch (final Exception ex) {
// ex.printStackTrace(); <-- spammy console
}
return version;
@ -306,39 +295,39 @@ public class Title {
* Namespace url
* @return Class
*/
private Class<?> getClass(String namespace) {
private Class<?> getClass(final String namespace) {
try {
return Class.forName(namespace);
}
catch (Exception e) {
catch (final Exception e) {
return null;
}
}
private Field getField(String name, Class<?> clazz) throws Exception {
private Field getField(final String name, final Class<?> clazz) throws Exception {
return clazz.getDeclaredField(name);
}
private Object getValue(String name, Object obj) throws Exception {
Field f = getField(name, obj.getClass());
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) {
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];
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) {
private static boolean equalsTypeArray(final Class<?>[] a, final Class<?>[] o) {
if (a.length != o.length) {
return false;
}
@ -350,20 +339,20 @@ public class Title {
return true;
}
private Object getHandle(Object obj) {
private Object getHandle(final Object obj) {
try {
return getMethod("getHandle", obj.getClass()).invoke(obj);
}
catch (Exception e) {
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());
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;
}
@ -372,36 +361,36 @@ public class Title {
}
private String getVersion() {
String name = Bukkit.getServer().getClass().getPackage().getName();
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;
private Class<?> getNMSClass(final String className) {
final String fullName = "net.minecraft.server." + getVersion() + className;
Class<?> clazz = null;
try {
clazz = Class.forName(fullName);
}
catch (Exception e) {
catch (final Exception e) {
e.printStackTrace();
}
return clazz;
}
private Field getField(Class<?> clazz, String name) {
private Field getField(final Class<?> clazz, final String name) {
try {
Field field = clazz.getDeclaredField(name);
final Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
}
catch (Exception e) {
catch (final Exception e) {
e.printStackTrace();
return null;
}
}
private Method getMethod(Class<?> clazz, String name, Class<?>... args) {
for (Method m : clazz.getMethods()) {
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;
@ -410,7 +399,7 @@ public class Title {
return null;
}
private boolean ClassListEqual(Class<?>[] l1, Class<?>[] l2) {
private boolean ClassListEqual(final Class<?>[] l1, final Class<?>[] l2) {
boolean equal = true;
if (l1.length != l2.length) {
return false;

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,11 +25,14 @@ 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.
@ -36,6 +41,7 @@ public class UUIDHandler {
/**
* Online mode
*
* @see org.bukkit.Server#getOnlineMode()
*/
private static boolean online = Bukkit.getServer().getOnlineMode();
@ -47,6 +53,7 @@ public class UUIDHandler {
/**
* Get the map containing all names/uuids
*
* @return map with names + uuids
*/
public static BiMap<StringWrapper, UUID> getUuidMap() {
@ -55,74 +62,84 @@ 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) {
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) {
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) {
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
* @param name
* to use as key
* @return uuid
*/
public static UUID getUUID(String name) {
StringWrapper nameWrap = new StringWrapper(name);
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();
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 (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();
}
}
@ -134,18 +151,20 @@ public class UUIDHandler {
}
/**
* @param uuid to use as key
* @param uuid
* to use as key
* @return name (cache)
*/
private static StringWrapper loopSearch(UUID uuid) {
private static StringWrapper loopSearch(final UUID uuid) {
return uuidMap.inverse().get(uuid);
}
/**
* @param uuid to use as key
* @param uuid
* to use as key
* @return Name
*/
public static String getName(UUID uuid) {
public static String getName(final UUID uuid) {
if (uuidExists(uuid)) {
return loopSearch(uuid).value;
}
@ -157,38 +176,44 @@ public class UUIDHandler {
return name;
}
if (online) {
if(!Settings.CUSTOM_API) {
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();
}
}
@ -200,77 +225,70 @@ public class UUIDHandler {
}
/**
* @param name to use as key
* @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));
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
* @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()) {
private static String getNameOnlinePlayer(final UUID uuid) {
final Player player = Bukkit.getPlayer(uuid);
if ((player == null) || !player.isOnline()) {
return null;
}
String name = player.getName();
final String name = player.getName();
add(new StringWrapper(name), uuid);
return name;
}
/**
* @param uuid to use as key
* @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()) {
private static String getNameOfflinePlayer(final UUID uuid) {
final OfflinePlayer player = Bukkit.getOfflinePlayer(uuid);
if ((player == null) || !player.hasPlayedBefore()) {
return null;
}
String name = player.getName();
final String name = player.getName();
add(new StringWrapper(name), uuid);
return name;
}
/**
* @param name to use as key
* @param name
* to use as key
* @return UUID
*/
private static UUID getUuidOnlinePlayer(StringWrapper name) {
private static UUID getUuidOnlinePlayer(final StringWrapper name) {
@SuppressWarnings("deprecation")
Player player = Bukkit.getPlayer(name.value);
final Player player = Bukkit.getPlayer(name.value);
if (player == null) {
return null;
}
UUID uuid = player.getUniqueId();
final 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;
}
/**
* 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.
@ -52,7 +63,7 @@ public class PlotAPI {
// PlotMain.updatePlot(plot);
// To access plotMain stuff.
private PlotMain plotMain;
private final PlotMain plotMain;
// Reference
/**
@ -62,6 +73,7 @@ public class PlotAPI {
/**
* 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);
}
@ -115,21 +134,23 @@ public class PlotAPI {
/**
* Constructor. Insert any Plugin.
* (Optimally the plugin that is accessing the method)
* @param plugin Plugin used to access this method
*
* @param plugin
* Plugin used to access this method
*/
public PlotAPI(JavaPlugin plugin) {
public PlotAPI(final JavaPlugin plugin) {
this.plotMain = JavaPlugin.getPlugin(PlotMain.class);
}
/**
* Get the main class for this plugin <br>
* - Contains a lot of fields and methods - not very well organized
* <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;
return this.plotMain;
}
/**
@ -185,7 +206,7 @@ public class PlotAPI {
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(World world) {
public PlotManager getPlotManager(final World world) {
return PlotMain.getPlotManager(world);
}
@ -196,7 +217,7 @@ public class PlotAPI {
* @param world
* @return PlotManager
*/
public PlotManager getPlotManager(String world) {
public PlotManager getPlotManager(final String world) {
return PlotMain.getPlotManager(world);
}
@ -210,7 +231,7 @@ public class PlotAPI {
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(World world) {
public PlotWorld getWorldSettings(final World world) {
return PlotMain.getWorldSettings(world);
}
@ -222,7 +243,7 @@ public class PlotAPI {
* @return PlotWorld class for that world ! will return null if not a plot
* world world
*/
public PlotWorld getWorldSettings(String world) {
public PlotWorld getWorldSettings(final String world) {
return PlotMain.getWorldSettings(world);
}
@ -233,7 +254,7 @@ public class PlotAPI {
* @param c
* (Caption)
*/
public void sendMessage(Player player, C c) {
public void sendMessage(final Player player, final C c) {
PlayerFunctions.sendMessage(player, c);
}
@ -243,7 +264,7 @@ public class PlotAPI {
* @param player
* @param string
*/
public void sendMessage(Player player, String string) {
public void sendMessage(final Player player, final String string) {
PlayerFunctions.sendMessage(player, string);
}
@ -252,7 +273,7 @@ public class PlotAPI {
*
* @param msg
*/
public void sendConsoleMessage(String msg) {
public void sendConsoleMessage(final String msg) {
PlotMain.sendConsoleSenderMessage(msg);
}
@ -262,7 +283,7 @@ public class PlotAPI {
* @param c
* (Caption)
*/
public void sendConsoleMessage(C c) {
public void sendConsoleMessage(final C c) {
sendConsoleMessage(c.s());
}
@ -271,7 +292,7 @@ public class PlotAPI {
*
* @param flag
*/
public void addFlag(AbstractFlag flag) {
public void addFlag(final AbstractFlag flag) {
FlagManager.addFlag(flag);
}
@ -292,7 +313,7 @@ public class PlotAPI {
* @param z
* @return plot, null if ID is wrong
*/
public Plot getPlot(World world, int x, int z) {
public Plot getPlot(final World world, final int x, final int z) {
return PlotHelper.getPlot(world, new PlotId(x, z));
}
@ -302,7 +323,7 @@ public class PlotAPI {
* @param l
* @return plot if found, otherwise it creates a temporary plot-
*/
public Plot getPlot(Location l) {
public Plot getPlot(final Location l) {
return PlotHelper.getCurrentPlot(l);
}
@ -312,7 +333,7 @@ public class PlotAPI {
* @param player
* @return plot if found, otherwise it creates a temporary plot
*/
public Plot getPlot(Player player) {
public Plot getPlot(final Player player) {
return this.getPlot(player.getLocation());
}
@ -322,7 +343,7 @@ public class PlotAPI {
* @param player
* @return true if player has a plot, false if not.
*/
public boolean hasPlot(World world, Player player) {
public boolean hasPlot(final World world, final Player player) {
return (getPlots(world, player, true) != null) && (getPlots(world, player, true).length > 0);
}
@ -334,9 +355,9 @@ public class PlotAPI {
* @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()) {
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);
@ -358,7 +379,7 @@ public class PlotAPI {
* to get plots of
* @return Plot[] - array of plot objects in world
*/
public Plot[] getPlots(World world) {
public Plot[] getPlots(final World world) {
return PlotMain.getWorldPlots(world);
}
@ -378,7 +399,7 @@ public class PlotAPI {
* (to check if plot world)
* @return boolean (if plot world or not)
*/
public boolean isPlotWorld(World world) {
public boolean isPlotWorld(final World world) {
return PlotMain.isPlotWorld(world);
}
@ -388,10 +409,9 @@ public class PlotAPI {
* @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) };
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) };
}
/**
@ -400,7 +420,7 @@ public class PlotAPI {
* @param p
* @return plot bottom location
*/
public Location getHomeLocation(Plot p) {
public Location getHomeLocation(final Plot p) {
return PlotHelper.getPlotHome(p.getWorld(), p.id);
}
@ -410,8 +430,8 @@ public class PlotAPI {
* @param p
* @return plot bottom location
*/
public Location getBottomLocation(Plot p) {
World world = Bukkit.getWorld(p.world);
public Location getBottomLocation(final Plot p) {
final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotBottomLoc(world, p.id);
}
@ -421,8 +441,8 @@ public class PlotAPI {
* @param p
* @return plot top location
*/
public Location getTopLocation(Plot p) {
World world = Bukkit.getWorld(p.world);
public Location getTopLocation(final Plot p) {
final World world = Bukkit.getWorld(p.world);
return PlotHelper.getPlotTopLoc(world, p.id);
}
@ -432,7 +452,7 @@ public class PlotAPI {
* @param player
* @return true if the player is in a plot, false if not-
*/
public boolean isInPlot(Player player) {
public boolean isInPlot(final Player player) {
return PlayerFunctions.isInPlot(player);
}
@ -441,7 +461,7 @@ public class PlotAPI {
*
* @param c
*/
public void registerCommand(SubCommand c) {
public void registerCommand(final SubCommand c) {
MainCommand.subCommands.add(c);
}
@ -460,7 +480,7 @@ public class PlotAPI {
* @param player
* @return
*/
public int getPlayerPlotCount(World world, Player player) {
public int getPlayerPlotCount(final World world, final Player player) {
return PlayerFunctions.getPlayerPlotCount(world, player);
}
@ -470,7 +490,7 @@ public class PlotAPI {
* @param player
* @return a set containing the players plots
*/
public Set<Plot> getPlayerPlots(World world, Player player) {
public Set<Plot> getPlayerPlots(final World world, final Player player) {
return PlayerFunctions.getPlayerPlots(world, player);
}
@ -480,7 +500,7 @@ public class PlotAPI {
* @param player
* @return the number of allowed plots
*/
public int getAllowedPlots(Player player) {
public int getAllowedPlots(final Player player) {
return PlayerFunctions.getAllowedPlots(player);
}
}

View File

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

View File

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

View File

@ -28,18 +28,17 @@ public class Clear 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, "You're not in a plot.");
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId()))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
if (((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())) && !PlotMain.hasPermission(plr, "plots.admin")) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
}

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

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

View File

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

View File

@ -8,14 +8,18 @@
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.
@ -27,33 +31,32 @@ public class Comment 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);
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()));
if (PlotMain.hasPermission(plr, "plots.comment." + args[0].toLowerCase())) {
final String text = StringUtils.join(Arrays.copyOfRange(args, 1, args.length), " ");
final PlotComment comment = new PlotComment(text, plr.getName(), recipients.indexOf(args[0].toLowerCase()));
plot.settings.addComment(comment);
DBFunc.setComment(plr.getWorld().getName(), plot, comment);
return true;
}
else {
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment."+args[0].toLowerCase());
PlayerFunctions.sendMessage(plr, C.NO_PERMISSION, "plots.comment." + args[0].toLowerCase());
return false;
}
}

View File

@ -8,10 +8,15 @@
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.
*/
@ -22,14 +27,13 @@ public class Copy 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;
}
@ -38,14 +42,15 @@ public class Copy extends SubCommand {
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)));
// section.paste(plr.getWorld(), PlotHelper.getPlot(plr.getWorld()zs,
// new PlotId(plot.getId().x + 1, plot.getId().y)));
return true;
}
}

View File

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

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;
@ -47,14 +44,14 @@ public class DebugClaimTest extends SubCommand {
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
if (args.length<3) {
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;
}
World world = Bukkit.getWorld(args[0]);
if (world==null || !PlotMain.isPlotWorld(world)) {
final World world = Bukkit.getWorld(args[0]);
if ((world == null) || !PlotMain.isPlotWorld(world)) {
PlayerFunctions.sendMessage(plr, "&cInvalid plot world!");
return false;
}
@ -62,75 +59,75 @@ public class DebugClaimTest extends SubCommand {
PlotId min, max;
try {
String[] split1 = args[1].split(";");
String[] split2 = args[2].split(";");
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) {
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);
}
}
}
@ -138,12 +135,12 @@ public class DebugClaimTest extends SubCommand {
}
}
if (plots.size()>0) {
PlayerFunctions.sendMessage(plr, "&3Sign Block&8->&3PlotSquared&8: &7Updating '"+plots.size()+"' 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) {
for (final Plot plot : plots) {
PlotMain.updatePlot(plot);
}
@ -161,12 +158,12 @@ public class DebugClaimTest extends SubCommand {
return true;
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport) {
public static boolean claimPlot(final Player player, final Plot plot, final boolean teleport) {
return claimPlot(player, plot, teleport, "");
}
public static boolean claimPlot(Player player, Plot plot, boolean teleport, String schematic) {
PlayerClaimPlotEvent event = new PlayerClaimPlotEvent(player, plot);
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);

View File

@ -9,36 +9,12 @@
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
@ -50,14 +26,14 @@ public class DebugLoadTest extends SubCommand {
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
public boolean execute(final Player plr, final String... args) {
if (plr == null) {
try {
Field fPlots = PlotMain.class.getDeclaredField("plots");
final Field fPlots = PlotMain.class.getDeclaredField("plots");
fPlots.setAccessible(true);
fPlots.set(null, DBFunc.getPlots());
}
catch (Exception e) {
catch (final Exception e) {
PlotMain.sendConsoleSenderMessage("&3===FAILED&3===");
e.printStackTrace();
PlotMain.sendConsoleSenderMessage("&3===END OF STACKTRACE===");

View File

@ -9,34 +9,13 @@
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
@ -48,9 +27,9 @@ public class DebugSaveTest extends SubCommand {
}
@Override
public boolean execute(Player plr, String... args) {
if (plr==null) {
ArrayList<Plot> plots = new ArrayList<Plot>();
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);

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;
@ -30,35 +29,34 @@ public class Delete 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, "You're not in a plot.");
return false;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if (!PlayerFunctions.getTopPlot(plr.getWorld(), plot).equals(PlayerFunctions.getBottomPlot(plr.getWorld(), plot))) {
PlayerFunctions.sendMessage(plr, C.UNLINK_REQUIRED);
return false;
}
if ((((plot == null) || !plot.hasOwner() || !plot.getOwner().equals(plr.getUniqueId())))
&& !PlotMain.hasPermission(plr,"plots.admin")) {
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());
final PlotWorld pWorld = PlotMain.getWorldSettings(plot.getWorld());
if (PlotMain.useEconomy && pWorld.USE_ECONOMY) {
double c = pWorld.SELL_PRICE;
final double c = pWorld.SELL_PRICE;
if (c > 0d) {
Economy economy = PlotMain.economy;
final Economy economy = PlotMain.economy;
economy.depositPlayer(plr, c);
sendMessage(plr, C.ADDED_BALANCE, c + "");
}
}
boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
final boolean result = PlotMain.removePlot(plr.getWorld().getName(), plot.id, true);
if (result) {
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)) {
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;
}
}

View File

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

View File

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

View File

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

View File

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

View File

@ -13,13 +13,16 @@ 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.
*/
@ -42,7 +45,7 @@ public class Inbox extends SubCommand {
}
Integer tier = null;
UUID uuid = plr.getUniqueId();
final UUID uuid = plr.getUniqueId();
if (PlotMain.hasPermission(plr, "plots.admin")) {
tier = 0;
}
@ -62,7 +65,7 @@ public class Inbox extends SubCommand {
if (args.length > 0) {
switch (args[0].toLowerCase()) {
case "admin":
if (tier<=0) {
if (tier <= 0) {
tier = 0;
}
else {
@ -71,7 +74,7 @@ public class Inbox extends SubCommand {
}
break;
case "owner":
if (tier<=1) {
if (tier <= 1) {
tier = 1;
}
else {
@ -80,7 +83,7 @@ public class Inbox extends SubCommand {
}
break;
case "helper":
if (tier<=2) {
if (tier <= 2) {
tier = 2;
}
else {
@ -89,7 +92,7 @@ public class Inbox extends SubCommand {
}
break;
case "trusted":
if (tier<=3) {
if (tier <= 3) {
tier = 3;
}
else {
@ -98,7 +101,7 @@ public class Inbox extends SubCommand {
}
break;
case "everyone":
if (tier<=4) {
if (tier <= 4) {
tier = 4;
}
else {
@ -107,7 +110,7 @@ public class Inbox extends SubCommand {
}
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;
}
}
@ -125,41 +128,41 @@ 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());

View File

@ -8,19 +8,25 @@
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
@ -32,10 +38,10 @@ public class Info extends SubCommand {
}
@Override
public boolean execute(Player player, String... args) {
public boolean execute(final Player player, String... args) {
World world;
Plot plot;
if (player!=null) {
if (player != null) {
world = player.getWorld();
if (!PlayerFunctions.isInPlot(player)) {
PlayerFunctions.sendMessage(player, C.NOT_IN_PLOT);
@ -44,38 +50,38 @@ public class Info extends SubCommand {
plot = PlayerFunctions.getCurrentPlot(player);
}
else {
if (args.length<2) {
if (args.length < 2) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
PlotWorld plotworld = PlotMain.getWorldSettings(args[0]);
if (plotworld==null) {
final 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]));
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) {
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]};
if (args.length == 3) {
args = new String[] { args[2] };
}
else {
args = new String[0];
}
}
catch (Exception e) {
catch (final Exception e) {
PlayerFunctions.sendMessage(player, C.INFO_SYNTAX_CONSOLE);
return false;
}
}
boolean hasOwner = plot.hasOwner();
final boolean hasOwner = plot.hasOwner();
boolean containsEveryone;
boolean trustedEveryone;
@ -110,9 +116,9 @@ public class Info extends SubCommand {
}
String info = C.PLOT_INFO.s();
if (args.length==1) {
if (args.length == 1) {
info = getCaption(args[0].toLowerCase());
if (info==null) {
if (info == null) {
PlayerFunctions.sendMessage(player, "&6Categories&7: &ahelpers&7, &aalias&7, &abiome&7, &adenied&7, &aflags&7, &aid&7, &asize&7, &atrusted&7, &aowner&7, &arating");
return false;
}
@ -124,7 +130,7 @@ public class Info extends SubCommand {
return true;
}
private String getCaption(String string) {
private String getCaption(final String string) {
switch (string) {
case "helpers":
return C.PLOT_INFO_HELPERS.s();
@ -151,19 +157,19 @@ public class Info extends SubCommand {
}
}
private String format(String info, World world, Plot plot, Player player) {
private String format(String info, final World world, final Plot plot, final Player player) {
PlotId id = plot.id;
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);
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,19 +190,18 @@ 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) {
private String getPlayerList(final ArrayList<UUID> l) {
if ((l == null) || (l.size() < 1)) {
return " none";
}
String c = C.PLOT_USER_LIST.s();
StringBuilder list = new StringBuilder();
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(",", ""));
@ -208,7 +213,7 @@ public class Info extends SubCommand {
return list.toString();
}
private String getPlayerName(UUID uuid) {
private String getPlayerName(final UUID uuid) {
if (uuid == null) {
return "unknown";
}
@ -222,9 +227,9 @@ public class Info extends SubCommand {
return UUIDHandler.getName(uuid);
}
private Biome getBiomeAt(Plot plot) {
World w = Bukkit.getWorld(plot.world);
Location bl = PlotHelper.getPlotTopLoc(w, plot.id);
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

@ -24,16 +24,16 @@ public class Inventory extends SubCommand {
}
@Override
public boolean execute(final Player plr, String... args) {
ArrayList<SubCommand> cmds = new ArrayList<>();
for (SubCommand cmd : MainCommand.subCommands) {
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);
}
}
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) {
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);
@ -41,11 +41,10 @@ public class Inventory extends SubCommand {
}
private ItemStack getItem(final SubCommand cmd) {
ItemStack stack = new ItemStack(Material.COMMAND);
ItemMeta meta = stack.getItemMeta();
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.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());

View File

@ -26,14 +26,13 @@ public class Kick 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, "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")) {
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;
}
@ -45,10 +44,8 @@ public class Kick extends SubCommand {
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)) {
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;
}

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,10 +32,7 @@ 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>() {
{
@ -43,73 +40,77 @@ public class MainCommand implements CommandExecutor, TabCompleter {
}
};
public static boolean no_permission(Player player, String permission) {
public static boolean no_permission(final Player player, final String permission) {
PlayerFunctions.sendMessage(player, C.NO_PERMISSION, permission);
return false;
}
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (sender instanceof Player) ? (Player) sender : null;
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"))
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 < 1) || ((args.length >= 1) && (args[0].equalsIgnoreCase("help") || args[0].equalsIgnoreCase("he")))) {
if (args.length < 2) {
StringBuilder builder = new StringBuilder();
final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
String cat = args[1];
final String cat = args[1];
SubCommand.CommandCategory cato = null;
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
if (cat.equalsIgnoreCase(category.toString())) {
cato = category;
break;
}
}
if (cato == null) {
StringBuilder builder = new StringBuilder();
final StringBuilder builder = new StringBuilder();
builder.append(C.HELP_INFO.s());
for (SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
for (final SubCommand.CommandCategory category : SubCommand.CommandCategory.values()) {
builder.append("\n").append(C.HELP_INFO_ITEM.s().replaceAll("%category%", category.toString().toLowerCase()).replaceAll("%category_desc%", category.toString()));
}
PlayerFunctions.sendMessage(player, builder.toString());
return true;
}
StringBuilder help = new StringBuilder();
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) {
for (final SubCommand command : subCommands) {
if (command.cmd.equalsIgnoreCase(args[0]) || command.alias.equalsIgnoreCase(args[0])) {
String[] arguments = new String[args.length - 1];
final String[] arguments = new String[args.length - 1];
System.arraycopy(args, 1, arguments, 0, args.length - 1);
if (command.permission.hasPermission(player)) {
if (player!=null || !command.isPlayer ) {
if ((player != null) || !command.isPlayer) {
return command.execute(player, arguments);
}
else {
@ -124,81 +125,77 @@ public class MainCommand implements CommandExecutor, TabCompleter {
}
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;
}
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,7 +205,7 @@ 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)));
}
@ -219,18 +216,20 @@ public class MainCommand implements CommandExecutor, TabCompleter {
return help;
}
private static String t(String 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

@ -41,7 +41,7 @@ public class Merge extends SubCommand {
public static String direction(float yaw) {
yaw = yaw / 90;
int i = Math.round(yaw);
final int i = Math.round(yaw);
switch (i) {
case -4:
case 0:
@ -62,12 +62,12 @@ public class Merge 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 true;
}
Plot plot = PlayerFunctions.getCurrentPlot(plr);
final Plot plot = PlayerFunctions.getCurrentPlot(plr);
if ((plot == null) || !plot.hasOwner()) {
PlayerFunctions.sendMessage(plr, C.NO_PLOT_PERMS);
return false;
@ -77,8 +77,7 @@ public class Merge extends SubCommand {
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.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;
}
@ -90,49 +89,44 @@ public class Merge extends SubCommand {
}
}
if (direction == -1) {
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s()
+ StringUtils.join(values, C.BLOCK_LIST_SEPARATER.s()));
PlayerFunctions.sendMessage(plr, C.SUBCOMMAND_SET_OPTIONS_HEADER.s() + 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;
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));
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));
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));
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));
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);
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);
final 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;
final Economy economy = PlotMain.economy;
if (economy.getBalance(plr) < cost) {
sendMessage(plr, C.CANNOT_AFFORD_MERGE, cost + "");
return false;
@ -142,7 +136,7 @@ public class Merge extends SubCommand {
}
}
PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
final PlotMergeEvent event = new PlotMergeEvent(world, plot, plots);
Bukkit.getServer().getPluginManager().callEvent(event);
if (event.isCancelled()) {

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

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

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