getValues(final boolean deep);
-
+
/**
* Checks if this {@link ConfigurationSection} contains the given path.
*
@@ -53,7 +52,7 @@ public interface ConfigurationSection
* @throws IllegalArgumentException Thrown when path is null.
*/
public boolean contains(final String path);
-
+
/**
* Checks if this {@link ConfigurationSection} has a value set for the
* given path.
@@ -67,7 +66,7 @@ public interface ConfigurationSection
* @throws IllegalArgumentException Thrown when path is null.
*/
public boolean isSet(final String path);
-
+
/**
* Gets the path of this {@link ConfigurationSection} from its root {@link
* Configuration}
@@ -84,7 +83,7 @@ public interface ConfigurationSection
* @return Path of this section relative to its root
*/
public String getCurrentPath();
-
+
/**
* Gets the name of this individual {@link ConfigurationSection}, in the
* path.
@@ -95,7 +94,7 @@ public interface ConfigurationSection
* @return Name of this section
*/
public String getName();
-
+
/**
* Gets the root {@link Configuration} that contains this {@link
* ConfigurationSection}
@@ -109,7 +108,7 @@ public interface ConfigurationSection
* @return Root configuration containing this section.
*/
public Configuration getRoot();
-
+
/**
* Gets the parent {@link ConfigurationSection} that directly contains
* this {@link ConfigurationSection}.
@@ -122,7 +121,7 @@ public interface ConfigurationSection
* @return Parent section containing this section.
*/
public ConfigurationSection getParent();
-
+
/**
* Gets the requested Object by path.
*
@@ -134,7 +133,7 @@ public interface ConfigurationSection
* @return Requested Object.
*/
public Object get(final String path);
-
+
/**
* Gets the requested Object by path, returning a default value if not
* found.
@@ -148,7 +147,7 @@ public interface ConfigurationSection
* @return Requested Object.
*/
public Object get(final String path, final Object def);
-
+
/**
* Sets the specified path to the given value.
*
@@ -164,7 +163,7 @@ public interface ConfigurationSection
* @param value New value to set the path to.
*/
public void set(final String path, final Object value);
-
+
/**
* Creates an empty {@link ConfigurationSection} at the specified path.
*
@@ -176,7 +175,7 @@ public interface ConfigurationSection
* @return Newly created section
*/
public ConfigurationSection createSection(final String path);
-
+
/**
* Creates a {@link ConfigurationSection} at the specified path, with
* specified values.
@@ -190,7 +189,7 @@ public interface ConfigurationSection
* @return Newly created section
*/
public ConfigurationSection createSection(final String path, final Map, ?> map);
-
+
// Primitives
/**
* Gets the requested String by path.
@@ -203,7 +202,7 @@ public interface ConfigurationSection
* @return Requested String.
*/
public String getString(final String path);
-
+
/**
* Gets the requested String by path, returning a default value if not
* found.
@@ -218,7 +217,7 @@ public interface ConfigurationSection
* @return Requested String.
*/
public String getString(final String path, final String def);
-
+
/**
* Checks if the specified path is a String.
*
@@ -231,7 +230,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a String.
*/
public boolean isString(final String path);
-
+
/**
* Gets the requested int by path.
*
@@ -243,7 +242,7 @@ public interface ConfigurationSection
* @return Requested int.
*/
public int getInt(final String path);
-
+
/**
* Gets the requested int by path, returning a default value if not found.
*
@@ -257,7 +256,7 @@ public interface ConfigurationSection
* @return Requested int.
*/
public int getInt(final String path, final int def);
-
+
/**
* Checks if the specified path is an int.
*
@@ -270,7 +269,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is an int.
*/
public boolean isInt(final String path);
-
+
/**
* Gets the requested boolean by path.
*
@@ -282,7 +281,7 @@ public interface ConfigurationSection
* @return Requested boolean.
*/
public boolean getBoolean(final String path);
-
+
/**
* Gets the requested boolean by path, returning a default value if not
* found.
@@ -297,7 +296,7 @@ public interface ConfigurationSection
* @return Requested boolean.
*/
public boolean getBoolean(final String path, final boolean def);
-
+
/**
* Checks if the specified path is a boolean.
*
@@ -310,7 +309,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a boolean.
*/
public boolean isBoolean(final String path);
-
+
/**
* Gets the requested double by path.
*
@@ -322,7 +321,7 @@ public interface ConfigurationSection
* @return Requested double.
*/
public double getDouble(final String path);
-
+
/**
* Gets the requested double by path, returning a default value if not
* found.
@@ -337,7 +336,7 @@ public interface ConfigurationSection
* @return Requested double.
*/
public double getDouble(final String path, final double def);
-
+
/**
* Checks if the specified path is a double.
*
@@ -350,7 +349,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a double.
*/
public boolean isDouble(final String path);
-
+
/**
* Gets the requested long by path.
*
@@ -362,7 +361,7 @@ public interface ConfigurationSection
* @return Requested long.
*/
public long getLong(final String path);
-
+
/**
* Gets the requested long by path, returning a default value if not
* found.
@@ -377,7 +376,7 @@ public interface ConfigurationSection
* @return Requested long.
*/
public long getLong(final String path, final long def);
-
+
/**
* Checks if the specified path is a long.
*
@@ -390,7 +389,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a long.
*/
public boolean isLong(final String path);
-
+
// Java
/**
* Gets the requested List by path.
@@ -403,7 +402,7 @@ public interface ConfigurationSection
* @return Requested List.
*/
public List> getList(final String path);
-
+
/**
* Gets the requested List by path, returning a default value if not
* found.
@@ -418,7 +417,7 @@ public interface ConfigurationSection
* @return Requested List.
*/
public List> getList(final String path, final List> def);
-
+
/**
* Checks if the specified path is a List.
*
@@ -431,7 +430,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a List.
*/
public boolean isList(final String path);
-
+
/**
* Gets the requested List of String by path.
*
@@ -446,7 +445,7 @@ public interface ConfigurationSection
* @return Requested List of String.
*/
public List getStringList(final String path);
-
+
/**
* Gets the requested List of Integer by path.
*
@@ -461,7 +460,7 @@ public interface ConfigurationSection
* @return Requested List of Integer.
*/
public List getIntegerList(final String path);
-
+
/**
* Gets the requested List of Boolean by path.
*
@@ -476,7 +475,7 @@ public interface ConfigurationSection
* @return Requested List of Boolean.
*/
public List getBooleanList(final String path);
-
+
/**
* Gets the requested List of Double by path.
*
@@ -491,7 +490,7 @@ public interface ConfigurationSection
* @return Requested List of Double.
*/
public List getDoubleList(final String path);
-
+
/**
* Gets the requested List of Float by path.
*
@@ -506,7 +505,7 @@ public interface ConfigurationSection
* @return Requested List of Float.
*/
public List getFloatList(final String path);
-
+
/**
* Gets the requested List of Long by path.
*
@@ -521,7 +520,7 @@ public interface ConfigurationSection
* @return Requested List of Long.
*/
public List getLongList(final String path);
-
+
/**
* Gets the requested List of Byte by path.
*
@@ -536,7 +535,7 @@ public interface ConfigurationSection
* @return Requested List of Byte.
*/
public List getByteList(final String path);
-
+
/**
* Gets the requested List of Character by path.
*
@@ -551,7 +550,7 @@ public interface ConfigurationSection
* @return Requested List of Character.
*/
public List getCharacterList(final String path);
-
+
/**
* Gets the requested List of Short by path.
*
@@ -566,7 +565,7 @@ public interface ConfigurationSection
* @return Requested List of Short.
*/
public List getShortList(final String path);
-
+
/**
* Gets the requested List of Maps by path.
*
@@ -581,7 +580,7 @@ public interface ConfigurationSection
* @return Requested List of Maps.
*/
public List> getMapList(final String path);
-
+
/**
* Gets the requested ConfigurationSection by path.
*
@@ -594,7 +593,7 @@ public interface ConfigurationSection
* @return Requested ConfigurationSection.
*/
public ConfigurationSection getConfigurationSection(final String path);
-
+
/**
* Checks if the specified path is a ConfigurationSection.
*
@@ -608,7 +607,7 @@ public interface ConfigurationSection
* @return Whether or not the specified path is a ConfigurationSection.
*/
public boolean isConfigurationSection(final String path);
-
+
/**
* Gets the equivalent {@link ConfigurationSection} from the default
* {@link Configuration} defined in {@link #getRoot()}.
@@ -620,7 +619,7 @@ public interface ConfigurationSection
* @return Equivalent section in root configuration
*/
public ConfigurationSection getDefaultSection();
-
+
/**
* Sets the default value in the root at the given path as provided.
*
diff --git a/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java b/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java
index c7769dd7d..00791c3ce 100644
--- a/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java
+++ b/src/main/java/com/intellectualcrafters/configuration/InvalidConfigurationException.java
@@ -4,38 +4,34 @@ package com.intellectualcrafters.configuration;
* Exception thrown when attempting to load an invalid {@link Configuration}
*/
@SuppressWarnings("serial")
-public class InvalidConfigurationException extends Exception
-{
-
+public class InvalidConfigurationException extends Exception {
+
/**
* Creates a new instance of InvalidConfigurationException without a
* message or cause.
*/
- public InvalidConfigurationException()
- {}
-
+ public InvalidConfigurationException() {}
+
/**
* Constructs an instance of InvalidConfigurationException with the
* specified message.
*
* @param msg The details of the exception.
*/
- public InvalidConfigurationException(final String msg)
- {
+ public InvalidConfigurationException(final String msg) {
super(msg);
}
-
+
/**
* Constructs an instance of InvalidConfigurationException with the
* specified cause.
*
* @param cause The cause of the exception.
*/
- public InvalidConfigurationException(final Throwable cause)
- {
+ public InvalidConfigurationException(final Throwable cause) {
super(cause);
}
-
+
/**
* Constructs an instance of InvalidConfigurationException with the
* specified message and cause.
@@ -43,8 +39,7 @@ public class InvalidConfigurationException extends Exception
* @param cause The cause of the exception.
* @param msg The details of the exception.
*/
- public InvalidConfigurationException(final String msg, final Throwable cause)
- {
+ public InvalidConfigurationException(final String msg, final Throwable cause) {
super(msg, cause);
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java
index 5448f837a..d22312cae 100644
--- a/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java
+++ b/src/main/java/com/intellectualcrafters/configuration/MemoryConfiguration.java
@@ -7,17 +7,15 @@ import java.util.Map;
* from any source, and stores all values in memory only.
* This is useful for temporary Configurations for providing defaults.
*/
-public class MemoryConfiguration extends MemorySection implements Configuration
-{
+public class MemoryConfiguration extends MemorySection implements Configuration {
protected Configuration defaults;
protected MemoryConfigurationOptions options;
-
+
/**
* Creates an empty {@link MemoryConfiguration} with no default values.
*/
- public MemoryConfiguration()
- {}
-
+ public MemoryConfiguration() {}
+
/**
* Creates an empty {@link MemoryConfiguration} using the specified {@link
* Configuration} as a source for all default values.
@@ -25,70 +23,67 @@ public class MemoryConfiguration extends MemorySection implements Configuration
* @param defaults Default value provider
* @throws IllegalArgumentException Thrown if defaults is null
*/
- public MemoryConfiguration(final Configuration defaults)
- {
+ public MemoryConfiguration(final Configuration defaults) {
this.defaults = defaults;
}
-
+
@Override
- public void addDefault(final String path, final Object value)
- {
- if (path == null) { throw new NullPointerException("Path may not be null"); }
- if (defaults == null)
- {
+ public void addDefault(final String path, final Object value) {
+ if (path == null) {
+ throw new NullPointerException("Path may not be null");
+ }
+ if (defaults == null) {
defaults = new MemoryConfiguration();
}
-
+
defaults.set(path, value);
}
-
+
@Override
- public void addDefaults(final Map defaults)
- {
- if (defaults == null) { throw new NullPointerException("Defaults may not be null"); }
-
- for (final Map.Entry entry : defaults.entrySet())
- {
+ public void addDefaults(final Map defaults) {
+ if (defaults == null) {
+ throw new NullPointerException("Defaults may not be null");
+ }
+
+ for (final Map.Entry entry : defaults.entrySet()) {
addDefault(entry.getKey(), entry.getValue());
}
}
-
+
@Override
- public void addDefaults(final Configuration defaults)
- {
- if (defaults == null) { throw new NullPointerException("Defaults may not be null"); }
-
+ public void addDefaults(final Configuration defaults) {
+ if (defaults == null) {
+ throw new NullPointerException("Defaults may not be null");
+ }
+
addDefaults(defaults.getValues(true));
}
-
+
@Override
- public void setDefaults(final Configuration defaults)
- {
- if (defaults == null) { throw new NullPointerException("Defaults may not be null"); }
-
+ public void setDefaults(final Configuration defaults) {
+ if (defaults == null) {
+ throw new NullPointerException("Defaults may not be null");
+ }
+
this.defaults = defaults;
}
-
+
@Override
- public Configuration getDefaults()
- {
+ public Configuration getDefaults() {
return defaults;
}
-
+
@Override
- public ConfigurationSection getParent()
- {
+ public ConfigurationSection getParent() {
return null;
}
-
+
@Override
- public MemoryConfigurationOptions options()
- {
- if (options == null)
- {
+ public MemoryConfigurationOptions options() {
+ if (options == null) {
options = new MemoryConfigurationOptions(this);
}
-
+
return options;
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java
index 4e6af36c2..d395c0a7b 100644
--- a/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java
+++ b/src/main/java/com/intellectualcrafters/configuration/MemoryConfigurationOptions.java
@@ -4,29 +4,24 @@ package com.intellectualcrafters.configuration;
* Various settings for controlling the input and output of a {@link
* MemoryConfiguration}
*/
-public class MemoryConfigurationOptions extends ConfigurationOptions
-{
- protected MemoryConfigurationOptions(final MemoryConfiguration configuration)
- {
+public class MemoryConfigurationOptions extends ConfigurationOptions {
+ protected MemoryConfigurationOptions(final MemoryConfiguration configuration) {
super(configuration);
}
-
+
@Override
- public MemoryConfiguration configuration()
- {
+ public MemoryConfiguration configuration() {
return (MemoryConfiguration) super.configuration();
}
-
+
@Override
- public MemoryConfigurationOptions copyDefaults(final boolean value)
- {
+ public MemoryConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
-
+
@Override
- public MemoryConfigurationOptions pathSeparator(final char value)
- {
+ public MemoryConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java
index 042e9efe4..149aca21b 100644
--- a/src/main/java/com/intellectualcrafters/configuration/MemorySection.java
+++ b/src/main/java/com/intellectualcrafters/configuration/MemorySection.java
@@ -10,74 +10,64 @@ import java.util.Set;
/**
* A type of {@link ConfigurationSection} that is stored in memory.
*/
-public class MemorySection implements ConfigurationSection
-{
+public class MemorySection implements ConfigurationSection {
protected final Map map = new LinkedHashMap();
private final Configuration root;
private final ConfigurationSection parent;
private final String path;
private final String fullPath;
-
- public static double toDouble(final Object obj, final double def)
- {
- if (obj instanceof Number) { return ((Number) obj).doubleValue(); }
- if (obj instanceof String)
- {
- try
- {
+
+ public static double toDouble(final Object obj, final double def) {
+ if (obj instanceof Number) {
+ return ((Number) obj).doubleValue();
+ }
+ if (obj instanceof String) {
+ try {
return Double.parseDouble((String) obj);
- }
- catch (final Exception e)
- {}
- }
- else if (obj instanceof List)
- {
+ } catch (final Exception e) {}
+ } else if (obj instanceof List) {
final List> val = ((List>) obj);
- if (val.size() > 0) { return toDouble(val.get(0), def); }
+ if (val.size() > 0) {
+ return toDouble(val.get(0), def);
+ }
}
return def;
}
-
- public static int toInt(final Object obj, final int def)
- {
- if (obj instanceof Number) { return ((Number) obj).intValue(); }
- if (obj instanceof String)
- {
- try
- {
+
+ public static int toInt(final Object obj, final int def) {
+ if (obj instanceof Number) {
+ return ((Number) obj).intValue();
+ }
+ if (obj instanceof String) {
+ try {
return Integer.parseInt((String) obj);
- }
- catch (final Exception e)
- {}
- }
- else if (obj instanceof List)
- {
+ } catch (final Exception e) {}
+ } else if (obj instanceof List) {
final List> val = ((List>) obj);
- if (val.size() > 0) { return toInt(val.get(0), def); }
+ if (val.size() > 0) {
+ return toInt(val.get(0), def);
+ }
}
return def;
}
-
- public static long toLong(final Object obj, final long def)
- {
- if (obj instanceof Number) { return ((Number) obj).longValue(); }
- if (obj instanceof String)
- {
- try
- {
+
+ public static long toLong(final Object obj, final long def) {
+ if (obj instanceof Number) {
+ return ((Number) obj).longValue();
+ }
+ if (obj instanceof String) {
+ try {
return Long.parseLong((String) obj);
- }
- catch (final Exception e)
- {}
- }
- else if (obj instanceof List)
- {
+ } catch (final Exception e) {}
+ } else if (obj instanceof List) {
final List> val = ((List>) obj);
- if (val.size() > 0) { return toLong(val.get(0), def); }
+ if (val.size() > 0) {
+ return toLong(val.get(0), def);
+ }
}
return def;
}
-
+
/**
* Creates an empty MemorySection for use as a root {@link Configuration}
* section.
@@ -88,16 +78,17 @@ public class MemorySection implements ConfigurationSection
* @throws IllegalStateException Thrown if this is not a {@link
* Configuration} root.
*/
- protected MemorySection()
- {
- if (!(this instanceof Configuration)) { throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration"); }
-
+ protected MemorySection() {
+ if (!(this instanceof Configuration)) {
+ throw new IllegalStateException("Cannot construct a root MemorySection when not a Configuration");
+ }
+
path = "";
fullPath = "";
parent = null;
root = (Configuration) this;
}
-
+
/**
* Creates an empty MemorySection with the specified parent and path.
*
@@ -107,808 +98,697 @@ public class MemorySection implements ConfigurationSection
* @throws IllegalArgumentException Thrown is parent or path is null, or
* if parent contains no root Configuration.
*/
- protected MemorySection(final ConfigurationSection parent, final String path)
- {
- if (parent == null) { throw new NullPointerException("Parent may not be null"); }
- if (path == null) { throw new NullPointerException("Path may not be null"); }
-
+ protected MemorySection(final ConfigurationSection parent, final String path) {
+ if (parent == null) {
+ throw new NullPointerException("Parent may not be null");
+ }
+ if (path == null) {
+ throw new NullPointerException("Path may not be null");
+ }
+
this.path = path;
this.parent = parent;
root = parent.getRoot();
-
- if (root == null) { throw new NullPointerException("Path may not be orphaned"); }
-
+
+ if (root == null) {
+ throw new NullPointerException("Path may not be orphaned");
+ }
+
fullPath = createPath(parent, path);
}
-
+
@Override
- public Set getKeys(final boolean deep)
- {
+ public Set getKeys(final boolean deep) {
final Set result = new LinkedHashSet();
-
+
final Configuration root = getRoot();
- if ((root != null) && root.options().copyDefaults())
- {
+ if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
-
- if (defaults != null)
- {
+
+ if (defaults != null) {
result.addAll(defaults.getKeys(deep));
}
}
-
+
mapChildrenKeys(result, this, deep);
-
+
return result;
}
-
+
@Override
- public Map getValues(final boolean deep)
- {
+ public Map getValues(final boolean deep) {
final Map result = new LinkedHashMap();
-
+
final Configuration root = getRoot();
- if ((root != null) && root.options().copyDefaults())
- {
+ if ((root != null) && root.options().copyDefaults()) {
final ConfigurationSection defaults = getDefaultSection();
-
- if (defaults != null)
- {
+
+ if (defaults != null) {
result.putAll(defaults.getValues(deep));
}
}
-
+
mapChildrenValues(result, this, deep);
-
+
return result;
}
-
+
@Override
- public boolean contains(final String path)
- {
+ public boolean contains(final String path) {
return get(path) != null;
}
-
+
@Override
- public boolean isSet(final String path)
- {
+ public boolean isSet(final String path) {
final Configuration root = getRoot();
- if (root == null) { return false; }
- if (root.options().copyDefaults()) { return contains(path); }
+ if (root == null) {
+ return false;
+ }
+ if (root.options().copyDefaults()) {
+ return contains(path);
+ }
return get(path, null) != null;
}
-
+
@Override
- public String getCurrentPath()
- {
+ public String getCurrentPath() {
return fullPath;
}
-
+
@Override
- public String getName()
- {
+ public String getName() {
return path;
}
-
+
@Override
- public Configuration getRoot()
- {
+ public Configuration getRoot() {
return root;
}
-
+
@Override
- public ConfigurationSection getParent()
- {
+ public ConfigurationSection getParent() {
return parent;
}
-
+
@Override
- public void addDefault(final String path, final Object value)
- {
- if (path == null) { throw new NullPointerException("Path cannot be null"); }
-
+ public void addDefault(final String path, final Object value) {
+ if (path == null) {
+ throw new NullPointerException("Path cannot be null");
+ }
+
final Configuration root = getRoot();
- if (root == null) { throw new IllegalStateException("Cannot add default without root"); }
- if (root == this) { throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation"); }
+ if (root == null) {
+ throw new IllegalStateException("Cannot add default without root");
+ }
+ if (root == this) {
+ throw new UnsupportedOperationException("Unsupported addDefault(String, Object) implementation");
+ }
root.addDefault(createPath(this, path), value);
}
-
+
@Override
- public ConfigurationSection getDefaultSection()
- {
+ public ConfigurationSection getDefaultSection() {
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
-
- if (defaults != null)
- {
- if (defaults.isConfigurationSection(getCurrentPath())) { return defaults.getConfigurationSection(getCurrentPath()); }
+
+ if (defaults != null) {
+ if (defaults.isConfigurationSection(getCurrentPath())) {
+ return defaults.getConfigurationSection(getCurrentPath());
+ }
}
-
+
return null;
}
-
+
@Override
- public void set(final String path, final Object value)
- {
- if (path == null) { throw new NullPointerException("Cannot set to an empty path"); }
-
+ public void set(final String path, final Object value) {
+ if (path == null) {
+ throw new NullPointerException("Cannot set to an empty path");
+ }
+
final Configuration root = getRoot();
- if (root == null) { throw new IllegalStateException("Cannot use section without a root"); }
-
+ if (root == null) {
+ throw new IllegalStateException("Cannot use section without a root");
+ }
+
final char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
ConfigurationSection section = this;
- while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1)
- {
+ while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
final String node = path.substring(i2, i1);
final ConfigurationSection subSection = section.getConfigurationSection(node);
- if (subSection == null)
- {
+ if (subSection == null) {
section = section.createSection(node);
- }
- else
- {
+ } else {
section = subSection;
}
}
-
+
final String key = path.substring(i2);
- if (section == this)
- {
- if (value == null)
- {
+ if (section == this) {
+ if (value == null) {
map.remove(key);
- }
- else
- {
+ } else {
map.put(key, value);
}
- }
- else
- {
+ } else {
section.set(key, value);
}
}
-
+
@Override
- public Object get(final String path)
- {
+ public Object get(final String path) {
return get(path, getDefault(path));
}
-
+
@Override
- public Object get(final String path, final Object def)
- {
- if (path == null) { throw new NullPointerException("Path cannot be null"); }
-
- if (path.length() == 0) { return this; }
-
+ public Object get(final String path, final Object def) {
+ if (path == null) {
+ throw new NullPointerException("Path cannot be null");
+ }
+
+ if (path.length() == 0) {
+ return this;
+ }
+
final Configuration root = getRoot();
- if (root == null) { throw new IllegalStateException("Cannot access section without a root"); }
-
+ if (root == null) {
+ throw new IllegalStateException("Cannot access section without a root");
+ }
+
final char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
ConfigurationSection section = this;
- while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1)
- {
+ while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
section = section.getConfigurationSection(path.substring(i2, i1));
- if (section == null) { return def; }
+ if (section == null) {
+ return def;
+ }
}
-
+
final String key = path.substring(i2);
- if (section == this)
- {
+ if (section == this) {
final Object result = map.get(key);
return (result == null) ? def : result;
}
return section.get(key, def);
}
-
+
@Override
- public ConfigurationSection createSection(final String path)
- {
- if (path == null) { throw new NullPointerException("Cannot create section at empty path"); }
+ public ConfigurationSection createSection(final String path) {
+ if (path == null) {
+ throw new NullPointerException("Cannot create section at empty path");
+ }
final Configuration root = getRoot();
- if (root == null) { throw new IllegalStateException("Cannot create section without a root"); }
-
+ if (root == null) {
+ throw new IllegalStateException("Cannot create section without a root");
+ }
+
final char separator = root.options().pathSeparator();
// i1 is the leading (higher) index
// i2 is the trailing (lower) index
int i1 = -1, i2;
ConfigurationSection section = this;
- while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1)
- {
+ while ((i1 = path.indexOf(separator, i2 = i1 + 1)) != -1) {
final String node = path.substring(i2, i1);
final ConfigurationSection subSection = section.getConfigurationSection(node);
- if (subSection == null)
- {
+ if (subSection == null) {
section = section.createSection(node);
- }
- else
- {
+ } else {
section = subSection;
}
}
-
+
final String key = path.substring(i2);
- if (section == this)
- {
+ if (section == this) {
final ConfigurationSection result = new MemorySection(this, key);
map.put(key, result);
return result;
}
return section.createSection(key);
}
-
+
@Override
- public ConfigurationSection createSection(final String path, final Map, ?> map)
- {
+ public ConfigurationSection createSection(final String path, final Map, ?> map) {
final ConfigurationSection section = createSection(path);
-
- for (final Map.Entry, ?> entry : map.entrySet())
- {
- if (entry.getValue() instanceof Map)
- {
+
+ for (final Map.Entry, ?> entry : map.entrySet()) {
+ if (entry.getValue() instanceof Map) {
section.createSection(entry.getKey().toString(), (Map, ?>) entry.getValue());
- }
- else
- {
+ } else {
section.set(entry.getKey().toString(), entry.getValue());
}
}
-
+
return section;
}
-
+
// Primitives
@Override
- public String getString(final String path)
- {
+ public String getString(final String path) {
final Object def = getDefault(path);
return getString(path, def != null ? def.toString() : null);
}
-
+
@Override
- public String getString(final String path, final String def)
- {
+ public String getString(final String path, final String def) {
final Object val = get(path, def);
return (val != null) ? val.toString() : def;
}
-
+
@Override
- public boolean isString(final String path)
- {
+ public boolean isString(final String path) {
final Object val = get(path);
return val instanceof String;
}
-
+
@Override
- public int getInt(final String path)
- {
+ public int getInt(final String path) {
final Object def = getDefault(path);
return getInt(path, toInt(def, 0));
}
-
+
@Override
- public int getInt(final String path, final int def)
- {
+ public int getInt(final String path, final int def) {
final Object val = get(path, def);
return toInt(val, def);
}
-
+
@Override
- public boolean isInt(final String path)
- {
+ public boolean isInt(final String path) {
final Object val = get(path);
return val instanceof Integer;
}
-
+
@Override
- public boolean getBoolean(final String path)
- {
+ public boolean getBoolean(final String path) {
final Object def = getDefault(path);
return getBoolean(path, (def instanceof Boolean) ? (Boolean) def : false);
}
-
+
@Override
- public boolean getBoolean(final String path, final boolean def)
- {
+ public boolean getBoolean(final String path, final boolean def) {
final Object val = get(path, def);
return (val instanceof Boolean) ? (Boolean) val : def;
}
-
+
@Override
- public boolean isBoolean(final String path)
- {
+ public boolean isBoolean(final String path) {
final Object val = get(path);
return val instanceof Boolean;
}
-
+
@Override
- public double getDouble(final String path)
- {
+ public double getDouble(final String path) {
final Object def = getDefault(path);
return getDouble(path, toDouble(def, 0));
}
-
+
@Override
- public double getDouble(final String path, final double def)
- {
+ public double getDouble(final String path, final double def) {
final Object val = get(path, def);
return toDouble(val, def);
}
-
+
@Override
- public boolean isDouble(final String path)
- {
+ public boolean isDouble(final String path) {
final Object val = get(path);
return val instanceof Double;
}
-
+
@Override
- public long getLong(final String path)
- {
+ public long getLong(final String path) {
final Object def = getDefault(path);
return getLong(path, toLong(def, 0));
}
-
+
@Override
- public long getLong(final String path, final long def)
- {
+ public long getLong(final String path, final long def) {
final Object val = get(path, def);
return toLong(val, def);
}
-
+
@Override
- public boolean isLong(final String path)
- {
+ public boolean isLong(final String path) {
final Object val = get(path);
return val instanceof Long;
}
-
+
// Java
@Override
- public List> getList(final String path)
- {
+ public List> getList(final String path) {
final Object def = getDefault(path);
return getList(path, (def instanceof List) ? (List>) def : null);
}
-
+
@Override
- public List> getList(final String path, final List> def)
- {
+ public List> getList(final String path, final List> def) {
final Object val = get(path, def);
return (List>) ((val instanceof List) ? val : def);
}
-
+
@Override
- public boolean isList(final String path)
- {
+ public boolean isList(final String path) {
final Object val = get(path);
return val instanceof List;
}
-
+
@Override
- public List getStringList(final String path)
- {
+ public List getStringList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if ((object instanceof String) || (isPrimitiveWrapper(object)))
- {
+
+ for (final Object object : list) {
+ if ((object instanceof String) || (isPrimitiveWrapper(object))) {
result.add(String.valueOf(object));
}
}
-
+
return result;
}
-
+
@Override
- public List getIntegerList(final String path)
- {
+ public List getIntegerList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Integer)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Integer) {
result.add((Integer) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Integer.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((int) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).intValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getBooleanList(final String path)
- {
+ public List getBooleanList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Boolean)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Boolean) {
result.add((Boolean) object);
- }
- else if (object instanceof String)
- {
- if (Boolean.TRUE.toString().equals(object))
- {
+ } else if (object instanceof String) {
+ if (Boolean.TRUE.toString().equals(object)) {
result.add(true);
- }
- else if (Boolean.FALSE.toString().equals(object))
- {
+ } else if (Boolean.FALSE.toString().equals(object)) {
result.add(false);
}
}
}
-
+
return result;
}
-
+
@Override
- public List getDoubleList(final String path)
- {
+ public List getDoubleList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Double)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Double) {
result.add((Double) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Double.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((double) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).doubleValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getFloatList(final String path)
- {
+ public List getFloatList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Float)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Float) {
result.add((Float) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Float.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((float) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).floatValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getLongList(final String path)
- {
+ public List getLongList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Long)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Long) {
result.add((Long) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Long.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((long) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).longValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getByteList(final String path)
- {
+ public List getByteList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Byte)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Byte) {
result.add((Byte) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Byte.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((byte) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).byteValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getCharacterList(final String path)
- {
+ public List getCharacterList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Character)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Character) {
result.add((Character) object);
- }
- else if (object instanceof String)
- {
+ } else if (object instanceof String) {
final String str = (String) object;
-
- if (str.length() == 1)
- {
+
+ if (str.length() == 1) {
result.add(str.charAt(0));
}
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add((char) ((Number) object).intValue());
}
}
-
+
return result;
}
-
+
@Override
- public List getShortList(final String path)
- {
+ public List getShortList(final String path) {
final List> list = getList(path);
-
- if (list == null) { return new ArrayList(0); }
-
+
+ if (list == null) {
+ return new ArrayList(0);
+ }
+
final List result = new ArrayList();
-
- for (final Object object : list)
- {
- if (object instanceof Short)
- {
+
+ for (final Object object : list) {
+ if (object instanceof Short) {
result.add((Short) object);
- }
- else if (object instanceof String)
- {
- try
- {
+ } else if (object instanceof String) {
+ try {
result.add(Short.valueOf((String) object));
- }
- catch (final Exception ex)
- {}
- }
- else if (object instanceof Character)
- {
+ } catch (final Exception ex) {}
+ } else if (object instanceof Character) {
result.add((short) ((Character) object).charValue());
- }
- else if (object instanceof Number)
- {
+ } else if (object instanceof Number) {
result.add(((Number) object).shortValue());
}
}
-
+
return result;
}
-
+
@Override
- public List> getMapList(final String path)
- {
+ public List> getMapList(final String path) {
final List> list = getList(path);
final List> result = new ArrayList>();
-
- if (list == null) { return result; }
-
- for (final Object object : list)
- {
- if (object instanceof Map)
- {
+
+ if (list == null) {
+ return result;
+ }
+
+ for (final Object object : list) {
+ if (object instanceof Map) {
result.add((Map, ?>) object);
}
}
-
+
return result;
}
-
+
@Override
- public ConfigurationSection getConfigurationSection(final String path)
- {
+ public ConfigurationSection getConfigurationSection(final String path) {
Object val = get(path, null);
- if (val != null) { return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null; }
-
+ if (val != null) {
+ return (val instanceof ConfigurationSection) ? (ConfigurationSection) val : null;
+ }
+
val = get(path, getDefault(path));
return (val instanceof ConfigurationSection) ? createSection(path) : null;
}
-
+
@Override
- public boolean isConfigurationSection(final String path)
- {
+ public boolean isConfigurationSection(final String path) {
final Object val = get(path);
return val instanceof ConfigurationSection;
}
-
- protected boolean isPrimitiveWrapper(final Object input)
- {
- return (input instanceof Integer) || (input instanceof Boolean) ||
- (input instanceof Character) || (input instanceof Byte) ||
- (input instanceof Short) || (input instanceof Double) ||
- (input instanceof Long) || (input instanceof Float);
+
+ protected boolean isPrimitiveWrapper(final Object input) {
+ return (input instanceof Integer)
+ || (input instanceof Boolean)
+ || (input instanceof Character)
+ || (input instanceof Byte)
+ || (input instanceof Short)
+ || (input instanceof Double)
+ || (input instanceof Long)
+ || (input instanceof Float);
}
-
- protected Object getDefault(final String path)
- {
- if (path == null) { throw new NullPointerException("Path may not be null"); }
-
+
+ protected Object getDefault(final String path) {
+ if (path == null) {
+ throw new NullPointerException("Path may not be null");
+ }
+
final Configuration root = getRoot();
final Configuration defaults = root == null ? null : root.getDefaults();
return (defaults == null) ? null : defaults.get(createPath(this, path));
}
-
- protected void mapChildrenKeys(final Set output, final ConfigurationSection section, final boolean deep)
- {
- if (section instanceof MemorySection)
- {
+
+ protected void mapChildrenKeys(final Set output, final ConfigurationSection section, final boolean deep) {
+ if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
-
- for (final Map.Entry entry : sec.map.entrySet())
- {
+
+ for (final Map.Entry entry : sec.map.entrySet()) {
output.add(createPath(section, entry.getKey(), this));
-
- if ((deep) && (entry.getValue() instanceof ConfigurationSection))
- {
+
+ if ((deep) && (entry.getValue() instanceof ConfigurationSection)) {
final ConfigurationSection subsection = (ConfigurationSection) entry.getValue();
mapChildrenKeys(output, subsection, deep);
}
}
- }
- else
- {
+ } else {
final Set keys = section.getKeys(deep);
-
- for (final String key : keys)
- {
+
+ for (final String key : keys) {
output.add(createPath(section, key, this));
}
}
}
-
- protected void mapChildrenValues(final Map output, final ConfigurationSection section, final boolean deep)
- {
- if (section instanceof MemorySection)
- {
+
+ protected void mapChildrenValues(final Map output, final ConfigurationSection section, final boolean deep) {
+ if (section instanceof MemorySection) {
final MemorySection sec = (MemorySection) section;
-
- for (final Map.Entry entry : sec.map.entrySet())
- {
+
+ for (final Map.Entry entry : sec.map.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
-
- if (entry.getValue() instanceof ConfigurationSection)
- {
- if (deep)
- {
+
+ if (entry.getValue() instanceof ConfigurationSection) {
+ if (deep) {
mapChildrenValues(output, (ConfigurationSection) entry.getValue(), deep);
}
}
}
- }
- else
- {
+ } else {
final Map values = section.getValues(deep);
-
- for (final Map.Entry entry : values.entrySet())
- {
+
+ for (final Map.Entry entry : values.entrySet()) {
output.put(createPath(section, entry.getKey(), this), entry.getValue());
}
}
}
-
+
/**
* Creates a full path to the given {@link ConfigurationSection} from its
* root {@link Configuration}.
@@ -920,11 +800,10 @@ public class MemorySection implements ConfigurationSection
* @param key Name of the specified section.
* @return Full path of the section from its root.
*/
- public static String createPath(final ConfigurationSection section, final String key)
- {
+ public static String createPath(final ConfigurationSection section, final String key) {
return createPath(section, key, (section == null) ? null : section.getRoot());
}
-
+
/**
* Creates a relative path to the given {@link ConfigurationSection} from
* the given relative section.
@@ -937,51 +816,42 @@ public class MemorySection implements ConfigurationSection
* @param relativeTo Section to create the path relative to.
* @return Full path of the section from its root.
*/
- public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo)
- {
- if (section == null) { throw new NullPointerException("Cannot create path without a section"); }
+ public static String createPath(final ConfigurationSection section, final String key, final ConfigurationSection relativeTo) {
+ if (section == null) {
+ throw new NullPointerException("Cannot create path without a section");
+ }
final Configuration root = section.getRoot();
- if (root == null) { throw new IllegalStateException("Cannot create path without a root"); }
+ if (root == null) {
+ throw new IllegalStateException("Cannot create path without a root");
+ }
final char separator = root.options().pathSeparator();
-
+
final StringBuilder builder = new StringBuilder();
- if (section != null)
- {
- for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent())
- {
- if (builder.length() > 0)
- {
+ if (section != null) {
+ for (ConfigurationSection parent = section; (parent != null) && (parent != relativeTo); parent = parent.getParent()) {
+ if (builder.length() > 0) {
builder.insert(0, separator);
}
-
+
builder.insert(0, parent.getName());
}
}
-
- if ((key != null) && (key.length() > 0))
- {
- if (builder.length() > 0)
- {
+
+ if ((key != null) && (key.length() > 0)) {
+ if (builder.length() > 0) {
builder.append(separator);
}
-
+
builder.append(key);
}
-
+
return builder.toString();
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final Configuration root = getRoot();
- return new StringBuilder()
- .append(getClass().getSimpleName())
- .append("[path='")
- .append(getCurrentPath())
- .append("', root='")
- .append(root == null ? null : root.getClass().getSimpleName())
- .append("']")
- .toString();
+ return new StringBuilder().append(getClass().getSimpleName()).append("[path='").append(getCurrentPath()).append("', root='").append(root == null ? null : root.getClass().getSimpleName())
+ .append("']").toString();
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java
index 5cec0073b..553b76044 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/FileConfiguration.java
@@ -24,8 +24,7 @@ import com.intellectualcrafters.configuration.MemoryConfiguration;
* This is a base class for all File based implementations of {@link
* Configuration}
*/
-public abstract class FileConfiguration extends MemoryConfiguration
-{
+public abstract class FileConfiguration extends MemoryConfiguration {
/**
* This value specified that the system default encoding should be
* completely ignored, as it cannot handle the ASCII character set, or it
@@ -50,8 +49,7 @@ public abstract class FileConfiguration extends MemoryConfiguration
*/
@Deprecated
public static final boolean SYSTEM_UTF;
- static
- {
+ static {
final byte[] testBytes = Base64Coder.decode("ICEiIyQlJicoKSorLC0uLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX4NCg==");
final String testString = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\r\n";
final Charset defaultCharset = Charset.defaultCharset();
@@ -61,26 +59,24 @@ public abstract class FileConfiguration extends MemoryConfiguration
SYSTEM_UTF = trueUTF || UTF8_OVERRIDE;
UTF_BIG = trueUTF && UTF8_OVERRIDE;
}
-
+
/**
* Creates an empty {@link FileConfiguration} with no default values.
*/
- public FileConfiguration()
- {
+ public FileConfiguration() {
super();
}
-
+
/**
* Creates an empty {@link FileConfiguration} using the specified {@link
* Configuration} as a source for all default values.
*
* @param defaults Default value provider
*/
- public FileConfiguration(final Configuration defaults)
- {
+ public FileConfiguration(final Configuration defaults) {
super(defaults);
}
-
+
/**
* Saves this {@link FileConfiguration} to the specified location.
*
@@ -96,25 +92,23 @@ public abstract class FileConfiguration extends MemoryConfiguration
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
- public void save(final File file) throws IOException
- {
- if (file == null) { throw new NullPointerException("File cannot be null"); }
- file.getParentFile().mkdirs();
-
- final String data = saveToString();
-
- final Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset());
-
- try
- {
- writer.write(data);
+ public void save(final File file) throws IOException {
+ if (file == null) {
+ throw new NullPointerException("File cannot be null");
}
- finally
- {
+ file.getParentFile().mkdirs();
+
+ final String data = saveToString();
+
+ final Writer writer = new OutputStreamWriter(new FileOutputStream(file), UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset());
+
+ try {
+ writer.write(data);
+ } finally {
writer.close();
}
}
-
+
/**
* Saves this {@link FileConfiguration} to the specified location.
*
@@ -130,20 +124,21 @@ public abstract class FileConfiguration extends MemoryConfiguration
* any reason.
* @throws IllegalArgumentException Thrown when file is null.
*/
- public void save(final String file) throws IOException
- {
- if (file == null) { throw new NullPointerException("File cannot be null"); }
-
+ public void save(final String file) throws IOException {
+ if (file == null) {
+ throw new NullPointerException("File cannot be null");
+ }
+
save(new File(file));
}
-
+
/**
* Saves this {@link FileConfiguration} to a string, and returns it.
*
* @return String containing this configuration.
*/
public abstract String saveToString();
-
+
/**
* Loads this {@link FileConfiguration} from the specified location.
*
@@ -166,15 +161,16 @@ public abstract class FileConfiguration extends MemoryConfiguration
* a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null.
*/
- public void load(final File file) throws IOException, InvalidConfigurationException
- {
- if (file == null) { throw new NullPointerException("File cannot be null"); }
-
+ public void load(final File file) throws IOException, InvalidConfigurationException {
+ if (file == null) {
+ throw new NullPointerException("File cannot be null");
+ }
+
final FileInputStream stream = new FileInputStream(file);
-
+
load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? StandardCharsets.UTF_8 : Charset.defaultCharset()));
}
-
+
/**
* Loads this {@link FileConfiguration} from the specified stream.
*
@@ -194,13 +190,14 @@ public abstract class FileConfiguration extends MemoryConfiguration
* @see #load(Reader)
*/
@Deprecated
- public void load(final InputStream stream) throws IOException, InvalidConfigurationException
- {
- if (stream == null) { throw new NullPointerException("Stream cannot be null"); }
-
+ public void load(final InputStream stream) throws IOException, InvalidConfigurationException {
+ if (stream == null) {
+ throw new NullPointerException("Stream cannot be null");
+ }
+
load(new InputStreamReader(stream, UTF8_OVERRIDE ? StandardCharsets.UTF_8 : Charset.defaultCharset()));
}
-
+
/**
* Loads this {@link FileConfiguration} from the specified reader.
*
@@ -214,30 +211,25 @@ public abstract class FileConfiguration extends MemoryConfiguration
* represent a valid Configuration
* @throws IllegalArgumentException thrown when reader is null
*/
- public void load(final Reader reader) throws IOException, InvalidConfigurationException
- {
+ public void load(final Reader reader) throws IOException, InvalidConfigurationException {
final BufferedReader input = reader instanceof BufferedReader ? (BufferedReader) reader : new BufferedReader(reader);
-
+
final StringBuilder builder = new StringBuilder();
-
- try
- {
+
+ try {
String line;
-
- while ((line = input.readLine()) != null)
- {
+
+ while ((line = input.readLine()) != null) {
builder.append(line);
builder.append('\n');
}
- }
- finally
- {
+ } finally {
input.close();
}
-
+
loadFromString(builder.toString());
}
-
+
/**
* Loads this {@link FileConfiguration} from the specified location.
*
@@ -256,13 +248,14 @@ public abstract class FileConfiguration extends MemoryConfiguration
* a valid Configuration.
* @throws IllegalArgumentException Thrown when file is null.
*/
- public void load(final String file) throws IOException, InvalidConfigurationException
- {
- if (file == null) { throw new NullPointerException("File cannot be null"); }
-
+ public void load(final String file) throws IOException, InvalidConfigurationException {
+ if (file == null) {
+ throw new NullPointerException("File cannot be null");
+ }
+
load(new File(file));
}
-
+
/**
* Loads this {@link FileConfiguration} from the specified string, as
* opposed to from file.
@@ -279,7 +272,7 @@ public abstract class FileConfiguration extends MemoryConfiguration
* @throws IllegalArgumentException Thrown if contents is null.
*/
public abstract void loadFromString(final String contents) throws InvalidConfigurationException;
-
+
/**
* Compiles the header for this {@link FileConfiguration} and returns the
* result.
@@ -291,15 +284,13 @@ public abstract class FileConfiguration extends MemoryConfiguration
* @return Compiled header
*/
protected abstract String buildHeader();
-
+
@Override
- public FileConfigurationOptions options()
- {
- if (options == null)
- {
+ public FileConfigurationOptions options() {
+ if (options == null) {
options = new FileConfigurationOptions(this);
}
-
+
return (FileConfigurationOptions) options;
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java
index 9b26be71c..8c3d830a3 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/FileConfigurationOptions.java
@@ -7,36 +7,31 @@ import com.intellectualcrafters.configuration.MemoryConfigurationOptions;
* Various settings for controlling the input and output of a {@link
* FileConfiguration}
*/
-public class FileConfigurationOptions extends MemoryConfigurationOptions
-{
+public class FileConfigurationOptions extends MemoryConfigurationOptions {
private String header = null;
private boolean copyHeader = true;
-
- protected FileConfigurationOptions(final MemoryConfiguration configuration)
- {
+
+ protected FileConfigurationOptions(final MemoryConfiguration configuration) {
super(configuration);
}
-
+
@Override
- public FileConfiguration configuration()
- {
+ public FileConfiguration configuration() {
return (FileConfiguration) super.configuration();
}
-
+
@Override
- public FileConfigurationOptions copyDefaults(final boolean value)
- {
+ public FileConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
-
+
@Override
- public FileConfigurationOptions pathSeparator(final char value)
- {
+ public FileConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}
-
+
/**
* Gets the header that will be applied to the top of the saved output.
*
@@ -51,11 +46,10 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions
*
* @return Header
*/
- public String header()
- {
+ public String header() {
return header;
}
-
+
/**
* Sets the header that will be applied to the top of the saved output.
*
@@ -71,12 +65,11 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions
* @param value New header
* @return This object, for chaining
*/
- public FileConfigurationOptions header(final String value)
- {
+ public FileConfigurationOptions header(final String value) {
header = value;
return this;
}
-
+
/**
* Gets whether or not the header should be copied from a default source.
*
@@ -95,11 +88,10 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions
*
* @return Whether or not to copy the header
*/
- public boolean copyHeader()
- {
+ public boolean copyHeader() {
return copyHeader;
}
-
+
/**
* Sets whether or not the header should be copied from a default source.
*
@@ -119,10 +111,9 @@ public class FileConfigurationOptions extends MemoryConfigurationOptions
* @param value Whether or not to copy the header
* @return This object, for chaining
*/
- public FileConfigurationOptions copyHeader(final boolean value)
- {
+ public FileConfigurationOptions copyHeader(final boolean value) {
copyHeader = value;
-
+
return this;
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java
index 2a3a5fc20..1ab3a6f61 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfiguration.java
@@ -22,170 +22,144 @@ import com.intellectualcrafters.plot.PS;
* An implementation of {@link Configuration} which saves all files in Yaml.
* Note that this implementation is not synchronized.
*/
-public class YamlConfiguration extends FileConfiguration
-{
+public class YamlConfiguration extends FileConfiguration {
protected static final String COMMENT_PREFIX = "# ";
protected static final String BLANK_CONFIG = "{}\n";
private final DumperOptions yamlOptions = new DumperOptions();
private final Representer yamlRepresenter = new YamlRepresenter();
private final Yaml yaml = new Yaml(new YamlConstructor(), yamlRepresenter, yamlOptions);
-
+
@Override
- public String saveToString()
- {
+ public String saveToString() {
yamlOptions.setIndent(options().indent());
yamlOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
yamlOptions.setAllowUnicode(SYSTEM_UTF);
yamlRepresenter.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
-
+
final String header = buildHeader();
String dump = yaml.dump(getValues(false));
-
- if (dump.equals(BLANK_CONFIG))
- {
+
+ if (dump.equals(BLANK_CONFIG)) {
dump = "";
}
-
+
return header + dump;
}
-
+
@Override
- public void loadFromString(final String contents) throws InvalidConfigurationException
- {
- if (contents == null) { throw new NullPointerException("Contents cannot be null"); }
-
+ public void loadFromString(final String contents) throws InvalidConfigurationException {
+ if (contents == null) {
+ throw new NullPointerException("Contents cannot be null");
+ }
+
Map, ?> input;
- try
- {
+ try {
input = (Map, ?>) yaml.load(contents);
- }
- catch (final YAMLException e)
- {
+ } catch (final YAMLException e) {
throw new InvalidConfigurationException(e);
- }
- catch (final ClassCastException e)
- {
+ } catch (final ClassCastException e) {
throw new InvalidConfigurationException("Top level is not a Map.");
}
-
+
final String header = parseHeader(contents);
- if (header.length() > 0)
- {
+ if (header.length() > 0) {
options().header(header);
}
-
- if (input != null)
- {
+
+ if (input != null) {
convertMapsToSections(input, this);
}
}
-
- protected void convertMapsToSections(final Map, ?> input, final ConfigurationSection section)
- {
- for (final Map.Entry, ?> entry : input.entrySet())
- {
+
+ protected void convertMapsToSections(final Map, ?> input, final ConfigurationSection section) {
+ for (final Map.Entry, ?> entry : input.entrySet()) {
final String key = entry.getKey().toString();
final Object value = entry.getValue();
-
- if (value instanceof Map)
- {
+
+ if (value instanceof Map) {
convertMapsToSections((Map, ?>) value, section.createSection(key));
- }
- else
- {
+ } else {
section.set(key, value);
}
}
}
-
- protected String parseHeader(final String input)
- {
+
+ protected String parseHeader(final String input) {
final String[] lines = input.split("\r?\n", -1);
final StringBuilder result = new StringBuilder();
boolean readingHeader = true;
boolean foundHeader = false;
-
- for (int i = 0; (i < lines.length) && (readingHeader); i++)
- {
+
+ for (int i = 0; (i < lines.length) && (readingHeader); i++) {
final String line = lines[i];
-
- if (line.startsWith(COMMENT_PREFIX))
- {
- if (i > 0)
- {
+
+ if (line.startsWith(COMMENT_PREFIX)) {
+ if (i > 0) {
result.append("\n");
}
-
- if (line.length() > COMMENT_PREFIX.length())
- {
+
+ if (line.length() > COMMENT_PREFIX.length()) {
result.append(line.substring(COMMENT_PREFIX.length()));
}
-
+
foundHeader = true;
- }
- else if ((foundHeader) && (line.length() == 0))
- {
+ } else if ((foundHeader) && (line.length() == 0)) {
result.append("\n");
- }
- else if (foundHeader)
- {
+ } else if (foundHeader) {
readingHeader = false;
}
}
-
+
return result.toString();
}
-
+
@Override
- protected String buildHeader()
- {
+ protected String buildHeader() {
final String header = options().header();
-
- if (options().copyHeader())
- {
+
+ if (options().copyHeader()) {
final Configuration def = getDefaults();
-
- if ((def != null) && (def instanceof FileConfiguration))
- {
+
+ if ((def != null) && (def instanceof FileConfiguration)) {
final FileConfiguration filedefaults = (FileConfiguration) def;
final String defaultsHeader = filedefaults.buildHeader();
-
- if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) { return defaultsHeader; }
+
+ if ((defaultsHeader != null) && (defaultsHeader.length() > 0)) {
+ return defaultsHeader;
+ }
}
}
-
- if (header == null) { return ""; }
-
+
+ if (header == null) {
+ return "";
+ }
+
final StringBuilder builder = new StringBuilder();
final String[] lines = header.split("\r?\n", -1);
boolean startedHeader = false;
-
- for (int i = lines.length - 1; i >= 0; i--)
- {
+
+ for (int i = lines.length - 1; i >= 0; i--) {
builder.insert(0, "\n");
-
- if ((startedHeader) || (lines[i].length() != 0))
- {
+
+ if ((startedHeader) || (lines[i].length() != 0)) {
builder.insert(0, lines[i]);
builder.insert(0, COMMENT_PREFIX);
startedHeader = true;
}
}
-
+
return builder.toString();
}
-
+
@Override
- public YamlConfigurationOptions options()
- {
- if (options == null)
- {
+ public YamlConfigurationOptions options() {
+ if (options == null) {
options = new YamlConfigurationOptions(this);
}
-
+
return (YamlConfigurationOptions) options;
}
-
+
/**
* Creates a new {@link YamlConfiguration}, loading from the given file.
*
@@ -199,25 +173,21 @@ public class YamlConfiguration extends FileConfiguration
* @return Resulting configuration
* @throws IllegalArgumentException Thrown if file is null
*/
- public static YamlConfiguration loadConfiguration(final File file)
- {
- if (file == null) { throw new NullPointerException("File cannot be null"); }
-
- final YamlConfiguration config = new YamlConfiguration();
-
- try
- {
- config.load(file);
+ public static YamlConfiguration loadConfiguration(final File file) {
+ if (file == null) {
+ throw new NullPointerException("File cannot be null");
}
- catch (final Exception ex)
- {
- try
- {
+
+ final YamlConfiguration config = new YamlConfiguration();
+
+ try {
+ config.load(file);
+ } catch (final Exception ex) {
+ try {
file.getAbsolutePath();
File dest = new File(file.getAbsolutePath() + "_broken");
int i = 0;
- while (dest.exists())
- {
+ while (dest.exists()) {
dest = new File(file.getAbsolutePath() + "_broken_" + i++);
}
Files.copy(file.toPath(), dest.toPath(), StandardCopyOption.REPLACE_EXISTING);
@@ -226,16 +196,14 @@ public class YamlConfiguration extends FileConfiguration
PS.debug("&c============ Full stacktrace ============");
ex.printStackTrace();
PS.debug("&c=========================================");
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
e.printStackTrace();
}
}
-
+
return config;
}
-
+
/**
* Creates a new {@link YamlConfiguration}, loading from the given stream.
*
@@ -251,30 +219,26 @@ public class YamlConfiguration extends FileConfiguration
* @see #loadConfiguration(Reader)
*/
@Deprecated
- public static YamlConfiguration loadConfiguration(final InputStream stream)
- {
- if (stream == null) { throw new NullPointerException("Stream cannot be null"); }
-
+ public static YamlConfiguration loadConfiguration(final InputStream stream) {
+ if (stream == null) {
+ throw new NullPointerException("Stream cannot be null");
+ }
+
final YamlConfiguration config = new YamlConfiguration();
-
- try
- {
+
+ try {
config.load(stream);
- }
- catch (final IOException ex)
- {
+ } catch (final IOException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
- }
- catch (final InvalidConfigurationException ex)
- {
+ } catch (final InvalidConfigurationException ex) {
ex.printStackTrace();
PS.debug("Cannot load configuration from stream");
}
-
+
return config;
}
-
+
/**
* Creates a new {@link YamlConfiguration}, loading from the given reader.
*
@@ -286,27 +250,23 @@ public class YamlConfiguration extends FileConfiguration
* @return resulting configuration
* @throws IllegalArgumentException Thrown if stream is null
*/
- public static YamlConfiguration loadConfiguration(final Reader reader)
- {
- if (reader == null) { throw new NullPointerException("Reader cannot be null"); }
-
+ public static YamlConfiguration loadConfiguration(final Reader reader) {
+ if (reader == null) {
+ throw new NullPointerException("Reader cannot be null");
+ }
+
final YamlConfiguration config = new YamlConfiguration();
-
- try
- {
+
+ try {
config.load(reader);
- }
- catch (final IOException ex)
- {
+ } catch (final IOException ex) {
+ PS.debug("Cannot load configuration from stream");
+ ex.printStackTrace();
+ } catch (final InvalidConfigurationException ex) {
PS.debug("Cannot load configuration from stream");
ex.printStackTrace();
}
- catch (final InvalidConfigurationException ex)
- {
- PS.debug("Cannot load configuration from stream");
- ex.printStackTrace();
- }
-
+
return config;
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java
index 75eae9250..236325ae0 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConfigurationOptions.java
@@ -4,49 +4,42 @@ package com.intellectualcrafters.configuration.file;
* Various settings for controlling the input and output of a {@link
* YamlConfiguration}
*/
-public class YamlConfigurationOptions extends FileConfigurationOptions
-{
+public class YamlConfigurationOptions extends FileConfigurationOptions {
private int indent = 2;
-
- protected YamlConfigurationOptions(final YamlConfiguration configuration)
- {
+
+ protected YamlConfigurationOptions(final YamlConfiguration configuration) {
super(configuration);
}
-
+
@Override
- public YamlConfiguration configuration()
- {
+ public YamlConfiguration configuration() {
return (YamlConfiguration) super.configuration();
}
-
+
@Override
- public YamlConfigurationOptions copyDefaults(final boolean value)
- {
+ public YamlConfigurationOptions copyDefaults(final boolean value) {
super.copyDefaults(value);
return this;
}
-
+
@Override
- public YamlConfigurationOptions pathSeparator(final char value)
- {
+ public YamlConfigurationOptions pathSeparator(final char value) {
super.pathSeparator(value);
return this;
}
-
+
@Override
- public YamlConfigurationOptions header(final String value)
- {
+ public YamlConfigurationOptions header(final String value) {
super.header(value);
return this;
}
-
+
@Override
- public YamlConfigurationOptions copyHeader(final boolean value)
- {
+ public YamlConfigurationOptions copyHeader(final boolean value) {
super.copyHeader(value);
return this;
}
-
+
/**
* Gets how much spaces should be used to indent each line.
*
@@ -54,11 +47,10 @@ public class YamlConfigurationOptions extends FileConfigurationOptions
*
* @return How much to indent by
*/
- public int indent()
- {
+ public int indent() {
return indent;
}
-
+
/**
* Sets how much spaces should be used to indent each line.
*
@@ -67,11 +59,14 @@ public class YamlConfigurationOptions extends FileConfigurationOptions
* @param value New indent
* @return This object, for chaining
*/
- public YamlConfigurationOptions indent(final int value)
- {
- if (value < 2) { throw new IllegalArgumentException("Indent must be at least 2 characters"); }
- if (value > 9) { throw new IllegalArgumentException("Indent cannot be greater than 9 characters"); }
-
+ public YamlConfigurationOptions indent(final int value) {
+ if (value < 2) {
+ throw new IllegalArgumentException("Indent must be at least 2 characters");
+ }
+ if (value > 9) {
+ throw new IllegalArgumentException("Indent cannot be greater than 9 characters");
+ }
+
indent = value;
return this;
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java
index 688a53791..0689c06d9 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlConstructor.java
@@ -10,47 +10,39 @@ import org.yaml.snakeyaml.nodes.Tag;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
-public class YamlConstructor extends SafeConstructor
-{
-
- public YamlConstructor()
- {
+public class YamlConstructor extends SafeConstructor {
+
+ public YamlConstructor() {
yamlConstructors.put(Tag.MAP, new ConstructCustomObject());
}
-
- private class ConstructCustomObject extends ConstructYamlMap
- {
+
+ private class ConstructCustomObject extends ConstructYamlMap {
@Override
- public Object construct(final Node node)
- {
- if (node.isTwoStepsConstruction()) { throw new YAMLException("Unexpected referential mapping structure. Node: " + node); }
-
+ public Object construct(final Node node) {
+ if (node.isTwoStepsConstruction()) {
+ throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
+ }
+
final Map, ?> raw = (Map, ?>) super.construct(node);
-
- if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY))
- {
+
+ if (raw.containsKey(ConfigurationSerialization.SERIALIZED_TYPE_KEY)) {
final Map typed = new LinkedHashMap(raw.size());
- for (final Map.Entry, ?> entry : raw.entrySet())
- {
+ for (final Map.Entry, ?> entry : raw.entrySet()) {
typed.put(entry.getKey().toString(), entry.getValue());
}
-
- try
- {
+
+ try {
return ConfigurationSerialization.deserializeObject(typed);
- }
- catch (final IllegalArgumentException ex)
- {
+ } catch (final IllegalArgumentException ex) {
throw new YAMLException("Could not deserialize object", ex);
}
}
-
+
return raw;
}
-
+
@Override
- public void construct2ndStep(final Node node, final Object object)
- {
+ public void construct2ndStep(final Node node, final Object object) {
throw new YAMLException("Unexpected referential mapping structure. Node: " + node);
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java b/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java
index f5bf748f2..3110456af 100644
--- a/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java
+++ b/src/main/java/com/intellectualcrafters/configuration/file/YamlRepresenter.java
@@ -10,34 +10,28 @@ import com.intellectualcrafters.configuration.ConfigurationSection;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerializable;
import com.intellectualcrafters.configuration.serialization.ConfigurationSerialization;
-public class YamlRepresenter extends Representer
-{
-
- public YamlRepresenter()
- {
+public class YamlRepresenter extends Representer {
+
+ public YamlRepresenter() {
multiRepresenters.put(ConfigurationSection.class, new RepresentConfigurationSection());
multiRepresenters.put(ConfigurationSerializable.class, new RepresentConfigurationSerializable());
}
-
- private class RepresentConfigurationSection extends RepresentMap
- {
+
+ private class RepresentConfigurationSection extends RepresentMap {
@Override
- public Node representData(final Object data)
- {
+ public Node representData(final Object data) {
return super.representData(((ConfigurationSection) data).getValues(false));
}
}
-
- private class RepresentConfigurationSerializable extends RepresentMap
- {
+
+ private class RepresentConfigurationSerializable extends RepresentMap {
@Override
- public Node representData(final Object data)
- {
+ public Node representData(final Object data) {
final ConfigurationSerializable serializable = (ConfigurationSerializable) data;
final Map values = new LinkedHashMap();
values.put(ConfigurationSerialization.SERIALIZED_TYPE_KEY, ConfigurationSerialization.getAlias(serializable.getClass()));
values.putAll(serializable.serialize());
-
+
return super.representData(values);
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java
index 0cca20083..4ffedde1f 100644
--- a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java
+++ b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerializable.java
@@ -21,9 +21,8 @@ import java.util.Map;
* @see DelegateDeserialization
* @see SerializableAs
*/
-public interface ConfigurationSerializable
-{
-
+public interface ConfigurationSerializable {
+
/**
* Creates a Map representation of this class.
*
diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java
index 17eb82574..2279db37e 100644
--- a/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java
+++ b/src/main/java/com/intellectualcrafters/configuration/serialization/ConfigurationSerialization.java
@@ -14,137 +14,107 @@ import com.intellectualcrafters.configuration.Configuration;
/**
* Utility class for storing and retrieving classes for {@link Configuration}.
*/
-public class ConfigurationSerialization
-{
+public class ConfigurationSerialization {
public static final String SERIALIZED_TYPE_KEY = "==";
private final Class extends ConfigurationSerializable> clazz;
private static Map> aliases = new HashMap>();
-
- protected ConfigurationSerialization(final Class extends ConfigurationSerializable> clazz)
- {
+
+ protected ConfigurationSerialization(final Class extends ConfigurationSerializable> clazz) {
this.clazz = clazz;
}
-
- protected Method getMethod(final String name, final boolean isStatic)
- {
- try
- {
+
+ protected Method getMethod(final String name, final boolean isStatic) {
+ try {
final Method method = clazz.getDeclaredMethod(name, Map.class);
-
- if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) { return null; }
- if (Modifier.isStatic(method.getModifiers()) != isStatic) { return null; }
-
+
+ if (!ConfigurationSerializable.class.isAssignableFrom(method.getReturnType())) {
+ return null;
+ }
+ if (Modifier.isStatic(method.getModifiers()) != isStatic) {
+ return null;
+ }
+
return method;
- }
- catch (final NoSuchMethodException ex)
- {
+ } catch (final NoSuchMethodException ex) {
return null;
- }
- catch (final SecurityException ex)
- {
+ } catch (final SecurityException ex) {
return null;
}
}
-
- protected Constructor extends ConfigurationSerializable> getConstructor()
- {
- try
- {
+
+ protected Constructor extends ConfigurationSerializable> getConstructor() {
+ try {
return clazz.getConstructor(Map.class);
- }
- catch (final NoSuchMethodException ex)
- {
+ } catch (final NoSuchMethodException ex) {
return null;
- }
- catch (final SecurityException ex)
- {
+ } catch (final SecurityException ex) {
return null;
}
}
-
- protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map args)
- {
- try
- {
+
+ protected ConfigurationSerializable deserializeViaMethod(final Method method, final Map args) {
+ try {
final ConfigurationSerializable result = (ConfigurationSerializable) method.invoke(null, args);
-
- if (result == null)
- {
+
+ if (result == null) {
Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE,
"Could not call method '" + method.toString() + "' of " + clazz + " for deserialization: method returned null");
- }
- else
- {
+ } else {
return result;
}
- }
- catch (final Throwable ex)
- {
- Logger.getLogger(ConfigurationSerialization.class.getName()).log(
- Level.SEVERE,
- "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
+ } catch (final Throwable ex) {
+ Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call method '" + method.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
-
+
return null;
}
-
- protected ConfigurationSerializable deserializeViaCtor(final Constructor extends ConfigurationSerializable> ctor, final Map args)
- {
- try
- {
+
+ protected ConfigurationSerializable deserializeViaCtor(final Constructor extends ConfigurationSerializable> ctor, final Map args) {
+ try {
return ctor.newInstance(args);
- }
- catch (final Throwable ex)
- {
- Logger.getLogger(ConfigurationSerialization.class.getName()).log(
- Level.SEVERE,
- "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
+ } catch (final Throwable ex) {
+ Logger.getLogger(ConfigurationSerialization.class.getName()).log(Level.SEVERE, "Could not call constructor '" + ctor.toString() + "' of " + clazz + " for deserialization",
ex instanceof InvocationTargetException ? ex.getCause() : ex);
}
-
+
return null;
}
-
- public ConfigurationSerializable deserialize(final Map args)
- {
- if (args == null) { throw new NullPointerException("Args must not be null"); }
+
+ public ConfigurationSerializable deserialize(final Map args) {
+ if (args == null) {
+ throw new NullPointerException("Args must not be null");
+ }
ConfigurationSerializable result = null;
Method method = null;
-
- if (result == null)
- {
+
+ if (result == null) {
method = getMethod("deserialize", true);
-
- if (method != null)
- {
+
+ if (method != null) {
result = deserializeViaMethod(method, args);
}
}
-
- if (result == null)
- {
+
+ if (result == null) {
method = getMethod("valueOf", true);
-
- if (method != null)
- {
+
+ if (method != null) {
result = deserializeViaMethod(method, args);
}
}
-
- if (result == null)
- {
+
+ if (result == null) {
final Constructor extends ConfigurationSerializable> constructor = getConstructor();
-
- if (constructor != null)
- {
+
+ if (constructor != null) {
result = deserializeViaCtor(constructor, args);
}
}
-
+
return result;
}
-
+
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
@@ -160,11 +130,10 @@ public class ConfigurationSerialization
* @param clazz Class to deserialize into
* @return New instance of the specified class
*/
- public static ConfigurationSerializable deserializeObject(final Map args, final Class extends ConfigurationSerializable> clazz)
- {
+ public static ConfigurationSerializable deserializeObject(final Map args, final Class extends ConfigurationSerializable> clazz) {
return new ConfigurationSerialization(clazz).deserialize(args);
}
-
+
/**
* Attempts to deserialize the given arguments into a new instance of the
* given class.
@@ -179,51 +148,46 @@ public class ConfigurationSerialization
* @param args Arguments for deserialization
* @return New instance of the specified class
*/
- public static ConfigurationSerializable deserializeObject(final Map args)
- {
+ public static ConfigurationSerializable deserializeObject(final Map args) {
Class extends ConfigurationSerializable> clazz = null;
-
- if (args.containsKey(SERIALIZED_TYPE_KEY))
- {
- try
- {
+
+ if (args.containsKey(SERIALIZED_TYPE_KEY)) {
+ try {
final String alias = (String) args.get(SERIALIZED_TYPE_KEY);
-
- if (alias == null) { throw new IllegalArgumentException("Cannot have null alias"); }
+
+ if (alias == null) {
+ throw new IllegalArgumentException("Cannot have null alias");
+ }
clazz = getClassByAlias(alias);
- if (clazz == null) { throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')"); }
- }
- catch (final ClassCastException ex)
- {
+ if (clazz == null) {
+ throw new IllegalArgumentException("Specified class does not exist ('" + alias + "')");
+ }
+ } catch (final ClassCastException ex) {
ex.fillInStackTrace();
throw ex;
}
- }
- else
- {
+ } else {
throw new IllegalArgumentException("Args doesn't contain type key ('" + SERIALIZED_TYPE_KEY + "')");
}
-
+
return new ConfigurationSerialization(clazz).deserialize(args);
}
-
+
/**
* Registers the given {@link ConfigurationSerializable} class by its
* alias
*
* @param clazz Class to register
*/
- public static void registerClass(final Class extends ConfigurationSerializable> clazz)
- {
+ public static void registerClass(final Class extends ConfigurationSerializable> clazz) {
final DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
-
- if (delegate == null)
- {
+
+ if (delegate == null) {
registerClass(clazz, getAlias(clazz));
registerClass(clazz, clazz.getName());
}
}
-
+
/**
* Registers the given alias to the specified {@link
* ConfigurationSerializable} class
@@ -232,33 +196,29 @@ public class ConfigurationSerialization
* @param alias Alias to register as
* @see SerializableAs
*/
- public static void registerClass(final Class extends ConfigurationSerializable> clazz, final String alias)
- {
+ public static void registerClass(final Class extends ConfigurationSerializable> clazz, final String alias) {
aliases.put(alias, clazz);
}
-
+
/**
* Unregisters the specified alias to a {@link ConfigurationSerializable}
*
* @param alias Alias to unregister
*/
- public static void unregisterClass(final String alias)
- {
+ public static void unregisterClass(final String alias) {
aliases.remove(alias);
}
-
+
/**
* Unregisters any aliases for the specified {@link
* ConfigurationSerializable} class
*
* @param clazz Class to unregister
*/
- public static void unregisterClass(final Class extends ConfigurationSerializable> clazz)
- {
- while (aliases.values().remove(clazz))
- {}
+ public static void unregisterClass(final Class extends ConfigurationSerializable> clazz) {
+ while (aliases.values().remove(clazz)) {}
}
-
+
/**
* Attempts to get a registered {@link ConfigurationSerializable} class by
* its alias
@@ -266,11 +226,10 @@ public class ConfigurationSerialization
* @param alias Alias of the serializable
* @return Registered class, or null if not found
*/
- public static Class extends ConfigurationSerializable> getClassByAlias(final String alias)
- {
+ public static Class extends ConfigurationSerializable> getClassByAlias(final String alias) {
return aliases.get(alias);
}
-
+
/**
* Gets the correct alias for the given {@link ConfigurationSerializable}
* class
@@ -278,29 +237,25 @@ public class ConfigurationSerialization
* @param clazz Class to get alias for
* @return Alias to use for the class
*/
- public static String getAlias(final Class extends ConfigurationSerializable> clazz)
- {
+ public static String getAlias(final Class extends ConfigurationSerializable> clazz) {
DelegateDeserialization delegate = clazz.getAnnotation(DelegateDeserialization.class);
-
- if (delegate != null)
- {
- if ((delegate.value() == null) || (delegate.value() == clazz))
- {
+
+ if (delegate != null) {
+ if ((delegate.value() == null) || (delegate.value() == clazz)) {
delegate = null;
- }
- else
- {
+ } else {
return getAlias(delegate.value());
}
}
-
- if (delegate == null)
- {
+
+ if (delegate == null) {
final SerializableAs alias = clazz.getAnnotation(SerializableAs.class);
-
- if ((alias != null) && (alias.value() != null)) { return alias.value(); }
+
+ if ((alias != null) && (alias.value() != null)) {
+ return alias.value();
+ }
}
-
+
return clazz.getName();
}
}
diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java b/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java
index bb0e04d68..bc505ccf2 100644
--- a/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java
+++ b/src/main/java/com/intellectualcrafters/configuration/serialization/DelegateDeserialization.java
@@ -11,8 +11,7 @@ import java.lang.annotation.Target;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
-public @interface DelegateDeserialization
-{
+public @interface DelegateDeserialization {
/**
* Which class should be used as a delegate for this classes
* deserialization
diff --git a/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java b/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java
index fde872a1b..668da9ac9 100644
--- a/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java
+++ b/src/main/java/com/intellectualcrafters/configuration/serialization/SerializableAs.java
@@ -21,8 +21,7 @@ import java.lang.annotation.Target;
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
-public @interface SerializableAs
-{
+public @interface SerializableAs {
/**
* This is the name your class will be stored and retrieved as.
*
diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java b/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java
index 146f4e658..48a7ce06c 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/ByteArrayTag.java
@@ -3,56 +3,48 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Byte_Array} tag.
*/
-public final class ByteArrayTag extends Tag
-{
+public final class ByteArrayTag extends Tag {
private final byte[] value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public ByteArrayTag(final byte[] value)
- {
+ public ByteArrayTag(final byte[] value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public ByteArrayTag(final String name, final byte[] value)
- {
+ public ByteArrayTag(final String name, final byte[] value) {
super(name);
this.value = value;
}
-
+
@Override
- public byte[] getValue()
- {
+ public byte[] getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final StringBuilder hex = new StringBuilder();
- for (final byte b : value)
- {
+ for (final byte b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase();
- if (hexDigits.length() == 1)
- {
+ if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Byte_Array" + append + ": " + hex;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java b/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java
index fbdb1d30e..40dc78046 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/ByteTag.java
@@ -3,46 +3,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Byte} tag.
*/
-public final class ByteTag extends Tag
-{
+public final class ByteTag extends Tag {
private final byte value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public ByteTag(final byte value)
- {
+ public ByteTag(final byte value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public ByteTag(final String name, final byte value)
- {
+ public ByteTag(final String name, final byte value) {
super(name);
this.value = value;
}
-
+
@Override
- public Byte getValue()
- {
+ public Byte getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Byte" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java b/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java
index 6400f748f..0709c06c4 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/CompoundTag.java
@@ -8,33 +8,30 @@ import java.util.Map;
/**
* The {@code TAG_Compound} tag.
*/
-public final class CompoundTag extends Tag
-{
+public final class CompoundTag extends Tag {
private final Map value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public CompoundTag(final Map value)
- {
+ public CompoundTag(final Map value) {
super();
this.value = Collections.unmodifiableMap(value);
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public CompoundTag(final String name, final Map value)
- {
+ public CompoundTag(final String name, final Map value) {
super(name);
this.value = Collections.unmodifiableMap(value);
}
-
+
/**
* Returns whether this compound tag contains the given key.
*
@@ -42,17 +39,15 @@ public final class CompoundTag extends Tag
*
* @return true if the tag contains the given key
*/
- public boolean containsKey(final String key)
- {
+ public boolean containsKey(final String key) {
return value.containsKey(key);
}
-
+
@Override
- public Map getValue()
- {
+ public Map getValue() {
return value;
}
-
+
/**
* Return a new compound tag with the given values.
*
@@ -60,21 +55,19 @@ public final class CompoundTag extends Tag
*
* @return the new compound tag
*/
- public CompoundTag setValue(final Map value)
- {
+ public CompoundTag setValue(final Map value) {
return new CompoundTag(getName(), value);
}
-
+
/**
* Create a compound tag builder.
*
* @return the builder
*/
- public CompoundTagBuilder createBuilder()
- {
+ public CompoundTagBuilder createBuilder() {
return new CompoundTagBuilder(new HashMap(value));
}
-
+
/**
* Get a byte array named with the given key. If the key does not exist or its value is not a byte array
* tag, then an empty byte array will be returned.
@@ -83,19 +76,15 @@ public final class CompoundTag extends Tag
*
* @return a byte array
*/
- public byte[] getByteArray(final String key)
- {
+ public byte[] getByteArray(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ByteArrayTag)
- {
+ if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
- }
- else
- {
+ } else {
return new byte[0];
}
}
-
+
/**
* Get a byte named with the given key. If the key does not exist or its value is not a byte tag, then
* {@code 0} will be returned.
@@ -104,19 +93,15 @@ public final class CompoundTag extends Tag
*
* @return a byte
*/
- public byte getByte(final String key)
- {
+ public byte getByte(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ByteTag)
- {
+ if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
- }
- else
- {
+ } else {
return (byte) 0;
}
}
-
+
/**
* Get a double named with the given key. If the key does not exist or its value is not a double tag, then
* {@code 0} will be returned.
@@ -125,19 +110,15 @@ public final class CompoundTag extends Tag
*
* @return a double
*/
- public double getDouble(final String key)
- {
+ public double getDouble(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof DoubleTag)
- {
+ if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a double named with the given key, even if it's another type of number. If the key does not exist or
* its value is not a number, then {@code 0} will be returned.
@@ -146,39 +127,25 @@ public final class CompoundTag extends Tag
*
* @return a double
*/
- public double asDouble(final String key)
- {
+ public double asDouble(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a float named with the given key. If the key does not exist or its value is not a float tag, then
* {@code 0} will be returned.
@@ -187,19 +154,15 @@ public final class CompoundTag extends Tag
*
* @return a float
*/
- public float getFloat(final String key)
- {
+ public float getFloat(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof FloatTag)
- {
+ if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a {@code int[]} named with the given key. If the key does not exist or its value is not an int array
* tag, then an empty array will be returned.
@@ -208,19 +171,15 @@ public final class CompoundTag extends Tag
*
* @return an int array
*/
- public int[] getIntArray(final String key)
- {
+ public int[] getIntArray(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof IntArrayTag)
- {
+ if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
- }
- else
- {
+ } else {
return new int[0];
}
}
-
+
/**
* Get an int named with the given key. If the key does not exist or its value is not an int tag, then
* {@code 0} will be returned.
@@ -229,19 +188,15 @@ public final class CompoundTag extends Tag
*
* @return an int
*/
- public int getInt(final String key)
- {
+ public int getInt(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof IntTag)
- {
+ if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get an int named with the given key, even if it's another type of number. If the key does not exist or
* its value is not a number, then {@code 0} will be returned.
@@ -250,39 +205,25 @@ public final class CompoundTag extends Tag
*
* @return an int
*/
- public int asInt(final String key)
- {
+ public int asInt(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a list of tags named with the given key. If the key does not exist or its value is not a list tag,
* then an empty list will be returned.
@@ -291,19 +232,15 @@ public final class CompoundTag extends Tag
*
* @return a list of tags
*/
- public List getList(final String key)
- {
+ public List getList(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
- }
- else
- {
+ } else {
return Collections.emptyList();
}
}
-
+
/**
* Get a {@code TagList} named with the given key. If the key does not exist or its value is not a list
* tag, then an empty tag list will be returned.
@@ -312,19 +249,15 @@ public final class CompoundTag extends Tag
*
* @return a tag list instance
*/
- public ListTag getListTag(final String key)
- {
+ public ListTag getListTag(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
return (ListTag) tag;
- }
- else
- {
+ } else {
return new ListTag(key, StringTag.class, Collections. emptyList());
}
}
-
+
/**
* Get a list of tags named with the given key. If the key does not exist or its value is not a list tag,
* then an empty list will be returned. If the given key references a list but the list of of a different type, then
@@ -337,27 +270,20 @@ public final class CompoundTag extends Tag
* @return a list of tags
*/
@SuppressWarnings("unchecked")
- public List getList(final String key, final Class listType)
- {
+ public List getList(final String key, final Class listType) {
final Tag tag = value.get(key);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
final ListTag listTag = (ListTag) tag;
- if (listTag.getType().equals(listType))
- {
+ if (listTag.getType().equals(listType)) {
return (List) listTag.getValue();
- }
- else
- {
+ } else {
return Collections.emptyList();
}
- }
- else
- {
+ } else {
return Collections.emptyList();
}
}
-
+
/**
* Get a long named with the given key. If the key does not exist or its value is not a long tag, then
* {@code 0} will be returned.
@@ -366,19 +292,15 @@ public final class CompoundTag extends Tag
*
* @return a long
*/
- public long getLong(final String key)
- {
+ public long getLong(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof LongTag)
- {
+ if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
- }
- else
- {
+ } else {
return 0L;
}
}
-
+
/**
* Get a long named with the given key, even if it's another type of number. If the key does not exist or
* its value is not a number, then {@code 0} will be returned.
@@ -387,39 +309,25 @@ public final class CompoundTag extends Tag
*
* @return a long
*/
- public long asLong(final String key)
- {
+ public long asLong(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a short named with the given key. If the key does not exist or its value is not a short tag, then
* {@code 0} will be returned.
@@ -428,19 +336,15 @@ public final class CompoundTag extends Tag
*
* @return a short
*/
- public short getShort(final String key)
- {
+ public short getShort(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof ShortTag)
- {
+ if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a string named with the given key. If the key does not exist or its value is not a string tag, then
* {@code ""} will be returned.
@@ -449,32 +353,25 @@ public final class CompoundTag extends Tag
*
* @return a string
*/
- public String getString(final String key)
- {
+ public String getString(final String key) {
final Tag tag = value.get(key);
- if (tag instanceof StringTag)
- {
+ if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
- }
- else
- {
+ } else {
return "";
}
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_Compound").append(append).append(": ").append(value.size()).append(" entries\r\n{\r\n");
- for (final Map.Entry entry : value.entrySet())
- {
+ for (final Map.Entry entry : value.entrySet()) {
bldr.append(" ").append(entry.getValue().toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
diff --git a/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java b/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java
index 69f4d7356..08eef4fc6 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/CompoundTagBuilder.java
@@ -8,39 +8,35 @@ import java.util.Map;
/**
* Helps create compound tags.
*/
-public class CompoundTagBuilder
-{
+public class CompoundTagBuilder {
private final Map entries;
-
+
/**
* Create a new instance.
*/
- CompoundTagBuilder()
- {
+ CompoundTagBuilder() {
entries = new HashMap();
}
-
+
/**
* Create a new instance and use the given map (which will be modified).
*
* @param value the value
*/
- CompoundTagBuilder(final Map value)
- {
+ CompoundTagBuilder(final Map value) {
checkNotNull(value);
entries = value;
}
-
+
/**
* Create a new builder instance.
*
* @return a new builder
*/
- public static CompoundTagBuilder create()
- {
+ public static CompoundTagBuilder create() {
return new CompoundTagBuilder();
}
-
+
/**
* Put the given key and tag into the compound tag.
*
@@ -49,14 +45,13 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder put(final String key, final Tag value)
- {
+ public CompoundTagBuilder put(final String key, final Tag value) {
checkNotNull(key);
checkNotNull(value);
entries.put(key, value);
return this;
}
-
+
/**
* Put the given key and value into the compound tag as a {@code ByteArrayTag}.
*
@@ -65,11 +60,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putByteArray(final String key, final 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}.
*
@@ -78,11 +72,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putByte(final String key, final 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}.
*
@@ -91,11 +84,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putDouble(final String key, final 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}.
*
@@ -104,11 +96,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putFloat(final String key, final float value)
- {
+ public CompoundTagBuilder putFloat(final String key, final float value) {
return put(key, new FloatTag(key, value));
}
-
+
/**
* Put the given key and value into the compound tag as a {@code IntArrayTag}.
*
@@ -117,11 +108,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putIntArray(final String key, final 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}.
*
@@ -130,11 +120,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putInt(final String key, final 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}.
*
@@ -143,11 +132,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putLong(final String key, final 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}.
*
@@ -156,11 +144,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putShort(final String key, final 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}.
*
@@ -169,11 +156,10 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putString(final String key, final 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.
*
@@ -181,26 +167,23 @@ public class CompoundTagBuilder
*
* @return this object
*/
- public CompoundTagBuilder putAll(final Map value)
- {
+ public CompoundTagBuilder putAll(final Map value) {
checkNotNull(value);
- for (final Map.Entry entry : value.entrySet())
- {
+ for (final Map.Entry entry : value.entrySet()) {
put(entry.getKey(), entry.getValue());
}
return this;
}
-
+
/**
* Build an unnamed compound tag with this builder's entries.
*
* @return the new compound tag
*/
- public CompoundTag build()
- {
+ public CompoundTag build() {
return new CompoundTag(new HashMap(entries));
}
-
+
/**
* Build a new compound tag with this builder's entries.
*
@@ -208,8 +191,7 @@ public class CompoundTagBuilder
*
* @return the created compound tag
*/
- public CompoundTag build(final String name)
- {
+ public CompoundTag build(final String name) {
return new CompoundTag(name, new HashMap(entries));
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java b/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java
index 272571f16..7c6a577b7 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/DoubleTag.java
@@ -3,46 +3,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Double} tag.
*/
-public final class DoubleTag extends Tag
-{
+public final class DoubleTag extends Tag {
private final double value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public DoubleTag(final double value)
- {
+ public DoubleTag(final double value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public DoubleTag(final String name, final double value)
- {
+ public DoubleTag(final String name, final double value) {
super(name);
this.value = value;
}
-
+
@Override
- public Double getValue()
- {
+ public Double getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Double" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/EndTag.java b/src/main/java/com/intellectualcrafters/jnbt/EndTag.java
index 811ab5e81..981925184 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/EndTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/EndTag.java
@@ -3,25 +3,21 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_End} tag.
*/
-public final class EndTag extends Tag
-{
+public final class EndTag extends Tag {
/**
* Creates the tag.
*/
- public EndTag()
- {
+ public EndTag() {
super();
}
-
+
@Override
- public Object getValue()
- {
+ public Object getValue() {
return null;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
return "TAG_End";
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java b/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java
index 6cb78472b..ae223ca57 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/FloatTag.java
@@ -3,46 +3,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Float} tag.
*/
-public final class FloatTag extends Tag
-{
+public final class FloatTag extends Tag {
private final float value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public FloatTag(final float value)
- {
+ public FloatTag(final float value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public FloatTag(final String name, final float value)
- {
+ public FloatTag(final String name, final float value) {
super(name);
this.value = value;
}
-
+
@Override
- public Float getValue()
- {
+ public Float getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Float" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java b/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java
index 14df42798..5a30bd41c 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/IntArrayTag.java
@@ -5,58 +5,50 @@ import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_Int_Array} tag.
*/
-public final class IntArrayTag extends Tag
-{
+public final class IntArrayTag extends Tag {
private final int[] value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public IntArrayTag(final int[] value)
- {
+ public IntArrayTag(final int[] value) {
super();
checkNotNull(value);
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public IntArrayTag(final String name, final int[] value)
- {
+ public IntArrayTag(final String name, final int[] value) {
super(name);
checkNotNull(value);
this.value = value;
}
-
+
@Override
- public int[] getValue()
- {
+ public int[] getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final StringBuilder hex = new StringBuilder();
- for (final int b : value)
- {
+ for (final int b : value) {
final String hexDigits = Integer.toHexString(b).toUpperCase();
- if (hexDigits.length() == 1)
- {
+ if (hexDigits.length() == 1) {
hex.append("0");
}
hex.append(hexDigits).append(" ");
}
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Int_Array" + append + ": " + hex;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/IntTag.java b/src/main/java/com/intellectualcrafters/jnbt/IntTag.java
index 389f4a67d..16f3487a9 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/IntTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/IntTag.java
@@ -3,46 +3,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Int} tag.
*/
-public final class IntTag extends Tag
-{
+public final class IntTag extends Tag {
private final int value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public IntTag(final int value)
- {
+ public IntTag(final int value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public IntTag(final String name, final int value)
- {
+ public IntTag(final String name, final int value) {
super(name);
this.value = value;
}
-
+
@Override
- public Integer getValue()
- {
+ public Integer getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Int" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTag.java b/src/main/java/com/intellectualcrafters/jnbt/ListTag.java
index 6a859ed57..d19fb0634 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/ListTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/ListTag.java
@@ -9,25 +9,23 @@ import java.util.NoSuchElementException;
/**
* The {@code TAG_List} tag.
*/
-public final class ListTag extends Tag
-{
+public final class ListTag extends Tag {
private final Class extends Tag> type;
private final List value;
-
+
/**
* Creates the tag with an empty name.
*
* @param type the type of tag
* @param value the value of the tag
*/
- public ListTag(final Class extends Tag> type, final List extends Tag> value)
- {
+ public ListTag(final Class extends Tag> type, final List extends Tag> value) {
super();
checkNotNull(value);
this.type = type;
this.value = Collections.unmodifiableList(value);
}
-
+
/**
* Creates the tag.
*
@@ -35,30 +33,27 @@ public final class ListTag extends Tag
* @param type the type of tag
* @param value the value of the tag
*/
- public ListTag(final String name, final Class extends Tag> type, final 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;
this.value = Collections.unmodifiableList(value);
}
-
+
/**
* Gets the type of item in this list.
*
* @return The type of item in this list.
*/
- public Class extends Tag> getType()
- {
+ public Class extends Tag> getType() {
return type;
}
-
+
@Override
- public List getValue()
- {
+ public List getValue() {
return value;
}
-
+
/**
* Create a new list tag with this tag's name and type.
*
@@ -66,11 +61,10 @@ public final class ListTag extends Tag
*
* @return a new list tag
*/
- public ListTag setValue(final List list)
- {
+ public ListTag setValue(final List list) {
return new ListTag(getName(), getType(), list);
}
-
+
/**
* Get the tag if it exists at the given index.
*
@@ -78,18 +72,14 @@ public final class ListTag extends Tag
*
* @return the tag or null
*/
- public Tag getIfExists(final int index)
- {
- try
- {
+ public Tag getIfExists(final int index) {
+ try {
return value.get(index);
- }
- catch (final NoSuchElementException e)
- {
+ } catch (final NoSuchElementException e) {
return null;
}
}
-
+
/**
* Get a byte array named with the given index. If the index does not exist or its value is not a byte
* array tag, then an empty byte array will be returned.
@@ -98,19 +88,15 @@ public final class ListTag extends Tag
*
* @return a byte array
*/
- public byte[] getByteArray(final int index)
- {
+ public byte[] getByteArray(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ByteArrayTag)
- {
+ if (tag instanceof ByteArrayTag) {
return ((ByteArrayTag) tag).getValue();
- }
- else
- {
+ } else {
return new byte[0];
}
}
-
+
/**
* Get a byte named with the given index. If the index does not exist or its value is not a byte tag, then
* {@code 0} will be returned.
@@ -119,19 +105,15 @@ public final class ListTag extends Tag
*
* @return a byte
*/
- public byte getByte(final int index)
- {
+ public byte getByte(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ByteTag)
- {
+ if (tag instanceof ByteTag) {
return ((ByteTag) tag).getValue();
- }
- else
- {
+ } else {
return (byte) 0;
}
}
-
+
/**
* Get a double named with the given index. If the index does not exist or its value is not a double tag,
* then {@code 0} will be returned.
@@ -140,19 +122,15 @@ public final class ListTag extends Tag
*
* @return a double
*/
- public double getDouble(final int index)
- {
+ public double getDouble(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof DoubleTag)
- {
+ if (tag instanceof DoubleTag) {
return ((DoubleTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a double named with the given index, even if it's another type of number. If the index does not
* exist or its value is not a number, then {@code 0} will be returned.
@@ -161,39 +139,25 @@ public final class ListTag extends Tag
*
* @return a double
*/
- public double asDouble(final int index)
- {
+ public double asDouble(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a float named with the given index. If the index does not exist or its value is not a float tag,
* then {@code 0} will be returned.
@@ -202,19 +166,15 @@ public final class ListTag extends Tag
*
* @return a float
*/
- public float getFloat(final int index)
- {
+ public float getFloat(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof FloatTag)
- {
+ if (tag instanceof FloatTag) {
return ((FloatTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a {@code int[]} named with the given index. If the index does not exist or its value is not an int
* array tag, then an empty array will be returned.
@@ -223,19 +183,15 @@ public final class ListTag extends Tag
*
* @return an int array
*/
- public int[] getIntArray(final int index)
- {
+ public int[] getIntArray(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof IntArrayTag)
- {
+ if (tag instanceof IntArrayTag) {
return ((IntArrayTag) tag).getValue();
- }
- else
- {
+ } else {
return new int[0];
}
}
-
+
/**
* Get an int named with the given index. If the index does not exist or its value is not an int tag, then
* {@code 0} will be returned.
@@ -244,19 +200,15 @@ public final class ListTag extends Tag
*
* @return an int
*/
- public int getInt(final int index)
- {
+ public int getInt(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof IntTag)
- {
+ if (tag instanceof IntTag) {
return ((IntTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get an int named with the given index, even if it's another type of number. If the index does not exist
* or its value is not a number, then {@code 0} will be returned.
@@ -265,39 +217,25 @@ public final class ListTag extends Tag
*
* @return an int
*/
- public int asInt(final int index)
- {
+ public int asInt(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a list of tags named with the given index. If the index does not exist or its value is not a list
* tag, then an empty list will be returned.
@@ -306,19 +244,15 @@ public final class ListTag extends Tag
*
* @return a list of tags
*/
- public List getList(final int index)
- {
+ public List getList(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
return ((ListTag) tag).getValue();
- }
- else
- {
+ } else {
return Collections.emptyList();
}
}
-
+
/**
* Get a {@code TagList} named with the given index. If the index does not exist or its value is not a list
* tag, then an empty tag list will be returned.
@@ -327,19 +261,15 @@ public final class ListTag extends Tag
*
* @return a tag list instance
*/
- public ListTag getListTag(final int index)
- {
+ public ListTag getListTag(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
return (ListTag) tag;
- }
- else
- {
+ } else {
return new ListTag(StringTag.class, Collections. emptyList());
}
}
-
+
/**
* Get a list of tags named with the given index. If the index does not exist or its value is not a list
* tag, then an empty list will be returned. If the given index references a list but the list of of a different
@@ -352,27 +282,20 @@ public final class ListTag extends Tag
* @return a list of tags
*/
@SuppressWarnings("unchecked")
- public List getList(final int index, final Class listType)
- {
+ public List getList(final int index, final Class listType) {
final Tag tag = getIfExists(index);
- if (tag instanceof ListTag)
- {
+ if (tag instanceof ListTag) {
final ListTag listTag = (ListTag) tag;
- if (listTag.getType().equals(listType))
- {
+ if (listTag.getType().equals(listType)) {
return (List) listTag.getValue();
- }
- else
- {
+ } else {
return Collections.emptyList();
}
- }
- else
- {
+ } else {
return Collections.emptyList();
}
}
-
+
/**
* Get a long named with the given index. If the index does not exist or its value is not a long tag, then
* {@code 0} will be returned.
@@ -381,19 +304,15 @@ public final class ListTag extends Tag
*
* @return a long
*/
- public long getLong(final int index)
- {
+ public long getLong(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof LongTag)
- {
+ if (tag instanceof LongTag) {
return ((LongTag) tag).getValue();
- }
- else
- {
+ } else {
return 0L;
}
}
-
+
/**
* Get a long named with the given index, even if it's another type of number. If the index does not exist
* or its value is not a number, then {@code 0} will be returned.
@@ -402,39 +321,25 @@ public final class ListTag extends Tag
*
* @return a long
*/
- public long asLong(final int index)
- {
+ public long asLong(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ByteTag)
- {
+ 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;
}
}
-
+
/**
* Get a short named with the given index. If the index does not exist or its value is not a short tag,
* then {@code 0} will be returned.
@@ -443,19 +348,15 @@ public final class ListTag extends Tag
*
* @return a short
*/
- public short getShort(final int index)
- {
+ public short getShort(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof ShortTag)
- {
+ if (tag instanceof ShortTag) {
return ((ShortTag) tag).getValue();
- }
- else
- {
+ } else {
return 0;
}
}
-
+
/**
* Get a string named with the given index. If the index does not exist or its value is not a string tag,
* then {@code ""} will be returned.
@@ -464,32 +365,25 @@ public final class ListTag extends Tag
*
* @return a string
*/
- public String getString(final int index)
- {
+ public String getString(final int index) {
final Tag tag = getIfExists(index);
- if (tag instanceof StringTag)
- {
+ if (tag instanceof StringTag) {
return ((StringTag) tag).getValue();
- }
- else
- {
+ } else {
return "";
}
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
final StringBuilder bldr = new StringBuilder();
bldr.append("TAG_List").append(append).append(": ").append(value.size()).append(" entries of type ").append(NBTUtils.getTypeName(type)).append("\r\n{\r\n");
- for (final Tag t : value)
- {
+ for (final Tag t : value) {
bldr.append(" ").append(t.toString().replaceAll("\r\n", "\r\n ")).append("\r\n");
}
bldr.append("}");
diff --git a/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java b/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java
index 013529fbb..d9dd65b14 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/ListTagBuilder.java
@@ -10,23 +10,21 @@ import java.util.List;
/**
* Helps create list tags.
*/
-public class ListTagBuilder
-{
+public class ListTagBuilder {
private final Class extends Tag> type;
private final List entries;
-
+
/**
* Create a new instance.
*
* @param type of tag contained in this list
*/
- ListTagBuilder(final Class extends Tag> type)
- {
+ ListTagBuilder(final Class extends Tag> type) {
checkNotNull(type);
this.type = type;
entries = new ArrayList();
}
-
+
/**
* Create a new builder instance.
*
@@ -34,11 +32,10 @@ public class ListTagBuilder
*
* @return a new builder
*/
- public static ListTagBuilder create(final Class extends Tag> type)
- {
+ public static ListTagBuilder create(final Class extends Tag> type) {
return new ListTagBuilder(type);
}
-
+
/**
* Create a new builder instance.
*
@@ -48,20 +45,22 @@ public class ListTagBuilder
* @return a new builder
*/
@SafeVarargs
- public static ListTagBuilder createWith(final T... entries)
- {
+ public static ListTagBuilder createWith(final T... entries) {
checkNotNull(entries);
- if (entries.length == 0) { throw new IllegalArgumentException("This method needs an array of at least one entry"); }
+ if (entries.length == 0) {
+ throw new IllegalArgumentException("This method needs an array of at least one entry");
+ }
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"); }
+ for (int i = 1; i < entries.length; i++) {
+ if (!type.isInstance(entries[i])) {
+ throw new IllegalArgumentException("An array of different tag types was provided");
+ }
}
final ListTagBuilder builder = new ListTagBuilder(type);
builder.addAll(Arrays.asList(entries));
return builder;
}
-
+
/**
* Add the given tag.
*
@@ -69,14 +68,15 @@ public class ListTagBuilder
*
* @return this object
*/
- public ListTagBuilder add(final 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 (!type.isInstance(value)) {
+ throw new IllegalArgumentException(value.getClass().getCanonicalName() + " is not of expected type " + type.getCanonicalName());
+ }
entries.add(value);
return this;
}
-
+
/**
* Add all the tags in the given list.
*
@@ -84,26 +84,23 @@ public class ListTagBuilder
*
* @return this object
*/
- public ListTagBuilder addAll(final Collection extends Tag> value)
- {
+ public ListTagBuilder addAll(final Collection extends Tag> value) {
checkNotNull(value);
- for (final Tag v : value)
- {
+ for (final Tag v : value) {
add(v);
}
return this;
}
-
+
/**
* Build an unnamed list tag with this builder's entries.
*
* @return the new list tag
*/
- public ListTag build()
- {
+ public ListTag build() {
return new ListTag(type, new ArrayList(entries));
}
-
+
/**
* Build a new list tag with this builder's entries.
*
@@ -111,8 +108,7 @@ public class ListTagBuilder
*
* @return the created list tag
*/
- public ListTag build(final String name)
- {
+ public ListTag build(final String name) {
return new ListTag(name, type, new ArrayList(entries));
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/LongTag.java b/src/main/java/com/intellectualcrafters/jnbt/LongTag.java
index f4e53f558..274e9448b 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/LongTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/LongTag.java
@@ -3,46 +3,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Long} tag.
*/
-public final class LongTag extends Tag
-{
+public final class LongTag extends Tag {
private final long value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public LongTag(final long value)
- {
+ public LongTag(final long value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public LongTag(final String name, final long value)
- {
+ public LongTag(final String name, final long value) {
super(name);
this.value = value;
}
-
+
@Override
- public Long getValue()
- {
+ public Long getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Long" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java
index 57f431dbf..d73b8964a 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/NBTConstants.java
@@ -25,18 +25,16 @@ import java.nio.charset.Charset;
/**
* A class which holds constant values.
*/
-public final class NBTConstants
-{
+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;
-
+
/**
* Default private constructor.
*/
- private NBTConstants()
- {}
-
+ private NBTConstants() {}
+
/**
* Convert a type ID to its corresponding {@link Tag} class.
*
@@ -46,10 +44,8 @@ public final class NBTConstants
*
* @throws IllegalArgumentException thrown if the tag ID is not valid
*/
- public static Class extends Tag> getClassFromType(final int id)
- {
- switch (id)
- {
+ public static Class extends Tag> getClassFromType(final int id) {
+ switch (id) {
case TYPE_END:
return EndTag.class;
case TYPE_BYTE:
diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java
index fce72a74b..3606d3355 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/NBTInputStream.java
@@ -14,12 +14,11 @@ import java.util.Map;
* subclasses of the {@code Tag} object. The NBT format was created by Markus Persson, and the specification
* may be found at @linktourl http://www.minecraft.net/docs/NBT.txt"> http://www.minecraft.net/docs/NBT.txt.
*/
-public final class NBTInputStream implements Closeable
-{
+public final class NBTInputStream implements Closeable {
private final DataInputStream is;
-
+
private int count;
-
+
/**
* Creates a new {@code NBTInputStream}, which will source its data from the specified input stream.
*
@@ -27,11 +26,10 @@ public final class NBTInputStream implements Closeable
*
* @throws IOException if an I/O error occurs
*/
- public NBTInputStream(final InputStream is) throws IOException
- {
+ public NBTInputStream(final InputStream is) throws IOException {
this.is = new DataInputStream(is);
}
-
+
/**
* Reads an NBT tag from the stream.
*
@@ -39,11 +37,10 @@ public final class NBTInputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- public Tag readTag() throws IOException
- {
+ public Tag readTag() throws IOException {
return readTag(0, Integer.MAX_VALUE);
}
-
+
/**
* Reads an NBT tag from the stream.
*
@@ -51,11 +48,10 @@ public final class NBTInputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- public Tag readTag(final int maxDepth) throws IOException
- {
+ public Tag readTag(final int maxDepth) throws IOException {
return readTag(0, maxDepth);
}
-
+
/**
* Reads an NBT from the stream.
*
@@ -65,25 +61,23 @@ public final class NBTInputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private Tag readTag(final int depth, final int maxDepth) throws IOException
- {
- if ((count++) > maxDepth) { throw new IOException("Exceeds max depth: " + count); }
+ private Tag readTag(final int depth, final int maxDepth) throws IOException {
+ if ((count++) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ }
final int type = is.readByte() & 0xFF;
String name;
- if (type != NBTConstants.TYPE_END)
- {
+ if (type != NBTConstants.TYPE_END) {
final int nameLength = is.readShort() & 0xFFFF;
final byte[] nameBytes = new byte[nameLength];
is.readFully(nameBytes);
name = new String(nameBytes, NBTConstants.CHARSET);
- }
- else
- {
+ } else {
name = "";
}
return readTagPayload(type, name, depth, maxDepth);
}
-
+
/**
* Reads the payload of a tag, given the name and type.
*
@@ -95,19 +89,16 @@ public final class NBTInputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private Tag readTagPayload(final int type, final String name, final int depth, final int maxDepth) throws IOException
- {
- if ((count++) > maxDepth) { throw new IOException("Exceeds max depth: " + count); }
+ private Tag readTagPayload(final int type, final String name, final int depth, final int maxDepth) throws IOException {
+ if ((count++) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ }
count++;
- switch (type)
- {
+ switch (type) {
case NBTConstants.TYPE_END:
- if (depth == 0)
- {
+ if (depth == 0) {
throw new IOException("TAG_End found without a TAG_Compound/TAG_List tag preceding it.");
- }
- else
- {
+ } else {
return new EndTag();
}
case NBTConstants.TYPE_BYTE:
@@ -124,54 +115,54 @@ public final class NBTInputStream implements Closeable
return new DoubleTag(name, is.readDouble());
case NBTConstants.TYPE_BYTE_ARRAY:
int length = is.readInt();
-
+
// Max depth
- if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count);
- //
+ if ((count += length) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ //
}
-
+
byte[] bytes = new byte[length];
is.readFully(bytes);
return new ByteArrayTag(name, bytes);
case NBTConstants.TYPE_STRING:
length = is.readShort();
-
+
// Max depth
- if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count);
- //
+ if ((count += length) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ //
}
-
+
bytes = new byte[length];
is.readFully(bytes);
return new StringTag(name, new String(bytes, NBTConstants.CHARSET));
case NBTConstants.TYPE_LIST:
final int childType = is.readByte();
length = is.readInt();
-
+
// Max depth
- if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count);
- //
+ if ((count += length) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ //
}
-
+
final List tagList = new ArrayList();
- for (int i = 0; i < length; ++i)
- {
+ for (int i = 0; i < length; ++i) {
final Tag tag = readTagPayload(childType, "", depth + 1, maxDepth);
- if (tag instanceof EndTag) { throw new IOException("TAG_End not permitted in a list."); }
+ if (tag instanceof EndTag) {
+ throw new IOException("TAG_End not permitted in a list.");
+ }
tagList.add(tag);
}
return new ListTag(name, NBTUtils.getTypeClass(childType), tagList);
case NBTConstants.TYPE_COMPOUND:
final Map tagMap = new HashMap();
- while (true)
- {
+ while (true) {
final Tag tag = readTag(depth + 1, maxDepth);
- if (tag instanceof EndTag)
- {
+ if (tag instanceof EndTag) {
break;
- }
- else
- {
+ } else {
tagMap.put(tag.getName(), tag);
}
}
@@ -179,11 +170,12 @@ public final class NBTInputStream implements Closeable
case NBTConstants.TYPE_INT_ARRAY:
length = is.readInt();
// Max depth
- if ((count += length) > maxDepth) { throw new IOException("Exceeds max depth: " + count); }
+ if ((count += length) > maxDepth) {
+ throw new IOException("Exceeds max depth: " + count);
+ }
//
final int[] data = new int[length];
- for (int i = 0; i < length; i++)
- {
+ for (int i = 0; i < length; i++) {
data[i] = is.readInt();
}
return new IntArrayTag(name, data);
@@ -191,10 +183,9 @@ public final class NBTInputStream implements Closeable
throw new IOException("Invalid tag type: " + type + ".");
}
}
-
+
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
is.close();
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java
index 2a628aeab..524156f65 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/NBTOutputStream.java
@@ -35,13 +35,12 @@ import java.util.List;
*
* @author Graham Edgecombe
*/
-public final class NBTOutputStream implements Closeable
-{
+public final class NBTOutputStream implements Closeable {
/**
* The output stream.
*/
private final DataOutputStream os;
-
+
/**
* Creates a new NBTOutputStream
, which will write data to the specified underlying output stream.
*
@@ -49,11 +48,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- public NBTOutputStream(final OutputStream os) throws IOException
- {
+ public NBTOutputStream(final OutputStream os) throws IOException {
this.os = new DataOutputStream(os);
}
-
+
/**
* Writes a tag.
*
@@ -61,18 +59,19 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- public void writeTag(final Tag tag) throws IOException
- {
+ 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);
- if (type == NBTConstants.TYPE_END) { throw new IOException("Named TAG_End not permitted."); }
+ if (type == NBTConstants.TYPE_END) {
+ throw new IOException("Named TAG_End not permitted.");
+ }
writeTagPayload(tag);
}
-
+
/**
* Writes tag payload.
*
@@ -80,11 +79,9 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeTagPayload(final Tag tag) throws IOException
- {
+ private void writeTagPayload(final Tag tag) throws IOException {
final int type = NBTUtils.getTypeCode(tag.getClass());
- switch (type)
- {
+ switch (type) {
case NBTConstants.TYPE_END:
writeEndTagPayload((EndTag) tag);
break;
@@ -125,7 +122,7 @@ public final class NBTOutputStream implements Closeable
throw new IOException("Invalid tag type: " + type + ".");
}
}
-
+
/**
* Writes a TAG_Byte
tag.
*
@@ -133,11 +130,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeByteTagPayload(final ByteTag tag) throws IOException
- {
+ private void writeByteTagPayload(final ByteTag tag) throws IOException {
os.writeByte(tag.getValue());
}
-
+
/**
* Writes a TAG_Byte_Array
tag.
*
@@ -145,13 +141,12 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException
- {
+ private void writeByteArrayTagPayload(final ByteArrayTag tag) throws IOException {
final byte[] bytes = tag.getValue();
os.writeInt(bytes.length);
os.write(bytes);
}
-
+
/**
* Writes a TAG_Compound
tag.
*
@@ -159,15 +154,13 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeCompoundTagPayload(final CompoundTag tag) throws IOException
- {
- for (final 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?
}
-
+
/**
* Writes a TAG_List
tag.
*
@@ -175,19 +168,17 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeListTagPayload(final ListTag tag) throws IOException
- {
+ private void writeListTagPayload(final ListTag tag) throws IOException {
final Class extends Tag> clazz = tag.getType();
final List tags = tag.getValue();
final int size = tags.size();
os.writeByte(NBTUtils.getTypeCode(clazz));
os.writeInt(size);
- for (final Tag tag1 : tags)
- {
+ for (final Tag tag1 : tags) {
writeTagPayload(tag1);
}
}
-
+
/**
* Writes a TAG_String
tag.
*
@@ -195,13 +186,12 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeStringTagPayload(final StringTag tag) throws IOException
- {
+ private void writeStringTagPayload(final StringTag tag) throws IOException {
final byte[] bytes = tag.getValue().getBytes(NBTConstants.CHARSET);
os.writeShort(bytes.length);
os.write(bytes);
}
-
+
/**
* Writes a TAG_Double
tag.
*
@@ -209,11 +199,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeDoubleTagPayload(final DoubleTag tag) throws IOException
- {
+ private void writeDoubleTagPayload(final DoubleTag tag) throws IOException {
os.writeDouble(tag.getValue());
}
-
+
/**
* Writes a TAG_Float
tag.
*
@@ -221,11 +210,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeFloatTagPayload(final FloatTag tag) throws IOException
- {
+ private void writeFloatTagPayload(final FloatTag tag) throws IOException {
os.writeFloat(tag.getValue());
}
-
+
/**
* Writes a TAG_Long
tag.
*
@@ -233,11 +221,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeLongTagPayload(final LongTag tag) throws IOException
- {
+ private void writeLongTagPayload(final LongTag tag) throws IOException {
os.writeLong(tag.getValue());
}
-
+
/**
* Writes a TAG_Int
tag.
*
@@ -245,11 +232,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeIntTagPayload(final IntTag tag) throws IOException
- {
+ private void writeIntTagPayload(final IntTag tag) throws IOException {
os.writeInt(tag.getValue());
}
-
+
/**
* Writes a TAG_Short
tag.
*
@@ -257,11 +243,10 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeShortTagPayload(final ShortTag tag) throws IOException
- {
+ private void writeShortTagPayload(final ShortTag tag) throws IOException {
os.writeShort(tag.getValue());
}
-
+
/**
* Writes a TAG_Empty
tag.
*
@@ -269,33 +254,28 @@ public final class NBTOutputStream implements Closeable
*
* @throws IOException if an I/O error occurs.
*/
- private void writeEndTagPayload(final EndTag tag)
- {
+ private void writeEndTagPayload(final EndTag tag) {
/* empty */
}
-
- private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException
- {
+
+ private void writeIntArrayTagPayload(final IntArrayTag tag) throws IOException {
final int[] data = tag.getValue();
os.writeInt(data.length);
- for (final int element : data)
- {
+ for (final int element : data) {
os.writeInt(element);
}
}
-
+
@Override
- public void close() throws IOException
- {
+ public void close() throws IOException {
os.close();
}
-
+
/**
* Flush output
* @throws IOException
*/
- public void flush() throws IOException
- {
+ public void flush() throws IOException {
os.flush();
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java b/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java
index a130d525e..f5118e77b 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/NBTUtils.java
@@ -5,14 +5,12 @@ import java.util.Map;
/**
* A class which contains NBT-related utility methods.
*/
-public final class NBTUtils
-{
+public final class NBTUtils {
/**
* Default private constructor.
*/
- private NBTUtils()
- {}
-
+ private NBTUtils() {}
+
/**
* Gets the type name of a tag.
*
@@ -20,62 +18,36 @@ public final class NBTUtils
*
* @return The type name.
*/
- public static String getTypeName(final Class extends Tag> clazz)
- {
- if (clazz.equals(ByteArrayTag.class))
- {
+ 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
- {
+ } else {
throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
}
}
-
+
/**
* Gets the type code of a tag class.
*
@@ -85,62 +57,36 @@ public final class NBTUtils
*
* @throws IllegalArgumentException if the tag class is invalid.
*/
- public static int getTypeCode(final Class extends Tag> clazz)
- {
- if (clazz.equals(ByteArrayTag.class))
- {
+ 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
- {
+ } else {
throw new IllegalArgumentException("Invalid tag classs (" + clazz.getName() + ").");
}
}
-
+
/**
* Gets the class of a type of tag.
*
@@ -150,10 +96,8 @@ public final class NBTUtils
*
* @throws IllegalArgumentException if the tag type is invalid.
*/
- public static Class extends Tag> getTypeClass(final int type)
- {
- switch (type)
- {
+ public static Class extends Tag> getTypeClass(final int type) {
+ switch (type) {
case NBTConstants.TYPE_END:
return EndTag.class;
case NBTConstants.TYPE_BYTE:
@@ -182,7 +126,7 @@ public final class NBTUtils
throw new IllegalArgumentException("Invalid tag type : " + type + ".");
}
}
-
+
/**
* Get child tag of a NBT structure.
*
@@ -193,11 +137,14 @@ public final class NBTUtils
*
* @return child tag
*/
- public static T getChildTag(final Map items, final String key, final Class expected) throws IllegalArgumentException
- {
- if (!items.containsKey(key)) { throw new IllegalArgumentException("Missing a \"" + key + "\" tag"); }
+ public static T getChildTag(final Map items, final String key, final Class expected) throws IllegalArgumentException {
+ if (!items.containsKey(key)) {
+ throw new IllegalArgumentException("Missing a \"" + key + "\" tag");
+ }
final Tag tag = items.get(key);
- if (!expected.isInstance(tag)) { throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName()); }
+ if (!expected.isInstance(tag)) {
+ throw new IllegalArgumentException(key + " tag is not of tag type " + expected.getName());
+ }
return expected.cast(tag);
}
}
diff --git a/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java b/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java
index 34a1adf9a..e1e5039f1 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/ShortTag.java
@@ -23,46 +23,40 @@ package com.intellectualcrafters.jnbt;
/**
* The {@code TAG_Short} tag.
*/
-public final class ShortTag extends Tag
-{
+public final class ShortTag extends Tag {
private final short value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public ShortTag(final short value)
- {
+ public ShortTag(final short value) {
super();
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public ShortTag(final String name, final short value)
- {
+ public ShortTag(final String name, final short value) {
super(name);
this.value = value;
}
-
+
@Override
- public Short getValue()
- {
+ public Short getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_Short" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/StringTag.java b/src/main/java/com/intellectualcrafters/jnbt/StringTag.java
index e69a75bcc..6dce84d0e 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/StringTag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/StringTag.java
@@ -5,48 +5,42 @@ import static com.google.common.base.Preconditions.checkNotNull;
/**
* The {@code TAG_String} tag.
*/
-public final class StringTag extends Tag
-{
+public final class StringTag extends Tag {
private final String value;
-
+
/**
* Creates the tag with an empty name.
*
* @param value the value of the tag
*/
- public StringTag(final String value)
- {
+ public StringTag(final String value) {
super();
checkNotNull(value);
this.value = value;
}
-
+
/**
* Creates the tag.
*
* @param name the name of the tag
* @param value the value of the tag
*/
- public StringTag(final String name, final String value)
- {
+ public StringTag(final String name, final String value) {
super(name);
checkNotNull(value);
this.value = value;
}
-
+
@Override
- public String getValue()
- {
+ public String getValue() {
return value;
}
-
+
@Override
- public String toString()
- {
+ public String toString() {
final String name = getName();
String append = "";
- if ((name != null) && !name.equals(""))
- {
+ if ((name != null) && !name.equals("")) {
append = "(\"" + getName() + "\")";
}
return "TAG_String" + append + ": " + value;
diff --git a/src/main/java/com/intellectualcrafters/jnbt/Tag.java b/src/main/java/com/intellectualcrafters/jnbt/Tag.java
index 0c50682ba..909683184 100644
--- a/src/main/java/com/intellectualcrafters/jnbt/Tag.java
+++ b/src/main/java/com/intellectualcrafters/jnbt/Tag.java
@@ -23,42 +23,37 @@ package com.intellectualcrafters.jnbt;
/**
* Represents a NBT tag.
*/
-public abstract class Tag
-{
+public abstract class Tag {
private final String name;
-
+
/**
* Create a new tag with an empty name.
*/
- Tag()
- {
+ Tag() {
this("");
}
-
+
/**
* Creates the tag with the specified name.
*
* @param name the name
*/
- Tag(String name)
- {
- if (name == null)
- {
+ Tag(String name) {
+ if (name == null) {
name = "";
}
this.name = name;
}
-
+
/**
* Gets the name of this tag.
*
* @return the name of this tag
*/
- public final String getName()
- {
+ public final String getName() {
return name;
}
-
+
/**
* Gets the value of this tag.
*
diff --git a/src/main/java/com/intellectualcrafters/json/CDL.java b/src/main/java/com/intellectualcrafters/json/CDL.java
index 0704da569..717b12349 100644
--- a/src/main/java/com/intellectualcrafters/json/CDL.java
+++ b/src/main/java/com/intellectualcrafters/json/CDL.java
@@ -17,8 +17,7 @@ package com.intellectualcrafters.json;
* @author JSON.org
* @version 2014-05-03
*/
-public class CDL
-{
+public class CDL {
/**
* Get the next value. The value can be wrapped in quotes. The value can be empty.
*
@@ -28,32 +27,28 @@ public class CDL
*
* @throws JSONException if the quoted string is badly formed.
*/
- private static String getValue(final JSONTokener x) throws JSONException
- {
+ private static String getValue(final JSONTokener x) throws JSONException {
char c;
char q;
StringBuffer sb;
- do
- {
+ do {
c = x.next();
- }
- while ((c == ' ') || (c == '\t'));
- switch (c)
- {
+ } while ((c == ' ') || (c == '\t'));
+ switch (c) {
case 0:
return null;
case '"':
case '\'':
q = c;
sb = new StringBuffer();
- for (;;)
- {
+ for (;;) {
c = x.next();
- if (c == q)
- {
+ if (c == q) {
break;
}
- if ((c == 0) || (c == '\n') || (c == '\r')) { throw x.syntaxError("Missing close quote '" + q + "'."); }
+ if ((c == 0) || (c == '\n') || (c == '\r')) {
+ throw x.syntaxError("Missing close quote '" + q + "'.");
+ }
sb.append(c);
}
return sb.toString();
@@ -65,7 +60,7 @@ public class CDL
return x.nextTo(',');
}
}
-
+
/**
* Produce a JSONArray of strings from a row of comma delimited values.
*
@@ -75,31 +70,30 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException
- {
+ public static JSONArray rowToJSONArray(final JSONTokener x) throws JSONException {
final JSONArray ja = new JSONArray();
- for (;;)
- {
+ for (;;) {
final String value = getValue(x);
char c = x.next();
- if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) { return null; }
+ if ((value == null) || ((ja.length() == 0) && (value.length() == 0) && (c != ','))) {
+ return null;
+ }
ja.put(value);
- for (;;)
- {
- if (c == ',')
- {
+ for (;;) {
+ if (c == ',') {
break;
}
- if (c != ' ')
- {
- if ((c == '\n') || (c == '\r') || (c == 0)) { return ja; }
+ if (c != ' ') {
+ if ((c == '\n') || (c == '\r') || (c == 0)) {
+ return ja;
+ }
throw x.syntaxError("Bad character '" + c + "' (" + (int) c + ").");
}
c = x.next();
}
}
}
-
+
/**
* Produce a JSONObject from a row of comma delimited text, using a parallel JSONArray of strings to provides the
* names of the elements.
@@ -112,12 +106,11 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException
- {
+ public static JSONObject rowToJSONObject(final JSONArray names, final JSONTokener x) throws JSONException {
final JSONArray ja = rowToJSONArray(x);
return ja != null ? ja.toJSONObject(names) : null;
}
-
+
/**
* Produce a comma delimited text row from a JSONArray. Values containing the comma character will be quoted.
* Troublesome characters may be removed.
@@ -126,35 +119,26 @@ public class CDL
*
* @return A string ending in NEWLINE.
*/
- public static String rowToString(final JSONArray ja)
- {
+ public static String rowToString(final JSONArray ja) {
final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < ja.length(); i += 1)
- {
- if (i > 0)
- {
+ for (int i = 0; i < ja.length(); i += 1) {
+ if (i > 0) {
sb.append(',');
}
final Object object = ja.opt(i);
- if (object != null)
- {
+ if (object != null) {
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) == '"')))
- {
+ if ((string.length() > 0) && ((string.indexOf(',') >= 0) || (string.indexOf('\n') >= 0) || (string.indexOf('\r') >= 0) || (string.indexOf(0) >= 0) || (string.charAt(0) == '"'))) {
sb.append('"');
final int length = string.length();
- for (int j = 0; j < length; j += 1)
- {
+ for (int j = 0; j < length; j += 1) {
final char c = string.charAt(j);
- if ((c >= ' ') && (c != '"'))
- {
+ if ((c >= ' ') && (c != '"')) {
sb.append(c);
}
}
sb.append('"');
- }
- else
- {
+ } else {
sb.append(string);
}
}
@@ -162,7 +146,7 @@ public class CDL
sb.append('\n');
return sb.toString();
}
-
+
/**
* Produce a JSONArray of JSONObjects from a comma delimited text string, using the first row as a source of names.
*
@@ -172,11 +156,10 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final 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.
*
@@ -186,11 +169,10 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final 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.
@@ -202,11 +184,10 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final JSONArray names, final 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.
@@ -218,23 +199,24 @@ public class CDL
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException
- {
- if ((names == null) || (names.length() == 0)) { return null; }
+ public static JSONArray toJSONArray(final JSONArray names, final JSONTokener x) throws JSONException {
+ if ((names == null) || (names.length() == 0)) {
+ return null;
+ }
final JSONArray ja = new JSONArray();
- for (;;)
- {
+ for (;;) {
final JSONObject jo = rowToJSONObject(names, x);
- if (jo == null)
- {
+ if (jo == null) {
break;
}
ja.put(jo);
}
- if (ja.length() == 0) { return null; }
+ if (ja.length() == 0) {
+ return null;
+ }
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.
@@ -245,17 +227,17 @@ public class CDL
*
* @throws JSONException
*/
- public static String toString(final JSONArray ja) throws JSONException
- {
+ public static String toString(final JSONArray ja) throws JSONException {
final JSONObject jo = ja.optJSONObject(0);
- if (jo != null)
- {
+ if (jo != null) {
final JSONArray names = jo.names();
- if (names != null) { return rowToString(names) + toString(names, ja); }
+ if (names != null) {
+ return rowToString(names) + toString(names, ja);
+ }
}
return null;
}
-
+
/**
* 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.
@@ -267,15 +249,14 @@ public class CDL
*
* @throws JSONException
*/
- public static String toString(final JSONArray names, final JSONArray ja) throws JSONException
- {
- if ((names == null) || (names.length() == 0)) { return null; }
+ public static String toString(final JSONArray names, final JSONArray ja) throws JSONException {
+ if ((names == null) || (names.length() == 0)) {
+ return null;
+ }
final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < ja.length(); i += 1)
- {
+ for (int i = 0; i < ja.length(); i += 1) {
final JSONObject jo = ja.optJSONObject(i);
- if (jo != null)
- {
+ if (jo != null) {
sb.append(rowToString(jo.toJSONArray(names)));
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/Cookie.java b/src/main/java/com/intellectualcrafters/json/Cookie.java
index 52f90895d..ee4def328 100644
--- a/src/main/java/com/intellectualcrafters/json/Cookie.java
+++ b/src/main/java/com/intellectualcrafters/json/Cookie.java
@@ -27,8 +27,7 @@ package com.intellectualcrafters.json;
* @author JSON.org
* @version 2014-05-03
*/
-public class Cookie
-{
+public class Cookie {
/**
* Produce a copy of a string in which the characters '+', '%', '=', ';' and control characters are replaced with
* "%hh". This is a gentle form of URL encoding, attempting to cause as little distortion to the string as possible.
@@ -40,29 +39,24 @@ public class Cookie
*
* @return The escaped result.
*/
- public static String escape(final String string)
- {
+ public static String escape(final String string) {
char c;
final String s = string.trim();
final int length = s.length();
final StringBuilder sb = new StringBuilder(length);
- for (int i = 0; i < length; i += 1)
- {
+ 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
- {
+ } 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 will be unescaped, possibly converting '+' and '%' sequences. The cookie properties
@@ -77,8 +71,7 @@ public class Cookie
*
* @throws JSONException
*/
- public static JSONObject toJSONObject(final String string) throws JSONException
- {
+ public static JSONObject toJSONObject(final String string) throws JSONException {
String name;
final JSONObject jo = new JSONObject();
Object value;
@@ -87,22 +80,15 @@ public class Cookie
x.next('=');
jo.put("value", x.nextTo(';'));
x.next();
- while (x.more())
- {
+ while (x.more()) {
name = unescape(x.nextTo("=;"));
- if (x.next() != '=')
- {
- if (name.equals("secure"))
- {
+ 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();
}
@@ -110,7 +96,7 @@ 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
@@ -122,34 +108,29 @@ public class Cookie
*
* @throws JSONException
*/
- public static String toString(final JSONObject jo) throws JSONException
- {
+ public static String toString(final JSONObject jo) throws JSONException {
final StringBuilder sb = new StringBuilder();
sb.append(escape(jo.getString("name")));
sb.append("=");
sb.append(escape(jo.getString("value")));
- if (jo.has("expires"))
- {
+ if (jo.has("expires")) {
sb.append(";expires=");
sb.append(jo.getString("expires"));
}
- if (jo.has("domain"))
- {
+ if (jo.has("domain")) {
sb.append(";domain=");
sb.append(escape(jo.getString("domain")));
}
- if (jo.has("path"))
- {
+ if (jo.has("path")) {
sb.append(";path=");
sb.append(escape(jo.getString("path")));
}
- if (jo.optBoolean("secure"))
- {
+ if (jo.optBoolean("secure")) {
sb.append(";secure");
}
return sb.toString();
}
-
+
/**
* Convert %
hh sequences to single characters, and convert plus to space.
*
@@ -158,23 +139,17 @@ public class Cookie
*
* @return The unescaped string.
*/
- public static String unescape(final String string)
- {
+ 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)
- {
+ for (int i = 0; i < length; ++i) {
char c = string.charAt(i);
- if (c == '+')
- {
+ if (c == '+') {
c = ' ';
- }
- else if ((c == '%') && ((i + 2) < length))
- {
+ } 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))
- {
+ if ((d >= 0) && (e >= 0)) {
c = (char) ((d * 16) + e);
i += 2;
}
diff --git a/src/main/java/com/intellectualcrafters/json/CookieList.java b/src/main/java/com/intellectualcrafters/json/CookieList.java
index add20262f..c0bf0f994 100644
--- a/src/main/java/com/intellectualcrafters/json/CookieList.java
+++ b/src/main/java/com/intellectualcrafters/json/CookieList.java
@@ -8,8 +8,7 @@ import java.util.Iterator;
* @author JSON.org
* @version 2014-05-03
*/
-public class CookieList
-{
+public class CookieList {
/**
* Convert a cookie list into a JSONObject. A cookie list is a sequence of name/value pairs. The names are separated
* from the values by '='. The pairs are separated by ';'. The names and the values will be unescaped, possibly
@@ -24,12 +23,10 @@ public class CookieList
*
* @throws JSONException
*/
- public static JSONObject toJSONObject(final String string) throws JSONException
- {
+ public static JSONObject toJSONObject(final String string) throws JSONException {
final JSONObject jo = new JSONObject();
final JSONTokener x = new JSONTokener(string);
- while (x.more())
- {
+ while (x.more()) {
final String name = Cookie.unescape(x.nextTo('='));
x.next('=');
jo.put(name, Cookie.unescape(x.nextTo(';')));
@@ -37,7 +34,7 @@ public class CookieList
}
return jo;
}
-
+
/**
* Convert a JSONObject into a cookie list. A cookie list is a sequence of name/value pairs. The names are separated
* from the values by '='. The pairs are separated by ';'. The characters '%', '+', '=', and ';' in the names and
@@ -49,19 +46,15 @@ public class CookieList
*
* @throws JSONException
*/
- public static String toString(final JSONObject jo) throws JSONException
- {
+ public static String toString(final JSONObject jo) throws JSONException {
boolean b = false;
final Iterator keys = jo.keys();
String string;
final StringBuilder sb = new StringBuilder();
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
string = keys.next();
- if (!jo.isNull(string))
- {
- if (b)
- {
+ if (!jo.isNull(string)) {
+ if (b) {
sb.append(';');
}
sb.append(Cookie.escape(string));
diff --git a/src/main/java/com/intellectualcrafters/json/HTTP.java b/src/main/java/com/intellectualcrafters/json/HTTP.java
index 01d5e26e9..9548fb151 100644
--- a/src/main/java/com/intellectualcrafters/json/HTTP.java
+++ b/src/main/java/com/intellectualcrafters/json/HTTP.java
@@ -28,37 +28,31 @@ import java.util.Iterator;
* @author JSON.org
* @version 2014-05-03
*/
-public class HTTP
-{
+public class HTTP {
/**
* Carriage return/line feed.
*/
public static final String CRLF = "\r\n";
-
- public static JSONObject toJSONObject(final String string) throws JSONException
- {
+
+ 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"))
- {
+ if (token.toUpperCase().startsWith("HTTP")) {
// Response
jo.put("HTTP-Version", token);
jo.put("Status-Code", x.nextToken());
jo.put("Reason-Phrase", x.nextTo('\0'));
x.next();
- }
- else
- {
+ } else {
// Request
jo.put("Method", token);
jo.put("Request-URI", x.nextToken());
jo.put("HTTP-Version", x.nextToken());
}
// Fields
- while (x.more())
- {
+ while (x.more()) {
final String name = x.nextTo(':');
x.next(':');
jo.put(name, x.nextTo('\0'));
@@ -66,7 +60,7 @@ public class HTTP
}
return jo;
}
-
+
/**
* Convert a JSONObject into an HTTP header. A request header must contain
*
@@ -98,21 +92,17 @@ public class HTTP
*
* @throws JSONException if the object does not contain enough information.
*/
- public static String toString(final JSONObject jo) throws JSONException
- {
+ public static String toString(final JSONObject jo) throws JSONException {
final Iterator keys = jo.keys();
String string;
final StringBuilder sb = new StringBuilder();
- if (jo.has("Status-Code") && jo.has("Reason-Phrase"))
- {
+ 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('"');
@@ -120,17 +110,13 @@ 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())
- {
+ while (keys.hasNext()) {
string = keys.next();
- if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string))
- {
+ if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) {
sb.append(string);
sb.append(": ");
sb.append(jo.getString(string));
diff --git a/src/main/java/com/intellectualcrafters/json/HTTPTokener.java b/src/main/java/com/intellectualcrafters/json/HTTPTokener.java
index ad99eae1d..5a3fb1e56 100644
--- a/src/main/java/com/intellectualcrafters/json/HTTPTokener.java
+++ b/src/main/java/com/intellectualcrafters/json/HTTPTokener.java
@@ -6,18 +6,16 @@ package com.intellectualcrafters.json;
* @author JSON.org
* @version 2014-05-03
*/
-public class HTTPTokener extends JSONTokener
-{
+public class HTTPTokener extends JSONTokener {
/**
* Construct an HTTPTokener from a string.
*
* @param string A source string.
*/
- public HTTPTokener(final String string)
- {
+ public HTTPTokener(final String string) {
super(string);
}
-
+
/**
* Get the next token or string. This is used in parsing HTTP headers.
*
@@ -25,30 +23,30 @@ public class HTTPTokener extends JSONTokener
*
* @throws JSONException
*/
- public String nextToken() throws JSONException
- {
+ public String nextToken() throws JSONException {
char c;
char q;
final StringBuilder sb = new StringBuilder();
- do
- {
+ do {
c = next();
- }
- while (Character.isWhitespace(c));
- if ((c == '"') || (c == '\''))
- {
+ } while (Character.isWhitespace(c));
+ if ((c == '"') || (c == '\'')) {
q = c;
- for (;;)
- {
+ for (;;) {
c = next();
- if (c < ' ') { throw syntaxError("Unterminated string."); }
- if (c == q) { return sb.toString(); }
+ if (c < ' ') {
+ throw syntaxError("Unterminated string.");
+ }
+ if (c == q) {
+ return sb.toString();
+ }
sb.append(c);
}
}
- for (;;)
- {
- if ((c == 0) || Character.isWhitespace(c)) { return sb.toString(); }
+ for (;;) {
+ if ((c == 0) || Character.isWhitespace(c)) {
+ return sb.toString();
+ }
sb.append(c);
c = next();
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONArray.java b/src/main/java/com/intellectualcrafters/json/JSONArray.java
index 64711cea6..2b8587aad 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONArray.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONArray.java
@@ -56,21 +56,19 @@ import java.util.Map;
* @author JSON.org
* @version 2014-05-03
*/
-public class JSONArray
-{
+public class JSONArray {
/**
* The arrayList where the JSONArray's properties are kept.
*/
private final ArrayList myArrayList;
-
+
/**
* Construct an empty JSONArray.
*/
- public JSONArray()
- {
+ public JSONArray() {
myArrayList = new ArrayList();
}
-
+
/**
* Construct a JSONArray from a JSONTokener.
*
@@ -78,29 +76,26 @@ public class JSONArray
*
* @throws JSONException If there is a syntax error.
*/
- public JSONArray(final JSONTokener x) throws JSONException
- {
+ public JSONArray(final JSONTokener x) throws JSONException {
this();
- if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); }
- if (x.nextClean() != ']')
- {
+ if (x.nextClean() != '[') {
+ throw x.syntaxError("A JSONArray text must start with '['");
+ }
+ if (x.nextClean() != ']') {
x.back();
- for (;;)
- {
- if (x.nextClean() == ',')
- {
+ for (;;) {
+ if (x.nextClean() == ',') {
x.back();
myArrayList.add(JSONObject.NULL);
- }
- else
- {
+ } else {
x.back();
myArrayList.add(x.nextValue());
}
- switch (x.nextClean())
- {
+ switch (x.nextClean()) {
case ',':
- if (x.nextClean() == ']') { return; }
+ if (x.nextClean() == ']') {
+ return;
+ }
x.back();
break;
case ']':
@@ -111,7 +106,7 @@ public class JSONArray
}
}
}
-
+
/**
* Construct a JSONArray from a source JSON text.
*
@@ -120,50 +115,41 @@ public class JSONArray
*
* @throws JSONException If there is a syntax error.
*/
- public JSONArray(final String source) throws JSONException
- {
+ public JSONArray(final String source) throws JSONException {
this(new JSONTokener(source));
}
-
+
/**
* Construct a JSONArray from a Collection.
*
* @param collection A Collection.
*/
- public JSONArray(final Collection collection)
- {
+ public JSONArray(final Collection collection) {
myArrayList = new ArrayList();
- if (collection != null)
- {
- for (final Object aCollection : collection)
- {
+ if (collection != null) {
+ for (final Object aCollection : collection) {
myArrayList.add(JSONObject.wrap(aCollection));
}
}
}
-
+
/**
* Construct a JSONArray from an array
*
* @throws JSONException If not an array.
*/
- public JSONArray(final Object array) throws JSONException
- {
+ public JSONArray(final Object array) throws JSONException {
this();
- if (array.getClass().isArray())
- {
+ if (array.getClass().isArray()) {
final int length = Array.getLength(array);
- for (int i = 0; i < length; i += 1)
- {
+ for (int i = 0; i < length; i += 1) {
this.put(JSONObject.wrap(Array.get(array, i)));
}
- }
- else
- {
+ } else {
throw new JSONException("JSONArray initial value should be a string or collection or array.");
}
}
-
+
/**
* Get the object value associated with an index.
*
@@ -173,13 +159,14 @@ public class JSONArray
*
* @throws JSONException If there is no value for the index.
*/
- public Object get(final int index) throws JSONException
- {
+ public Object get(final int index) throws JSONException {
final Object object = opt(index);
- if (object == null) { throw new JSONException("JSONArray[" + index + "] not found."); }
+ if (object == null) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
+ }
return object;
}
-
+
/**
* Get the boolean value associated with an index. The string values "true" and "false" are converted to boolean.
*
@@ -189,17 +176,16 @@ public class JSONArray
*
* @throws JSONException If there is no value for the index or if the value is not convertible to boolean.
*/
- public boolean getBoolean(final int index) throws JSONException
- {
+ public boolean getBoolean(final int index) throws JSONException {
final Object object = get(index);
- if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false")))
- {
+ 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"))) {
+ return 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.");
}
-
+
/**
* Get the double value associated with an index.
*
@@ -209,19 +195,15 @@ public class JSONArray
*
* @throws JSONException If the key is not found or if the value cannot be converted to a number.
*/
- public double getDouble(final int index) throws JSONException
- {
+ public double getDouble(final int index) throws JSONException {
final Object object = get(index);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
-
+
/**
* Get the int value associated with an index.
*
@@ -231,19 +213,15 @@ public class JSONArray
*
* @throws JSONException If the key is not found or if the value is not a number.
*/
- public int getInt(final int index) throws JSONException
- {
+ public int getInt(final int index) throws JSONException {
final Object object = get(index);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
-
+
/**
* Get the JSONArray associated with an index.
*
@@ -253,13 +231,14 @@ public class JSONArray
*
* @throws JSONException If there is no value for the index. or if the value is not a JSONArray
*/
- public JSONArray getJSONArray(final int index) throws JSONException
- {
+ public JSONArray getJSONArray(final int index) throws JSONException {
final Object object = get(index);
- if (object instanceof JSONArray) { return (JSONArray) object; }
+ if (object instanceof JSONArray) {
+ return (JSONArray) object;
+ }
throw new JSONException("JSONArray[" + index + "] is not a JSONArray.");
}
-
+
/**
* Get the JSONObject associated with an index.
*
@@ -269,13 +248,14 @@ public class JSONArray
*
* @throws JSONException If there is no value for the index or if the value is not a JSONObject
*/
- public JSONObject getJSONObject(final int index) throws JSONException
- {
+ public JSONObject getJSONObject(final int index) throws JSONException {
final Object object = get(index);
- if (object instanceof JSONObject) { return (JSONObject) object; }
+ if (object instanceof JSONObject) {
+ return (JSONObject) object;
+ }
throw new JSONException("JSONArray[" + index + "] is not a JSONObject.");
}
-
+
/**
* Get the long value associated with an index.
*
@@ -285,19 +265,15 @@ public class JSONArray
*
* @throws JSONException If the key is not found or if the value cannot be converted to a number.
*/
- public long getLong(final int index) throws JSONException
- {
+ public long getLong(final int index) throws JSONException {
final Object object = get(index);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONArray[" + index + "] is not a number.");
}
}
-
+
/**
* Get the string associated with an index.
*
@@ -307,13 +283,14 @@ public class JSONArray
*
* @throws JSONException If there is no string value for the index.
*/
- public String getString(final int index) throws JSONException
- {
+ public String getString(final int index) throws JSONException {
final Object object = get(index);
- if (object instanceof String) { return (String) object; }
+ if (object instanceof String) {
+ return (String) object;
+ }
throw new JSONException("JSONArray[" + index + "] not a string.");
}
-
+
/**
* Determine if the value is null.
*
@@ -321,11 +298,10 @@ public class JSONArray
*
* @return true if the value at the index is null, or if there is no value.
*/
- public boolean isNull(final int index)
- {
+ public boolean isNull(final int index) {
return JSONObject.NULL.equals(opt(index));
}
-
+
/**
* Make a string from the contents of this JSONArray. The separator
string is inserted between each
* element. Warning: This method assumes that the data structure is acyclical.
@@ -336,31 +312,27 @@ public class JSONArray
*
* @throws JSONException If the array contains an invalid number.
*/
- public String join(final String separator) throws JSONException
- {
+ public String join(final String separator) throws JSONException {
final int len = length();
final StringBuilder sb = new StringBuilder();
- for (int i = 0; i < len; i += 1)
- {
- if (i > 0)
- {
+ for (int i = 0; i < len; i += 1) {
+ if (i > 0) {
sb.append(separator);
}
sb.append(JSONObject.valueToString(myArrayList.get(i)));
}
return sb.toString();
}
-
+
/**
* Get the number of elements in the JSONArray, included nulls.
*
* @return The length (or size).
*/
- public int length()
- {
+ public int length() {
return myArrayList.size();
}
-
+
/**
* Get the optional object value associated with an index.
*
@@ -368,11 +340,10 @@ public class JSONArray
*
* @return An object value, or null if there is no object at that index.
*/
- public Object opt(final int index)
- {
+ public Object opt(final int index) {
return ((index < 0) || (index >= length())) ? null : myArrayList.get(index);
}
-
+
/**
* Get the optional boolean value associated with an index. It returns false if there is no value at that index, or
* if the value is not Boolean.TRUE or the String "true".
@@ -381,11 +352,10 @@ public class JSONArray
*
* @return The truth.
*/
- public boolean optBoolean(final int index)
- {
+ public boolean optBoolean(final int index) {
return this.optBoolean(index, false);
}
-
+
/**
* Get the optional boolean value associated with an index. It returns the defaultValue if there is no value at that
* index or if it is not a Boolean or the String "true" or "false" (case insensitive).
@@ -395,18 +365,14 @@ public class JSONArray
*
* @return The truth.
*/
- public boolean optBoolean(final int index, final boolean defaultValue)
- {
- try
- {
+ public boolean optBoolean(final int index, final boolean defaultValue) {
+ try {
return getBoolean(index);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get the optional double value associated with an index. NaN is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number.
@@ -415,11 +381,10 @@ public class JSONArray
*
* @return The value.
*/
- public double optDouble(final int index)
- {
+ public double optDouble(final int index) {
return this.optDouble(index, Double.NaN);
}
-
+
/**
* Get the optional double value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number.
@@ -429,18 +394,14 @@ public class JSONArray
*
* @return The value.
*/
- public double optDouble(final int index, final double defaultValue)
- {
- try
- {
+ public double optDouble(final int index, final double defaultValue) {
+ try {
return getDouble(index);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get the optional int value associated with an index. Zero is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number.
@@ -449,11 +410,10 @@ public class JSONArray
*
* @return The value.
*/
- public int optInt(final int index)
- {
+ public int optInt(final int index) {
return this.optInt(index, 0);
}
-
+
/**
* Get the optional int value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number.
@@ -463,18 +423,14 @@ public class JSONArray
*
* @return The value.
*/
- public int optInt(final int index, final int defaultValue)
- {
- try
- {
+ public int optInt(final int index, final int defaultValue) {
+ try {
return getInt(index);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get the optional JSONArray associated with an index.
*
@@ -482,12 +438,11 @@ 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(final int index)
- {
+ public JSONArray optJSONArray(final int index) {
final Object o = opt(index);
return o instanceof JSONArray ? (JSONArray) o : null;
}
-
+
/**
* Get the optional JSONObject associated with an index. Null is returned if the key is not found, or null if the
* index has no value, or if the value is not a JSONObject.
@@ -496,12 +451,11 @@ public class JSONArray
*
* @return A JSONObject value.
*/
- public JSONObject optJSONObject(final int index)
- {
+ public JSONObject optJSONObject(final int index) {
final Object o = opt(index);
return o instanceof JSONObject ? (JSONObject) o : null;
}
-
+
/**
* Get the optional long value associated with an index. Zero is returned if there is no value for the index, or if
* the value is not a number and cannot be converted to a number.
@@ -510,11 +464,10 @@ public class JSONArray
*
* @return The value.
*/
- public long optLong(final int index)
- {
+ public long optLong(final int index) {
return this.optLong(index, 0);
}
-
+
/**
* Get the optional long value associated with an index. The defaultValue is returned if there is no value for the
* index, or if the value is not a number and cannot be converted to a number.
@@ -524,18 +477,14 @@ public class JSONArray
*
* @return The value.
*/
- public long optLong(final int index, final long defaultValue)
- {
- try
- {
+ public long optLong(final int index, final long defaultValue) {
+ try {
return getLong(index);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get the optional string value associated with an index. It returns an empty string if there is no value at that
* index. If the value is not a string and is not null, then it is coverted to a string.
@@ -544,11 +493,10 @@ public class JSONArray
*
* @return A String value.
*/
- public String optString(final int index)
- {
+ public String optString(final int index) {
return this.optString(index, "");
}
-
+
/**
* Get the optional string associated with an index. The defaultValue is returned if the key is not found.
*
@@ -557,12 +505,11 @@ public class JSONArray
*
* @return A String value.
*/
- public String optString(final int index, final String defaultValue)
- {
+ public String optString(final int index, final String defaultValue) {
final Object object = opt(index);
return JSONObject.NULL.equals(object) ? defaultValue : object.toString();
}
-
+
/**
* Append a boolean value. This increases the array's length by one.
*
@@ -570,12 +517,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final boolean value)
- {
+ public JSONArray put(final boolean value) {
this.put(value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
-
+
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
*
@@ -583,12 +529,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final Collection value)
- {
+ public JSONArray put(final Collection value) {
this.put(new JSONArray(value));
return this;
}
-
+
/**
* Append a double value. This increases the array's length by one.
*
@@ -598,14 +543,13 @@ public class JSONArray
*
* @throws JSONException if the value is not finite.
*/
- public JSONArray put(final double value) throws JSONException
- {
+ public JSONArray put(final double value) throws JSONException {
final Double d = value;
JSONObject.testValidity(d);
this.put(d);
return this;
}
-
+
/**
* Append an int value. This increases the array's length by one.
*
@@ -613,12 +557,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final int value)
- {
+ public JSONArray put(final int value) {
this.put(new Integer(value));
return this;
}
-
+
/**
* Append an long value. This increases the array's length by one.
*
@@ -626,12 +569,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final long value)
- {
+ public JSONArray put(final long value) {
this.put(new Long(value));
return this;
}
-
+
/**
* Put a value in the JSONArray, where the value will be a JSONObject which is produced from a Map.
*
@@ -639,12 +581,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final Map value)
- {
+ public JSONArray put(final Map value) {
this.put(new JSONObject(value));
return this;
}
-
+
/**
* Append an object value. This increases the array's length by one.
*
@@ -653,12 +594,11 @@ public class JSONArray
*
* @return this.
*/
- public JSONArray put(final Object value)
- {
+ public JSONArray put(final Object value) {
myArrayList.add(value);
return this;
}
-
+
/**
* Put or replace a boolean value in the JSONArray. If the index is greater than the length of the JSONArray, then
* null elements will be added as necessary to pad it out.
@@ -670,12 +610,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative.
*/
- public JSONArray put(final int index, final 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;
}
-
+
/**
* Put a value in the JSONArray, where the value will be a JSONArray which is produced from a Collection.
*
@@ -686,12 +625,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative or if the value is not finite.
*/
- public JSONArray put(final int index, final Collection value) throws JSONException
- {
+ public JSONArray put(final int index, final Collection value) throws JSONException {
this.put(index, new JSONArray(value));
return this;
}
-
+
/**
* Put or replace a double value. If the index is greater than the length of the JSONArray, then null elements will
* be added as necessary to pad it out.
@@ -703,12 +641,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative or if the value is not finite.
*/
- public JSONArray put(final int index, final double value) throws JSONException
- {
+ public JSONArray put(final int index, final double value) throws JSONException {
this.put(index, new Double(value));
return this;
}
-
+
/**
* Put or replace an int value. If the index is greater than the length of the JSONArray, then null elements will be
* added as necessary to pad it out.
@@ -720,12 +657,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative.
*/
- public JSONArray put(final int index, final int value) throws JSONException
- {
+ public JSONArray put(final int index, final int value) throws JSONException {
this.put(index, new Integer(value));
return this;
}
-
+
/**
* Put or replace a long value. If the index is greater than the length of the JSONArray, then null elements will be
* added as necessary to pad it out.
@@ -737,12 +673,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative.
*/
- public JSONArray put(final int index, final long value) throws JSONException
- {
+ public JSONArray put(final int index, final long value) throws JSONException {
this.put(index, new Long(value));
return this;
}
-
+
/**
* Put a value in the JSONArray, where the value will be a JSONObject that is produced from a Map.
*
@@ -753,12 +688,11 @@ public class JSONArray
*
* @throws JSONException If the index is negative or if the the value is an invalid number.
*/
- public JSONArray put(final int index, final Map value) throws JSONException
- {
+ public JSONArray put(final int index, final Map value) throws JSONException {
this.put(index, new JSONObject(value));
return this;
}
-
+
/**
* Put or replace an object value in the JSONArray. If the index is greater than the length of the JSONArray, then
* null elements will be added as necessary to pad it out.
@@ -771,25 +705,22 @@ public class JSONArray
*
* @throws JSONException If the index is negative or if the the value is an invalid number.
*/
- public JSONArray put(final int index, final 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 < length())
- {
- myArrayList.set(index, value);
+ if (index < 0) {
+ throw new JSONException("JSONArray[" + index + "] not found.");
}
- else
- {
- while (index != length())
- {
+ if (index < length()) {
+ myArrayList.set(index, value);
+ } else {
+ while (index != length()) {
this.put(JSONObject.NULL);
}
this.put(value);
}
return this;
}
-
+
/**
* Remove an index and close the hole.
*
@@ -797,11 +728,10 @@ public class JSONArray
*
* @return The value that was associated with the index, or null if there was no value.
*/
- public Object remove(final int index)
- {
+ public Object remove(final int index) {
return (index >= 0) && (index < length()) ? myArrayList.remove(index) : null;
}
-
+
/**
* Determine if two JSONArrays are similar. They must contain similar sequences.
*
@@ -809,28 +739,32 @@ public class JSONArray
*
* @return true if they are equal
*/
- public boolean similar(final Object other)
- {
- if (!(other instanceof JSONArray)) { return false; }
+ public boolean similar(final Object other) {
+ if (!(other instanceof JSONArray)) {
+ return false;
+ }
final int len = length();
- if (len != ((JSONArray) other).length()) { return false; }
- for (int i = 0; i < len; i += 1)
- {
+ if (len != ((JSONArray) other).length()) {
+ return false;
+ }
+ for (int i = 0; i < len; i += 1) {
final Object valueThis = get(i);
final Object valueOther = ((JSONArray) other).get(i);
- if (valueThis instanceof JSONObject)
- {
- if (!((JSONObject) valueThis).similar(valueOther)) { return false; }
+ if (valueThis instanceof JSONObject) {
+ if (!((JSONObject) valueThis).similar(valueOther)) {
+ return false;
+ }
+ } else if (valueThis instanceof JSONArray) {
+ if (!((JSONArray) valueThis).similar(valueOther)) {
+ return false;
+ }
+ } else if (!valueThis.equals(valueOther)) {
+ return false;
}
- else if (valueThis instanceof JSONArray)
- {
- if (!((JSONArray) valueThis).similar(valueOther)) { return false; }
- }
- else if (!valueThis.equals(valueOther)) { return false; }
}
return true;
}
-
+
/**
* Produce a JSONObject by combining a JSONArray of names with the values of this JSONArray.
*
@@ -840,17 +774,17 @@ public class JSONArray
*
* @throws JSONException If any of the names are null.
*/
- public JSONObject toJSONObject(final JSONArray names) throws JSONException
- {
- if ((names == null) || (names.length() == 0) || (length() == 0)) { return null; }
+ public JSONObject toJSONObject(final JSONArray names) throws JSONException {
+ if ((names == null) || (names.length() == 0) || (length() == 0)) {
+ return null;
+ }
final JSONObject jo = new JSONObject();
- for (int i = 0; i < names.length(); i += 1)
- {
+ for (int i = 0; i < names.length(); i += 1) {
jo.put(names.getString(i), opt(i));
}
return jo;
}
-
+
/**
* Make a JSON text of this JSONArray. For compactness, no unnecessary whitespace is added. If it is not possible to
* produce a syntactically correct JSON text then null will be returned instead. This could occur if the array
@@ -861,18 +795,14 @@ public class JSONArray
* @return a printable, displayable, transmittable representation of the array.
*/
@Override
- public String toString()
- {
- try
- {
+ public String toString() {
+ try {
return this.toString(0);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return null;
}
}
-
+
/**
* Make a prettyprinted JSON text of this JSONArray. Warning: This method assumes that the data structure is
* acyclical.
@@ -885,15 +815,13 @@ public class JSONArray
*
* @throws JSONException
*/
- public String toString(final int indentFactor) throws JSONException
- {
+ public String toString(final int indentFactor) throws JSONException {
final StringWriter sw = new StringWriter();
- synchronized (sw.getBuffer())
- {
+ synchronized (sw.getBuffer()) {
return this.write(sw, indentFactor, 0).toString();
}
}
-
+
/**
* Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
*
@@ -903,11 +831,10 @@ public class JSONArray
*
* @throws JSONException
*/
- public Writer write(final Writer writer) throws JSONException
- {
+ public Writer write(final Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
-
+
/**
* Write the contents of the JSONArray as JSON text to a writer. For compactness, no whitespace is added.
*
@@ -920,45 +847,34 @@ public class JSONArray
*
* @throws JSONException
*/
- Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException
- {
- try
- {
+ Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
+ try {
boolean commanate = false;
final int length = length();
writer.write('[');
- if (length == 1)
- {
+ if (length == 1) {
JSONObject.writeValue(writer, myArrayList.get(0), indentFactor, indent);
- }
- else if (length != 0)
- {
+ } else if (length != 0) {
final int newindent = indent + indentFactor;
- for (int i = 0; i < length; i += 1)
- {
- if (commanate)
- {
+ for (int i = 0; i < length; i += 1) {
+ if (commanate) {
writer.write(',');
}
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, newindent);
JSONObject.writeValue(writer, myArrayList.get(i), indentFactor, newindent);
commanate = true;
}
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write('\n');
}
JSONObject.indent(writer, indent);
}
writer.write(']');
return writer;
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new JSONException(e);
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONException.java b/src/main/java/com/intellectualcrafters/json/JSONException.java
index b30bd7425..0d2acb352 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONException.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONException.java
@@ -6,40 +6,36 @@ package com.intellectualcrafters.json;
* @author JSON.org
* @version 2014-05-03
*/
-public class JSONException extends RuntimeException
-{
+public class JSONException extends RuntimeException {
private static final long serialVersionUID = 0;
private Throwable cause;
-
+
/**
* Constructs a JSONException with an explanatory message.
*
* @param message Detail about the reason for the exception.
*/
- public JSONException(final String message)
- {
+ public JSONException(final String message) {
super(message);
}
-
+
/**
* Constructs a new JSONException with the specified cause.
*
* @param cause The cause.
*/
- public JSONException(final Throwable cause)
- {
+ public JSONException(final Throwable cause) {
super(cause.getMessage());
this.cause = cause;
}
-
+
/**
* Returns the cause of this exception or null if the cause is nonexistent or unknown.
*
* @return the cause of this exception or null if the cause is nonexistent or unknown.
*/
@Override
- public Throwable getCause()
- {
+ public Throwable getCause() {
return cause;
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONML.java b/src/main/java/com/intellectualcrafters/json/JSONML.java
index 0153d1e0c..43d2431d5 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONML.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONML.java
@@ -9,8 +9,7 @@ import java.util.Iterator;
* @author JSON.org
* @version 2014-05-03
*/
-public class JSONML
-{
+public class JSONML {
/**
* Parse XML values and store them in a JSONArray.
*
@@ -22,8 +21,7 @@ public class JSONML
*
* @throws JSONException
*/
- private static Object parse(final XMLTokener x, final boolean arrayForm, final 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;
@@ -37,194 +35,155 @@ public class JSONML
//
//
// ... ?>
- while (true)
- {
- if (!x.more()) { throw x.syntaxError("Bad XML"); }
+ while (true) {
+ if (!x.more()) {
+ throw x.syntaxError("Bad XML");
+ }
token = x.nextContent();
- if (token == XML.LT)
- {
+ if (token == XML.LT) {
token = x.nextToken();
- if (token instanceof Character)
- {
- if (token == XML.SLASH)
- {
+ if (token instanceof Character) {
+ if (token == XML.SLASH) {
// Close tag
token = x.nextToken();
- if (!(token instanceof String)) { throw new JSONException("Expected a closing name instead of '" + token + "'."); }
- if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped close tag"); }
+ if (!(token instanceof String)) {
+ 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) {
// ");
- }
- else
- {
+ } else {
x.back();
}
- }
- else if (c == '[')
- {
+ } else if (c == '[') {
token = x.nextToken();
- if (token.equals("CDATA") && (x.next() == '['))
- {
- if (ja != null)
- {
+ 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
- {
+ do {
token = x.nextMeta();
- if (token == null)
- {
+ if (token == null) {
throw x.syntaxError("Missing '>' after ' 0);
+ } while (i > 0);
}
- }
- else if (token == XML.QUEST)
- {
+ } else if (token == XML.QUEST) {
//
x.skipPast("?>");
- }
- else
- {
+ } else {
throw x.syntaxError("Misshaped tag");
}
// Open tag <
- }
- else
- {
- if (!(token instanceof String)) { throw x.syntaxError("Bad tagName '" + token + "'."); }
+ } else {
+ if (!(token instanceof String)) {
+ throw x.syntaxError("Bad tagName '" + token + "'.");
+ }
tagName = (String) token;
newja = new JSONArray();
newjo = new JSONObject();
- if (arrayForm)
- {
+ if (arrayForm) {
newja.put(tagName);
- if (ja != null)
- {
+ if (ja != null) {
ja.put(newja);
}
- }
- else
- {
+ } else {
newjo.put("tagName", tagName);
- if (ja != null)
- {
+ if (ja != null) {
ja.put(newjo);
}
}
token = null;
- for (;;)
- {
- if (token == null)
- {
+ for (;;) {
+ if (token == null) {
token = x.nextToken();
}
- if (token == null) { throw x.syntaxError("Misshaped tag"); }
- if (!(token instanceof String))
- {
+ if (token == null) {
+ throw x.syntaxError("Misshaped tag");
+ }
+ if (!(token instanceof String)) {
break;
}
// attribute = value
attribute = (String) token;
- if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { throw x.syntaxError("Reserved attribute."); }
+ if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
+ throw x.syntaxError("Reserved attribute.");
+ }
token = x.nextToken();
- if (token == XML.EQ)
- {
+ if (token == XML.EQ) {
token = x.nextToken();
- if (!(token instanceof String)) { throw x.syntaxError("Missing value"); }
+ if (!(token instanceof String)) {
+ throw x.syntaxError("Missing value");
+ }
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 <.../>
- if (token == XML.SLASH)
- {
- if (x.nextToken() != XML.GT) { throw x.syntaxError("Misshaped tag"); }
- if (ja == null)
- {
- if (arrayForm)
- {
+ if (token == XML.SLASH) {
+ if (x.nextToken() != XML.GT) {
+ throw x.syntaxError("Misshaped tag");
+ }
+ if (ja == null) {
+ if (arrayForm) {
return newja;
- }
- else
- {
+ } else {
return newjo;
}
}
// Content, between <...> and
- }
- else
- {
- if (token != XML.GT) { throw x.syntaxError("Misshaped tag"); }
+ } else {
+ if (token != XML.GT) {
+ throw x.syntaxError("Misshaped tag");
+ }
closeTag = (String) parse(x, arrayForm, newja);
- if (closeTag != null)
- {
- if (!closeTag.equals(tagName)) { throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); }
+ if (closeTag != null) {
+ if (!closeTag.equals(tagName)) {
+ 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)
- {
+ if (ja == null) {
+ if (arrayForm) {
return newja;
- }
- else
- {
+ } else {
return newjo;
}
}
}
}
}
- }
- else
- {
- if (ja != null)
- {
+ } else {
+ if (ja != null) {
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 a JSONArray in which the first element is the tag name. If the tag has attributes, then
@@ -236,11 +195,10 @@ public class JSONML
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final 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 a JSONArray in which the first element is the tag name. If the tag has attributes, then
@@ -254,11 +212,10 @@ public class JSONML
*
* @throws JSONException
*/
- public static JSONArray toJSONArray(final XMLTokener x) throws JSONException
- {
+ 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 a JSONObject with a "tagName" property. If the tag has attributes, then the attributes
@@ -273,11 +230,10 @@ public class JSONML
*
* @throws JSONException
*/
- public static JSONObject toJSONObject(final XMLTokener x) throws JSONException
- {
+ 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 a JSONObject with a "tagName" property. If the tag has attributes, then the attributes
@@ -292,11 +248,10 @@ public class JSONML
*
* @throws JSONException
*/
- public static JSONObject toJSONObject(final 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.
*
@@ -306,8 +261,7 @@ public class JSONML
*
* @throws JSONException
*/
- public static String toString(final JSONArray ja) throws JSONException
- {
+ public static String toString(final JSONArray ja) throws JSONException {
int i;
JSONObject jo;
String key;
@@ -324,19 +278,16 @@ public class JSONML
sb.append('<');
sb.append(tagName);
object = ja.opt(1);
- if (object instanceof JSONObject)
- {
+ if (object instanceof JSONObject) {
i = 2;
jo = (JSONObject) object;
// Emit the attributes
keys = jo.keys();
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
key = keys.next();
XML.noSpace(key);
value = jo.optString(key);
- if (value != null)
- {
+ if (value != null) {
sb.append(' ');
sb.append(XML.escape(key));
sb.append('=');
@@ -345,42 +296,29 @@ public class JSONML
sb.append('"');
}
}
- }
- else
- {
+ } else {
i = 1;
}
// Emit content in body
length = ja.length();
- if (i >= length)
- {
+ if (i >= length) {
sb.append('/');
sb.append('>');
- }
- else
- {
+ } else {
sb.append('>');
- do
- {
+ do {
object = ja.get(i);
i += 1;
- if (object != null)
- {
- if (object instanceof String)
- {
+ if (object != null) {
+ if (object instanceof String) {
sb.append(XML.escape(object.toString()));
- }
- else if (object instanceof JSONObject)
- {
+ } else if (object instanceof JSONObject) {
sb.append(toString((JSONObject) object));
- }
- else if (object instanceof JSONArray)
- {
+ } else if (object instanceof JSONArray) {
sb.append(toString((JSONArray) object));
}
}
- }
- while (i < length);
+ } while (i < length);
sb.append('<');
sb.append('/');
sb.append(tagName);
@@ -388,7 +326,7 @@ public class JSONML
}
return sb.toString();
}
-
+
/**
* Reverse the JSONML transformation, making an XML text from a JSONObject. 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
@@ -400,8 +338,7 @@ public class JSONML
*
* @throws JSONException
*/
- public static String toString(final JSONObject jo) throws JSONException
- {
+ public static String toString(final JSONObject jo) throws JSONException {
final StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
@@ -413,22 +350,21 @@ public class JSONML
String value;
// Emit ');
- }
- else
- {
+ } else {
sb.append('>');
length = ja.length();
- for (i = 0; i < length; i += 1)
- {
+ for (i = 0; i < length; i += 1) {
object = ja.get(i);
- if (object != null)
- {
- if (object instanceof String)
- {
+ if (object != null) {
+ if (object instanceof String) {
sb.append(XML.escape(object.toString()));
- }
- else if (object instanceof JSONObject)
- {
+ } else if (object instanceof JSONObject) {
sb.append(toString((JSONObject) object));
- }
- else if (object instanceof JSONArray)
- {
+ } else if (object instanceof JSONArray) {
sb.append(toString((JSONArray) object));
- }
- else
- {
+ } else {
sb.append(object.toString());
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONObject.java b/src/main/java/com/intellectualcrafters/json/JSONObject.java
index 2f126f21d..81f89ff01 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONObject.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONObject.java
@@ -53,8 +53,7 @@ import java.util.Set;
* @author JSON.org
* @version 2014-05-03
*/
-public class JSONObject
-{
+public class JSONObject {
/**
* It is sometimes more convenient and less ambiguous to have a NULL
object than to use Java's
* null
value. JSONObject.NULL.equals(null)
returns true
.
@@ -65,15 +64,14 @@ public class JSONObject
* The map where the JSONObject's properties are kept.
*/
private final Map map;
-
+
/**
* Construct an empty JSONObject.
*/
- public JSONObject()
- {
+ public JSONObject() {
map = new HashMap();
}
-
+
/**
* Construct a JSONObject from a subset of another JSONObject. An array of strings is used to identify the keys that
* should be copied. Missing keys are ignored.
@@ -84,20 +82,15 @@ public class JSONObject
* @throws JSONException
* @throws JSONException If a value is a non-finite number or if a name is duplicated.
*/
- public JSONObject(final JSONObject jo, final String[] names)
- {
+ public JSONObject(final JSONObject jo, final String[] names) {
this();
- for (final String name : names)
- {
- try
- {
+ for (final String name : names) {
+ try {
putOnce(name, jo.opt(name));
- }
- catch (final Exception ignore)
- {}
+ } catch (final Exception ignore) {}
}
}
-
+
/**
* Construct a JSONObject from a JSONTokener.
*
@@ -105,17 +98,16 @@ public class JSONObject
*
* @throws JSONException If there is a syntax error in the source string or a duplicated key.
*/
- public JSONObject(final JSONTokener x) throws JSONException
- {
+ public JSONObject(final JSONTokener x) throws JSONException {
this();
char c;
String key;
- if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); }
- for (;;)
- {
+ if (x.nextClean() != '{') {
+ throw x.syntaxError("A JSONObject text must begin with '{'");
+ }
+ for (;;) {
c = x.nextClean();
- switch (c)
- {
+ switch (c) {
case 0:
throw x.syntaxError("A JSONObject text must end with '}'");
case '}':
@@ -126,14 +118,17 @@ public class JSONObject
}
// The key is followed by ':'.
c = x.nextClean();
- if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); }
+ if (c != ':') {
+ throw x.syntaxError("Expected a ':' after a key");
+ }
putOnce(key, x.nextValue());
// Pairs are separated by ','.
- switch (x.nextClean())
- {
+ switch (x.nextClean()) {
case ';':
case ',':
- if (x.nextClean() == '}') { return; }
+ if (x.nextClean() == '}') {
+ return;
+ }
x.back();
break;
case '}':
@@ -143,7 +138,7 @@ public class JSONObject
}
}
}
-
+
/**
* Construct a JSONObject from a Map.
*
@@ -151,22 +146,18 @@ public class JSONObject
*
* @throws JSONException
*/
- public JSONObject(final Map map)
- {
+ public JSONObject(final Map map) {
this.map = new HashMap();
- if (map != null)
- {
- for (final Entry entry : map.entrySet())
- {
+ if (map != null) {
+ for (final Entry entry : map.entrySet()) {
final Object value = entry.getValue();
- if (value != null)
- {
+ if (value != null) {
this.map.put(entry.getKey(), wrap(value));
}
}
}
}
-
+
/**
* Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object.
* For each of the methods with no parameters and a name starting with "get"
or "is"
@@ -182,12 +173,11 @@ public class JSONObject
*
* @param bean An object that has getter methods that should be used to make a JSONObject.
*/
- public JSONObject(final Object bean)
- {
+ public JSONObject(final Object bean) {
this();
populateMap(bean);
}
-
+
/**
* Construct a JSONObject from an Object, using reflection to find the public members. The resulting JSONObject's
* keys will be the strings from the names array, and the values will be the field values associated with those keys
@@ -196,21 +186,16 @@ public class JSONObject
* @param object An object that has fields that should be used to make a JSONObject.
* @param names An array of strings, the names of the fields to be obtained from the object.
*/
- public JSONObject(final Object object, final String names[])
- {
+ public JSONObject(final Object object, final String names[]) {
this();
final Class c = object.getClass();
- for (final String name : names)
- {
- try
- {
+ for (final String name : names) {
+ try {
putOpt(name, c.getField(name).get(object));
- }
- catch (final Exception ignore)
- {}
+ } catch (final Exception ignore) {}
}
}
-
+
/**
* Construct a JSONObject from a source JSON text string. This is the most commonly used JSONObject constructor.
*
@@ -219,11 +204,10 @@ public class JSONObject
*
* @throws JSONException If there is a syntax error in the source string or a duplicated key.
*/
- public JSONObject(final String source) throws JSONException
- {
+ public JSONObject(final String source) throws JSONException {
this(new JSONTokener(source));
}
-
+
/**
* Construct a JSONObject from a ResourceBundle.
*
@@ -232,17 +216,14 @@ public class JSONObject
*
* @throws JSONException If any JSONExceptions are detected.
*/
- public JSONObject(final String baseName, final Locale locale) throws JSONException
- {
+ public JSONObject(final String baseName, final Locale locale) throws JSONException {
this();
final ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader());
// Iterate through the keys in the bundle.
final Enumeration keys = bundle.getKeys();
- while (keys.hasMoreElements())
- {
+ while (keys.hasMoreElements()) {
final Object key = keys.nextElement();
- if (key != null)
- {
+ if (key != null) {
// Go through the path, ensuring that there is a nested
// JSONObject for each
// segment except the last. Add the value using the last
@@ -251,12 +232,10 @@ public class JSONObject
final String[] path = ((String) key).split("\\.");
final int last = path.length - 1;
JSONObject target = this;
- for (int i = 0; i < last; i += 1)
- {
+ for (int i = 0; i < last; i += 1) {
final String segment = path[i];
JSONObject nextTarget = target.optJSONObject(segment);
- if (nextTarget == null)
- {
+ if (nextTarget == null) {
nextTarget = new JSONObject();
target.put(segment, nextTarget);
}
@@ -266,7 +245,7 @@ public class JSONObject
}
}
}
-
+
/**
* Produce a string from a double. The string "null" will be returned if the number is not finite.
*
@@ -274,65 +253,65 @@ public class JSONObject
*
* @return A String.
*/
- public static String doubleToString(final double d)
- {
- if (Double.isInfinite(d) || Double.isNaN(d)) { return "null"; }
+ public static String doubleToString(final double d) {
+ if (Double.isInfinite(d) || Double.isNaN(d)) {
+ return "null";
+ }
// Shave off trailing zeros and decimal point, if possible.
String string = Double.toString(d);
- if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0))
- {
- while (string.endsWith("0"))
- {
+ if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) {
+ while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
- if (string.endsWith("."))
- {
+ if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
-
+
/**
* Get an array of field names from a JSONObject.
*
* @return An array of field names, or null if there are no names.
*/
- public static String[] getNames(final JSONObject jo)
- {
+ public static String[] getNames(final JSONObject jo) {
final int length = jo.length();
- if (length == 0) { return null; }
+ if (length == 0) {
+ return null;
+ }
final Iterator iterator = jo.keys();
final String[] names = new String[length];
int i = 0;
- while (iterator.hasNext())
- {
+ while (iterator.hasNext()) {
names[i] = iterator.next();
i += 1;
}
return names;
}
-
+
/**
* Get an array of field names from an Object.
*
* @return An array of field names, or null if there are no names.
*/
- public static String[] getNames(final Object object)
- {
- if (object == null) { return null; }
+ public static String[] getNames(final Object object) {
+ if (object == null) {
+ return null;
+ }
final Class klass = object.getClass();
final Field[] fields = klass.getFields();
final int length = fields.length;
- if (length == 0) { return null; }
+ if (length == 0) {
+ return null;
+ }
final String[] names = new String[length];
- for (int i = 0; i < length; i += 1)
- {
+ for (int i = 0; i < length; i += 1) {
names[i] = fields[i].getName();
}
return names;
}
-
+
/**
* Produce a string from a Number.
*
@@ -342,26 +321,24 @@ public class JSONObject
*
* @throws JSONException If n is a non-finite number.
*/
- public static String numberToString(final Number number) throws JSONException
- {
- if (number == null) { throw new JSONException("Null pointer"); }
+ public static String numberToString(final Number number) throws JSONException {
+ if (number == null) {
+ throw new JSONException("Null pointer");
+ }
testValidity(number);
// Shave off trailing zeros and decimal point, if possible.
String string = number.toString();
- if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0))
- {
- while (string.endsWith("0"))
- {
+ if ((string.indexOf('.') > 0) && (string.indexOf('e') < 0) && (string.indexOf('E') < 0)) {
+ while (string.endsWith("0")) {
string = string.substring(0, string.length() - 1);
}
- if (string.endsWith("."))
- {
+ if (string.endsWith(".")) {
string = string.substring(0, string.length() - 1);
}
}
return string;
}
-
+
/**
* Produce a string in double quotes with backslash sequences in all the right places. A backslash will be inserted
* control character or an unescaped quote or backslash.
@@ -370,27 +347,20 @@ public class JSONObject
*
* @return A String correctly formatted for insertion in a JSON text.
*/
- public static String quote(final String string)
- {
+ public static String quote(final String string) {
final StringWriter sw = new StringWriter();
- synchronized (sw.getBuffer())
- {
- try
- {
+ synchronized (sw.getBuffer()) {
+ try {
return quote(string, sw).toString();
- }
- catch (final IOException ignored)
- {
+ } catch (final IOException ignored) {
// will never happen - we are writing to a string writer
return "";
}
}
}
-
- public static Writer quote(final String string, final Writer w) throws IOException
- {
- if ((string == null) || (string.length() == 0))
- {
+
+ public static Writer quote(final String string, final Writer w) throws IOException {
+ if ((string == null) || (string.length() == 0)) {
w.write("\"\"");
return w;
}
@@ -400,20 +370,17 @@ public class JSONObject
int i;
final int len = string.length();
w.write('"');
- for (i = 0; i < len; i += 1)
- {
+ for (i = 0; i < len; i += 1) {
b = c;
c = string.charAt(i);
- switch (c)
- {
+ switch (c) {
case '\\':
case '"':
w.write('\\');
w.write(c);
break;
case '/':
- if (b == '<')
- {
+ if (b == '<') {
w.write('\\');
}
w.write(c);
@@ -434,15 +401,12 @@ public class JSONObject
w.write("\\r");
break;
default:
- if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100')))
- {
+ if ((c < ' ') || ((c >= '\u0080') && (c < '\u00a0')) || ((c >= '\u2000') && (c < '\u2100'))) {
w.write("\\u");
hhhh = Integer.toHexString(c);
w.write("0000", 0, 4 - hhhh.length());
w.write(hhhh);
- }
- else
- {
+ } else {
w.write(c);
}
}
@@ -450,7 +414,7 @@ public class JSONObject
w.write('"');
return w;
}
-
+
/**
* Try to convert a string into a number, boolean, or null. If the string can't be converted, return the string.
*
@@ -458,49 +422,47 @@ public class JSONObject
*
* @return A simple JSON value.
*/
- public static Object stringToValue(final String string)
- {
+ public static Object stringToValue(final String string) {
Double d;
- if (string.equals("")) { return string; }
- if (string.equalsIgnoreCase("true")) { return Boolean.TRUE; }
- if (string.equalsIgnoreCase("false")) { return Boolean.FALSE; }
- if (string.equalsIgnoreCase("null")) { return JSONObject.NULL; }
+ if (string.equals("")) {
+ return string;
+ }
+ if (string.equalsIgnoreCase("true")) {
+ return Boolean.TRUE;
+ }
+ if (string.equalsIgnoreCase("false")) {
+ return Boolean.FALSE;
+ }
+ if (string.equalsIgnoreCase("null")) {
+ return JSONObject.NULL;
+ }
/*
* If it might be a number, try converting it. If a number cannot be
* produced, then the value will just be a string.
*/
final char b = string.charAt(0);
- if (((b >= '0') && (b <= '9')) || (b == '-'))
- {
- try
- {
- if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1))
- {
+ if (((b >= '0') && (b <= '9')) || (b == '-')) {
+ try {
+ if ((string.indexOf('.') > -1) || (string.indexOf('e') > -1) || (string.indexOf('E') > -1)) {
d = Double.valueOf(string);
- if (!d.isInfinite() && !d.isNaN()) { return d; }
- }
- else
- {
+ if (!d.isInfinite() && !d.isNaN()) {
+ return d;
+ }
+ } else {
final Long myLong = new Long(string);
- if (string.equals(myLong.toString()))
- {
- if (myLong == myLong.intValue())
- {
+ if (string.equals(myLong.toString())) {
+ if (myLong == myLong.intValue()) {
return myLong.intValue();
- }
- else
- {
+ } else {
return myLong;
}
}
}
- }
- catch (final Exception ignore)
- {}
+ } catch (final Exception ignore) {}
}
return string;
}
-
+
/**
* Throw an exception if the object is a NaN or infinite number.
*
@@ -508,21 +470,20 @@ public class JSONObject
*
* @throws JSONException If o is a non-finite number.
*/
- public static void testValidity(final Object o) throws JSONException
- {
- if (o != null)
- {
- if (o instanceof Double)
- {
- if (((Double) o).isInfinite() || ((Double) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); }
- }
- else if (o instanceof Float)
- {
- if (((Float) o).isInfinite() || ((Float) o).isNaN()) { throw new JSONException("JSON does not allow non-finite numbers."); }
+ public static void testValidity(final Object o) throws JSONException {
+ if (o != null) {
+ if (o instanceof Double) {
+ if (((Double) o).isInfinite() || ((Double) o).isNaN()) {
+ throw new JSONException("JSON does not allow non-finite numbers.");
+ }
+ } else if (o instanceof Float) {
+ if (((Float) o).isInfinite() || ((Float) o).isNaN()) {
+ throw new JSONException("JSON does not allow non-finite numbers.");
+ }
}
}
}
-
+
/**
* Make a JSON text of an Object value. If the object has an value.toJSONString() method, then that method will be
* used to produce the JSON text. The method is required to produce a strictly conforming text. If the object does
@@ -542,31 +503,40 @@ public class JSONObject
*
* @throws JSONException If the value is or contains an invalid number.
*/
- public static String valueToString(final Object value) throws JSONException
- {
- if ((value == null) || value.equals(null)) { return "null"; }
- if (value instanceof JSONString)
- {
+ public static String valueToString(final Object value) throws JSONException {
+ if ((value == null) || value.equals(null)) {
+ return "null";
+ }
+ if (value instanceof JSONString) {
Object object;
- try
- {
+ try {
object = ((JSONString) value).toJSONString();
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException(e);
}
- if (object instanceof String) { return (String) object; }
+ if (object instanceof String) {
+ return (String) object;
+ }
throw new JSONException("Bad value from toJSONString: " + object);
}
- if (value instanceof Number) { return numberToString((Number) value); }
- if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) { return value.toString(); }
- if (value instanceof Map) { return new JSONObject((Map) value).toString(); }
- if (value instanceof Collection) { return new JSONArray((Collection) value).toString(); }
- if (value.getClass().isArray()) { return new JSONArray(value).toString(); }
+ if (value instanceof Number) {
+ return numberToString((Number) value);
+ }
+ if ((value instanceof Boolean) || (value instanceof JSONObject) || (value instanceof JSONArray)) {
+ return value.toString();
+ }
+ if (value instanceof Map) {
+ return new JSONObject((Map) value).toString();
+ }
+ if (value instanceof Collection) {
+ return new JSONArray((Collection) value).toString();
+ }
+ if (value.getClass().isArray()) {
+ return new JSONArray(value).toString();
+ }
return quote(value.toString());
}
-
+
/**
* Wrap an object, if necessary. If the object is null, return the NULL object. If it is an array or collection,
* wrap it in a JSONArray. If it is a map, wrap it in a JSONObject. If it is a standard property (Double, String, et
@@ -577,11 +547,11 @@ public class JSONObject
*
* @return The wrapped value
*/
- public static Object wrap(final Object object)
- {
- try
- {
- if (object == null) { return NULL; }
+ public static Object wrap(final Object object) {
+ try {
+ if (object == null) {
+ return NULL;
+ }
if ((object instanceof JSONObject)
|| (object instanceof JSONArray)
|| NULL.equals(object)
@@ -594,83 +564,66 @@ public class JSONObject
|| (object instanceof Boolean)
|| (object instanceof Float)
|| (object instanceof Double)
- || (object instanceof String)) { return object; }
- if (object instanceof Collection) { return new JSONArray((Collection) object); }
- if (object.getClass().isArray()) { return new JSONArray(object); }
- if (object instanceof Map) { return new JSONObject((Map) object); }
+ || (object instanceof String)) {
+ return object;
+ }
+ if (object instanceof Collection) {
+ return new JSONArray((Collection) object);
+ }
+ if (object.getClass().isArray()) {
+ return new JSONArray(object);
+ }
+ if (object instanceof Map) {
+ return new JSONObject((Map) object);
+ }
final Package objectPackage = object.getClass().getPackage();
final String objectPackageName = objectPackage != null ? objectPackage.getName() : "";
- if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) { return object.toString(); }
+ if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || (object.getClass().getClassLoader() == null)) {
+ return object.toString();
+ }
return new JSONObject(object);
- }
- catch (final Exception exception)
- {
+ } catch (final Exception exception) {
return null;
}
}
-
- static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException
- {
- if ((value == null) || value.equals(null))
- {
+
+ static final Writer writeValue(final Writer writer, final Object value, final int indentFactor, final int indent) throws JSONException, IOException {
+ if ((value == null) || value.equals(null)) {
writer.write("null");
- }
- else if (value instanceof JSONObject)
- {
+ } else if (value instanceof JSONObject) {
((JSONObject) value).write(writer, indentFactor, indent);
- }
- else if (value instanceof JSONArray)
- {
+ } else if (value instanceof JSONArray) {
((JSONArray) value).write(writer, indentFactor, indent);
- }
- else if (value instanceof Map)
- {
+ } else if (value instanceof Map) {
new JSONObject((Map) value).write(writer, indentFactor, indent);
- }
- else if (value instanceof Collection)
- {
+ } else if (value instanceof Collection) {
new JSONArray((Collection) value).write(writer, indentFactor, indent);
- }
- else if (value.getClass().isArray())
- {
+ } else if (value.getClass().isArray()) {
new JSONArray(value).write(writer, indentFactor, indent);
- }
- else if (value instanceof Number)
- {
+ } else if (value instanceof Number) {
writer.write(numberToString((Number) value));
- }
- else if (value instanceof Boolean)
- {
+ } else if (value instanceof Boolean) {
writer.write(value.toString());
- }
- else if (value instanceof JSONString)
- {
+ } else if (value instanceof JSONString) {
Object o;
- try
- {
+ try {
o = ((JSONString) value).toJSONString();
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException(e);
}
writer.write(o != null ? o.toString() : quote(value.toString()));
- }
- else
- {
+ } else {
quote(value.toString(), writer);
}
return writer;
}
-
- static final void indent(final Writer writer, final int indent) throws IOException
- {
- for (int i = 0; i < indent; i += 1)
- {
+
+ static final void indent(final Writer writer, final int indent) throws IOException {
+ for (int i = 0; i < indent; i += 1) {
writer.write(' ');
}
}
-
+
/**
* Accumulate values under a key. It is similar to the put method except that if there is already an object stored
* under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already
@@ -686,25 +639,19 @@ public class JSONObject
*
* @throws JSONException If the value is an invalid number or if the key is null.
*/
- public JSONObject accumulate(final String key, final Object value) throws JSONException
- {
+ public JSONObject accumulate(final String key, final Object value) throws JSONException {
testValidity(value);
final Object object = opt(key);
- if (object == null)
- {
+ if (object == null) {
this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value);
- }
- else if (object instanceof JSONArray)
- {
+ } else if (object instanceof JSONArray) {
((JSONArray) object).put(value);
- }
- else
- {
+ } else {
this.put(key, new JSONArray().put(object).put(value));
}
return this;
}
-
+
/**
* Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the
* JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated
@@ -717,25 +664,19 @@ public class JSONObject
*
* @throws JSONException If the key is null or if the current value associated with the key is not a JSONArray.
*/
- public JSONObject append(final String key, final Object value) throws JSONException
- {
+ public JSONObject append(final String key, final Object value) throws JSONException {
testValidity(value);
final Object object = opt(key);
- if (object == null)
- {
+ if (object == null) {
this.put(key, new JSONArray().put(value));
- }
- else if (object instanceof JSONArray)
- {
+ } else if (object instanceof JSONArray) {
this.put(key, ((JSONArray) object).put(value));
- }
- else
- {
+ } else {
throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
}
return this;
}
-
+
/**
* Get the value object associated with a key.
*
@@ -745,14 +686,17 @@ public class JSONObject
*
* @throws JSONException if the key is not found.
*/
- public Object get(final String key) throws JSONException
- {
- if (key == null) { throw new JSONException("Null key."); }
+ public Object get(final String key) throws JSONException {
+ if (key == null) {
+ throw new JSONException("Null key.");
+ }
final Object object = opt(key);
- if (object == null) { throw new JSONException("JSONObject[" + quote(key) + "] not found."); }
+ if (object == null) {
+ throw new JSONException("JSONObject[" + quote(key) + "] not found.");
+ }
return object;
}
-
+
/**
* Get the boolean value associated with a key.
*
@@ -762,17 +706,16 @@ public class JSONObject
*
* @throws JSONException if the value is not a Boolean or the String "true" or "false".
*/
- public boolean getBoolean(final String key) throws JSONException
- {
+ public boolean getBoolean(final String key) throws JSONException {
final Object object = get(key);
- if (object.equals(Boolean.FALSE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("false")))
- {
+ 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"))) {
+ return true;
}
- else if (object.equals(Boolean.TRUE) || ((object instanceof String) && ((String) object).equalsIgnoreCase("true"))) { return true; }
throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean.");
}
-
+
/**
* Get the double value associated with a key.
*
@@ -783,19 +726,15 @@ public class JSONObject
* @throws JSONException if the key is not found or if the value is not a Number object and cannot be converted to a
* number.
*/
- public double getDouble(final String key) throws JSONException
- {
+ public double getDouble(final String key) throws JSONException {
final Object object = get(key);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a number.");
}
}
-
+
/**
* Get the int value associated with a key.
*
@@ -805,19 +744,15 @@ public class JSONObject
*
* @throws JSONException if the key is not found or if the value cannot be converted to an integer.
*/
- public int getInt(final String key) throws JSONException
- {
+ public int getInt(final String key) throws JSONException {
final Object object = get(key);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not an int.");
}
}
-
+
/**
* Get the JSONArray value associated with a key.
*
@@ -827,13 +762,14 @@ public class JSONObject
*
* @throws JSONException if the key is not found or if the value is not a JSONArray.
*/
- public JSONArray getJSONArray(final String key) throws JSONException
- {
+ public JSONArray getJSONArray(final String key) throws JSONException {
final Object object = get(key);
- if (object instanceof JSONArray) { return (JSONArray) object; }
+ if (object instanceof JSONArray) {
+ return (JSONArray) object;
+ }
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray.");
}
-
+
/**
* Get the JSONObject value associated with a key.
*
@@ -843,13 +779,14 @@ public class JSONObject
*
* @throws JSONException if the key is not found or if the value is not a JSONObject.
*/
- public JSONObject getJSONObject(final String key) throws JSONException
- {
+ public JSONObject getJSONObject(final String key) throws JSONException {
final Object object = get(key);
- if (object instanceof JSONObject) { return (JSONObject) object; }
+ if (object instanceof JSONObject) {
+ return (JSONObject) object;
+ }
throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject.");
}
-
+
/**
* Get the long value associated with a key.
*
@@ -859,19 +796,15 @@ public class JSONObject
*
* @throws JSONException if the key is not found or if the value cannot be converted to a long.
*/
- public long getLong(final String key) throws JSONException
- {
+ public long getLong(final String key) throws JSONException {
final Object object = get(key);
- try
- {
+ try {
return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
throw new JSONException("JSONObject[" + quote(key) + "] is not a long.");
}
}
-
+
/**
* Get the string associated with a key.
*
@@ -881,13 +814,14 @@ public class JSONObject
*
* @throws JSONException if there is no string value for the key.
*/
- public String getString(final String key) throws JSONException
- {
+ public String getString(final String key) throws JSONException {
final Object object = get(key);
- if (object instanceof String) { return (String) object; }
+ if (object instanceof String) {
+ return (String) object;
+ }
throw new JSONException("JSONObject[" + quote(key) + "] not a string.");
}
-
+
/**
* Determine if the JSONObject contains a specific key.
*
@@ -895,11 +829,10 @@ public class JSONObject
*
* @return true if the key exists in the JSONObject.
*/
- public boolean has(final String key)
- {
+ public boolean has(final String key) {
return map.containsKey(key);
}
-
+
/**
* Increment a property of a JSONObject. If there is no such property, create one with a value of 1. If there is
* such a property, and if it is an Integer, Long, Double, or Float, then add one to it.
@@ -911,36 +844,24 @@ public class JSONObject
* @throws JSONException If there is already a property with this name that is not an Integer, Long, Double, or
* Float.
*/
- public JSONObject increment(final String key) throws JSONException
- {
+ public JSONObject increment(final String key) throws JSONException {
final Object value = opt(key);
- if (value == null)
- {
+ if (value == null) {
this.put(key, 1);
- }
- else if (value instanceof Integer)
- {
+ } else if (value instanceof Integer) {
this.put(key, (Integer) value + 1);
- }
- else if (value instanceof Long)
- {
+ } else if (value instanceof Long) {
this.put(key, (Long) value + 1);
- }
- else if (value instanceof Double)
- {
+ } else if (value instanceof Double) {
this.put(key, (Double) value + 1);
- }
- else if (value instanceof Float)
- {
+ } else if (value instanceof Float) {
this.put(key, (Float) value + 1);
- }
- else
- {
+ } else {
throw new JSONException("Unable to increment [" + quote(key) + "].");
}
return this;
}
-
+
/**
* Determine if the value associated with the key is null or if there is no value.
*
@@ -948,57 +869,51 @@ public class JSONObject
*
* @return true if there is no value associated with the key or if the value is the JSONObject.NULL object.
*/
- public boolean isNull(final String key)
- {
+ public boolean isNull(final String key) {
return JSONObject.NULL.equals(opt(key));
}
-
+
/**
* Get an enumeration of the keys of the JSONObject.
*
* @return An iterator of the keys.
*/
- public Iterator keys()
- {
+ public Iterator keys() {
return keySet().iterator();
}
-
+
/**
* Get a set of keys of the JSONObject.
*
* @return A keySet.
*/
- public Set keySet()
- {
+ public Set keySet() {
return map.keySet();
}
-
+
/**
* Get the number of keys stored in the JSONObject.
*
* @return The number of keys in the JSONObject.
*/
- public int length()
- {
+ public int length() {
return map.size();
}
-
+
/**
* Produce a JSONArray containing the names of the elements of this JSONObject.
*
* @return A JSONArray containing the key strings, or null if the JSONObject is empty.
*/
- public JSONArray names()
- {
+ public JSONArray names() {
final JSONArray ja = new JSONArray();
final Iterator keys = keys();
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
ja.put(keys.next());
}
return ja.length() == 0 ? null : ja;
}
-
+
/**
* Get an optional value associated with a key.
*
@@ -1006,11 +921,10 @@ public class JSONObject
*
* @return An object which is the value, or null if there is no value.
*/
- public Object opt(final String key)
- {
+ public Object opt(final String key) {
return key == null ? null : map.get(key);
}
-
+
/**
* Get an optional boolean associated with a key. It returns false if there is no such key, or if the value is not
* Boolean.TRUE or the String "true".
@@ -1019,11 +933,10 @@ public class JSONObject
*
* @return The truth.
*/
- public boolean optBoolean(final String key)
- {
+ public boolean optBoolean(final String key) {
return this.optBoolean(key, false);
}
-
+
/**
* Get an optional boolean associated with a key. It returns the defaultValue if there is no such key, or if it is
* not a Boolean or the String "true" or "false" (case insensitive).
@@ -1033,18 +946,14 @@ public class JSONObject
*
* @return The truth.
*/
- public boolean optBoolean(final String key, final boolean defaultValue)
- {
- try
- {
+ public boolean optBoolean(final String key, final boolean defaultValue) {
+ try {
return getBoolean(key);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get an optional double associated with a key, or NaN if there is no such key or if its value is not a number. If
* the value is a string, an attempt will be made to evaluate it as a number.
@@ -1053,11 +962,10 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public double optDouble(final String key)
- {
+ public double optDouble(final String key) {
return this.optDouble(key, Double.NaN);
}
-
+
/**
* Get an optional double associated with a key, or the defaultValue if there is no such key or if its value is not
* a number. If the value is a string, an attempt will be made to evaluate it as a number.
@@ -1067,18 +975,14 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public double optDouble(final String key, final double defaultValue)
- {
- try
- {
+ public double optDouble(final String key, final double defaultValue) {
+ try {
return getDouble(key);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get an optional int value associated with a key, or zero if there is no such key or if the value is not a number.
* If the value is a string, an attempt will be made to evaluate it as a number.
@@ -1087,11 +991,10 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public int optInt(final String key)
- {
+ public int optInt(final String key) {
return this.optInt(key, 0);
}
-
+
/**
* Get an optional int value associated with a key, or the default if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number.
@@ -1101,18 +1004,14 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public int optInt(final String key, final int defaultValue)
- {
- try
- {
+ public int optInt(final String key, final int defaultValue) {
+ try {
return getInt(key);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get an optional JSONArray associated with a key. It returns null if there is no such key, or if its value is not
* a JSONArray.
@@ -1121,12 +1020,11 @@ public class JSONObject
*
* @return A JSONArray which is the value.
*/
- public JSONArray optJSONArray(final String key)
- {
+ public JSONArray optJSONArray(final String key) {
final Object o = opt(key);
return o instanceof JSONArray ? (JSONArray) o : null;
}
-
+
/**
* Get an optional JSONObject associated with a key. It returns null if there is no such key, or if its value is not
* a JSONObject.
@@ -1135,12 +1033,11 @@ public class JSONObject
*
* @return A JSONObject which is the value.
*/
- public JSONObject optJSONObject(final String key)
- {
+ public JSONObject optJSONObject(final String key) {
final Object object = opt(key);
return object instanceof JSONObject ? (JSONObject) object : null;
}
-
+
/**
* Get an optional long value associated with a key, or zero if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number.
@@ -1149,11 +1046,10 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public long optLong(final String key)
- {
+ public long optLong(final String key) {
return this.optLong(key, 0);
}
-
+
/**
* Get an optional long value associated with a key, or the default if there is no such key or if the value is not a
* number. If the value is a string, an attempt will be made to evaluate it as a number.
@@ -1163,18 +1059,14 @@ public class JSONObject
*
* @return An object which is the value.
*/
- public long optLong(final String key, final long defaultValue)
- {
- try
- {
+ public long optLong(final String key, final long defaultValue) {
+ try {
return getLong(key);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return defaultValue;
}
}
-
+
/**
* Get an optional string associated with a key. It returns an empty string if there is no such key. If the value is
* not a string and is not null, then it is converted to a string.
@@ -1183,11 +1075,10 @@ public class JSONObject
*
* @return A string which is the value.
*/
- public String optString(final String key)
- {
+ public String optString(final String key) {
return this.optString(key, "");
}
-
+
/**
* Get an optional string associated with a key. It returns the defaultValue if there is no such key.
*
@@ -1196,64 +1087,46 @@ public class JSONObject
*
* @return A string which is the value.
*/
- public String optString(final String key, final String defaultValue)
- {
+ public String optString(final String key, final String defaultValue) {
final Object object = opt(key);
return NULL.equals(object) ? defaultValue : object.toString();
}
-
- private void populateMap(final Object bean)
- {
+
+ private void populateMap(final Object bean) {
final Class klass = bean.getClass();
// If klass is a System class then set includeSuperClass to false.
final boolean includeSuperClass = klass.getClassLoader() != null;
final Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods();
- for (final Method method : methods)
- {
- try
- {
- if (Modifier.isPublic(method.getModifiers()))
- {
+ for (final Method method : methods) {
+ try {
+ if (Modifier.isPublic(method.getModifiers())) {
final String name = method.getName();
String key = "";
- if (name.startsWith("get"))
- {
- if ("getClass".equals(name) || "getDeclaringClass".equals(name))
- {
+ if (name.startsWith("get")) {
+ if ("getClass".equals(name) || "getDeclaringClass".equals(name)) {
key = "";
- }
- else
- {
+ } else {
key = name.substring(3);
}
- }
- else if (name.startsWith("is"))
- {
+ } else if (name.startsWith("is")) {
key = name.substring(2);
}
- if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0))
- {
- if (key.length() == 1)
- {
+ if ((key.length() > 0) && Character.isUpperCase(key.charAt(0)) && (method.getParameterTypes().length == 0)) {
+ if (key.length() == 1) {
key = key.toLowerCase();
- }
- else if (!Character.isUpperCase(key.charAt(1)))
- {
+ } else if (!Character.isUpperCase(key.charAt(1))) {
key = key.substring(0, 1).toLowerCase() + key.substring(1);
}
final Object result = method.invoke(bean, (Object[]) null);
- if (result != null)
- {
+ if (result != null) {
map.put(key, wrap(result));
}
}
}
- }
- catch (final Exception ignore)
- {}
+ } catch (final Exception ignore) {}
}
}
-
+
/**
* Put a key/boolean pair in the JSONObject.
*
@@ -1264,12 +1137,11 @@ public class JSONObject
*
* @throws JSONException If the key is null.
*/
- public JSONObject put(final String key, final boolean value) throws JSONException
- {
+ public JSONObject put(final String key, final boolean value) throws JSONException {
this.put(key, value ? Boolean.TRUE : Boolean.FALSE);
return this;
}
-
+
/**
* Put a key/value pair in the JSONObject, where the value will be a JSONArray which is produced from a Collection.
*
@@ -1280,12 +1152,11 @@ public class JSONObject
*
* @throws JSONException
*/
- public JSONObject put(final String key, final Collection value) throws JSONException
- {
+ public JSONObject put(final String key, final Collection value) throws JSONException {
this.put(key, new JSONArray(value));
return this;
}
-
+
/**
* Put a key/double pair in the JSONObject.
*
@@ -1296,12 +1167,11 @@ public class JSONObject
*
* @throws JSONException If the key is null or if the number is invalid.
*/
- public JSONObject put(final String key, final double value) throws JSONException
- {
+ public JSONObject put(final String key, final double value) throws JSONException {
this.put(key, new Double(value));
return this;
}
-
+
/**
* Put a key/int pair in the JSONObject.
*
@@ -1312,12 +1182,11 @@ public class JSONObject
*
* @throws JSONException If the key is null.
*/
- public JSONObject put(final String key, final int value) throws JSONException
- {
+ public JSONObject put(final String key, final int value) throws JSONException {
this.put(key, new Integer(value));
return this;
}
-
+
/**
* Put a key/long pair in the JSONObject.
*
@@ -1328,12 +1197,11 @@ public class JSONObject
*
* @throws JSONException If the key is null.
*/
- public JSONObject put(final String key, final long value) throws JSONException
- {
+ public JSONObject put(final String key, final long value) throws JSONException {
this.put(key, new Long(value));
return this;
}
-
+
/**
* Put a key/value pair in the JSONObject, where the value will be a JSONObject which is produced from a Map.
*
@@ -1344,12 +1212,11 @@ public class JSONObject
*
* @throws JSONException
*/
- public JSONObject put(final String key, final Map value) throws JSONException
- {
+ public JSONObject put(final String key, final Map value) throws JSONException {
this.put(key, new JSONObject(value));
return this;
}
-
+
/**
* Put a key/value pair in the JSONObject. If the value is null, then the key will be removed from the JSONObject if
* it is present.
@@ -1362,21 +1229,19 @@ public class JSONObject
*
* @throws JSONException If the value is non-finite number or if the key is null.
*/
- public JSONObject put(final String key, final Object value) throws JSONException
- {
- if (key == null) { throw new NullPointerException("Null key."); }
- if (value != null)
- {
+ public JSONObject put(final String key, final Object value) throws JSONException {
+ if (key == null) {
+ throw new NullPointerException("Null key.");
+ }
+ if (value != null) {
testValidity(value);
map.put(key, value);
- }
- else
- {
+ } else {
remove(key);
}
return this;
}
-
+
/**
* Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and only if there is
* not already a member with that name.
@@ -1388,16 +1253,16 @@ public class JSONObject
*
* @throws JSONException if the key is a duplicate
*/
- public JSONObject putOnce(final String key, final Object value) throws JSONException
- {
- if ((key != null) && (value != null))
- {
- if (opt(key) != null) { throw new JSONException("Duplicate key \"" + key + "\""); }
+ public JSONObject putOnce(final String key, final Object value) throws JSONException {
+ if ((key != null) && (value != null)) {
+ if (opt(key) != null) {
+ throw new JSONException("Duplicate key \"" + key + "\"");
+ }
this.put(key, value);
}
return this;
}
-
+
/**
* Put a key/value pair in the JSONObject, but only if the key and the value are both non-null.
*
@@ -1409,15 +1274,13 @@ public class JSONObject
*
* @throws JSONException If the value is a non-finite number.
*/
- public JSONObject putOpt(final String key, final Object value) throws JSONException
- {
- if ((key != null) && (value != null))
- {
+ public JSONObject putOpt(final String key, final Object value) throws JSONException {
+ if ((key != null) && (value != null)) {
this.put(key, value);
}
return this;
}
-
+
/**
* Remove a name and its value, if present.
*
@@ -1425,11 +1288,10 @@ public class JSONObject
*
* @return The value that was associated with the name, or null if there was no value.
*/
- public Object remove(final String key)
- {
+ public Object remove(final String key) {
return map.remove(key);
}
-
+
/**
* Determine if two JSONObjects are similar. They must contain the same set of names which must be associated with
* similar values.
@@ -1438,35 +1300,36 @@ public class JSONObject
*
* @return true if they are equal
*/
- public boolean similar(final Object other)
- {
- try
- {
- if (!(other instanceof JSONObject)) { return false; }
+ public boolean similar(final Object other) {
+ try {
+ if (!(other instanceof JSONObject)) {
+ return false;
+ }
final Set set = keySet();
- if (!set.equals(((JSONObject) other).keySet())) { return false; }
- for (final String name : set)
- {
+ if (!set.equals(((JSONObject) other).keySet())) {
+ return false;
+ }
+ for (final String name : set) {
final Object valueThis = get(name);
final Object valueOther = ((JSONObject) other).get(name);
- if (valueThis instanceof JSONObject)
- {
- if (!((JSONObject) valueThis).similar(valueOther)) { return false; }
+ if (valueThis instanceof JSONObject) {
+ if (!((JSONObject) valueThis).similar(valueOther)) {
+ return false;
+ }
+ } else if (valueThis instanceof JSONArray) {
+ if (!((JSONArray) valueThis).similar(valueOther)) {
+ return false;
+ }
+ } else if (!valueThis.equals(valueOther)) {
+ return false;
}
- else if (valueThis instanceof JSONArray)
- {
- if (!((JSONArray) valueThis).similar(valueOther)) { return false; }
- }
- else if (!valueThis.equals(valueOther)) { return false; }
}
return true;
- }
- catch (final Throwable exception)
- {
+ } catch (final Throwable exception) {
return false;
}
}
-
+
/**
* Produce a JSONArray containing the values of the members of this JSONObject.
*
@@ -1477,17 +1340,17 @@ public class JSONObject
*
* @throws JSONException If any of the values are non-finite numbers.
*/
- public JSONArray toJSONArray(final JSONArray names) throws JSONException
- {
- if ((names == null) || (names.length() == 0)) { return null; }
+ public JSONArray toJSONArray(final JSONArray names) throws JSONException {
+ if ((names == null) || (names.length() == 0)) {
+ return null;
+ }
final JSONArray ja = new JSONArray();
- for (int i = 0; i < names.length(); i += 1)
- {
+ for (int i = 0; i < names.length(); i += 1) {
ja.put(opt(names.getString(i)));
}
return ja;
}
-
+
/**
* Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not result in a
* syntactically correct JSON text, then null will be returned instead.
@@ -1499,18 +1362,14 @@ public class JSONObject
* brace).
*/
@Override
- public String toString()
- {
- try
- {
+ public String toString() {
+ try {
return this.toString(0);
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return null;
}
}
-
+
/**
* Make a prettyprinted JSON text of this JSONObject.
*
@@ -1524,15 +1383,13 @@ public class JSONObject
*
* @throws JSONException If the object contains an invalid number.
*/
- public String toString(final int indentFactor) throws JSONException
- {
+ public String toString(final int indentFactor) throws JSONException {
final StringWriter w = new StringWriter();
- synchronized (w.getBuffer())
- {
+ synchronized (w.getBuffer()) {
return this.write(w, indentFactor, 0).toString();
}
}
-
+
/**
* Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.
*
@@ -1542,11 +1399,10 @@ public class JSONObject
*
* @throws JSONException
*/
- public Writer write(final Writer writer) throws JSONException
- {
+ public Writer write(final Writer writer) throws JSONException {
return this.write(writer, 0, 0);
}
-
+
/**
* Write the contents of the JSONObject as JSON text to a writer. For compactness, no whitespace is added.
*
@@ -1556,88 +1412,70 @@ public class JSONObject
*
* @throws JSONException
*/
- Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException
- {
- try
- {
+ Writer write(final Writer writer, final int indentFactor, final int indent) throws JSONException {
+ try {
boolean commanate = false;
final int length = length();
final Iterator keys = keys();
writer.write('{');
- if (length == 1)
- {
+ if (length == 1) {
final Object key = keys.next();
writer.write(quote(key.toString()));
writer.write(':');
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer, map.get(key), indentFactor, indent);
- }
- else if (length != 0)
- {
+ } else if (length != 0) {
final int newindent = indent + indentFactor;
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
final Object key = keys.next();
- if (commanate)
- {
+ if (commanate) {
writer.write(',');
}
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, newindent);
writer.write(quote(key.toString()));
writer.write(':');
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write(' ');
}
writeValue(writer, map.get(key), indentFactor, newindent);
commanate = true;
}
- if (indentFactor > 0)
- {
+ if (indentFactor > 0) {
writer.write('\n');
}
indent(writer, indent);
}
writer.write('}');
return writer;
- }
- catch (final IOException exception)
- {
+ } catch (final IOException exception) {
throw new JSONException(exception);
}
}
-
+
/**
* JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is equivalent to the
* value that JavaScript calls undefined.
*/
- private static final class Null
- {
+ private static final class Null {
/**
* There is only intended to be a single instance of the NULL object, so the clone method returns itself.
*
* @return NULL.
*/
@Override
- protected final Object clone()
- {
- try
- {
+ protected final Object clone() {
+ try {
return super.clone();
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
return this;
}
}
-
+
/**
* A Null object is equal to the null value and to itself.
*
@@ -1646,19 +1484,17 @@ public class JSONObject
* @return true if the object parameter is the JSONObject.NULL object or null.
*/
@Override
- public boolean equals(final Object object)
- {
+ public boolean equals(final Object object) {
return (object == null) || (object == this);
}
-
+
/**
* Get the "null" string value.
*
* @return The string "null".
*/
@Override
- public String toString()
- {
+ public String toString() {
return "null";
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONString.java b/src/main/java/com/intellectualcrafters/json/JSONString.java
index c8494287f..2cf8273a9 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONString.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONString.java
@@ -6,8 +6,7 @@ package com.intellectualcrafters.json;
* JSONWriter.value(
Object)
. The toJSONString
method will be used instead of the
* default behavior of using the Object's toString()
method and quoting the result.
*/
-public interface JSONString
-{
+public interface JSONString {
/**
* The toJSONString
method allows a class to produce its own JSON serialization.
*
diff --git a/src/main/java/com/intellectualcrafters/json/JSONStringer.java b/src/main/java/com/intellectualcrafters/json/JSONStringer.java
index fbc59094a..ecacb861e 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONStringer.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONStringer.java
@@ -33,16 +33,14 @@ import java.io.StringWriter;
* @author JSON.org
* @version 2008-09-18
*/
-public class JSONStringer extends JSONWriter
-{
+public class JSONStringer extends JSONWriter {
/**
* Make a fresh JSONStringer. It can be used to build one JSON text.
*/
- public JSONStringer()
- {
+ public JSONStringer() {
super(new StringWriter());
}
-
+
/**
* Return the JSON text. This method is used to obtain the product of the JSONStringer instance. It will return
* null
if there was a problem in the construction of the JSON text (such as the calls to
@@ -51,8 +49,7 @@ public class JSONStringer extends JSONWriter
* @return The JSON text.
*/
@Override
- public String toString()
- {
+ public String toString() {
return mode == 'd' ? writer.toString() : null;
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONTokener.java b/src/main/java/com/intellectualcrafters/json/JSONTokener.java
index 3391e1255..b6ad424e0 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONTokener.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONTokener.java
@@ -14,8 +14,7 @@ import java.io.StringReader;
* @author JSON.org
* @version 2014-05-03
*/
-public class JSONTokener
-{
+public class JSONTokener {
private final Reader reader;
private long character;
private boolean eof;
@@ -23,14 +22,13 @@ public class JSONTokener
private long line;
private char previous;
private boolean usePrevious;
-
+
/**
* Construct a JSONTokener from a Reader.
*
* @param reader A reader.
*/
- public JSONTokener(final Reader reader)
- {
+ public JSONTokener(final Reader reader) {
this.reader = reader.markSupported() ? reader : new BufferedReader(reader);
eof = false;
usePrevious = false;
@@ -39,27 +37,25 @@ public class JSONTokener
character = 1;
line = 1;
}
-
+
/**
* Construct a JSONTokener from an InputStream.
*
* @param inputStream The source.
*/
- public JSONTokener(final 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.
*/
- public JSONTokener(final String s)
- {
+ public JSONTokener(final String s) {
this(new StringReader(s));
}
-
+
/**
* Get the hex value of a character (base16).
*
@@ -67,93 +63,86 @@ public class JSONTokener
*
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
- public static int dehexchar(final char c)
- {
- if ((c >= '0') && (c <= '9')) { return c - '0'; }
- if ((c >= 'A') && (c <= 'F')) { return c - ('A' - 10); }
- if ((c >= 'a') && (c <= 'f')) { return c - ('a' - 10); }
+ public static int dehexchar(final char c) {
+ if ((c >= '0') && (c <= '9')) {
+ return c - '0';
+ }
+ if ((c >= 'A') && (c <= 'F')) {
+ return c - ('A' - 10);
+ }
+ if ((c >= 'a') && (c <= 'f')) {
+ return c - ('a' - 10);
+ }
return -1;
}
-
+
/**
* 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 (usePrevious || (index <= 0)) { throw new JSONException("Stepping back two steps is not supported"); }
+ public void back() throws JSONException {
+ if (usePrevious || (index <= 0)) {
+ throw new JSONException("Stepping back two steps is not supported");
+ }
index -= 1;
character -= 1;
usePrevious = true;
eof = false;
}
-
- public boolean end()
- {
+
+ public boolean end() {
return eof && !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
- {
+ public boolean more() throws JSONException {
this.next();
- if (end()) { return false; }
+ if (end()) {
+ return false;
+ }
back();
return true;
}
-
+
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
*/
- public char next() throws JSONException
- {
+ public char next() throws JSONException {
int c;
- if (usePrevious)
- {
+ if (usePrevious) {
usePrevious = false;
c = previous;
- }
- else
- {
- try
- {
+ } else {
+ try {
c = reader.read();
- }
- catch (final IOException exception)
- {
+ } catch (final IOException exception) {
throw new JSONException(exception);
}
- if (c <= 0)
- { // End of stream
+ if (c <= 0) { // End of stream
eof = true;
c = 0;
}
}
index += 1;
- if (previous == '\r')
- {
+ if (previous == '\r') {
line += 1;
character = c == '\n' ? 0 : 1;
- }
- else if (c == '\n')
- {
+ } else if (c == '\n') {
line += 1;
character = 0;
- }
- else
- {
+ } else {
character += 1;
}
previous = (char) c;
return previous;
}
-
+
/**
* Consume the next character, and check that it matches a specified character.
*
@@ -163,13 +152,14 @@ public class JSONTokener
*
* @throws JSONException if the character does not match.
*/
- public char next(final char c) throws JSONException
- {
+ public char next(final char c) throws JSONException {
final char n = this.next();
- if (n != c) { throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); }
+ if (n != c) {
+ throw syntaxError("Expected '" + c + "' and instead saw '" + n + "'");
+ }
return n;
}
-
+
/**
* Get the next n characters.
*
@@ -179,20 +169,22 @@ public class JSONTokener
*
* @throws JSONException Substring bounds error if there are not n characters remaining in the source string.
*/
- public String next(final int n) throws JSONException
- {
- if (n == 0) { return ""; }
+ public String next(final int n) throws JSONException {
+ if (n == 0) {
+ return "";
+ }
final char[] chars = new char[n];
int pos = 0;
- while (pos < n)
- {
+ while (pos < n) {
chars[pos] = this.next();
- if (end()) { throw syntaxError("Substring bounds error"); }
+ if (end()) {
+ throw syntaxError("Substring bounds error");
+ }
pos += 1;
}
return new String(chars);
}
-
+
/**
* Get the next char in the string, skipping whitespace.
*
@@ -200,15 +192,15 @@ public class JSONTokener
*
* @throws JSONException
*/
- public char nextClean() throws JSONException
- {
- for (;;)
- {
+ public char nextClean() throws JSONException {
+ for (;;) {
final char c = this.next();
- if ((c == 0) || (c > ' ')) { return c; }
+ 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.
@@ -220,23 +212,19 @@ public class JSONTokener
*
* @throws JSONException Unterminated string.
*/
- public String nextString(final char quote) throws JSONException
- {
+ public String nextString(final char quote) throws JSONException {
char c;
final StringBuilder sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
c = this.next();
- switch (c)
- {
+ switch (c) {
case 0:
case '\n':
case '\r':
throw syntaxError("Unterminated string");
case '\\':
c = this.next();
- switch (c)
- {
+ switch (c) {
case 'b':
sb.append('\b');
break;
@@ -266,12 +254,14 @@ public class JSONTokener
}
break;
default:
- if (c == quote) { return sb.toString(); }
+ if (c == quote) {
+ return sb.toString();
+ }
sb.append(c);
}
}
}
-
+
/**
* Get the text up but not including the specified character or the end of line, whichever comes first.
*
@@ -279,16 +269,12 @@ public class JSONTokener
*
* @return A string.
*/
- public String nextTo(final char delimiter) throws JSONException
- {
+ public String nextTo(final char delimiter) throws JSONException {
final StringBuilder sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
final char c = this.next();
- if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r'))
- {
- if (c != 0)
- {
+ if ((c == delimiter) || (c == 0) || (c == '\n') || (c == '\r')) {
+ if (c != 0) {
back();
}
return sb.toString().trim();
@@ -296,7 +282,7 @@ public class JSONTokener
sb.append(c);
}
}
-
+
/**
* Get the text up but not including one of the specified delimiter characters or the end of line, whichever comes
* first.
@@ -305,17 +291,13 @@ public class JSONTokener
*
* @return A string, trimmed.
*/
- public String nextTo(final String delimiters) throws JSONException
- {
+ public String nextTo(final String delimiters) throws JSONException {
char c;
final StringBuilder sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
c = this.next();
- if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r'))
- {
- if (c != 0)
- {
+ if ((delimiters.indexOf(c) >= 0) || (c == 0) || (c == '\n') || (c == '\r')) {
+ if (c != 0) {
back();
}
return sb.toString().trim();
@@ -323,7 +305,7 @@ public class JSONTokener
sb.append(c);
}
}
-
+
/**
* Get the next value. The value can be a Boolean, Double, Integer, JSONArray, JSONObject, Long, or String, or the
* JSONObject.NULL object.
@@ -332,12 +314,10 @@ public class JSONTokener
*
* @throws JSONException If syntax error.
*/
- public Object nextValue() throws JSONException
- {
+ public Object nextValue() throws JSONException {
char c = nextClean();
String string;
- switch (c)
- {
+ switch (c) {
case '"':
case '\'':
return nextString(c);
@@ -356,17 +336,18 @@ public class JSONTokener
* formatting character.
*/
final StringBuilder sb = new StringBuilder();
- while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0))
- {
+ while ((c >= ' ') && (",:]}/\\\"[{;=#".indexOf(c) < 0)) {
sb.append(c);
c = this.next();
}
back();
string = sb.toString().trim();
- if ("".equals(string)) { throw syntaxError("Missing value"); }
+ if ("".equals(string)) {
+ throw syntaxError("Missing value");
+ }
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.
@@ -375,37 +356,30 @@ public class JSONTokener
*
* @return The requested character, or zero if the requested character is not found.
*/
- public char skipTo(final char to) throws JSONException
- {
+ public char skipTo(final char to) throws JSONException {
char c;
- try
- {
+ try {
final long startIndex = index;
final long startCharacter = character;
final long startLine = line;
reader.mark(1000000);
- do
- {
+ do {
c = this.next();
- if (c == 0)
- {
+ if (c == 0) {
reader.reset();
index = startIndex;
character = startCharacter;
line = startLine;
return c;
}
- }
- while (c != to);
- }
- catch (final IOException exception)
- {
+ } while (c != to);
+ } catch (final IOException exception) {
throw new JSONException(exception);
}
back();
return c;
}
-
+
/**
* Make a JSONException to signal a syntax error.
*
@@ -413,19 +387,17 @@ public class JSONTokener
*
* @return A JSONException object, suitable for throwing
*/
- public JSONException syntaxError(final String message)
- {
+ public JSONException syntaxError(final String message) {
return new JSONException(message + toString());
}
-
+
/**
* Make a printable string of this JSONTokener.
*
* @return " at {index} [character {character} line {line}]"
*/
@Override
- public String toString()
- {
+ public String toString() {
return " at " + index + " [character " + character + " line " + line + "]";
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/JSONWriter.java b/src/main/java/com/intellectualcrafters/json/JSONWriter.java
index 52ac862ce..44f893ce6 100644
--- a/src/main/java/com/intellectualcrafters/json/JSONWriter.java
+++ b/src/main/java/com/intellectualcrafters/json/JSONWriter.java
@@ -33,8 +33,7 @@ import java.io.Writer;
* @author JSON.org
* @version 2011-11-24
*/
-public class JSONWriter
-{
+public class JSONWriter {
private static final int maxdepth = 200;
/**
* The writer that will receive the output.
@@ -56,19 +55,18 @@ public class JSONWriter
* The stack top index. A value of 0 indicates that the stack is empty.
*/
private int top;
-
+
/**
* Make a fresh JSONWriter. It can be used to build one JSON text.
*/
- public JSONWriter(final Writer w)
- {
+ public JSONWriter(final Writer w) {
comma = false;
mode = 'i';
stack = new JSONObject[maxdepth];
top = 0;
writer = w;
}
-
+
/**
* Append a value.
*
@@ -78,25 +76,20 @@ public class JSONWriter
*
* @throws JSONException If the value is out of sequence.
*/
- private JSONWriter append(final String string) throws JSONException
- {
- if (string == null) { throw new JSONException("Null pointer"); }
- if ((mode == 'o') || (mode == 'a'))
- {
- try
- {
- if (comma && (mode == 'a'))
- {
+ private JSONWriter append(final String string) throws JSONException {
+ if (string == null) {
+ throw new JSONException("Null pointer");
+ }
+ if ((mode == 'o') || (mode == 'a')) {
+ try {
+ if (comma && (mode == 'a')) {
writer.write(',');
}
writer.write(string);
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new JSONException(e);
}
- if (mode == 'o')
- {
+ if (mode == 'o') {
mode = 'k';
}
comma = true;
@@ -104,7 +97,7 @@ public class JSONWriter
}
throw new JSONException("Value out of sequence.");
}
-
+
/**
* Begin appending a new array. All values until the balancing endArray
will be appended to this array.
* The endArray
method must be called to mark the array's end.
@@ -114,10 +107,8 @@ public class JSONWriter
* @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 ((mode == 'i') || (mode == 'o') || (mode == 'a'))
- {
+ public JSONWriter array() throws JSONException {
+ if ((mode == 'i') || (mode == 'o') || (mode == 'a')) {
push(null);
append("[");
comma = false;
@@ -125,7 +116,7 @@ public class JSONWriter
}
throw new JSONException("Misplaced array.");
}
-
+
/**
* End something.
*
@@ -136,22 +127,20 @@ public class JSONWriter
*
* @throws JSONException If unbalanced.
*/
- private JSONWriter end(final char mode, final char c) throws JSONException
- {
- if (this.mode != mode) { throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); }
- pop(mode);
- try
- {
- writer.write(c);
+ private JSONWriter end(final char mode, final char c) throws JSONException {
+ if (this.mode != mode) {
+ throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject.");
}
- catch (final IOException e)
- {
+ pop(mode);
+ try {
+ writer.write(c);
+ } catch (final IOException e) {
throw new JSONException(e);
}
comma = true;
return this;
}
-
+
/**
* End an array. This method most be called to balance calls to array
.
*
@@ -159,11 +148,10 @@ public class JSONWriter
*
* @throws JSONException If incorrectly nested.
*/
- public JSONWriter endArray() throws JSONException
- {
+ public JSONWriter endArray() throws JSONException {
return end('a', ']');
}
-
+
/**
* End an object. This method most be called to balance calls to object
.
*
@@ -171,11 +159,10 @@ public class JSONWriter
*
* @throws JSONException If incorrectly nested.
*/
- public JSONWriter endObject() throws JSONException
- {
+ public JSONWriter endObject() throws JSONException {
return end('k', '}');
}
-
+
/**
* Append a key. The key will be associated with the next value. In an object, every value must be preceded by a
* key.
@@ -187,16 +174,14 @@ public class JSONWriter
* @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(final String string) throws JSONException
- {
- if (string == null) { throw new JSONException("Null key."); }
- if (mode == 'k')
- {
- try
- {
+ public JSONWriter key(final String string) throws JSONException {
+ if (string == null) {
+ throw new JSONException("Null key.");
+ }
+ if (mode == 'k') {
+ try {
stack[top - 1].putOnce(string, Boolean.TRUE);
- if (comma)
- {
+ if (comma) {
writer.write(',');
}
writer.write(JSONObject.quote(string));
@@ -204,15 +189,13 @@ public class JSONWriter
comma = false;
mode = 'o';
return this;
- }
- catch (final IOException e)
- {
+ } catch (final IOException e) {
throw new JSONException(e);
}
}
throw new JSONException("Misplaced key.");
}
-
+
/**
* Begin appending a new object. All keys and values until the balancing endObject
will be appended to
* this object. The endObject
method must be called to mark the object's end.
@@ -222,14 +205,11 @@ public class JSONWriter
* @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 (mode == 'i')
- {
+ public JSONWriter object() throws JSONException {
+ if (mode == 'i') {
mode = 'o';
}
- if ((mode == 'o') || (mode == 'a'))
- {
+ if ((mode == 'o') || (mode == 'a')) {
append("{");
push(new JSONObject());
comma = false;
@@ -237,7 +217,7 @@ public class JSONWriter
}
throw new JSONException("Misplaced object.");
}
-
+
/**
* Pop an array or object scope.
*
@@ -245,15 +225,18 @@ public class JSONWriter
*
* @throws JSONException If nesting is wrong.
*/
- private void pop(final char c) throws JSONException
- {
- if (top <= 0) { throw new JSONException("Nesting error."); }
+ private void pop(final char c) throws JSONException {
+ if (top <= 0) {
+ throw new JSONException("Nesting error.");
+ }
final char m = stack[top - 1] == null ? 'a' : 'k';
- if (m != c) { throw new JSONException("Nesting error."); }
+ if (m != c) {
+ throw new JSONException("Nesting error.");
+ }
top -= 1;
mode = top == 0 ? 'd' : stack[top - 1] == null ? 'a' : 'k';
}
-
+
/**
* Push an array or object scope.
*
@@ -261,14 +244,15 @@ public class JSONWriter
*
* @throws JSONException If nesting is too deep.
*/
- private void push(final JSONObject jo) throws JSONException
- {
- if (top >= maxdepth) { throw new JSONException("Nesting too deep."); }
+ private void push(final JSONObject jo) throws JSONException {
+ if (top >= maxdepth) {
+ throw new JSONException("Nesting too deep.");
+ }
stack[top] = jo;
mode = jo == null ? 'a' : 'k';
top += 1;
}
-
+
/**
* Append either the value true
or the value false
.
*
@@ -278,11 +262,10 @@ public class JSONWriter
*
* @throws JSONException
*/
- public JSONWriter value(final boolean b) throws JSONException
- {
+ public JSONWriter value(final boolean b) throws JSONException {
return append(b ? "true" : "false");
}
-
+
/**
* Append a double value.
*
@@ -292,11 +275,10 @@ public class JSONWriter
*
* @throws JSONException If the number is not finite.
*/
- public JSONWriter value(final double d) throws JSONException
- {
+ public JSONWriter value(final double d) throws JSONException {
return this.value(new Double(d));
}
-
+
/**
* Append a long value.
*
@@ -306,11 +288,10 @@ public class JSONWriter
*
* @throws JSONException
*/
- public JSONWriter value(final long l) throws JSONException
- {
+ public JSONWriter value(final long l) throws JSONException {
return append(Long.toString(l));
}
-
+
/**
* Append an object value.
*
@@ -321,8 +302,7 @@ public class JSONWriter
*
* @throws JSONException If the value is out of sequence.
*/
- public JSONWriter value(final Object object) throws JSONException
- {
+ public JSONWriter value(final Object object) throws JSONException {
return append(JSONObject.valueToString(object));
}
}
diff --git a/src/main/java/com/intellectualcrafters/json/Kim.java b/src/main/java/com/intellectualcrafters/json/Kim.java
index 391bcf4e2..7209e26c3 100644
--- a/src/main/java/com/intellectualcrafters/json/Kim.java
+++ b/src/main/java/com/intellectualcrafters/json/Kim.java
@@ -26,8 +26,7 @@ package com.intellectualcrafters.json;
*
* @version 2013-04-18
*/
-public class Kim
-{
+public class Kim {
/**
* The number of bytes in the kim. The number of bytes can be as much as three times the number of characters.
*/
@@ -44,7 +43,7 @@ public class Kim
* The memoization of toString().
*/
private String string = null;
-
+
/**
* Make a kim from a portion of a byte array.
*
@@ -52,8 +51,7 @@ public class Kim
* @param from The index of the first byte.
* @param thru The index of the last byte plus one.
*/
- public Kim(final byte[] bytes, final int from, final 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.
@@ -61,11 +59,9 @@ public class Kim
int value;
hashcode = 0;
length = thru - from;
- if (length > 0)
- {
+ if (length > 0) {
this.bytes = new byte[length];
- for (int at = 0; at < length; at += 1)
- {
+ for (int at = 0; at < length; at += 1) {
value = bytes[at + from] & 0xFF;
sum += value;
hashcode += sum;
@@ -74,18 +70,17 @@ public class Kim
hashcode += sum << 16;
}
}
-
+
/**
* Make a kim from a byte array.
*
* @param bytes The byte array.
* @param length The number of bytes.
*/
- public Kim(final byte[] bytes, final int length)
- {
+ public Kim(final byte[] bytes, final int length) {
this(bytes, 0, length);
}
-
+
/**
* Make a new kim from a substring of an existing kim. The coordinates are in byte units, not character units.
*
@@ -93,11 +88,10 @@ public class Kim
* @param from The point at which to take bytes.
* @param thru The point at which to stop taking bytes.
*/
- public Kim(final Kim kim, final int from, final int thru)
- {
+ public Kim(final Kim kim, final int from, final int thru) {
this(kim.bytes, from, thru);
}
-
+
/**
* Make a kim from a string.
*
@@ -105,33 +99,26 @@ public class Kim
*
* @throws JSONException if surrogate pair mismatch.
*/
- public Kim(final String string) throws JSONException
- {
+ public Kim(final String string) throws JSONException {
final int stringLength = string.length();
hashcode = 0;
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.
- if (stringLength > 0)
- {
- for (int i = 0; i < stringLength; i += 1)
- {
+ if (stringLength > 0) {
+ for (int i = 0; i < stringLength; i += 1) {
final int c = string.charAt(i);
- if (c <= 0x7F)
- {
+ if (c <= 0x7F) {
length += 1;
- }
- else if (c <= 0x3FFF)
- {
+ } else if (c <= 0x3FFF) {
length += 2;
- }
- else
- {
- if ((c >= 0xD800) && (c <= 0xDFFF))
- {
+ } else {
+ if ((c >= 0xD800) && (c <= 0xDFFF)) {
i += 1;
final int d = string.charAt(i);
- if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) { throw new JSONException("Bad UTF16"); }
+ if ((c > 0xDBFF) || (d < 0xDC00) || (d > 0xDFFF)) {
+ throw new JSONException("Bad UTF16");
+ }
}
length += 3;
}
@@ -143,18 +130,14 @@ public class Kim
int at = 0;
int b;
int sum = 1;
- for (int i = 0; i < stringLength; i += 1)
- {
+ for (int i = 0; i < stringLength; i += 1) {
int character = string.charAt(i);
- if (character <= 0x7F)
- {
+ if (character <= 0x7F) {
bytes[at] = (byte) character;
sum += character;
hashcode += sum;
at += 1;
- }
- else if (character <= 0x3FFF)
- {
+ } else if (character <= 0x3FFF) {
b = 0x80 | (character >>> 7);
bytes[at] = (byte) b;
sum += b;
@@ -165,11 +148,8 @@ public class Kim
sum += b;
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;
}
@@ -193,7 +173,7 @@ public class Kim
hashcode += sum << 16;
}
}
-
+
/**
* Returns the number of bytes needed to contain the character in Kim format.
*
@@ -203,12 +183,13 @@ public class Kim
*
* @throws JSONException if the character is not representable in a kim.
*/
- public static int characterSize(final int character) throws JSONException
- {
- if ((character < 0) || (character > 0x10FFFF)) { throw new JSONException("Bad character " + character); }
+ 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;
}
-
+
/**
* Returns the character at the specified index. The index refers to byte values and ranges from 0 to length - 1.
* The index of the next character is at index + Kim.characterSize(kim.characterAt(index)).
@@ -218,26 +199,28 @@ public class Kim
* @throws JSONException if at does not point to a valid character.
* @return a Unicode character between 0 and 0x10FFFF.
*/
- public int characterAt(final int at) throws JSONException
- {
+ public int characterAt(final int at) throws JSONException {
final int c = get(at);
- if ((c & 0x80) == 0) { return c; }
+ if ((c & 0x80) == 0) {
+ return c;
+ }
int character;
final int c1 = get(at + 1);
- if ((c1 & 0x80) == 0)
- {
+ if ((c1 & 0x80) == 0) {
character = ((c & 0x7F) << 7) | c1;
- if (character > 0x7F) { return character; }
- }
- else
- {
+ if (character > 0x7F) {
+ return character;
+ }
+ } 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))) { return character; }
+ if (((c2 & 0x80) == 0) && (character > 0x3FFF) && (character <= 0x10FFFF) && ((character < 0xD800) || (character > 0xDFFF))) {
+ return character;
+ }
}
throw new JSONException("Bad character at " + at);
}
-
+
/**
* Copy the contents of this kim to a byte array.
*
@@ -246,12 +229,11 @@ public class Kim
*
* @return The position immediately after the copy.
*/
- public int copy(final byte[] bytes, final int at)
- {
+ public int copy(final byte[] bytes, final int at) {
System.arraycopy(this.bytes, 0, bytes, at, length);
return at + length;
}
-
+
/**
* Two kim objects containing exactly the same bytes in the same order are equal to each other.
*
@@ -260,15 +242,20 @@ public class Kim
* @return true if this and obj are both kim objects containing identical byte sequences.
*/
@Override
- public boolean equals(final Object obj)
- {
- if (!(obj instanceof Kim)) { return false; }
+ public boolean equals(final Object obj) {
+ if (!(obj instanceof Kim)) {
+ return false;
+ }
final Kim that = (Kim) obj;
- if (this == that) { return true; }
- if (hashcode != that.hashcode) { return false; }
+ if (this == that) {
+ return true;
+ }
+ if (hashcode != that.hashcode) {
+ return false;
+ }
return java.util.Arrays.equals(bytes, that.bytes);
}
-
+
/**
* Get a byte from a kim.
*
@@ -278,21 +265,21 @@ public class Kim
*
* @throws JSONException if there is no byte at that position.
*/
- public int get(final int at) throws JSONException
- {
- if ((at < 0) || (at > length)) { throw new JSONException("Bad character at " + at); }
+ public int get(final int at) throws JSONException {
+ if ((at < 0) || (at > length)) {
+ throw new JSONException("Bad character at " + at);
+ }
return (bytes[at]) & 0xFF;
}
-
+
/**
* Returns a hash code value for the kim.
*/
@Override
- public int hashCode()
- {
+ public int hashCode() {
return hashcode;
}
-
+
/**
* Produce a UTF-16 String from this kim. The number of codepoints in the string will not be greater than the number
* of bytes in the kim, although it could be less.
@@ -302,23 +289,17 @@ public class Kim
* @throws JSONException if the kim is not valid.
*/
@Override
- public String toString() throws JSONException
- {
- if (string == null)
- {
+ public String toString() throws JSONException {
+ if (string == null) {
int c;
int length = 0;
final char chars[] = new char[this.length];
- for (int at = 0; at < this.length; at += characterSize(c))
- {
+ for (int at = 0; at < this.length; at += characterSize(c)) {
c = characterAt(at);
- if (c < 0x10000)
- {
+ if (c < 0x10000) {
chars[length] = (char) c;
length += 1;
- }
- else
- {
+ } else {
chars[length] = (char) (0xD800 | ((c - 0x10000) >>> 10));
length += 1;
chars[length] = (char) (0xDC00 | (c & 0x03FF));
diff --git a/src/main/java/com/intellectualcrafters/json/Property.java b/src/main/java/com/intellectualcrafters/json/Property.java
index db31b325d..a177df954 100644
--- a/src/main/java/com/intellectualcrafters/json/Property.java
+++ b/src/main/java/com/intellectualcrafters/json/Property.java
@@ -30,8 +30,7 @@ import java.util.Properties;
* @author JSON.org
* @version 2014-05-03
*/
-public class Property
-{
+public class Property {
/**
* Converts a property file object into a JSONObject. The property file object is a table of name value pairs.
*
@@ -41,21 +40,18 @@ public class Property
*
* @throws JSONException
*/
- public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException
- {
+ public static JSONObject toJSONObject(final java.util.Properties properties) throws JSONException {
final JSONObject jo = new JSONObject();
- if ((properties != null) && !properties.isEmpty())
- {
+ if ((properties != null) && !properties.isEmpty()) {
final Enumeration enumProperties = properties.propertyNames();
- while (enumProperties.hasMoreElements())
- {
+ while (enumProperties.hasMoreElements()) {
final String name = (String) enumProperties.nextElement();
jo.put(name, properties.getProperty(name));
}
}
return jo;
}
-
+
/**
* Converts the JSONObject into a property file object.
*
@@ -65,14 +61,11 @@ public class Property
*
* @throws JSONException
*/
- public static Properties toProperties(final JSONObject jo) throws JSONException
- {
+ public static Properties toProperties(final JSONObject jo) throws JSONException {
final Properties properties = new Properties();
- if (jo != null)
- {
+ if (jo != null) {
final Iterator keys = jo.keys();
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
final String name = keys.next();
properties.put(name, jo.getString(name));
}
diff --git a/src/main/java/com/intellectualcrafters/json/XML.java b/src/main/java/com/intellectualcrafters/json/XML.java
index 594660570..7f95563cc 100644
--- a/src/main/java/com/intellectualcrafters/json/XML.java
+++ b/src/main/java/com/intellectualcrafters/json/XML.java
@@ -8,8 +8,7 @@ import java.util.Iterator;
* @author JSON.org
* @version 2014-05-03
*/
-public class XML
-{
+public class XML {
public static final Character AMP = '&';
public static final Character APOS = '\'';
public static final Character BANG = '!';
@@ -19,15 +18,12 @@ public class XML
public static final Character QUEST = '?';
public static final Character QUOT = '"';
public static final Character SLASH = '/';
-
- public static String escape(final String string)
- {
+
+ public static String escape(final String string) {
final StringBuilder sb = new StringBuilder(string.length());
- for (int i = 0, length = string.length(); i < length; i++)
- {
+ for (int i = 0, length = string.length(); i < length; i++) {
final char c = string.charAt(i);
- switch (c)
- {
+ switch (c) {
case '&':
sb.append("&");
break;
@@ -49,7 +45,7 @@ public class XML
}
return sb.toString();
}
-
+
/**
* Throw an exception if the string contains whitespace. Whitespace is not allowed in tagNames and attributes.
*
@@ -57,17 +53,19 @@ public class XML
*
* @throws JSONException
*/
- public static void noSpace(final String string) throws JSONException
- {
+ 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."); }
+ 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.");
+ }
}
}
-
+
/**
* Scan the content following the named tag, attaching it to the context.
*
@@ -79,8 +77,7 @@ public class XML
*
* @throws JSONException
*/
- private static boolean parse(final XMLTokener x, final JSONObject context, final 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;
@@ -98,28 +95,20 @@ public class XML
// <<
token = x.nextToken();
// ");
return false;
}
x.back();
- }
- else if (c == '[')
- {
+ } else if (c == '[') {
token = x.nextToken();
- if ("CDATA".equals(token))
- {
- if (x.next() == '[')
- {
+ if ("CDATA".equals(token)) {
+ if (x.next() == '[') {
string = x.nextCDATA();
- if (string.length() > 0)
- {
+ if (string.length() > 0) {
context.accumulate("content", string);
}
return false;
@@ -128,136 +117,105 @@ public class XML
throw x.syntaxError("Expected 'CDATA['");
}
i = 1;
- do
- {
+ do {
token = x.nextMeta();
- if (token == null)
- {
+ if (token == null) {
throw x.syntaxError("Missing '>' after ' 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
token = x.nextToken();
- if (name == null) { throw x.syntaxError("Mismatched close tag " + token); }
- if (!token.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + token); }
- if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); }
+ if (name == null) {
+ throw x.syntaxError("Mismatched close tag " + token);
+ }
+ if (!token.equals(name)) {
+ throw x.syntaxError("Mismatched " + name + " and " + token);
+ }
+ if (x.nextToken() != GT) {
+ throw x.syntaxError("Misshaped close tag");
+ }
return true;
- }
- else if (token instanceof Character)
- {
+ } else if (token instanceof Character) {
throw x.syntaxError("Misshaped tag");
// Open tag <
- }
- else
- {
+ } else {
tagName = (String) token;
token = null;
jsonobject = new JSONObject();
- for (;;)
- {
- if (token == null)
- {
+ for (;;) {
+ if (token == null) {
token = x.nextToken();
}
// attribute = value
- if (token instanceof String)
- {
+ if (token instanceof String) {
string = (String) token;
token = x.nextToken();
- if (token == EQ)
- {
+ if (token == EQ) {
token = x.nextToken();
- if (!(token instanceof String)) { throw x.syntaxError("Missing value"); }
+ if (!(token instanceof String)) {
+ throw x.syntaxError("Missing value");
+ }
jsonobject.accumulate(string, XML.stringToValue((String) token));
token = null;
- }
- else
- {
+ } else {
jsonobject.accumulate(string, "");
}
// Empty tag <.../>
- }
- else if (token == SLASH)
- {
- if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); }
- if (jsonobject.length() > 0)
- {
- context.accumulate(tagName, jsonobject);
+ } else if (token == SLASH) {
+ if (x.nextToken() != GT) {
+ throw x.syntaxError("Misshaped tag");
}
- else
- {
+ if (jsonobject.length() > 0) {
+ context.accumulate(tagName, jsonobject);
+ } else {
context.accumulate(tagName, "");
}
return false;
// Content, between <...> and
- }
- else if (token == GT)
- {
- for (;;)
- {
+ } else if (token == GT) {
+ for (;;) {
token = x.nextContent();
- if (token == null)
- {
- if (tagName != null) { throw x.syntaxError("Unclosed tag " + tagName); }
+ if (token == null) {
+ if (tagName != null) {
+ throw x.syntaxError("Unclosed tag " + tagName);
+ }
return false;
- }
- else if (token instanceof String)
- {
+ } else if (token instanceof String) {
string = (String) token;
- if (string.length() > 0)
- {
+ if (string.length() > 0) {
jsonobject.accumulate("content", XML.stringToValue(string));
}
// Nested element
- }
- else if (token == LT)
- {
- if (parse(x, jsonobject, tagName))
- {
- if (jsonobject.length() == 0)
- {
+ } 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))
- {
+ } else if ((jsonobject.length() == 1) && (jsonobject.opt("content") != null)) {
context.accumulate(tagName, jsonobject.opt("content"));
- }
- else
- {
+ } 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
@@ -267,47 +225,47 @@ public class XML
*
* @return A simple JSON value.
*/
- public static Object stringToValue(final String string)
- {
- if ("true".equalsIgnoreCase(string)) { return Boolean.TRUE; }
- if ("false".equalsIgnoreCase(string)) { return Boolean.FALSE; }
- if ("null".equalsIgnoreCase(string)) { return JSONObject.NULL; }
+ public static Object stringToValue(final String string) {
+ if ("true".equalsIgnoreCase(string)) {
+ return Boolean.TRUE;
+ }
+ if ("false".equalsIgnoreCase(string)) {
+ return Boolean.FALSE;
+ }
+ if ("null".equalsIgnoreCase(string)) {
+ 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.
- try
- {
+ try {
final char initial = string.charAt(0);
- if ((initial == '-') || ((initial >= '0') && (initial <= '9')))
- {
+ if ((initial == '-') || ((initial >= '0') && (initial <= '9'))) {
final Long value = new Long(string);
- if (value.toString().equals(string)) { return value; }
+ if (value.toString().equals(string)) {
+ return value;
+ }
}
- }
- catch (final Exception ignore)
- {
- try
- {
+ } catch (final Exception ignore) {
+ try {
final Double value = new Double(string);
- if (value.toString().equals(string)) { return value; }
- }
- catch (final Exception ignoreAlso)
- {}
+ if (value.toString().equals(string)) {
+ return value;
+ }
+ } catch (final Exception ignoreAlso) {}
}
return string;
}
-
- public static JSONObject toJSONObject(final String string) throws JSONException
- {
+
+ 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("<"))
- {
+ while (x.more() && x.skipPast("<")) {
parse(x, jo, null);
}
return jo;
}
-
+
/**
* Convert a JSONObject into a well-formed, element-normal XML string.
*
@@ -317,11 +275,10 @@ public class XML
*
* @throws JSONException
*/
- public static String toString(final 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.
*
@@ -332,8 +289,7 @@ public class XML
*
* @throws JSONException
*/
- public static String toString(Object object, final String tagName) throws JSONException
- {
+ public static String toString(Object object, final String tagName) throws JSONException {
final StringBuilder sb = new StringBuilder();
int i;
JSONArray ja;
@@ -343,11 +299,9 @@ public class XML
int length;
String string;
Object value;
- if (object instanceof JSONObject)
- {
+ if (object instanceof JSONObject) {
// Emit
- if (tagName != null)
- {
+ if (tagName != null) {
sb.append('<');
sb.append(tagName);
sb.append('>');
@@ -355,46 +309,34 @@ public class XML
// Loop thru the keys.
jo = (JSONObject) object;
keys = jo.keys();
- while (keys.hasNext())
- {
+ while (keys.hasNext()) {
key = keys.next();
value = jo.opt(key);
- if (value == null)
- {
+ if (value == null) {
value = "";
}
string = value instanceof String ? (String) value : null;
// Emit content in body
- if ("content".equals(key))
- {
- if (value instanceof JSONArray)
- {
+ if ("content".equals(key)) {
+ if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
- for (i = 0; i < length; i += 1)
- {
- if (i > 0)
- {
+ for (i = 0; i < length; i += 1) {
+ if (i > 0) {
sb.append('\n');
}
sb.append(escape(ja.get(i).toString()));
}
- }
- else
- {
+ } else {
sb.append(escape(value.toString()));
}
// Emit an array of similar keys
- }
- else if (value instanceof JSONArray)
- {
+ } else if (value instanceof JSONArray) {
ja = (JSONArray) value;
length = ja.length();
- for (i = 0; i < length; i += 1)
- {
+ for (i = 0; i < length; i += 1) {
value = ja.get(i);
- if (value instanceof JSONArray)
- {
+ if (value instanceof JSONArray) {
sb.append('<');
sb.append(key);
sb.append('>');
@@ -402,27 +344,20 @@ 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
- }
- else
- {
+ } else {
sb.append(toString(value, key));
}
}
- if (tagName != null)
- {
+ if (tagName != null) {
// Emit the close tag
sb.append("");
sb.append(tagName);
@@ -432,25 +367,18 @@ public class XML
// XML does not have good support for arrays. If an array appears in
// a place
// where XML is lacking, synthesize an element.
- }
- else
- {
- if (object.getClass().isArray())
- {
+ } else {
+ if (object.getClass().isArray()) {
object = new JSONArray(object);
}
- if (object instanceof JSONArray)
- {
+ if (object instanceof JSONArray) {
ja = (JSONArray) object;
length = ja.length();
- for (i = 0; i < length; i += 1)
- {
+ for (i = 0; i < length; i += 1) {
sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName));
}
return sb.toString();
- }
- else
- {
+ } else {
string = (object == null) ? "null" : escape(object.toString());
return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + "" + tagName + ">";
}
diff --git a/src/main/java/com/intellectualcrafters/json/XMLTokener.java b/src/main/java/com/intellectualcrafters/json/XMLTokener.java
index e34e6dbe2..c7751ebdd 100644
--- a/src/main/java/com/intellectualcrafters/json/XMLTokener.java
+++ b/src/main/java/com/intellectualcrafters/json/XMLTokener.java
@@ -6,14 +6,12 @@ package com.intellectualcrafters.json;
* @author JSON.org
* @version 2014-05-03
*/
-public class XMLTokener extends JSONTokener
-{
+public class XMLTokener extends JSONTokener {
/**
* The table of entity values. It initially contains Character values for amp, apos, gt, lt, quot.
*/
public static final java.util.HashMap entity;
- static
- {
+ static {
entity = new java.util.HashMap(8);
entity.put("amp", XML.AMP);
entity.put("apos", XML.APOS);
@@ -21,17 +19,16 @@ public class XMLTokener extends JSONTokener
entity.put("lt", XML.LT);
entity.put("quot", XML.QUOT);
}
-
+
/**
* Construct an XMLTokener from a string.
*
* @param s A source string.
*/
- public XMLTokener(final String s)
- {
+ public XMLTokener(final String s) {
super(s);
}
-
+
/**
* Get the text in the CDATA block.
*
@@ -39,25 +36,24 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException If the ]]>
is not found.
*/
- public String nextCDATA() throws JSONException
- {
+ public String nextCDATA() throws JSONException {
char c;
int i;
final StringBuilder sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
c = next();
- if (end()) { throw syntaxError("Unclosed CDATA"); }
+ if (end()) {
+ throw syntaxError("Unclosed CDATA");
+ }
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 text between markup tags.
@@ -66,37 +62,33 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException
*/
- public Object nextContent() throws JSONException
- {
+ public Object nextContent() throws JSONException {
char c;
StringBuilder sb;
- do
- {
+ do {
c = next();
+ } while (Character.isWhitespace(c));
+ if (c == 0) {
+ return null;
+ }
+ if (c == '<') {
+ return XML.LT;
}
- while (Character.isWhitespace(c));
- if (c == 0) { return null; }
- if (c == '<') { return XML.LT; }
sb = new StringBuilder();
- for (;;)
- {
- if ((c == '<') || (c == 0))
- {
+ for (;;) {
+ if ((c == '<') || (c == 0)) {
back();
return sb.toString().trim();
}
- if (c == '&')
- {
+ if (c == '&') {
sb.append(nextEntity(c));
- }
- else
- {
+ } else {
sb.append(c);
}
c = next();
}
}
-
+
/**
* Return the next entity. These entities are translated to Characters: & " > <
* "
.
@@ -107,22 +99,15 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException If missing ';' in XML entity.
*/
- public Object nextEntity(final char ampersand) throws JSONException
- {
+ public Object nextEntity(final char ampersand) throws JSONException {
final StringBuilder sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
final char c = next();
- if (Character.isLetterOrDigit(c) || (c == '#'))
- {
+ 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);
}
}
@@ -130,7 +115,7 @@ public class XMLTokener extends JSONTokener
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.
*
@@ -139,17 +124,13 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException If a string is not properly closed or if the XML is badly structured.
*/
- public Object nextMeta() throws JSONException
- {
+ public Object nextMeta() throws JSONException {
char c;
char q;
- do
- {
+ do {
c = next();
- }
- while (Character.isWhitespace(c));
- switch (c)
- {
+ } while (Character.isWhitespace(c));
+ switch (c) {
case 0:
throw syntaxError("Misshaped meta tag");
case '<':
@@ -167,19 +148,22 @@ public class XMLTokener extends JSONTokener
case '"':
case '\'':
q = c;
- for (;;)
- {
+ for (;;) {
c = next();
- if (c == 0) { throw syntaxError("Unterminated string"); }
- if (c == q) { return Boolean.TRUE; }
+ if (c == 0) {
+ throw syntaxError("Unterminated string");
+ }
+ if (c == q) {
+ return Boolean.TRUE;
+ }
}
default:
- for (;;)
- {
+ for (;;) {
c = next();
- if (Character.isWhitespace(c)) { return Boolean.TRUE; }
- switch (c)
- {
+ if (Character.isWhitespace(c)) {
+ return Boolean.TRUE;
+ }
+ switch (c) {
case 0:
case '<':
case '>':
@@ -195,7 +179,7 @@ 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:
* / >= ! ?
or it may be a string wrapped in single quotes or double quotes, or it may be a name.
@@ -204,18 +188,14 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException If the XML is not well formed.
*/
- public Object nextToken() throws JSONException
- {
+ public Object nextToken() throws JSONException {
char c;
char q;
StringBuilder sb;
- do
- {
+ do {
c = next();
- }
- while (Character.isWhitespace(c));
- switch (c)
- {
+ } while (Character.isWhitespace(c));
+ switch (c) {
case 0:
throw syntaxError("Misshaped element");
case '<':
@@ -235,30 +215,30 @@ public class XMLTokener extends JSONTokener
case '\'':
q = c;
sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
c = next();
- if (c == 0) { throw syntaxError("Unterminated string"); }
- if (c == q) { return sb.toString(); }
- if (c == '&')
- {
- sb.append(nextEntity(c));
+ if (c == 0) {
+ throw syntaxError("Unterminated string");
}
- else
- {
+ if (c == q) {
+ return sb.toString();
+ }
+ if (c == '&') {
+ sb.append(nextEntity(c));
+ } else {
sb.append(c);
}
}
default:
// Name
sb = new StringBuilder();
- for (;;)
- {
+ for (;;) {
sb.append(c);
c = next();
- if (Character.isWhitespace(c)) { return sb.toString(); }
- switch (c)
- {
+ if (Character.isWhitespace(c)) {
+ return sb.toString();
+ }
+ switch (c) {
case 0:
return sb.toString();
case '>':
@@ -278,7 +258,7 @@ 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.
@@ -287,8 +267,7 @@ public class XMLTokener extends JSONTokener
*
* @throws JSONException
*/
- public boolean skipPast(final String to) throws JSONException
- {
+ public boolean skipPast(final String to) throws JSONException {
boolean b;
char c;
int i;
@@ -300,44 +279,44 @@ public class XMLTokener extends JSONTokener
* First fill the circle buffer with as many characters as are in the
* to string. If we reach an early end, bail.
*/
- for (i = 0; i < length; i += 1)
- {
+ for (i = 0; i < length; i += 1) {
c = next();
- if (c == 0) { return false; }
+ if (c == 0) {
+ return false;
+ }
circle[i] = c;
}
/* We will loop, possibly for all of the remaining characters. */
- for (;;)
- {
+ for (;;) {
j = offset;
b = true;
/* Compare the circle buffer with the to string. */
- for (i = 0; i < length; i += 1)
- {
- if (circle[j] != to.charAt(i))
- {
+ for (i = 0; i < length; i += 1) {
+ if (circle[j] != to.charAt(i)) {
b = false;
break;
}
j += 1;
- if (j >= length)
- {
+ if (j >= length) {
j -= length;
}
}
/* If we exit the loop with b intact, then victory is ours. */
- if (b) { return true; }
+ if (b) {
+ return true;
+ }
/* Get the next character. If there isn't one, then defeat is ours. */
c = next();
- if (c == 0) { return false; }
+ if (c == 0) {
+ return false;
+ }
/*
* Shove the character in the circle buffer and advance the
* circle offset. The offset is mod n.
*/
circle[offset] = c;
offset += 1;
- if (offset >= length)
- {
+ if (offset >= length) {
offset -= length;
}
}
diff --git a/src/main/java/com/intellectualcrafters/plot/IPlotMain.java b/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
index 19bb3edf3..5132c94c8 100644
--- a/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
+++ b/src/main/java/com/intellectualcrafters/plot/IPlotMain.java
@@ -17,21 +17,20 @@ import com.intellectualcrafters.plot.util.SetupUtils;
import com.intellectualcrafters.plot.util.TaskManager;
import com.intellectualcrafters.plot.util.UUIDHandlerImplementation;
-public interface IPlotMain
-{
-
+public interface IPlotMain {
+
/**
* Log a message to console
* @param message
*/
void log(final String message);
-
+
/**
* Get the `PlotSquared` directory (e.g. /plugins/PlotSquared or /mods/PlotSquared)
* @return
*/
File getDirectory();
-
+
/**
* Get the directory containing all the worlds
* @return
@@ -44,161 +43,161 @@ public interface IPlotMain
* @return
*/
PlotPlayer wrapPlayer(final Object obj);
-
+
/**
* Disable the implementation
* - If a full disable isn't feasibly, just disable what it can
*/
void disable();
-
+
/**
* Get the version of the PlotSquared being used
* @return
*/
int[] getPluginVersion();
-
+
/**
* Get the version of Minecraft that is running
* (used to check what protocols and such are supported)
* @return
*/
int[] getServerVersion();
-
+
/**
* Get the nms package prefix
* @return
*/
String getNMSPackage();
-
+
/**
* Get the schematic handler
* @return
*/
SchematicHandler initSchematicHandler();
-
+
/**
* Get the schematic handler
* @return
*/
ChatManager initChatManager();
-
+
/**
* The task manager will run and manage minecraft tasks
* @return
*/
TaskManager getTaskManager();
-
+
/**
* Run the task that will kill road mobs
*/
void runEntityTask();
-
+
/**
* Register the implementation specific commands
*/
void registerCommands();
-
+
/**
* Register the protection system (used to protect blocks and such)
*/
void registerPlayerEvents();
-
+
/**
* Register inventory related events (used for inventory guis)
*/
void registerInventoryEvents();
-
+
/**
* Register plot plus related events (whatever these are?)
*/
void registerPlotPlusEvents();
-
+
/**
* Register force field events (why is this a thing?)
*/
void registerForceFieldEvents();
-
+
/**
* Register the WorldEdit hook
*/
boolean initWorldEdit();
-
+
/**
* Register TNT related events (if TNT protection is enabled)
*/
void registerTNTListener();
-
+
/**
* Get the economy provider
* @return
*/
EconHandler getEconomyHandler();
-
+
/**
* Get the block manager
* @return
*/
BlockManager initBlockManager();
-
+
/**
* Get the EventUtil class
* @return
*/
EventUtil initEventUtil();
-
+
/**
* Get the chunk manager
* @return
*/
ChunkManager initChunkManager();
-
+
/**
* Get the setuputils class (used for world creation)
* @return
*/
SetupUtils initSetupUtils();
-
+
/**
* Get HybridUtils class (common functions useful for hybrid world generation)
* @return
*/
HybridUtils initHybridUtils();
-
+
/**
* Start the metrics task
*/
void startMetrics();
-
+
/**
* If a world is already loaded, set the generator (use NMS if required)
* @param world
*/
void setGenerator(final String world);
-
+
/**
* Get the UUIDHandlerImplementation which will cache and provide UUIDs
* @return
*/
UUIDHandlerImplementation initUUIDHandler();
-
+
/**
* Get the InventoryUtil class (used for implementation specific inventory guis)
* @return
*/
InventoryUtil initInventoryUtil();
-
+
/**
* Run the converter for the implementation (not necessarily PlotMe, just any plugin that we can convert from)
* @return
*/
boolean initPlotMeConverter();
-
+
/**
* Unregister a PlotPlayer from cache e.g. if they have logged off
* @param player
*/
void unregister(final PlotPlayer player);
-
+
/**
* Get the generator wrapper for a world (world) and generator (name)
* @param world
@@ -206,23 +205,23 @@ public interface IPlotMain
* @return
*/
PlotGenerator> getGenerator(final String world, final String name);
-
+
/**
* Register the chunk processor which will clean out chunks that have too many blockstates or entities
*/
void registerChunkProcessor();
-
+
/**
* Register the world initialization events (used to keep track of worlds being generated)
*/
void registerWorldEvents();
-
+
/**
* Get the name of the server
* @return
*/
String getServerName();
-
+
/**
* Get the class that will manage player titles
* @return
diff --git a/src/main/java/com/intellectualcrafters/plot/PS.java b/src/main/java/com/intellectualcrafters/plot/PS.java
index a897f1d6d..7466c62d3 100644
--- a/src/main/java/com/intellectualcrafters/plot/PS.java
+++ b/src/main/java/com/intellectualcrafters/plot/PS.java
@@ -90,16 +90,15 @@ import com.sk89q.worldedit.WorldEdit;
* @author Sauilitired | Citymonstret
* @author boy0001 | Empire92
*/
-public class PS
-{
-
+public class PS {
+
// protected static:
public static PS instance;
-
+
// private final:
private final HashMap plotworlds = new HashMap<>();
private final HashMap plotmanagers = new HashMap<>();
-
+
// public:
public File configFile;
public File translationFile;
@@ -110,7 +109,7 @@ public class PS
public TaskManager TASK;
public WorldEdit worldedit;
public URL update;
-
+
// private:
private File styleFile;
private File storageFile;
@@ -123,53 +122,44 @@ public class PS
private Database database;
private Connection connection;
private Thread thread;
-
+
/**
* Initialize PlotSquared with the desired Implementation class
* @param imp_class
*/
- public PS(final IPlotMain imp_class, final String platform)
- {
- try
- {
+ public PS(final IPlotMain imp_class, final String platform) {
+ try {
instance = this;
thread = Thread.currentThread();
SetupUtils.generators = new HashMap<>();
IMP = imp_class;
new ReflectionUtils(IMP.getNMSPackage());
URL url;
- try
- {
+ try {
url = PS.class.getProtectionDomain().getCodeSource().getLocation();
FILE = new File(new URL(url.toURI().toString().split("\\!")[0].replaceAll("jar:file", "file")).toURI().getPath());
- }
- catch (final Exception e)
- {
+ } catch (final Exception e) {
e.printStackTrace();
FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared.jar");
- if (!FILE.exists())
- {
+ if (!FILE.exists()) {
FILE = new File(IMP.getDirectory().getParentFile(), "PlotSquared-" + platform + ".jar");
}
}
VERSION = IMP.getPluginVersion();
PLATFORM = platform;
EconHandler.manager = IMP.getEconomyHandler();
- if (getJavaVersion() < 1.7)
- {
+ if (getJavaVersion() < 1.7) {
log(C.PREFIX.s() + "&cYour java version is outdated. Please update to at least 1.7.");
// Didn't know of any other link :D
log(C.PREFIX.s() + "&cURL: &6https://java.com/en/download/index.jsp");
IMP.disable();
return;
}
- if (getJavaVersion() < 1.8)
- {
+ if (getJavaVersion() < 1.8) {
log(C.PREFIX.s() + "&cIt's really recommended to run Java 1.8, as it increases performance");
}
TASK = IMP.getTaskManager();
- if (C.ENABLED.s().length() > 0)
- {
+ if (C.ENABLED.s().length() > 0) {
log(C.ENABLED.s());
}
setupConfigs();
@@ -179,17 +169,15 @@ public class PS
setupDatabase();
CommentManager.registerDefaultInboxes();
// Tasks
- if (Settings.KILL_ROAD_MOBS || Settings.KILL_ROAD_VEHICLES)
- {
+ if (Settings.KILL_ROAD_MOBS || Settings.KILL_ROAD_VEHICLES) {
IMP.runEntityTask();
}
- if (IMP.initWorldEdit())
- {
+ if (IMP.initWorldEdit()) {
worldedit = WorldEdit.getInstance();
WorldEdit.getInstance().getEventBus().register(new WESubscriber());
MainCommand.getInstance().createCommand(new WE_Anywhere());
}
-
+
// Events
IMP.registerCommands();
IMP.registerPlayerEvents();
@@ -197,64 +185,47 @@ public class PS
IMP.registerPlotPlusEvents();
IMP.registerForceFieldEvents();
IMP.registerWorldEvents();
- if (Settings.METRICS)
- {
+ if (Settings.METRICS) {
IMP.startMetrics();
- }
- else
- {
+ } else {
log("&dUsing metrics will allow us to improve the plugin, please consider it :)");
}
IMP.startMetrics();
- if (Settings.TNT_LISTENER)
- {
+ if (Settings.TNT_LISTENER) {
IMP.registerTNTListener();
}
- if (Settings.CHUNK_PROCESSOR)
- {
+ if (Settings.CHUNK_PROCESSOR) {
IMP.registerChunkProcessor();
}
// create UUIDWrapper
UUIDHandler.implementation = IMP.initUUIDHandler();
- TaskManager.runTaskLater(new Runnable()
- {
+ TaskManager.runTaskLater(new Runnable() {
@Override
- public void run()
- {
+ public void run() {
PS.debug("Starting UUID caching");
- UUIDHandler.startCaching(new Runnable()
- {
+ UUIDHandler.startCaching(new Runnable() {
@Override
- public void run()
- {
- for (final Plot plot : getPlots())
- {
- if ((plot.owner != null) && (plot.temp != -1))
- {
- if (UUIDHandler.getName(plot.owner) == null)
- {
+ public void run() {
+ for (final Plot plot : getPlots()) {
+ if ((plot.owner != null) && (plot.temp != -1)) {
+ if (UUIDHandler.getName(plot.owner) == null) {
UUIDHandler.implementation.unknown.add(plot.owner);
}
}
}
// Auto clearing
- if (Settings.AUTO_CLEAR)
- {
+ if (Settings.AUTO_CLEAR) {
ExpireManager.runTask();
}
// PlotMe
- if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME)
- {
- TaskManager.runTaskLater(new Runnable()
- {
-
+ if (Settings.CONVERT_PLOTME || Settings.CACHE_PLOTME) {
+ TaskManager.runTaskLater(new Runnable() {
+
@Override
- public void run()
- {
- if (IMP.initPlotMeConverter())
- {
+ public void run() {
+ if (IMP.initPlotMeConverter()) {
log("&c=== IMPORTANT ===");
log("&cTHIS MESSAGE MAY BE EXTREMELY HELPFUL IF YOU HAVE TROUBLE CONVERTING PLOTME!");
log("&c - Make sure 'UUID.read-from-disk' is disabled (false)!");
@@ -286,53 +257,39 @@ public class PS
AbstractTitle.TITLE_CLASS = IMP.initTitleManager();
// Chat
ChatManager.manager = IMP.initChatManager();
-
+
// Check for updates
- TaskManager.runTaskAsync(new Runnable()
- {
+ TaskManager.runTaskAsync(new Runnable() {
@Override
- public void run()
- {
+ public void run() {
final URL url = getUpdate();
- if (url != null)
- {
+ if (url != null) {
update = url;
- }
- else if ((LAST_VERSION != null) && !StringMan.join(VERSION, ".").equals(LAST_VERSION))
- {
+ } else if ((LAST_VERSION != null) && !StringMan.join(VERSION, ".").equals(LAST_VERSION)) {
log("&aThanks for updating from: " + LAST_VERSION + " to " + StringMan.join(VERSION, "."));
}
}
});
-
+
// World generators:
final ConfigurationSection section = config.getConfigurationSection("worlds");
- if (section != null)
- {
- for (final String world : section.getKeys(false))
- {
- if (world.equals("CheckingPlotSquaredGenerator"))
- {
+ if (section != null) {
+ for (final String world : section.getKeys(false)) {
+ if (world.equals("CheckingPlotSquaredGenerator")) {
continue;
}
- if (BlockManager.manager.isWorld(world))
- {
+ if (BlockManager.manager.isWorld(world)) {
IMP.setGenerator(world);
}
}
- TaskManager.runTaskLater(new Runnable()
- {
+ TaskManager.runTaskLater(new Runnable() {
@Override
- public void run()
- {
- for (final String world : section.getKeys(false))
- {
- if (world.equals("CheckingPlotSquaredGenerator"))
- {
+ public void run() {
+ for (final String world : section.getKeys(false)) {
+ if (world.equals("CheckingPlotSquaredGenerator")) {
continue;
}
- if (!BlockManager.manager.isWorld(world) || (BlockManager.manager.isWorld(world) && !isPlotWorld(world)))
- {
+ if (!BlockManager.manager.isWorld(world) || (BlockManager.manager.isWorld(world) && !isPlotWorld(world))) {
PS.debug("&c`" + world + "` was not properly loaded - PlotSquared will now try to load it properly: ");
PS.debug("&8 - &7Are you trying to delete this world? Remember to remove it from the settings.yml as well");
PS.debug("&8 - &7Your world management plugin may be faulty. Consider using an up to date plugin.");
@@ -342,7 +299,7 @@ public class PS
}
}, 1);
}
-
+
// Copy files
copyFile("automerge.js", "scripts");
copyFile("town.template", "templates");
@@ -352,112 +309,98 @@ public class PS
copyFile("s_chinese.yml", "translations");
copyFile("italian.yml", "translations");
showDebug();
- }
- catch (final Throwable e)
- {
+ } catch (final Throwable e) {
e.printStackTrace();
}
}
-
- public boolean isMainThread(final Thread thread)
- {
+
+ public boolean isMainThread(final Thread thread) {
return this.thread == thread;
}
-
- public boolean checkVersion(final int[] version, final int major, final int minor, final int minor2)
- {
+
+ public boolean checkVersion(final int[] version, final int major, final int minor, final int minor2) {
return (version[0] > major) || ((version[0] == major) && (version[1] > minor)) || ((version[0] == major) && (version[1] == minor) && (version[2] >= minor2));
}
-
+
/**
* Get the instance of PlotSquared
*
* @return the instance created by IPlotMain
*/
- public static PS get()
- {
+ public static PS get() {
return instance;
}
-
+
/**
* Get the last PlotSquared version
* @return last version in config or null
*/
- public String getLastVersion()
- {
+ public String getLastVersion() {
return LAST_VERSION;
}
-
+
/**
* Get the current PlotSquared version
* @return current version in config or null
*/
- public int[] getVersion()
- {
+ public int[] getVersion() {
return VERSION;
}
-
+
/**
* Get the platform this is running on (Bukkit, Sponge)
* @return
*/
- public String getPlatform()
- {
+ public String getPlatform() {
return PLATFORM;
}
-
+
/**
* Log a message to the IPlotMain logger
*
* @param message Message to log
* @see IPlotMain#log(String)
*/
- public static void log(final Object message)
- {
+ public static void log(final Object message) {
get().IMP.log(StringMan.getString(message));
}
-
+
/**
* Log a message to the IPlotMain logger
*
* @param message Message to log
* @see IPlotMain#log(String)
*/
- public static void debug(final Object message)
- {
- if (Settings.DEBUG)
- {
+ public static void debug(final Object message) {
+ if (Settings.DEBUG) {
log(message);
}
}
-
+
/**
* Get the database object
*
* @return Database object
* @see #getConnection() Get the database connection
*/
- public Database getDatabase()
- {
+ public Database getDatabase() {
return database;
}
-
+
/**
* Update the global reference
* to a plot object
*
* @param plot Plot Object to update
*/
- public void updatePlot(final Plot plot)
- {
+ public void updatePlot(final Plot plot) {
final String world = plot.world;
- if (!plots.containsKey(world))
- {
+ if (!plots.containsKey(world)) {
plots.put(world, new ConcurrentHashMap());
}
plots.get(world).put(plot.id, plot);
}
-
+
/**
* Get the plot world based on the
* name identifier
@@ -466,12 +409,13 @@ public class PS
* @return plot world | null if not existing
* @see #getPlotWorldsString() Get all plot world names
*/
- public PlotWorld getPlotWorld(final String world)
- {
- if (plotworlds.containsKey(world)) { return plotworlds.get(world); }
+ public PlotWorld getPlotWorld(final String world) {
+ if (plotworlds.containsKey(world)) {
+ return plotworlds.get(world);
+ }
return null;
}
-
+
/**
* Add a global reference to a plot world
*
@@ -480,38 +424,34 @@ public class PS
* @param manager PlotManager
* @see #removePlotWorld(String) To remove the reference
*/
- public void addPlotWorld(final String world, final PlotWorld plotworld, final PlotManager manager)
- {
+ public void addPlotWorld(final String world, final PlotWorld plotworld, final PlotManager manager) {
plotworlds.put(world, plotworld);
plotmanagers.put(world, manager);
- if (!plots.containsKey(world))
- {
+ if (!plots.containsKey(world)) {
plots.put(world, new ConcurrentHashMap());
}
}
-
+
/**
* Remove a plot world reference
*
* @param world World name
* @see #addPlotWorld(String, PlotWorld, PlotManager) To add a reference
*/
- public void removePlotWorld(final String world)
- {
+ public void removePlotWorld(final String world) {
plots.remove(world);
plotmanagers.remove(world);
plotworlds.remove(world);
}
-
+
/**
* @param world World Name
*/
- public void removePlotWorldAbs(final String world)
- {
+ public void removePlotWorldAbs(final String world) {
plotmanagers.remove(world);
plotworlds.remove(world);
}
-
+
/**
* Get all plots as raw objects
*
@@ -521,34 +461,26 @@ public class PS
* @return HashMap containing the world name, and another map with the plot id and the plot object
*/
@Deprecated
- public Map> getAllPlotsRaw()
- {
+ public Map> getAllPlotsRaw() {
return plots;
}
-
+
/**
* A more generic way to filter plots - make your own method if you need complex filters
* @param filters
* @return
*/
- public Set getPlots(final PlotFilter... filters)
- {
+ public Set getPlots(final PlotFilter... filters) {
final HashSet set = new HashSet<>();
- for (final Entry