diff --git a/src/main/java/ch/m4th1eu/json/CDL.java b/src/main/java/ch/m4th1eu/json/CDL.java index 6daf829..e442e88 100644 --- a/src/main/java/ch/m4th1eu/json/CDL.java +++ b/src/main/java/ch/m4th1eu/json/CDL.java @@ -40,6 +40,7 @@ SOFTWARE. * A comma delimited list can be converted into a JSONArray of JSONObjects. * The names for the elements in the JSONObjects can be taken from the names * in the first row. + * * @author JSON.org * @version 2016-05-01 */ @@ -48,6 +49,7 @@ public class CDL { /** * Get the next value. The value can be wrapped in quotes. The value can * be empty. + * * @param x A JSONTokener of the source text. * @return The value string, or null if empty. * @throws JSONException if the quoted string is badly formed. @@ -60,49 +62,50 @@ public class CDL { c = x.next(); } while (c == ' ' || c == '\t'); switch (c) { - case 0: - return null; - case '"': - case '\'': - q = c; - sb = new StringBuffer(); - for (;;) { - c = x.next(); - if (c == q) { - //Handle escaped double-quote - char nextC = x.next(); - if(nextC != '\"') { - // if our quote was the end of the file, don't step - if(nextC > 0) { - x.back(); + case 0: + return null; + case '"': + case '\'': + q = c; + sb = new StringBuffer(); + for (; ; ) { + c = x.next(); + if (c == q) { + //Handle escaped double-quote + char nextC = x.next(); + if (nextC != '\"') { + // if our quote was the end of the file, don't step + if (nextC > 0) { + x.back(); + } + break; } - break; } + if (c == 0 || c == '\n' || c == '\r') { + throw x.syntaxError("Missing close quote '" + q + "'."); + } + sb.append(c); } - if (c == 0 || c == '\n' || c == '\r') { - throw x.syntaxError("Missing close quote '" + q + "'."); - } - sb.append(c); - } - return sb.toString(); - case ',': - x.back(); - return ""; - default: - x.back(); - return x.nextTo(','); + return sb.toString(); + case ',': + x.back(); + return ""; + default: + x.back(); + return x.nextTo(','); } } /** * Produce a JSONArray of strings from a row of comma delimited values. + * * @param x A JSONTokener of the source text. * @return A JSONArray of strings. * @throws JSONException */ public static JSONArray rowToJSONArray(JSONTokener x) throws JSONException { JSONArray ja = new JSONArray(); - for (;;) { + for (; ; ) { String value = getValue(x); char c = x.next(); if (value == null || @@ -110,7 +113,7 @@ public class CDL { return null; } ja.put(value); - for (;;) { + for (; ; ) { if (c == ',') { break; } @@ -119,7 +122,7 @@ public class CDL { return ja; } throw x.syntaxError("Bad character '" + c + "' (" + - (int)c + ")."); + (int) c + ")."); } c = x.next(); } @@ -129,23 +132,25 @@ public class CDL { /** * Produce a JSONObject from a row of comma delimited text, using a * parallel JSONArray of strings to provides the names of the elements. + * * @param names A JSONArray of names. This is commonly obtained from the - * first row of a comma delimited text file using the rowToJSONArray - * method. - * @param x A JSONTokener of the source text. + * first row of a comma delimited text file using the rowToJSONArray + * method. + * @param x A JSONTokener of the source text. * @return A JSONObject combining the names and values. * @throws JSONException */ public static JSONObject rowToJSONObject(JSONArray names, JSONTokener x) throws JSONException { JSONArray ja = rowToJSONArray(x); - return ja != null ? ja.toJSONObject(names) : null; + return ja != null ? ja.toJSONObject(names) : null; } /** * Produce a comma delimited text row from a JSONArray. Values containing * the comma character will be quoted. Troublesome characters may be * removed. + * * @param ja A JSONArray of strings. * @return A string ending in NEWLINE. */ @@ -182,6 +187,7 @@ public class CDL { /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. + * * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException @@ -193,6 +199,7 @@ public class CDL { /** * Produce a JSONArray of JSONObjects from a comma delimited text string, * using the first row as a source of names. + * * @param x The JSONTokener containing the comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException @@ -204,7 +211,8 @@ public class CDL { /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. - * @param names A JSONArray of strings. + * + * @param names A JSONArray of strings. * @param string The comma delimited text. * @return A JSONArray of JSONObjects. * @throws JSONException @@ -217,8 +225,9 @@ public class CDL { /** * Produce a JSONArray of JSONObjects from a comma delimited text string * using a supplied JSONArray as the source of element names. + * * @param names A JSONArray of strings. - * @param x A JSONTokener of the source text. + * @param x A JSONTokener of the source text. * @return A JSONArray of JSONObjects. * @throws JSONException */ @@ -228,7 +237,7 @@ public class CDL { return null; } JSONArray ja = new JSONArray(); - for (;;) { + for (; ; ) { JSONObject jo = rowToJSONObject(names, x); if (jo == null) { break; @@ -246,6 +255,7 @@ public class CDL { * Produce a comma delimited text from a JSONArray of JSONObjects. The * first row will be a list of names obtained by inspecting the first * JSONObject. + * * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException @@ -265,8 +275,9 @@ public class CDL { * Produce a comma delimited text from a JSONArray of JSONObjects using * a provided list of names. The list of names is not included in the * output. + * * @param names A JSONArray of strings. - * @param ja A JSONArray of JSONObjects. + * @param ja A JSONArray of JSONObjects. * @return A comma delimited text. * @throws JSONException */ diff --git a/src/main/java/ch/m4th1eu/json/Cookie.java b/src/main/java/ch/m4th1eu/json/Cookie.java index f0463cf..eef2f6b 100644 --- a/src/main/java/ch/m4th1eu/json/Cookie.java +++ b/src/main/java/ch/m4th1eu/json/Cookie.java @@ -27,6 +27,7 @@ SOFTWARE. /** * Convert a web browser cookie specification to a JSONObject and back. * JSON and Cookies are both notations for name/value pairs. + * * @author JSON.org * @version 2015-12-09 */ @@ -41,20 +42,21 @@ public class Cookie { * only a convention, not a standard. Often, cookies are expected to have * encoded values. We encode '=' and ';' because we must. We encode '%' and * '+' because they are meta characters in URL encoding. + * * @param string The source string. - * @return The escaped result. + * @return The escaped result. */ public static String escape(String string) { - char c; - String s = string.trim(); - int length = s.length(); - StringBuilder sb = new StringBuilder(length); + char c; + String s = string.trim(); + int length = s.length(); + StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i += 1) { c = s.charAt(i); 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)); + sb.append(Character.forDigit((char) ((c >>> 4) & 0x0f), 16)); + sb.append(Character.forDigit((char) (c & 0x0f), 16)); } else { sb.append(c); } @@ -73,15 +75,16 @@ public class Cookie { * stored under the key "value". This method does not do checking or * validation of the parameters. It only converts the cookie string into * a JSONObject. + * * @param string The cookie specification string. * @return A JSONObject containing "name", "value", and possibly other - * members. + * members. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { - String name; - JSONObject jo = new JSONObject(); - Object value; + String name; + JSONObject jo = new JSONObject(); + Object value; JSONTokener x = new JSONTokener(string); jo.put("name", x.nextTo('=')); x.next('='); @@ -111,6 +114,7 @@ public class Cookie { * If the JSONObject contains "expires", "domain", "path", or "secure" * members, they will be appended to the cookie specification string. * All other members are ignored. + * * @param jo A JSONObject * @return A cookie specification string * @throws JSONException @@ -142,9 +146,10 @@ public class Cookie { /** * Convert %hh sequences to single characters, and * convert plus to space. + * * @param string A string that may contain - * + (plus) and - * %hh sequences. + * + (plus) and + * %hh sequences. * @return The unescaped string. */ public static String unescape(String string) { @@ -158,7 +163,7 @@ public class Cookie { int d = JSONTokener.dehexchar(string.charAt(i + 1)); int e = JSONTokener.dehexchar(string.charAt(i + 2)); if (d >= 0 && e >= 0) { - c = (char)(d * 16 + e); + c = (char) (d * 16 + e); i += 2; } } diff --git a/src/main/java/ch/m4th1eu/json/CookieList.java b/src/main/java/ch/m4th1eu/json/CookieList.java index 57388d5..5f558d8 100644 --- a/src/main/java/ch/m4th1eu/json/CookieList.java +++ b/src/main/java/ch/m4th1eu/json/CookieList.java @@ -26,6 +26,7 @@ SOFTWARE. /** * Convert a web browser cookie list string to a JSONObject and back. + * * @author JSON.org * @version 2015-12-09 */ @@ -36,11 +37,12 @@ public class CookieList { * 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 converting '+' and '%' sequences. - * + *

* To add a cookie to a cookie list, * cookielistJSONObject.put(cookieJSONObject.getString("name"), - * cookieJSONObject.getString("value")); - * @param string A cookie list string + * cookieJSONObject.getString("value")); + * + * @param string A cookie list string * @return A JSONObject * @throws JSONException */ @@ -61,12 +63,13 @@ public class CookieList { * of name/value pairs. The names are separated from the values by '='. * The pairs are separated by ';'. The characters '%', '+', '=', and ';' * in the names and values are replaced by "%hh". + * * @param jo A JSONObject * @return A cookie list string * @throws JSONException */ public static String toString(JSONObject jo) throws JSONException { - boolean b = false; + boolean b = false; final StringBuilder sb = new StringBuilder(); // Don't use the new entrySet API to maintain Android support for (final String key : jo.keySet()) { diff --git a/src/main/java/ch/m4th1eu/json/HTTP.java b/src/main/java/ch/m4th1eu/json/HTTP.java index d490cf4..400d275 100644 --- a/src/main/java/ch/m4th1eu/json/HTTP.java +++ b/src/main/java/ch/m4th1eu/json/HTTP.java @@ -28,12 +28,15 @@ import java.util.Locale; /** * Convert an HTTP header to a JSONObject and back. + * * @author JSON.org * @version 2015-12-09 */ public class HTTP { - /** Carriage return/line feed. */ + /** + * Carriage return/line feed. + */ public static final String CRLF = "\r\n"; /** @@ -63,15 +66,16 @@ public class HTTP { * ...} * It does no further checking or conversion. It does not parse dates. * It does not do '%' transforms on URLs. + * * @param string An HTTP header string. * @return A JSONObject containing the elements and attributes * of the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; token = x.nextToken(); if (token.toUpperCase(Locale.ROOT).startsWith("HTTP")) { @@ -119,13 +123,14 @@ public class HTTP { * } * Any other members of the JSONObject will be output as HTTP fields. * The result will end with two CRLF pairs. + * * @param jo A JSONObject * @return An HTTP header string. * @throws JSONException if the object does not contain enough - * information. + * information. */ public static String toString(JSONObject jo) throws JSONException { - StringBuilder sb = new StringBuilder(); + StringBuilder sb = new StringBuilder(); if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { sb.append(jo.getString("HTTP-Version")); sb.append(' '); @@ -147,9 +152,9 @@ public class HTTP { // Don't use the new entrySet API to maintain Android support for (final String key : jo.keySet()) { String value = jo.optString(key); - if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && + if (!"HTTP-Version".equals(key) && !"Status-Code".equals(key) && !"Reason-Phrase".equals(key) && !"Method".equals(key) && - !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) { + !"Request-URI".equals(key) && !JSONObject.NULL.equals(value)) { sb.append(key); sb.append(": "); sb.append(jo.optString(key)); diff --git a/src/main/java/ch/m4th1eu/json/HTTPTokener.java b/src/main/java/ch/m4th1eu/json/HTTPTokener.java index 2fcf50f..1a8b9d7 100644 --- a/src/main/java/ch/m4th1eu/json/HTTPTokener.java +++ b/src/main/java/ch/m4th1eu/json/HTTPTokener.java @@ -27,6 +27,7 @@ SOFTWARE. /** * The HTTPTokener extends the JSONTokener to provide additional methods * for the parsing of HTTP headers. + * * @author JSON.org * @version 2015-12-09 */ @@ -34,6 +35,7 @@ public class HTTPTokener extends JSONTokener { /** * Construct an HTTPTokener from a string. + * * @param string A source string. */ public HTTPTokener(String string) { @@ -43,8 +45,9 @@ public class HTTPTokener extends JSONTokener { /** * Get the next token or string. This is used in parsing HTTP headers. - * @throws JSONException + * * @return A String. + * @throws JSONException */ public String nextToken() throws JSONException { char c; @@ -55,7 +58,7 @@ public class HTTPTokener extends JSONTokener { } while (Character.isWhitespace(c)); if (c == '"' || c == '\'') { q = c; - for (;;) { + for (; ; ) { c = next(); if (c < ' ') { throw syntaxError("Unterminated string."); @@ -66,7 +69,7 @@ public class HTTPTokener extends JSONTokener { sb.append(c); } } - for (;;) { + for (; ; ) { if (c == 0 || Character.isWhitespace(c)) { return sb.toString(); } diff --git a/src/main/java/ch/m4th1eu/json/JSONArray.java b/src/main/java/ch/m4th1eu/json/JSONArray.java index a8066de..11462aa 100644 --- a/src/main/java/ch/m4th1eu/json/JSONArray.java +++ b/src/main/java/ch/m4th1eu/json/JSONArray.java @@ -30,11 +30,7 @@ import java.io.Writer; import java.lang.reflect.Array; import java.math.BigDecimal; import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; +import java.util.*; /** @@ -98,17 +94,15 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a JSONTokener. * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. */ public JSONArray(JSONTokener x) throws JSONException { this(); if (x.nextClean() != '[') { throw x.syntaxError("A JSONArray text must start with '['"); } - + char nextChar = x.nextClean(); if (nextChar == 0) { // array is unclosed. No ']' found, instead EOF @@ -116,7 +110,7 @@ public class JSONArray implements Iterable { } if (nextChar != ']') { x.back(); - for (;;) { + for (; ; ) { if (x.nextClean() == ',') { x.back(); this.myArrayList.add(JSONObject.NULL); @@ -125,24 +119,24 @@ public class JSONArray implements Iterable { this.myArrayList.add(x.nextValue()); } switch (x.nextClean()) { - case 0: - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - case ',': - nextChar = x.nextClean(); - if (nextChar == 0) { + case 0: // array is unclosed. No ']' found, instead EOF throw x.syntaxError("Expected a ',' or ']'"); - } - if (nextChar == ']') { + case ',': + nextChar = x.nextClean(); + if (nextChar == 0) { + // array is unclosed. No ']' found, instead EOF + throw x.syntaxError("Expected a ',' or ']'"); + } + if (nextChar == ']') { + return; + } + x.back(); + break; + case ']': return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); + default: + throw x.syntaxError("Expected a ',' or ']'"); } } } @@ -151,12 +145,10 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a source JSON text. * - * @param source - * A string that begins with [ (left - * bracket) and ends with ] - *  (right bracket). - * @throws JSONException - * If there is a syntax error. + * @param source A string that begins with [ (left + * bracket) and ends with ] + *  (right bracket). + * @throws JSONException If there is a syntax error. */ public JSONArray(String source) throws JSONException { this(new JSONTokener(source)); @@ -165,31 +157,26 @@ public class JSONArray implements Iterable { /** * Construct a JSONArray from a Collection. * - * @param collection - * A Collection. + * @param collection A Collection. */ public JSONArray(Collection collection) { if (collection == null) { this.myArrayList = new ArrayList(); } else { this.myArrayList = new ArrayList(collection.size()); - for (Object o: collection){ - this.myArrayList.add(JSONObject.wrap(o)); - } + for (Object o : collection) { + this.myArrayList.add(JSONObject.wrap(o)); + } } } /** * Construct a JSONArray from an array. * - * @param array - * Array. If the parameter passed is null, or not an array, an - * exception will be thrown. - * - * @throws JSONException - * If not an array or if an array value is non-finite number. - * @throws NullPointerException - * Thrown if the array parameter is null. + * @param array Array. If the parameter passed is null, or not an array, an + * exception will be thrown. + * @throws JSONException If not an array or if an array value is non-finite number. + * @throws NullPointerException Thrown if the array parameter is null. */ public JSONArray(Object array) throws JSONException { this(); @@ -213,11 +200,9 @@ public class JSONArray implements Iterable { /** * Get the object value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return An object value. - * @throws JSONException - * If there is no value for the index. + * @throws JSONException If there is no value for the index. */ public Object get(int index) throws JSONException { Object object = this.opt(index); @@ -231,22 +216,20 @@ public class JSONArray implements Iterable { * Get the boolean value associated with an index. The string values "true" * and "false" are converted to boolean. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. + * @throws JSONException If there is no value for the index or if the value is not + * convertible to boolean. */ public boolean getBoolean(int index) throws JSONException { Object object = this.get(index); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object) - .equalsIgnoreCase("false"))) { + .equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object) - .equalsIgnoreCase("true"))) { + .equalsIgnoreCase("true"))) { return true; } throw new JSONException("JSONArray[" + index + "] is not a boolean."); @@ -255,12 +238,10 @@ public class JSONArray implements Iterable { /** * Get the double value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. */ public double getDouble(int index) throws JSONException { return this.getNumber(index).doubleValue(); @@ -269,12 +250,10 @@ public class JSONArray implements Iterable { /** * Get the float value associated with a key. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. + * @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 float getFloat(int index) throws JSONException { return this.getNumber(index).floatValue(); @@ -283,18 +262,16 @@ public class JSONArray implements Iterable { /** * Get the Number value associated with a key. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. + * @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 Number getNumber(int index) throws JSONException { Object object = this.get(index); try { if (object instanceof Number) { - return (Number)object; + return (Number) object; } return JSONObject.stringToNumber(object.toString()); } catch (Exception e) { @@ -304,21 +281,17 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with an index. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. */ public > E getEnum(Class clazz, int index) throws JSONException { E val = optEnum(clazz, index); - if(val==null) { + if (val == null) { // JSONException should really take a throwable argument. // If it did, I would re-implement this with the Enum.valueOf // method and place any thrown exception in the JSONException @@ -334,19 +307,17 @@ public class JSONArray implements Iterable { * will be used. See notes on the constructor for conversion issues that * may arise. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigDecimal. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigDecimal. */ - public BigDecimal getBigDecimal (int index) throws JSONException { + public BigDecimal getBigDecimal(int index) throws JSONException { Object object = this.get(index); BigDecimal val = JSONObject.objectToBigDecimal(object, null); - if(val == null) { + if (val == null) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal ("+ object + ")."); + "] could not convert to BigDecimal (" + object + ")."); } return val; } @@ -354,19 +325,17 @@ public class JSONArray implements Iterable { /** * Get the BigInteger value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigInteger. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigInteger. */ - public BigInteger getBigInteger (int index) throws JSONException { + public BigInteger getBigInteger(int index) throws JSONException { Object object = this.get(index); BigInteger val = JSONObject.objectToBigInteger(object, null); - if(val == null) { + if (val == null) { throw new JSONException("JSONArray[" + index + - "] could not convert to BigDecimal ("+ object + ")."); + "] could not convert to BigDecimal (" + object + ")."); } return val; } @@ -374,11 +343,9 @@ public class JSONArray implements Iterable { /** * Get the int value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. + * @throws JSONException If the key is not found or if the value is not a number. */ public int getInt(int index) throws JSONException { return this.getNumber(index).intValue(); @@ -387,12 +354,10 @@ public class JSONArray implements Iterable { /** * Get the JSONArray associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray + * @throws JSONException If there is no value for the index. or if the value is not a + * JSONArray */ public JSONArray getJSONArray(int index) throws JSONException { Object object = this.get(index); @@ -405,12 +370,10 @@ public class JSONArray implements Iterable { /** * Get the JSONObject associated with an index. * - * @param index - * subscript + * @param index subscript * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject + * @throws JSONException If there is no value for the index or if the value is not a + * JSONObject */ public JSONObject getJSONObject(int index) throws JSONException { Object object = this.get(index); @@ -423,12 +386,10 @@ public class JSONArray implements Iterable { /** * Get the long value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. */ public long getLong(int index) throws JSONException { return this.getNumber(index).longValue(); @@ -437,11 +398,9 @@ public class JSONArray implements Iterable { /** * Get the string associated with an index. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A string value. - * @throws JSONException - * If there is no string value for the index. + * @throws JSONException If there is no string value for the index. */ public String getString(int index) throws JSONException { Object object = this.get(index); @@ -454,8 +413,7 @@ public class JSONArray implements Iterable { /** * Determine if the value is null. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return true if the value at the index is null, or if there is no value. */ public boolean isNull(int index) { @@ -467,24 +425,22 @@ public class JSONArray implements Iterable { * separator string is inserted between each element. Warning: * This method assumes that the data structure is acyclical. * - * @param separator - * A string that will be inserted between the elements. + * @param separator A string that will be inserted between the elements. * @return a string. - * @throws JSONException - * If the array contains an invalid number. + * @throws JSONException If the array contains an invalid number. */ public String join(String separator) throws JSONException { int len = this.length(); if (len == 0) { return ""; } - + StringBuilder sb = new StringBuilder( - JSONObject.valueToString(this.myArrayList.get(0))); + JSONObject.valueToString(this.myArrayList.get(0))); for (int i = 1; i < len; i++) { sb.append(separator) - .append(JSONObject.valueToString(this.myArrayList.get(i))); + .append(JSONObject.valueToString(this.myArrayList.get(i))); } return sb.toString(); } @@ -501,8 +457,7 @@ public class JSONArray implements Iterable { /** * Get the optional object value associated with an index. * - * @param index - * The index must be between 0 and length() - 1. If not, null is returned. + * @param index The index must be between 0 and length() - 1. If not, null is returned. * @return An object value, or null if there is no object at that index. */ public Object opt(int index) { @@ -515,8 +470,7 @@ public class JSONArray implements Iterable { * if there is no value at that index, or if the value is not Boolean.TRUE * or the String "true". * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The truth. */ public boolean optBoolean(int index) { @@ -528,10 +482,8 @@ public class JSONArray implements Iterable { * defaultValue if there is no value at that index or if it is not a Boolean * or the String "true" or "false" (case insensitive). * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. * @return The truth. */ public boolean optBoolean(int index, boolean defaultValue) { @@ -547,8 +499,7 @@ public class JSONArray implements Iterable { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public double optDouble(int index) { @@ -560,10 +511,8 @@ public class JSONArray implements Iterable { * 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. * - * @param index - * subscript - * @param defaultValue - * The default value. + * @param index subscript + * @param defaultValue The default value. * @return The value. */ public double optDouble(int index, double defaultValue) { @@ -583,8 +532,7 @@ public class JSONArray implements Iterable { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public float optFloat(int index) { @@ -596,10 +544,8 @@ public class JSONArray implements Iterable { * 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. * - * @param index - * subscript - * @param defaultValue - * The default value. + * @param index subscript + * @param defaultValue The default value. * @return The value. */ public float optFloat(int index, float defaultValue) { @@ -619,8 +565,7 @@ public class JSONArray implements Iterable { * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public int optInt(int index) { @@ -632,10 +577,8 @@ public class JSONArray implements Iterable { * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public int optInt(int index, int defaultValue) { @@ -648,13 +591,10 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. * @return The enum value at the index location or null if not found */ public > E optEnum(Class clazz, int index) { @@ -663,17 +603,13 @@ public class JSONArray implements Iterable { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default in case the value is not found + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default in case the value is not found * @return The enum value at the index location or defaultValue if - * the value is not found or cannot be assigned to clazz + * the value is not found or cannot be assigned to clazz */ public > E optEnum(Class clazz, int index, E defaultValue) { try { @@ -696,14 +632,12 @@ public class JSONArray implements Iterable { } /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the + * Get the optional BigInteger 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. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public BigInteger optBigInteger(int index, BigInteger defaultValue) { @@ -712,17 +646,15 @@ public class JSONArray implements Iterable { } /** - * Get the optional BigDecimal value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the + * Get the optional BigDecimal 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. If the value * is float or double, the the {@link BigDecimal#BigDecimal(double)} * constructor will be used. See notes on the constructor for conversion * issues that may arise. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { @@ -733,10 +665,9 @@ public class JSONArray implements Iterable { /** * Get the optional JSONArray associated with an index. * - * @param index - * subscript + * @param index subscript * @return A JSONArray value, or null if the index has no value, or if the - * value is not a JSONArray. + * value is not a JSONArray. */ public JSONArray optJSONArray(int index) { Object o = this.opt(index); @@ -748,8 +679,7 @@ public class JSONArray implements Iterable { * the key is not found, or null if the index has no value, or if the value * is not a JSONObject. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A JSONObject value. */ public JSONObject optJSONObject(int index) { @@ -762,8 +692,7 @@ public class JSONArray implements Iterable { * there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return The value. */ public long optLong(int index) { @@ -775,10 +704,8 @@ public class JSONArray implements Iterable { * returned if there is no value for the index, or if the value is not a * number and cannot be converted to a number. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return The value. */ public long optLong(int index, long defaultValue) { @@ -795,8 +722,7 @@ public class JSONArray implements Iterable { * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method * would be used in cases where type coercion of the number value is unwanted. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return An object which is the value. */ public Number optNumber(int index) { @@ -809,10 +735,8 @@ public class JSONArray implements Iterable { * an attempt will be made to evaluate it as a number ({@link BigDecimal}). This method * would be used in cases where type coercion of the number value is unwanted. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default. * @return An object which is the value. */ public Number optNumber(int index, Number defaultValue) { @@ -820,10 +744,10 @@ public class JSONArray implements Iterable { if (JSONObject.NULL.equals(val)) { return defaultValue; } - if (val instanceof Number){ + if (val instanceof Number) { return (Number) val; } - + if (val instanceof String) { try { return JSONObject.stringToNumber((String) val); @@ -839,8 +763,7 @@ public class JSONArray implements Iterable { * empty string if there is no value at that index. If the value is not a * string and is not null, then it is converted to a string. * - * @param index - * The index must be between 0 and length() - 1. + * @param index The index must be between 0 and length() - 1. * @return A String value. */ public String optString(int index) { @@ -851,10 +774,8 @@ public class JSONArray implements Iterable { * Get the optional string associated with an index. The defaultValue is * returned if the key is not found. * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. * @return A String value. */ public String optString(int index, String defaultValue) { @@ -866,8 +787,7 @@ public class JSONArray implements Iterable { /** * Append a boolean value. This increases the array's length by one. * - * @param value - * A boolean value. + * @param value A boolean value. * @return this. */ public JSONArray put(boolean value) { @@ -878,11 +798,9 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * - * @param value - * A Collection value. + * @param value A Collection value. * @return this. - * @throws JSONException - * If the value is non-finite number. + * @throws JSONException If the value is non-finite number. */ public JSONArray put(Collection value) { return this.put(new JSONArray(value)); @@ -891,24 +809,20 @@ public class JSONArray implements Iterable { /** * Append a double value. This increases the array's length by one. * - * @param value - * A double value. + * @param value A double value. * @return this. - * @throws JSONException - * if the value is not finite. + * @throws JSONException if the value is not finite. */ public JSONArray put(double value) throws JSONException { return this.put(Double.valueOf(value)); } - + /** * Append a float value. This increases the array's length by one. * - * @param value - * A float value. + * @param value A float value. * @return this. - * @throws JSONException - * if the value is not finite. + * @throws JSONException if the value is not finite. */ public JSONArray put(float value) throws JSONException { return this.put(Float.valueOf(value)); @@ -917,8 +831,7 @@ public class JSONArray implements Iterable { /** * Append an int value. This increases the array's length by one. * - * @param value - * An int value. + * @param value An int value. * @return this. */ public JSONArray put(int value) { @@ -928,8 +841,7 @@ public class JSONArray implements Iterable { /** * Append an long value. This increases the array's length by one. * - * @param value - * A long value. + * @param value A long value. * @return this. */ public JSONArray put(long value) { @@ -940,13 +852,10 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONObject which * is produced from a Map. * - * @param value - * A Map value. + * @param value A Map value. * @return this. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null */ public JSONArray put(Map value) { return this.put(new JSONObject(value)); @@ -955,13 +864,11 @@ public class JSONArray implements Iterable { /** * Append an object value. This increases the array's length by one. * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. + * @param value An object value. The value should be a Boolean, Double, + * Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. * @return this. - * @throws JSONException - * If the value is non-finite number. + * @throws JSONException If the value is non-finite number. */ public JSONArray put(Object value) { JSONObject.testValidity(value); @@ -974,13 +881,10 @@ public class JSONArray implements Iterable { * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * - * @param index - * The subscript. - * @param value - * A boolean value. + * @param index The subscript. + * @param value A boolean value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, boolean value) throws JSONException { return this.put(index, value ? Boolean.TRUE : Boolean.FALSE); @@ -990,13 +894,10 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONArray which * is produced from a Collection. * - * @param index - * The subscript. - * @param value - * A Collection value. + * @param index The subscript. + * @param value A Collection value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, Collection value) throws JSONException { return this.put(index, new JSONArray(value)); @@ -1007,13 +908,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A double value. + * @param index The subscript. + * @param value A double value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, double value) throws JSONException { return this.put(index, Double.valueOf(value)); @@ -1024,13 +922,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A float value. + * @param index The subscript. + * @param value A float value. * @return this. - * @throws JSONException - * If the index is negative or if the value is non-finite. + * @throws JSONException If the index is negative or if the value is non-finite. */ public JSONArray put(int index, float value) throws JSONException { return this.put(index, Float.valueOf(value)); @@ -1041,13 +936,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * An int value. + * @param index The subscript. + * @param value An int value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, int value) throws JSONException { return this.put(index, Integer.valueOf(value)); @@ -1058,13 +950,10 @@ public class JSONArray implements Iterable { * the JSONArray, then null elements will be added as necessary to pad it * out. * - * @param index - * The subscript. - * @param value - * A long value. + * @param index The subscript. + * @param value A long value. * @return this. - * @throws JSONException - * If the index is negative. + * @throws JSONException If the index is negative. */ public JSONArray put(int index, long value) throws JSONException { return this.put(index, Long.valueOf(value)); @@ -1074,16 +963,12 @@ public class JSONArray implements Iterable { * Put a value in the JSONArray, where the value will be a JSONObject that * is produced from a Map. * - * @param index - * The subscript. - * @param value - * The Map value. + * @param index The subscript. + * @param value The Map value. * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - * @throws NullPointerException - * If a key in the map is null + * @throws JSONException If the index is negative or if the the value is an invalid + * number. + * @throws NullPointerException If a key in the map is null */ public JSONArray put(int index, Map value) throws JSONException { this.put(index, new JSONObject(value)); @@ -1095,16 +980,13 @@ public class JSONArray implements Iterable { * than the length of the JSONArray, then null elements will be added as * necessary to pad it out. * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or + * String, or the JSONObject.NULL object. * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. + * @throws JSONException If the index is negative or if the the value is an invalid + * number. */ public JSONArray put(int index, Object value) throws JSONException { if (index < 0) { @@ -1115,7 +997,7 @@ public class JSONArray implements Iterable { this.myArrayList.set(index, value); return this; } - if(index == this.length()){ + if (index == this.length()) { // simple append return this.put(value); } @@ -1128,9 +1010,9 @@ public class JSONArray implements Iterable { } return this.put(value); } - + /** - * Creates a JSONPointer using an initialization string and tries to + * Creates a JSONPointer using an initialization string and tries to * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *
@@ -1138,7 +1020,7 @@ public class JSONArray implements Iterable {
      *     {"b":"c"}
      * ]
      * 
-     * and this JSONPointer string: 
+     * and this JSONPointer string:
      * 
      * "/0/b"
      * 
@@ -1151,9 +1033,9 @@ public class JSONArray implements Iterable { public Object query(String jsonPointer) { return query(new JSONPointer(jsonPointer)); } - + /** - * Uses a user initialized JSONPointer and tries to + * Uses a user initialized JSONPointer and tries to * match it to an item within this JSONArray. For example, given a * JSONArray initialized with this document: *
@@ -1161,7 +1043,7 @@ public class JSONArray implements Iterable {
      *     {"b":"c"}
      * ]
      * 
-     * and this JSONPointer: 
+     * and this JSONPointer:
      * 
      * "/0/b"
      * 
@@ -1174,23 +1056,23 @@ public class JSONArray implements Iterable { public Object query(JSONPointer jsonPointer) { return jsonPointer.queryFrom(this); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer the string representation of the JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); + return optQuery(new JSONPointer(jsonPointer)); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax @@ -1206,15 +1088,14 @@ public class JSONArray implements Iterable { /** * Remove an index and close the hole. * - * @param index - * The index of the element to be removed. + * @param index The index of the element to be removed. * @return The value that was associated with the index, or null if there - * was no value. + * was no value. */ public Object remove(int index) { return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; + ? this.myArrayList.remove(index) + : null; } /** @@ -1229,24 +1110,24 @@ public class JSONArray implements Iterable { return false; } int len = this.length(); - if (len != ((JSONArray)other).length()) { + if (len != ((JSONArray) other).length()) { return false; } for (int i = 0; i < len; i += 1) { Object valueThis = this.myArrayList.get(i); - Object valueOther = ((JSONArray)other).myArrayList.get(i); - if(valueThis == valueOther) { - continue; + Object valueOther = ((JSONArray) other).myArrayList.get(i); + if (valueThis == valueOther) { + continue; } - if(valueThis == null) { - return false; + if (valueThis == null) { + return false; } if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { @@ -1260,13 +1141,11 @@ public class JSONArray implements Iterable { * Produce a JSONObject by combining a JSONArray of names with the values of * this JSONArray. * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. + * has no values. + * @throws JSONException If any of the names are null. */ public JSONObject toJSONObject(JSONArray names) throws JSONException { if (names == null || names.isEmpty() || this.isEmpty()) { @@ -1289,7 +1168,7 @@ public class JSONArray implements Iterable { * * * @return a printable, displayable, transmittable representation of the - * array. + * array. */ @Override public String toString() { @@ -1302,11 +1181,11 @@ public class JSONArray implements Iterable { /** * Make a pretty-printed JSON text of this JSONArray. - * + * *

If indentFactor > 0 and the {@link JSONArray} has only * one element, then the array will be output on a single line: *

{@code [1]}
- * + * *

If an array has 2 or more elements, then it will be output across * multiple lines:

{@code
      * [
@@ -1318,13 +1197,12 @@ public class JSONArray implements Iterable {
      * 

* Warning: This method assumes that the data structure is acyclical. * - * - * @param indentFactor - * The number of spaces to add to each level of indentation. + * + * @param indentFactor The number of spaces to add to each level of indentation. * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ] - *  (right bracket). + * object, beginning with [ (left + * bracket) and ending with ] + *  (right bracket). * @throws JSONException */ public String toString(int indentFactor) throws JSONException { @@ -1339,7 +1217,7 @@ public class JSONArray implements Iterable { * compactness, no whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. - * + * * * @return The writer. * @throws JSONException @@ -1350,11 +1228,11 @@ public class JSONArray implements Iterable { /** * Write the contents of the JSONArray as JSON text to a writer. - * + * *

If indentFactor > 0 and the {@link JSONArray} has only * one element, then the array will be output on a single line: *

{@code [1]}
- * + * *

If an array has 2 or more elements, then it will be output across * multiple lines:

{@code
      * [
@@ -1367,12 +1245,9 @@ public class JSONArray implements Iterable {
      * Warning: This method assumes that the data structure is acyclical.
      * 
      *
-     * @param writer
-     *            Writes the serialized JSON
-     * @param indentFactor
-     *            The number of spaces to add to each level of indentation.
-     * @param indent
-     *            The indentation of the top level.
+     * @param writer       Writes the serialized JSON
+     * @param indentFactor The number of spaces to add to each level of indentation.
+     * @param indent       The indentation of the top level.
      * @return The writer.
      * @throws JSONException
      */
diff --git a/src/main/java/ch/m4th1eu/json/JSONException.java b/src/main/java/ch/m4th1eu/json/JSONException.java
index 3f00ae2..703bc7e 100644
--- a/src/main/java/ch/m4th1eu/json/JSONException.java
+++ b/src/main/java/ch/m4th1eu/json/JSONException.java
@@ -7,14 +7,15 @@ package ch.m4th1eu.json;
  * @version 2015-12-09
  */
 public class JSONException extends RuntimeException {
-    /** Serialization ID */
+    /**
+     * Serialization ID
+     */
     private static final long serialVersionUID = 0;
 
     /**
      * Constructs a JSONException with an explanatory message.
      *
-     * @param message
-     *            Detail about the reason for the exception.
+     * @param message Detail about the reason for the exception.
      */
     public JSONException(final String message) {
         super(message);
@@ -22,11 +23,9 @@ public class JSONException extends RuntimeException {
 
     /**
      * Constructs a JSONException with an explanatory message and cause.
-     * 
-     * @param message
-     *            Detail about the reason for the exception.
-     * @param cause
-     *            The cause.
+     *
+     * @param message Detail about the reason for the exception.
+     * @param cause   The cause.
      */
     public JSONException(final String message, final Throwable cause) {
         super(message, cause);
@@ -34,9 +33,8 @@ public class JSONException extends RuntimeException {
 
     /**
      * Constructs a new JSONException with the specified cause.
-     * 
-     * @param cause
-     *            The cause.
+     *
+     * @param cause The cause.
      */
     public JSONException(final Throwable cause) {
         super(cause.getMessage(), cause);
diff --git a/src/main/java/ch/m4th1eu/json/JSONML.java b/src/main/java/ch/m4th1eu/json/JSONML.java
index 938719a..4662752 100644
--- a/src/main/java/ch/m4th1eu/json/JSONML.java
+++ b/src/main/java/ch/m4th1eu/json/JSONML.java
@@ -35,28 +35,29 @@ SOFTWARE.
 public class JSONML {
     /**
      * Parse XML values and store them in a JSONArray.
-     * @param x       The XMLTokener containing the source string.
-     * @param arrayForm true if array form, false if object form.
-     * @param ja      The JSONArray that is containing the current tag or null
-     *     if we are at the outermost level.
-     * @param keepStrings	Don't type-convert text nodes and attribute values
+     *
+     * @param x           The XMLTokener containing the source string.
+     * @param arrayForm   true if array form, false if object form.
+     * @param ja          The JSONArray that is containing the current tag or null
+     *                    if we are at the outermost level.
+     * @param keepStrings Don't type-convert text nodes and attribute values
      * @return A JSONArray if the value is the outermost tag, otherwise null.
      * @throws JSONException
      */
     private static Object parse(
-        XMLTokener x,
-        boolean    arrayForm,
-        JSONArray  ja,
-        boolean keepStrings
+            XMLTokener x,
+            boolean arrayForm,
+            JSONArray ja,
+            boolean keepStrings
     ) throws JSONException {
-        String     attribute;
-        char       c;
-        String     closeTag = null;
-        int        i;
-        JSONArray  newja = null;
+        String attribute;
+        char c;
+        String closeTag = null;
+        int i;
+        JSONArray newja = null;
         JSONObject newjo = null;
-        Object     token;
-        String     tagName = null;
+        Object token;
+        String tagName = null;
 
 // Test for and skip past these forms:
 //      
@@ -80,7 +81,7 @@ public class JSONML {
                         if (!(token instanceof String)) {
                             throw new JSONException(
                                     "Expected a closing name instead of '" +
-                                    token + "'.");
+                                            token + "'.");
                         }
                         if (x.nextToken() != XML.GT) {
                             throw x.syntaxError("Misshaped close tag");
@@ -134,7 +135,7 @@ public class JSONML {
                     if (!(token instanceof String)) {
                         throw x.syntaxError("Bad tagName '" + token + "'.");
                     }
-                    tagName = (String)token;
+                    tagName = (String) token;
                     newja = new JSONArray();
                     newjo = new JSONObject();
                     if (arrayForm) {
@@ -149,7 +150,7 @@ public class JSONML {
                         }
                     }
                     token = null;
-                    for (;;) {
+                    for (; ; ) {
                         if (token == null) {
                             token = x.nextToken();
                         }
@@ -162,7 +163,7 @@ public class JSONML {
 
 // attribute = value
 
-                        attribute = (String)token;
+                        attribute = (String) token;
                         if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) {
                             throw x.syntaxError("Reserved attribute.");
                         }
@@ -172,7 +173,7 @@ public class JSONML {
                             if (!(token instanceof String)) {
                                 throw x.syntaxError("Missing value");
                             }
-                            newjo.accumulate(attribute, keepStrings ? ((String)token) :XML.stringToValue((String)token));
+                            newjo.accumulate(attribute, keepStrings ? ((String) token) : XML.stringToValue((String) token));
                             token = null;
                         } else {
                             newjo.accumulate(attribute, "");
@@ -201,7 +202,7 @@ public class JSONML {
                         if (token != XML.GT) {
                             throw x.syntaxError("Misshaped tag");
                         }
-                        closeTag = (String)parse(x, arrayForm, newja, keepStrings);
+                        closeTag = (String) parse(x, arrayForm, newja, keepStrings);
                         if (closeTag != null) {
                             if (!closeTag.equals(tagName)) {
                                 throw x.syntaxError("Mismatched '" + tagName +
@@ -223,8 +224,8 @@ public class JSONML {
             } else {
                 if (ja != null) {
                     ja.put(token instanceof String
-                        ? keepStrings ? XML.unescape((String)token) :XML.stringToValue((String)token)
-                        : token);
+                            ? keepStrings ? XML.unescape((String) token) : XML.stringToValue((String) token)
+                            : token);
                 }
             }
         }
@@ -239,12 +240,13 @@ public class JSONML {
      * name/value pairs. If the tag contains children, then strings and
      * JSONArrays will represent the child tags.
      * Comments, prologs, DTDs, and <[ [ ]]> are ignored.
+     *
      * @param string The source string.
      * @return A JSONArray containing the structured data from the XML string.
      * @throws JSONException Thrown on error converting to a JSONArray
      */
     public static JSONArray toJSONArray(String string) throws JSONException {
-        return (JSONArray)parse(new XMLTokener(string), true, null, false);
+        return (JSONArray) parse(new XMLTokener(string), true, null, false);
     }
 
 
@@ -255,18 +257,19 @@ public class JSONML {
      * attributes, then the second element will be JSONObject containing the
      * name/value pairs. If the tag contains children, then strings and
      * JSONArrays will represent the child tags.
-     * As opposed to toJSONArray this method does not attempt to convert 
-     * any text node or attribute value to any type 
+     * As opposed to toJSONArray this method does not attempt to convert
+     * any text node or attribute value to any type
      * but just leaves it as a string.
      * Comments, prologs, DTDs, and <[ [ ]]> are ignored.
-     * @param string The source string.
+     *
+     * @param string      The source string.
      * @param keepStrings If true, then values will not be coerced into boolean
-     *  or numeric values and will instead be left as strings
+     *                    or numeric values and will instead be left as strings
      * @return A JSONArray containing the structured data from the XML string.
      * @throws JSONException Thrown on error converting to a JSONArray
      */
     public static JSONArray toJSONArray(String string, boolean keepStrings) throws JSONException {
-        return (JSONArray)parse(new XMLTokener(string), true, null, keepStrings);
+        return (JSONArray) parse(new XMLTokener(string), true, null, keepStrings);
     }
 
 
@@ -277,18 +280,19 @@ public class JSONML {
      * attributes, then the second element will be JSONObject containing the
      * name/value pairs. If the tag contains children, then strings and
      * JSONArrays will represent the child content and tags.
-     * As opposed to toJSONArray this method does not attempt to convert 
-     * any text node or attribute value to any type 
+     * As opposed to toJSONArray this method does not attempt to convert
+     * any text node or attribute value to any type
      * but just leaves it as a string.
      * Comments, prologs, DTDs, and <[ [ ]]> are ignored.
-     * @param x An XMLTokener.
+     *
+     * @param x           An XMLTokener.
      * @param keepStrings If true, then values will not be coerced into boolean
-     *  or numeric values and will instead be left as strings
+     *                    or numeric values and will instead be left as strings
      * @return A JSONArray containing the structured data from the XML string.
      * @throws JSONException Thrown on error converting to a JSONArray
      */
     public static JSONArray toJSONArray(XMLTokener x, boolean keepStrings) throws JSONException {
-        return (JSONArray)parse(x, true, null, keepStrings);
+        return (JSONArray) parse(x, true, null, keepStrings);
     }
 
 
@@ -300,12 +304,13 @@ public class JSONML {
      * name/value pairs. If the tag contains children, then strings and
      * JSONArrays will represent the child content and tags.
      * Comments, prologs, DTDs, and <[ [ ]]> are ignored.
+     *
      * @param x An XMLTokener.
      * @return A JSONArray containing the structured data from the XML string.
      * @throws JSONException Thrown on error converting to a JSONArray
      */
     public static JSONArray toJSONArray(XMLTokener x) throws JSONException {
-        return (JSONArray)parse(x, true, null, false);
+        return (JSONArray) parse(x, true, null, false);
     }
 
 
@@ -316,17 +321,18 @@ public class JSONML {
      * the attributes will be in the JSONObject as properties. If the tag
      * contains children, the object will have a "childNodes" property which
      * will be an array of strings and JsonML JSONObjects.
-
+     * 

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * * @param string The XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject */ public static JSONObject toJSONObject(String string) throws JSONException { - return (JSONObject)parse(new XMLTokener(string), false, null, false); + return (JSONObject) parse(new XMLTokener(string), false, null, false); } - - + + /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as @@ -334,19 +340,20 @@ public class JSONML { * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - + *

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param string The XML source text. + * + * @param string The XML source text. * @param keepStrings If true, then values will not be coerced into boolean - * or numeric values and will instead be left as strings + * or numeric values and will instead be left as strings * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject */ public static JSONObject toJSONObject(String string, boolean keepStrings) throws JSONException { - return (JSONObject)parse(new XMLTokener(string), false, null, keepStrings); + return (JSONObject) parse(new XMLTokener(string), false, null, keepStrings); } - + /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject using the JsonML transform. Each XML tag is represented as @@ -354,14 +361,15 @@ public class JSONML { * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - + *

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * * @param x An XMLTokener of the XML source text. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject */ public static JSONObject toJSONObject(XMLTokener x) throws JSONException { - return (JSONObject)parse(x, false, null, false); + return (JSONObject) parse(x, false, null, false); } @@ -372,32 +380,34 @@ public class JSONML { * the attributes will be in the JSONObject as properties. If the tag * contains children, the object will have a "childNodes" property which * will be an array of strings and JsonML JSONObjects. - + *

* Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * @param x An XMLTokener of the XML source text. + * + * @param x An XMLTokener of the XML source text. * @param keepStrings If true, then values will not be coerced into boolean - * or numeric values and will instead be left as strings + * or numeric values and will instead be left as strings * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown on error converting to a JSONObject */ public static JSONObject toJSONObject(XMLTokener x, boolean keepStrings) throws JSONException { - return (JSONObject)parse(x, false, null, keepStrings); + return (JSONObject) parse(x, false, null, keepStrings); } /** * Reverse the JSONML transformation, making an XML text from a JSONArray. + * * @param ja A JSONArray. * @return An XML string. * @throws JSONException Thrown on error converting to a string */ public static String toString(JSONArray ja) throws JSONException { - int i; - JSONObject jo; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; + int i; + JSONObject jo; + int length; + Object object; + StringBuilder sb = new StringBuilder(); + String tagName; // Emit - * + *

* produces the string {"JSON": "Hello, World"}. *

* The texts produced by the toString methods strictly conform to @@ -102,59 +94,15 @@ import java.util.regex.Pattern; */ public class JSONObject { /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. + * 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. + * JSONObject.NULL.toString() returns "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() { - return this; - } - - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - public boolean equals(Object object) { - return object == null || object == this; - } - /** - * A Null object is equal to the null value and to itself. - * - * @return always returns 0. - */ - @Override - public int hashCode() { - return 0; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - @Override - public String toString() { - return "null"; - } - } - + public static final Object NULL = new Null(); /** - * Regular Expression Pattern that matches JSON Numbers. This is primarily used for - * output to guarantee that we are always writing valid JSON. + * Regular Expression Pattern that matches JSON Numbers. This is primarily used for + * output to guarantee that we are always writing valid JSON. */ static final Pattern NUMBER_PATTERN = Pattern.compile("-?(?:0|[1-9]\\d*)(?:\\.\\d+)?(?:[eE][+-]?\\d+)?"); @@ -163,22 +111,14 @@ public class JSONObject { */ private final Map map; - /** - * 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. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - /** * Construct an empty JSONObject. */ public JSONObject() { - // HashMap is used on purpose to ensure that elements are unordered by + // HashMap is used on purpose to ensure that elements are unordered by // the specification. - // JSON tends to be a portable transfer format to allows the container - // implementations to rearrange their items for a faster element + // JSON tends to be a portable transfer format to allows the container + // implementations to rearrange their items for a faster element // retrieval based on associative access. // Therefore, an implementation mustn't rely on the order of the item. this.map = new HashMap(); @@ -189,10 +129,8 @@ public class JSONObject { * strings is used to identify the keys that should be copied. Missing keys * are ignored. * - * @param jo - * A JSONObject. - * @param names - * An array of strings. + * @param jo A JSONObject. + * @param names An array of strings. */ public JSONObject(JSONObject jo, String[] names) { this(names.length); @@ -207,11 +145,9 @@ public class JSONObject { /** * Construct a JSONObject from a JSONTokener. * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(JSONTokener x) throws JSONException { this(); @@ -221,16 +157,16 @@ public class JSONObject { if (x.nextClean() != '{') { throw x.syntaxError("A JSONObject text must begin with '{'"); } - for (;;) { + for (; ; ) { c = x.nextClean(); switch (c) { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); } // The key is followed by ':'. @@ -239,9 +175,9 @@ public class JSONObject { if (c != ':') { throw x.syntaxError("Expected a ':' after a key"); } - + // Use syntaxError(..) to include error location - + if (key != null) { // Check if key exists if (this.opt(key) != null) { @@ -250,7 +186,7 @@ public class JSONObject { } // Only add value if non-null Object value = x.nextValue(); - if (value!=null) { + if (value != null) { this.put(key, value); } } @@ -258,17 +194,17 @@ public class JSONObject { // Pairs are separated by ','. switch (x.nextClean()) { - case ';': - case ',': - if (x.nextClean() == '}') { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); + default: + throw x.syntaxError("Expected a ',' or '}'"); } } } @@ -276,23 +212,20 @@ public class JSONObject { /** * Construct a JSONObject from a Map. * - * @param m - * A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - * If a value in the map is non-finite number. - * @throws NullPointerException - * If a key in the map is null + * @param m A map object that can be used to initialize the contents of + * the JSONObject. + * @throws JSONException If a value in the map is non-finite number. + * @throws NullPointerException If a key in the map is null */ public JSONObject(Map m) { if (m == null) { this.map = new HashMap(); } else { this.map = new HashMap(m.size()); - for (final Entry e : m.entrySet()) { - if(e.getKey() == null) { - throw new NullPointerException("Null key."); - } + for (final Entry e : m.entrySet()) { + if (e.getKey() == null) { + throw new NullPointerException("Null key."); + } final Object value = e.getValue(); if (value != null) { this.map.put(String.valueOf(e.getKey()), wrap(value)); @@ -350,14 +283,13 @@ public class JSONObject { * method from being serialized: *

      * @JSONPropertyName("FullName")
-     * @JSONPropertyIgnore 
+     * @JSONPropertyIgnore
      * public String getName() { return this.name; }
      * 
*

- * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. + * + * @param bean An object that has getter methods that should be used to make + * a JSONObject. */ public JSONObject(Object bean) { this(); @@ -371,14 +303,12 @@ public class JSONObject { * those keys in the object. If a key is not found or not visible, then it * will not be copied into the new 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. + * @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(Object object, String names[]) { + public JSONObject(Object object, String[] names) { this(names.length); Class c = object.getClass(); for (int i = 0; i < names.length; i += 1) { @@ -394,13 +324,11 @@ public class JSONObject { * Construct a JSONObject from a source JSON text string. This is the most * commonly used JSONObject constructor. * - * @param source - * A string beginning with { (left - * brace) and ending with } - *  (right brace). - * @exception JSONException - * If there is a syntax error in the source string or a - * duplicated key. + * @param source A string beginning with { (left + * brace) and ending with } + *  (right brace). + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. */ public JSONObject(String source) throws JSONException { this(new JSONTokener(source)); @@ -409,12 +337,9 @@ public class JSONObject { /** * Construct a JSONObject from a ResourceBundle. * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. */ public JSONObject(String baseName, Locale locale) throws JSONException { this(); @@ -448,91 +373,23 @@ public class JSONObject { } } } - + /** - * Constructor to specify an initial capacity of the internal map. Useful for library + * Constructor to specify an initial capacity of the internal map. Useful for library * internal calls where we know, or at least can best guess, how big this JSONObject * will be. - * + * * @param initialCapacity initial capacity of the internal map. */ - protected JSONObject(int initialCapacity){ + protected JSONObject(int initialCapacity) { this.map = new HashMap(initialCapacity); } - /** - * 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 a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, - value instanceof JSONArray ? new JSONArray().put(value) - : value); - } else if (object instanceof JSONArray) { - ((JSONArray) object).put(value); - } 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 with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the current value associated with - * the key is not a JSONArray. - * @throws NullPointerException - * If the key is null. - */ - public JSONObject append(String key, Object value) throws JSONException { - testValidity(value); - Object object = this.opt(key); - if (object == null) { - this.put(key, new JSONArray().put(value)); - } else if (object instanceof JSONArray) { - this.put(key, ((JSONArray) object).put(value)); - } else { - throw new JSONException("JSONObject[" + key - + "] is not a JSONArray."); - } - return this; - } - /** * Produce a string from a double. The string "null" will be returned if the * number is not finite. * - * @param d - * A double. + * @param d A double. * @return A String. */ public static String doubleToString(double d) { @@ -555,241 +412,10 @@ public class JSONObject { return string; } - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException { - if (key == null) { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if (object == null) { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, String key) throws JSONException { - E val = optEnum(clazz, key); - if(val==null) { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + quote(key) - + "] is not an enum of type " + quote(clazz.getSimpleName()) - + "."); - } - return val; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException { - Object object = this.get(key); - 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; - } - throw new JSONException("JSONObject[" + quote(key) - + "] is not a Boolean."); - } - - /** - * Get the BigInteger value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot - * be converted to BigInteger. - */ - public BigInteger getBigInteger(String key) throws JSONException { - Object object = this.get(key); - BigInteger ret = objectToBigInteger(object, null); - if (ret != null) { - return ret; - } - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigInteger (" + object + ")."); - } - - /** - * Get the BigDecimal value associated with a key. If the value is float or - * double, the the {@link BigDecimal#BigDecimal(double)} constructor will - * be used. See notes on the constructor for conversion issues that may - * arise. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value - * cannot be converted to BigDecimal. - */ - public BigDecimal getBigDecimal(String key) throws JSONException { - Object object = this.get(key); - BigDecimal ret = objectToBigDecimal(object, null); - if (ret != null) { - return ret; - } - throw new JSONException("JSONObject[" + quote(key) - + "] could not be converted to BigDecimal (" + object + ")."); - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @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(String key) throws JSONException { - return this.getNumber(key).doubleValue(); - } - - /** - * Get the float value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @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 float getFloat(String key) throws JSONException { - return this.getNumber(key).floatValue(); - } - - /** - * Get the Number value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @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 Number getNumber(String key) throws JSONException { - Object object = this.get(key); - try { - if (object instanceof Number) { - return (Number)object; - } - return stringToNumber(object.toString()); - } catch (Exception e) { - throw new JSONException("JSONObject[" + quote(key) - + "] is not a number.", e); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException { - return this.getNumber(key).intValue(); - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException { - Object object = this.get(key); - 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. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException { - Object object = this.get(key); - 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. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException { - return this.getNumber(key).longValue(); - } - /** * Get an array of field names from a JSONObject. * - * @param jo - * JSON object + * @param jo JSON object * @return An array of field names, or null if there are no names. */ public static String[] getNames(JSONObject jo) { @@ -802,8 +428,7 @@ public class JSONObject { /** * Get an array of public field names from an Object. * - * @param object - * object to read + * @param object object to read * @return An array of field names, or null if there are no names. */ public static String[] getNames(Object object) { @@ -823,14 +448,856 @@ public class JSONObject { return names; } + /** + * Produce a string from a Number. + * + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(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")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or is null. + * @return BigDecimal conversion of the original value, or the defaultValue if unable + * to convert. + */ + static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigDecimal) { + return (BigDecimal) val; + } + if (val instanceof BigInteger) { + return new BigDecimal((BigInteger) val); + } + if (val instanceof Double || val instanceof Float) { + final double d = ((Number) val).doubleValue(); + if (Double.isNaN(d)) { + return defaultValue; + } + return new BigDecimal(((Number) val).doubleValue()); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte) { + return new BigDecimal(((Number) val).longValue()); + } + // don't check if it's a string in case of unchecked Number subclasses + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * @param val value to convert + * @param defaultValue default value to return is the conversion doesn't work or is null. + * @return BigInteger conversion of the original value, or the defaultValue if unable + * to convert. + */ + static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { + if (NULL.equals(val)) { + return defaultValue; + } + if (val instanceof BigInteger) { + return (BigInteger) val; + } + if (val instanceof BigDecimal) { + return ((BigDecimal) val).toBigInteger(); + } + if (val instanceof Double || val instanceof Float) { + final double d = ((Number) val).doubleValue(); + if (Double.isNaN(d)) { + return defaultValue; + } + return new BigDecimal(d).toBigInteger(); + } + if (val instanceof Long || val instanceof Integer + || val instanceof Short || val instanceof Byte) { + return BigInteger.valueOf(((Number) val).longValue()); + } + // don't check if it's a string in case of unchecked Number subclasses + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + final String valStr = val.toString(); + if (isDecimalNotation(valStr)) { + return new BigDecimal(valStr).toBigInteger(); + } + return new BigInteger(valStr); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. + * + * @param type of the annotation + * @param m method to check + * @param annotationClass annotation to look for + * @return the {@link Annotation} if the annotation exists on the current method + * or one of it's super class definitions + */ + private static A getAnnotation(final Method m, final Class annotationClass) { + // if we have invalid data the result is null + if (m == null || annotationClass == null) { + return null; + } + + if (m.isAnnotationPresent(annotationClass)) { + return m.getAnnotation(annotationClass); + } + + // if we've already reached the Object class, return null; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return null; + } + + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + return getAnnotation(im, annotationClass); + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } + + try { + return getAnnotation( + c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), + annotationClass); + } catch (final SecurityException ex) { + return null; + } catch (final NoSuchMethodException ex) { + return null; + } + } + + /** + * Searches the class hierarchy to see if the method or it's super + * implementations and interfaces has the annotation. Returns the depth of the + * annotation in the hierarchy. + * + * @param type of the annotation + * @param m method to check + * @param annotationClass annotation to look for + * @return Depth of the annotation or -1 if the annotation is not on the method. + */ + private static int getAnnotationDepth(final Method m, final Class annotationClass) { + // if we have invalid data the result is -1 + if (m == null || annotationClass == null) { + return -1; + } + + if (m.isAnnotationPresent(annotationClass)) { + return 1; + } + + // if we've already reached the Object class, return -1; + Class c = m.getDeclaringClass(); + if (c.getSuperclass() == null) { + return -1; + } + + // check directly implemented interfaces for the method being checked + for (Class i : c.getInterfaces()) { + try { + Method im = i.getMethod(m.getName(), m.getParameterTypes()); + int d = getAnnotationDepth(im, annotationClass); + if (d > 0) { + // since the annotation was on the interface, add 1 + return d + 1; + } + } catch (final SecurityException ex) { + continue; + } catch (final NoSuchMethodException ex) { + continue; + } + } + + try { + int d = getAnnotationDepth( + c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), + annotationClass); + if (d > 0) { + // since the annotation was on the superclass, add 1 + return d + 1; + } + return -1; + } catch (final SecurityException ex) { + return -1; + } catch (final NoSuchMethodException ex) { + return -1; + } + } + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within </, producing + * <\/, allowing JSON text to be delivered in HTML. In JSON text, a + * string cannot contain a control character or an unescaped quote or + * backslash. + * + * @param string A String + * @return A String correctly formatted for insertion in a JSON text. + */ + public static String quote(String string) { + StringWriter sw = new StringWriter(); + synchronized (sw.getBuffer()) { + try { + return quote(string, sw).toString(); + } catch (IOException ignored) { + // will never happen - we are writing to a string writer + return ""; + } + } + } + + public static Writer quote(String string, Writer w) throws IOException { + if (string == null || string.isEmpty()) { + w.write("\"\""); + return w; + } + + char b; + char c = 0; + String hhhh; + int i; + int len = string.length(); + + w.write('"'); + for (i = 0; i < len; i += 1) { + b = c; + c = string.charAt(i); + switch (c) { + case '\\': + case '"': + w.write('\\'); + w.write(c); + break; + case '/': + if (b == '<') { + w.write('\\'); + } + w.write(c); + break; + case '\b': + w.write("\\b"); + break; + case '\t': + w.write("\\t"); + break; + case '\n': + w.write("\\n"); + break; + case '\f': + w.write("\\f"); + break; + case '\r': + w.write("\\r"); + break; + default: + 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 { + w.write(c); + } + } + } + w.write('"'); + return w; + } + + /** + * Tests if the value should be tried as a decimal. It makes no test if there are actual digits. + * + * @param val value to test + * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. + */ + protected static boolean isDecimalNotation(final String val) { + return val.indexOf('.') > -1 || val.indexOf('e') > -1 + || val.indexOf('E') > -1 || "-0".equals(val); + } + + /** + * Converts a string to a number using the narrowest possible type. Possible + * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. + * When a Double is returned, it should always be a valid Double and not NaN or +-infinity. + * + * @param val value to convert + * @return Number representation of the value. + * @throws NumberFormatException thrown if the value is not a valid number. A public + * caller should catch this and wrap it in a {@link JSONException} if applicable. + */ + protected static Number stringToNumber(final String val) throws NumberFormatException { + char initial = val.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + // decimal representation + if (isDecimalNotation(val)) { + // quick dirty way to see if we need a BigDecimal instead of a Double + // this only handles some cases of overflow or underflow + if (val.length() > 14) { + return new BigDecimal(val); + } + final Double d = Double.valueOf(val); + if (d.isInfinite() || d.isNaN()) { + // if we can't parse it as a double, go up to BigDecimal + // this is probably due to underflow like 4.32e-678 + // or overflow like 4.65e5324. The size of the string is small + // but can't be held in a Double. + return new BigDecimal(val); + } + return d; + } + // integer representation. + // This will narrow any values to the smallest reasonable Object representation + // (Integer, Long, or BigInteger) + + // string version + // The compare string length method reduces GC, + // but leads to smaller integers being placed in larger wrappers even though not + // needed. i.e. 1,000,000,000 -> Long even though it's an Integer + // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long + //if(val.length()<=9){ + // return Integer.valueOf(val); + //} + //if(val.length()<=18){ + // return Long.valueOf(val); + //} + //return new BigInteger(val); + + // BigInteger version: We use a similar bitLenth compare as + // BigInteger#intValueExact uses. Increases GC, but objects hold + // only what they need. i.e. Less runtime overhead if the value is + // long lived. Which is the better tradeoff? This is closer to what's + // in stringToValue. + BigInteger bi = new BigInteger(val); + if (bi.bitLength() <= 31) { + return Integer.valueOf(bi.intValue()); + } + if (bi.bitLength() <= 63) { + return Long.valueOf(bi.longValue()); + } + return bi; + } + throw new NumberFormatException("val [" + val + "] is not a valid number."); + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * + * @param string A String. can not be null. + * @return A simple JSON value. + * @throws NullPointerException Thrown if the string is null. + */ + // Changes to this method must be copied to the corresponding method in + // the XML class to keep full support for Android + public static Object stringToValue(String string) { + if ("".equals(string)) { + return string; + } + + // check JSON key words true/false/null + 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. If a number cannot be + * produced, then the value will just be a string. + */ + + char initial = string.charAt(0); + if ((initial >= '0' && initial <= '9') || initial == '-') { + try { + // if we want full Big Number support the contents of this + // `try` block can be replaced with: + // return stringToNumber(string); + if (isDecimalNotation(string)) { + Double d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()) { + return d; + } + } else { + Long myLong = Long.valueOf(string); + if (string.equals(myLong.toString())) { + if (myLong.longValue() == myLong.intValue()) { + return Integer.valueOf(myLong.intValue()); + } + return myLong; + } + } + } catch (Exception ignore) { + } + } + return string; + } + + /** + * Throw an exception if the object is a NaN or infinite number. + * + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(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 not contain a toJSONString method (which is the most + * common case), then a text will be produced by other means. If the value + * is an array or Collection, then a JSONArray will be made from it and its + * toJSONString method will be called. If the value is a MAP, then a + * JSONObject will be made from it and its toJSONString method will be + * called. Otherwise, the value's toString method will be called, and the + * result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @return a printable, displayable, transmittable representation of the + * object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + // moves the implementation to JSONWriter as: + // 1. It makes more sense to be part of the writer class + // 2. For Android support this method is not available. By implementing it in the Writer + // Android users can use the writer with the built in Android JSONObject implementation. + return JSONWriter.valueToString(value); + } + + /** + * 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 al) then it is already wrapped. Otherwise, if it comes from + * one of the java packages, turn it into a string. And if it doesn't, try + * to wrap it in a JSONObject. If the wrapping fails, then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray + || NULL.equals(object) || object instanceof JSONString + || object instanceof Byte || object instanceof Character + || object instanceof Short || object instanceof Integer + || object instanceof Long || object instanceof Boolean + || object instanceof Float || object instanceof Double + || object instanceof String || object instanceof BigInteger + || object instanceof BigDecimal || object instanceof Enum) { + return object; + } + + if (object instanceof Collection) { + Collection coll = (Collection) object; + return new JSONArray(coll); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + Map map = (Map) object; + return new JSONObject(map); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? objectPackage + .getName() : ""; + if (objectPackageName.startsWith("java.") + || objectPackageName.startsWith("javax.") + || object.getClass().getClassLoader() == null) { + return object.toString(); + } + return new JSONObject(object); + } catch (Exception exception) { + return null; + } + } + + static final Writer writeValue(Writer writer, Object value, + int indentFactor, int indent) throws JSONException, IOException { + if (value == null || value.equals(null)) { + writer.write("null"); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else if (value instanceof Number) { + // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary + final String numberAsString = numberToString((Number) value); + if (NUMBER_PATTERN.matcher(numberAsString).matches()) { + writer.write(numberAsString); + } else { + // The Number value is not a valid JSON number. + // Instead we will quote it as a string + quote(numberAsString, writer); + } + } else if (value instanceof Boolean) { + writer.write(value.toString()); + } else if (value instanceof Enum) { + writer.write(quote(((Enum) value).name())); + } else if (value instanceof JSONObject) { + ((JSONObject) value).write(writer, indentFactor, indent); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer, indentFactor, indent); + } else if (value instanceof Map) { + Map map = (Map) value; + new JSONObject(map).write(writer, indentFactor, indent); + } else if (value instanceof Collection) { + Collection coll = (Collection) value; + new JSONArray(coll).write(writer, indentFactor, indent); + } else if (value.getClass().isArray()) { + new JSONArray(value).write(writer, indentFactor, indent); + } else { + quote(value.toString(), writer); + } + return writer; + } + + static final void indent(Writer writer, 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 a JSONArray, then the new value is appended to it. In + * contrast, the put method replaces the previous value. + *

+ * If only one value is accumulated that is not a JSONArray, then the result + * will be the same as using put. But if multiple values are accumulated, + * then the result will be like append. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, + value instanceof JSONArray ? new JSONArray().put(value) + : value); + } else if (object instanceof JSONArray) { + ((JSONArray) object).put(value); + } 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 with a JSONArray, then the value parameter is appended to it. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is non-finite number or if the current value associated with + * the key is not a JSONArray. + * @throws NullPointerException If the key is null. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + this.put(key, ((JSONArray) object).put(value)); + } else { + throw new JSONException("JSONObject[" + key + + "] is not a JSONArray."); + } + return this; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** + * Get the enum value associated with a key. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. + */ + public > E getEnum(Class clazz, String key) throws JSONException { + E val = optEnum(clazz, key); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw new JSONException("JSONObject[" + quote(key) + + "] is not an enum of type " + quote(clazz.getSimpleName()) + + "."); + } + return val; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or + * "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object object = this.get(key); + 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; + } + throw new JSONException("JSONObject[" + quote(key) + + "] is not a Boolean."); + } + + /** + * Get the BigInteger value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot + * be converted to BigInteger. + */ + public BigInteger getBigInteger(String key) throws JSONException { + Object object = this.get(key); + BigInteger ret = objectToBigInteger(object, null); + if (ret != null) { + return ret; + } + throw new JSONException("JSONObject[" + quote(key) + + "] could not be converted to BigInteger (" + object + ")."); + } + + /** + * Get the BigDecimal value associated with a key. If the value is float or + * double, the the {@link BigDecimal#BigDecimal(double)} constructor will + * be used. See notes on the constructor for conversion issues that may + * arise. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value + * cannot be converted to BigDecimal. + */ + public BigDecimal getBigDecimal(String key) throws JSONException { + Object object = this.get(key); + BigDecimal ret = objectToBigDecimal(object, null); + if (ret != null) { + return ret; + } + throw new JSONException("JSONObject[" + quote(key) + + "] could not be converted to BigDecimal (" + object + ")."); + } + + /** + * Get the double value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @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(String key) throws JSONException { + return this.getNumber(key).doubleValue(); + } + + /** + * Get the float value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @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 float getFloat(String key) throws JSONException { + return this.getNumber(key).floatValue(); + } + + /** + * Get the Number value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @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 Number getNumber(String key) throws JSONException { + Object object = this.get(key); + try { + if (object instanceof Number) { + return (Number) object; + } + return stringToNumber(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + + "] is not a number.", e); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to an integer. + */ + public int getInt(String key) throws JSONException { + return this.getNumber(key).intValue(); + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = this.get(key); + 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. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = this.get(key); + 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. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to a long. + */ + public long getLong(String key) throws JSONException { + return this.getNumber(key).longValue(); + } + /** * Get the string associated with a key. * - * @param key - * A key string. + * @param key A key string. * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. + * @throws JSONException if there is no string value for the key. */ public String getString(String key) throws JSONException { Object object = this.get(key); @@ -843,8 +1310,7 @@ public class JSONObject { /** * Determine if the JSONObject contains a specific key. * - * @param key - * A key string. + * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { @@ -856,21 +1322,19 @@ public class JSONObject { * 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. * - * @param key - * A key string. + * @param key A key string. * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. + * @throws JSONException If there is already a property with this name that is not an + * Integer, Long, Double, or Float. */ public JSONObject increment(String key) throws JSONException { Object value = this.opt(key); if (value == null) { this.put(key, 1); } else if (value instanceof BigInteger) { - this.put(key, ((BigInteger)value).add(BigInteger.ONE)); + this.put(key, ((BigInteger) value).add(BigInteger.ONE)); } else if (value instanceof BigDecimal) { - this.put(key, ((BigDecimal)value).add(BigDecimal.ONE)); + this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); } else if (value instanceof Integer) { this.put(key, ((Integer) value).intValue() + 1); } else if (value instanceof Long) { @@ -889,10 +1353,9 @@ public class JSONObject { * Determine if the value associated with the key is null or if there is no * value. * - * @param key - * A key string. + * @param key A key string. * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. + * is the JSONObject.NULL object. */ public boolean isNull(String key) { return JSONObject.NULL.equals(this.opt(key)); @@ -902,9 +1365,8 @@ public class JSONObject { * Get an enumeration of the keys of the JSONObject. Modifying this key Set will also * modify the JSONObject. Use with caution. * - * @see Set#iterator() - * * @return An iterator of the keys. + * @see Set#iterator() */ public Iterator keys() { return this.keySet().iterator(); @@ -914,9 +1376,8 @@ public class JSONObject { * Get a set of keys of the JSONObject. Modifying this key Set will also modify the * JSONObject. Use with caution. * - * @see Map#keySet() - * * @return A keySet. + * @see Map#keySet() */ public Set keySet() { return this.map.keySet(); @@ -924,15 +1385,14 @@ public class JSONObject { /** * Get a set of entries of the JSONObject. These are raw values and may not - * match what is returned by the JSONObject get* and opt* functions. Modifying + * match what is returned by the JSONObject get* and opt* functions. Modifying * the returned EntrySet or the Entry objects contained therein will modify the * backing JSONObject. This does not return a clone or a read-only view. - * + *

* Use with caution. * - * @see Map#entrySet() - * * @return An Entry Set + * @see Map#entrySet() */ protected Set> entrySet() { return this.map.entrySet(); @@ -961,50 +1421,19 @@ public class JSONObject { * JSONObject. * * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. + * is empty. */ public JSONArray names() { - if(this.map.isEmpty()) { - return null; - } + if (this.map.isEmpty()) { + return null; + } return new JSONArray(this.map.keySet()); } - /** - * Produce a string from a Number. - * - * @param number - * A Number - * @return A String. - * @throws JSONException - * If n is a non-finite number. - */ - public static String numberToString(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")) { - string = string.substring(0, string.length() - 1); - } - if (string.endsWith(".")) { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - /** * Get an optional value associated with a key. * - * @param key - * A key string. + * @param key A key string. * @return An object which is the value, or null if there is no value. */ public Object opt(String key) { @@ -1013,13 +1442,10 @@ public class JSONObject { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. * @return The enum value associated with the key or null if not found */ public > E optEnum(Class clazz, String key) { @@ -1028,17 +1454,13 @@ public class JSONObject { /** * Get the enum value associated with a key. - * - * @param - * Enum Type - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @param defaultValue - * The default in case the value is not found + * + * @param Enum Type + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @param defaultValue The default in case the value is not found * @return The enum value associated with the key or defaultValue - * if the value is not found or cannot be assigned to clazz + * if the value is not found or cannot be assigned to clazz */ public > E optEnum(Class clazz, String key, E defaultValue) { try { @@ -1064,8 +1486,7 @@ public class JSONObject { * 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". * - * @param key - * A key string. + * @param key A key string. * @return The truth. */ public boolean optBoolean(String key) { @@ -1077,10 +1498,8 @@ public class JSONObject { * defaultValue if there is no such key, or if it is not a Boolean or the * String "true" or "false" (case insensitive). * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return The truth. */ public boolean optBoolean(String key, boolean defaultValue) { @@ -1088,7 +1507,7 @@ public class JSONObject { if (NULL.equals(val)) { return defaultValue; } - if (val instanceof Boolean){ + if (val instanceof Boolean) { return ((Boolean) val).booleanValue(); } try { @@ -1107,10 +1526,8 @@ public class JSONObject { * constructor will be used. See notes on the constructor for conversion * issues that may arise. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { @@ -1118,50 +1535,13 @@ public class JSONObject { return objectToBigDecimal(val, defaultValue); } - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @return BigDecimal conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue) { - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigDecimal){ - return (BigDecimal) val; - } - if (val instanceof BigInteger){ - return new BigDecimal((BigInteger) val); - } - if (val instanceof Double || val instanceof Float){ - final double d = ((Number) val).doubleValue(); - if(Double.isNaN(d)) { - return defaultValue; - } - return new BigDecimal(((Number) val).doubleValue()); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return new BigDecimal(((Number) val).longValue()); - } - // don't check if it's a string in case of unchecked Number subclasses - try { - return new BigDecimal(val.toString()); - } catch (Exception e) { - return defaultValue; - } - } - /** * Get an optional BigInteger 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. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public BigInteger optBigInteger(String key, BigInteger defaultValue) { @@ -1169,57 +1549,12 @@ public class JSONObject { return objectToBigInteger(val, defaultValue); } - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @return BigInteger conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigInteger objectToBigInteger(Object val, BigInteger defaultValue) { - if (NULL.equals(val)) { - return defaultValue; - } - if (val instanceof BigInteger){ - return (BigInteger) val; - } - if (val instanceof BigDecimal){ - return ((BigDecimal) val).toBigInteger(); - } - if (val instanceof Double || val instanceof Float){ - final double d = ((Number) val).doubleValue(); - if(Double.isNaN(d)) { - return defaultValue; - } - return new BigDecimal(d).toBigInteger(); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return BigInteger.valueOf(((Number) val).longValue()); - } - // don't check if it's a string in case of unchecked Number subclasses - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - final String valStr = val.toString(); - if(isDecimalNotation(valStr)) { - return new BigDecimal(valStr).toBigInteger(); - } - return new BigInteger(valStr); - } catch (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. * - * @param key - * A string which is the key. + * @param key A string which is the key. * @return An object which is the value. */ public double optDouble(String key) { @@ -1231,10 +1566,8 @@ public class JSONObject { * 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. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public double optDouble(String key, double defaultValue) { @@ -1254,8 +1587,7 @@ public class JSONObject { * if there is no value for the index, or if the value is not a number and * cannot be converted to a number. * - * @param key - * A key string. + * @param key A key string. * @return The value. */ public float optFloat(String key) { @@ -1267,10 +1599,8 @@ public class JSONObject { * 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. * - * @param key - * A key string. - * @param defaultValue - * The default value. + * @param key A key string. + * @param defaultValue The default value. * @return The value. */ public float optFloat(String key, float defaultValue) { @@ -1290,8 +1620,7 @@ public class JSONObject { * 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. * - * @param key - * A key string. + * @param key A key string. * @return An object which is the value. */ public int optInt(String key) { @@ -1303,10 +1632,8 @@ public class JSONObject { * 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. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public int optInt(String key, int defaultValue) { @@ -1321,8 +1648,7 @@ public class JSONObject { * 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. * - * @param key - * A key string. + * @param key A key string. * @return A JSONArray which is the value. */ public JSONArray optJSONArray(String key) { @@ -1334,8 +1660,7 @@ public class JSONObject { * 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. * - * @param key - * A key string. + * @param key A key string. * @return A JSONObject which is the value. */ public JSONObject optJSONObject(String key) { @@ -1348,8 +1673,7 @@ public class JSONObject { * 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. * - * @param key - * A key string. + * @param key A key string. * @return An object which is the value. */ public long optLong(String key) { @@ -1361,10 +1685,8 @@ public class JSONObject { * 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. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public long optLong(String key, long defaultValue) { @@ -1372,18 +1694,17 @@ public class JSONObject { if (val == null) { return defaultValue; } - + return val.longValue(); } - + /** * Get an optional {@link Number} value associated with a key, or null * 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 ({@link BigDecimal}). This method * would be used in cases where type coercion of the number value is unwanted. * - * @param key - * A key string. + * @param key A key string. * @return An object which is the value. */ public Number optNumber(String key) { @@ -1396,10 +1717,8 @@ public class JSONObject { * an attempt will be made to evaluate it as a number. This method * would be used in cases where type coercion of the number value is unwanted. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return An object which is the value. */ public Number optNumber(String key, Number defaultValue) { @@ -1407,24 +1726,23 @@ public class JSONObject { if (NULL.equals(val)) { return defaultValue; } - if (val instanceof Number){ + if (val instanceof Number) { return (Number) val; } - + try { return stringToNumber(val.toString()); } catch (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. * - * @param key - * A key string. + * @param key A key string. * @return A string which is the value. */ public String optString(String key) { @@ -1435,10 +1753,8 @@ public class JSONObject { * Get an optional string associated with a key. It returns the defaultValue * if there is no such key. * - * @param key - * A key string. - * @param defaultValue - * The default. + * @param key A key string. + * @param defaultValue The default. * @return A string which is the value. */ public String optString(String key, String defaultValue) { @@ -1450,10 +1766,8 @@ public class JSONObject { * Populates the internal map of the JSONObject with the bean properties. The * bean can not be recursive. * + * @param bean the bean * @see JSONObject#JSONObject(Object) - * - * @param bean - * the bean */ private void populateMap(Object bean) { Class klass = bean.getClass(); @@ -1537,133 +1851,14 @@ public class JSONObject { return key; } - /** - * Searches the class hierarchy to see if the method or it's super - * implementations and interfaces has the annotation. - * - * @param - * type of the annotation - * - * @param m - * method to check - * @param annotationClass - * annotation to look for - * @return the {@link Annotation} if the annotation exists on the current method - * or one of it's super class definitions - */ - private static A getAnnotation(final Method m, final Class annotationClass) { - // if we have invalid data the result is null - if (m == null || annotationClass == null) { - return null; - } - - if (m.isAnnotationPresent(annotationClass)) { - return m.getAnnotation(annotationClass); - } - - // if we've already reached the Object class, return null; - Class c = m.getDeclaringClass(); - if (c.getSuperclass() == null) { - return null; - } - - // check directly implemented interfaces for the method being checked - for (Class i : c.getInterfaces()) { - try { - Method im = i.getMethod(m.getName(), m.getParameterTypes()); - return getAnnotation(im, annotationClass); - } catch (final SecurityException ex) { - continue; - } catch (final NoSuchMethodException ex) { - continue; - } - } - - try { - return getAnnotation( - c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), - annotationClass); - } catch (final SecurityException ex) { - return null; - } catch (final NoSuchMethodException ex) { - return null; - } - } - - /** - * Searches the class hierarchy to see if the method or it's super - * implementations and interfaces has the annotation. Returns the depth of the - * annotation in the hierarchy. - * - * @param - * type of the annotation - * - * @param m - * method to check - * @param annotationClass - * annotation to look for - * @return Depth of the annotation or -1 if the annotation is not on the method. - */ - private static int getAnnotationDepth(final Method m, final Class annotationClass) { - // if we have invalid data the result is -1 - if (m == null || annotationClass == null) { - return -1; - } - - if (m.isAnnotationPresent(annotationClass)) { - return 1; - } - - // if we've already reached the Object class, return -1; - Class c = m.getDeclaringClass(); - if (c.getSuperclass() == null) { - return -1; - } - - // check directly implemented interfaces for the method being checked - for (Class i : c.getInterfaces()) { - try { - Method im = i.getMethod(m.getName(), m.getParameterTypes()); - int d = getAnnotationDepth(im, annotationClass); - if (d > 0) { - // since the annotation was on the interface, add 1 - return d + 1; - } - } catch (final SecurityException ex) { - continue; - } catch (final NoSuchMethodException ex) { - continue; - } - } - - try { - int d = getAnnotationDepth( - c.getSuperclass().getMethod(m.getName(), m.getParameterTypes()), - annotationClass); - if (d > 0) { - // since the annotation was on the superclass, add 1 - return d + 1; - } - return -1; - } catch (final SecurityException ex) { - return -1; - } catch (final NoSuchMethodException ex) { - return -1; - } - } - /** * Put a key/boolean pair in the JSONObject. * - * @param key - * A key string. - * @param value - * A boolean which is the value. + * @param key A key string. + * @param value A boolean which is the value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, boolean value) throws JSONException { return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); @@ -1673,15 +1868,11 @@ public class JSONObject { * Put a key/value pair in the JSONObject, where the value will be a * JSONArray which is produced from a Collection. * - * @param key - * A key string. - * @param value - * A Collection value. + * @param key A key string. + * @param value A Collection value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, Collection value) throws JSONException { return this.put(key, new JSONArray(value)); @@ -1690,32 +1881,24 @@ public class JSONObject { /** * Put a key/double pair in the JSONObject. * - * @param key - * A key string. - * @param value - * A double which is the value. + * @param key A key string. + * @param value A double which is the value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, double value) throws JSONException { return this.put(key, Double.valueOf(value)); } - + /** * Put a key/float pair in the JSONObject. * - * @param key - * A key string. - * @param value - * A float which is the value. + * @param key A key string. + * @param value A float which is the value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, float value) throws JSONException { return this.put(key, Float.valueOf(value)); @@ -1724,15 +1907,11 @@ public class JSONObject { /** * Put a key/int pair in the JSONObject. * - * @param key - * A key string. - * @param value - * An int which is the value. + * @param key A key string. + * @param value An int which is the value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, int value) throws JSONException { return this.put(key, Integer.valueOf(value)); @@ -1741,15 +1920,11 @@ public class JSONObject { /** * Put a key/long pair in the JSONObject. * - * @param key - * A key string. - * @param value - * A long which is the value. + * @param key A key string. + * @param value A long which is the value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, long value) throws JSONException { return this.put(key, Long.valueOf(value)); @@ -1759,15 +1934,11 @@ public class JSONObject { * Put a key/value pair in the JSONObject, where the value will be a * JSONObject which is produced from a Map. * - * @param key - * A key string. - * @param value - * A Map value. + * @param key A key string. + * @param value A Map value. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, Map value) throws JSONException { return this.put(key, new JSONObject(value)); @@ -1777,17 +1948,13 @@ public class JSONObject { * 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. * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. * @return this. - * @throws JSONException - * If the value is non-finite number. - * @throws NullPointerException - * If the key is null. + * @throws JSONException If the value is non-finite number. + * @throws NullPointerException If the key is null. */ public JSONObject put(String key, Object value) throws JSONException { if (key == null) { @@ -1807,13 +1974,10 @@ public class JSONObject { * are both non-null, and only if there is not already a member with that * name. * - * @param key - * key to insert into - * @param value - * value to insert + * @param key key to insert into + * @param value value to insert * @return this. - * @throws JSONException - * if the key is a duplicate + * @throws JSONException if the key is a duplicate */ public JSONObject putOnce(String key, Object value) throws JSONException { if (key != null && value != null) { @@ -1829,15 +1993,12 @@ public class JSONObject { * Put a key/value pair in the JSONObject, but only if the key and the value * are both non-null. * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. * @return this. - * @throws JSONException - * If the value is a non-finite number. + * @throws JSONException If the value is a non-finite number. */ public JSONObject putOpt(String key, Object value) throws JSONException { if (key != null && value != null) { @@ -1847,7 +2008,7 @@ public class JSONObject { } /** - * Creates a JSONPointer using an initialization string and tries to + * Creates a JSONPointer using an initialization string and tries to * match it to an item within this JSONObject. For example, given a * JSONObject initialized with this document: *

@@ -1855,21 +2016,22 @@ public class JSONObject {
      *     "a":{"b":"c"}
      * }
      * 
- * and this JSONPointer string: + * and this JSONPointer string: *
      * "/a/b"
      * 
* Then this method will return the String "c". * A JSONPointerException may be thrown from code called by this method. - * + * * @param jsonPointer string that can be used to create a JSONPointer * @return the item matched by the JSONPointer, otherwise null */ public Object query(String jsonPointer) { return query(new JSONPointer(jsonPointer)); } + /** - * Uses a user initialized JSONPointer and tries to + * Uses a user initialized JSONPointer and tries to * match it to an item within this JSONObject. For example, given a * JSONObject initialized with this document: *
@@ -1877,36 +2039,36 @@ public class JSONObject {
      *     "a":{"b":"c"}
      * }
      * 
- * and this JSONPointer: + * and this JSONPointer: *
      * "/a/b"
      * 
* Then this method will return the String "c". * A JSONPointerException may be thrown from code called by this method. - * + * * @param jsonPointer string that can be used to create a JSONPointer * @return the item matched by the JSONPointer, otherwise null */ public Object query(JSONPointer jsonPointer) { return jsonPointer.queryFrom(this); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer the string representation of the JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax */ public Object optQuery(String jsonPointer) { - return optQuery(new JSONPointer(jsonPointer)); + return optQuery(new JSONPointer(jsonPointer)); } - + /** * Queries and returns a value from this object using {@code jsonPointer}, or * returns null if the query fails due to a missing key. - * + * * @param jsonPointer The JSON pointer * @return the queried value or {@code null} * @throws IllegalArgumentException if {@code jsonPointer} has invalid syntax @@ -1919,95 +2081,12 @@ public class JSONObject { } } - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within </, producing - * <\/, allowing JSON text to be delivered in HTML. In JSON text, a - * string cannot contain a control character or an unescaped quote or - * backslash. - * - * @param string - * A String - * @return A String correctly formatted for insertion in a JSON text. - */ - public static String quote(String string) { - StringWriter sw = new StringWriter(); - synchronized (sw.getBuffer()) { - try { - return quote(string, sw).toString(); - } catch (IOException ignored) { - // will never happen - we are writing to a string writer - return ""; - } - } - } - - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.isEmpty()) { - w.write("\"\""); - return w; - } - - char b; - char c = 0; - String hhhh; - int i; - int len = string.length(); - - w.write('"'); - for (i = 0; i < len; i += 1) { - b = c; - c = string.charAt(i); - switch (c) { - case '\\': - case '"': - w.write('\\'); - w.write(c); - break; - case '/': - if (b == '<') { - w.write('\\'); - } - w.write(c); - break; - case '\b': - w.write("\\b"); - break; - case '\t': - w.write("\\t"); - break; - case '\n': - w.write("\\n"); - break; - case '\f': - w.write("\\f"); - break; - case '\r': - w.write("\\r"); - break; - default: - 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 { - w.write(c); - } - } - } - w.write('"'); - return w; - } - /** * Remove a name and its value, if present. * - * @param key - * The name to be removed. + * @param key The name to be removed. * @return The value that was associated with the name, or null if there was - * no value. + * no value. */ public Object remove(String key) { return this.map.remove(key); @@ -2026,25 +2105,25 @@ public class JSONObject { if (!(other instanceof JSONObject)) { return false; } - if (!this.keySet().equals(((JSONObject)other).keySet())) { + if (!this.keySet().equals(((JSONObject) other).keySet())) { return false; } - for (final Entry entry : this.entrySet()) { + for (final Entry entry : this.entrySet()) { String name = entry.getKey(); Object valueThis = entry.getValue(); - Object valueOther = ((JSONObject)other).get(name); - if(valueThis == valueOther) { - continue; + Object valueOther = ((JSONObject) other).get(name); + if (valueThis == valueOther) { + continue; } - if(valueThis == null) { - return false; + if (valueThis == null) { + return false; } if (valueThis instanceof JSONObject) { - if (!((JSONObject)valueThis).similar(valueOther)) { + if (!((JSONObject) valueThis).similar(valueOther)) { return false; } } else if (valueThis instanceof JSONArray) { - if (!((JSONArray)valueThis).similar(valueOther)) { + if (!((JSONArray) valueThis).similar(valueOther)) { return false; } } else if (!valueThis.equals(valueOther)) { @@ -2056,175 +2135,15 @@ public class JSONObject { return false; } } - - /** - * Tests if the value should be tried as a decimal. It makes no test if there are actual digits. - * - * @param val value to test - * @return true if the string is "-0" or if it contains '.', 'e', or 'E', false otherwise. - */ - protected static boolean isDecimalNotation(final String val) { - return val.indexOf('.') > -1 || val.indexOf('e') > -1 - || val.indexOf('E') > -1 || "-0".equals(val); - } - - /** - * Converts a string to a number using the narrowest possible type. Possible - * returns for this function are BigDecimal, Double, BigInteger, Long, and Integer. - * When a Double is returned, it should always be a valid Double and not NaN or +-infinity. - * - * @param val value to convert - * @return Number representation of the value. - * @throws NumberFormatException thrown if the value is not a valid number. A public - * caller should catch this and wrap it in a {@link JSONException} if applicable. - */ - protected static Number stringToNumber(final String val) throws NumberFormatException { - char initial = val.charAt(0); - if ((initial >= '0' && initial <= '9') || initial == '-') { - // decimal representation - if (isDecimalNotation(val)) { - // quick dirty way to see if we need a BigDecimal instead of a Double - // this only handles some cases of overflow or underflow - if (val.length()>14) { - return new BigDecimal(val); - } - final Double d = Double.valueOf(val); - if (d.isInfinite() || d.isNaN()) { - // if we can't parse it as a double, go up to BigDecimal - // this is probably due to underflow like 4.32e-678 - // or overflow like 4.65e5324. The size of the string is small - // but can't be held in a Double. - return new BigDecimal(val); - } - return d; - } - // integer representation. - // This will narrow any values to the smallest reasonable Object representation - // (Integer, Long, or BigInteger) - - // string version - // The compare string length method reduces GC, - // but leads to smaller integers being placed in larger wrappers even though not - // needed. i.e. 1,000,000,000 -> Long even though it's an Integer - // 1,000,000,000,000,000,000 -> BigInteger even though it's a Long - //if(val.length()<=9){ - // return Integer.valueOf(val); - //} - //if(val.length()<=18){ - // return Long.valueOf(val); - //} - //return new BigInteger(val); - - // BigInteger version: We use a similar bitLenth compare as - // BigInteger#intValueExact uses. Increases GC, but objects hold - // only what they need. i.e. Less runtime overhead if the value is - // long lived. Which is the better tradeoff? This is closer to what's - // in stringToValue. - BigInteger bi = new BigInteger(val); - if(bi.bitLength()<=31){ - return Integer.valueOf(bi.intValue()); - } - if(bi.bitLength()<=63){ - return Long.valueOf(bi.longValue()); - } - return bi; - } - throw new NumberFormatException("val ["+val+"] is not a valid number."); - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param string - * A String. can not be null. - * @return A simple JSON value. - * @throws NullPointerException - * Thrown if the string is null. - */ - // Changes to this method must be copied to the corresponding method in - // the XML class to keep full support for Android - public static Object stringToValue(String string) { - if ("".equals(string)) { - return string; - } - - // check JSON key words true/false/null - 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. If a number cannot be - * produced, then the value will just be a string. - */ - - char initial = string.charAt(0); - if ((initial >= '0' && initial <= '9') || initial == '-') { - try { - // if we want full Big Number support the contents of this - // `try` block can be replaced with: - // return stringToNumber(string); - if (isDecimalNotation(string)) { - Double d = Double.valueOf(string); - if (!d.isInfinite() && !d.isNaN()) { - return d; - } - } else { - Long myLong = Long.valueOf(string); - if (string.equals(myLong.toString())) { - if (myLong.longValue() == myLong.intValue()) { - return Integer.valueOf(myLong.intValue()); - } - return myLong; - } - } - } catch (Exception ignore) { - } - } - return string; - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. - */ - public static void testValidity(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."); - } - } - } - } /** * Produce a JSONArray containing the values of the members of this * JSONObject. * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. + * @param names A JSONArray containing a list of key strings. This determines + * the sequence of the values in the result. * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. + * @throws JSONException If any of the values are non-finite numbers. */ public JSONArray toJSONArray(JSONArray names) throws JSONException { if (names == null || names.isEmpty()) { @@ -2244,11 +2163,11 @@ public class JSONObject { *

* Warning: This method assumes that the data structure is acyclical. * - * + * * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). + * of the object, beginning with { (left + * brace) and ending with } (right + * brace). */ @Override public String toString() { @@ -2261,11 +2180,11 @@ public class JSONObject { /** * Make a pretty-printed JSON text of this JSONObject. - * + * *

If indentFactor > 0 and the {@link JSONObject} * has only one key, then the object will be output on a single line: *

{@code {"key": 1}}
- * + * *

If an object has 2 or more keys, then it will be output across * multiple lines:

{
      *  "key1": 1,
@@ -2276,14 +2195,12 @@ public class JSONObject {
      * Warning: This method assumes that the data structure is acyclical.
      * 
      *
-     * @param indentFactor
-     *            The number of spaces to add to each level of indentation.
+     * @param indentFactor The number of spaces to add to each level of indentation.
      * @return a printable, displayable, portable, transmittable representation
-     *         of the object, beginning with { (left
-     *         brace) and ending with } (right
-     *         brace).
-     * @throws JSONException
-     *             If the object contains an invalid number.
+     * of the object, beginning with { (left
+     * brace) and ending with } (right
+     * brace).
+     * @throws JSONException If the object contains an invalid number.
      */
     public String toString(int indentFactor) throws JSONException {
         StringWriter w = new StringWriter();
@@ -2292,98 +2209,13 @@ public class JSONObject {
         }
     }
 
-    /**
-     * 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 not contain a toJSONString method (which is the most
-     * common case), then a text will be produced by other means. If the value
-     * is an array or Collection, then a JSONArray will be made from it and its
-     * toJSONString method will be called. If the value is a MAP, then a
-     * JSONObject will be made from it and its toJSONString method will be
-     * called. Otherwise, the value's toString method will be called, and the
-     * result will be quoted.
-     *
-     * 

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException { - // moves the implementation to JSONWriter as: - // 1. It makes more sense to be part of the writer class - // 2. For Android support this method is not available. By implementing it in the Writer - // Android users can use the writer with the built in Android JSONObject implementation. - return JSONWriter.valueToString(value); - } - - /** - * 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 al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) { - try { - if (object == null) { - return NULL; - } - if (object instanceof JSONObject || object instanceof JSONArray - || NULL.equals(object) || object instanceof JSONString - || object instanceof Byte || object instanceof Character - || object instanceof Short || object instanceof Integer - || object instanceof Long || object instanceof Boolean - || object instanceof Float || object instanceof Double - || object instanceof String || object instanceof BigInteger - || object instanceof BigDecimal || object instanceof Enum) { - return object; - } - - if (object instanceof Collection) { - Collection coll = (Collection) object; - return new JSONArray(coll); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - Map map = (Map) object; - return new JSONObject(map); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage - .getName() : ""; - if (objectPackageName.startsWith("java.") - || objectPackageName.startsWith("javax.") - || object.getClass().getClassLoader() == null) { - return object.toString(); - } - return new JSONObject(object); - } catch (Exception exception) { - return null; - } - } - /** * Write the contents of the JSONObject as JSON text to a writer. For * compactness, no whitespace is added. *

* Warning: This method assumes that the data structure is acyclical. * - * + * * @return The writer. * @throws JSONException */ @@ -2391,63 +2223,13 @@ public class JSONObject { return this.write(writer, 0, 0); } - static final Writer writeValue(Writer writer, Object value, - int indentFactor, int indent) throws JSONException, IOException { - if (value == null || value.equals(null)) { - writer.write("null"); - } else if (value instanceof JSONString) { - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else if (value instanceof Number) { - // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary - final String numberAsString = numberToString((Number) value); - if(NUMBER_PATTERN.matcher(numberAsString).matches()) { - writer.write(numberAsString); - } else { - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - quote(numberAsString, writer); - } - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof Enum) { - writer.write(quote(((Enum)value).name())); - } else if (value instanceof JSONObject) { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if (value instanceof JSONArray) { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if (value instanceof Map) { - Map map = (Map) value; - new JSONObject(map).write(writer, indentFactor, indent); - } else if (value instanceof Collection) { - Collection coll = (Collection) value; - new JSONArray(coll).write(writer, indentFactor, indent); - } else if (value.getClass().isArray()) { - new JSONArray(value).write(writer, indentFactor, indent); - } else { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException { - for (int i = 0; i < indent; i += 1) { - writer.write(' '); - } - } - /** * Write the contents of the JSONObject as JSON text to a writer. - * + * *

If indentFactor > 0 and the {@link JSONObject} * has only one key, then the object will be output on a single line: *

{@code {"key": 1}}
- * + * *

If an object has 2 or more keys, then it will be output across * multiple lines:

{
      *  "key1": 1,
@@ -2458,12 +2240,9 @@ public class JSONObject {
      * Warning: This method assumes that the data structure is acyclical.
      * 
      *
-     * @param writer
-     *            Writes the serialized JSON
-     * @param indentFactor
-     *            The number of spaces to add to each level of indentation.
-     * @param indent
-     *            The indentation of the top level.
+     * @param writer       Writes the serialized JSON
+     * @param indentFactor The number of spaces to add to each level of indentation.
+     * @param indent       The indentation of the top level.
      * @return The writer.
      * @throws JSONException
      */
@@ -2475,21 +2254,21 @@ public class JSONObject {
             writer.write('{');
 
             if (length == 1) {
-            	final Entry entry = this.entrySet().iterator().next();
+                final Entry entry = this.entrySet().iterator().next();
                 final String key = entry.getKey();
                 writer.write(quote(key));
                 writer.write(':');
                 if (indentFactor > 0) {
                     writer.write(' ');
                 }
-                try{
+                try {
                     writeValue(writer, entry.getValue(), indentFactor, indent);
                 } catch (Exception e) {
                     throw new JSONException("Unable to write JSONObject value for key: " + key, e);
                 }
             } else if (length != 0) {
                 final int newindent = indent + indentFactor;
-                for (final Entry entry : this.entrySet()) {
+                for (final Entry entry : this.entrySet()) {
                     if (commanate) {
                         writer.write(',');
                     }
@@ -2548,4 +2327,55 @@ public class JSONObject {
         }
         return results;
     }
+
+    /**
+     * 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 {
+
+        /**
+         * 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() {
+            return this;
+        }
+
+        /**
+         * A Null object is equal to the null value and to itself.
+         *
+         * @param object An object to test for nullness.
+         * @return true if the object parameter is the JSONObject.NULL object or
+         * null.
+         */
+        @Override
+        public boolean equals(Object object) {
+            return object == null || object == this;
+        }
+
+        /**
+         * A Null object is equal to the null value and to itself.
+         *
+         * @return always returns 0.
+         */
+        @Override
+        public int hashCode() {
+            return 0;
+        }
+
+        /**
+         * Get the "null" string value.
+         *
+         * @return The string "null".
+         */
+        @Override
+        public String toString() {
+            return "null";
+        }
+    }
 }
diff --git a/src/main/java/ch/m4th1eu/json/JSONPointer.java b/src/main/java/ch/m4th1eu/json/JSONPointer.java
index 2176655..b93dbd5 100644
--- a/src/main/java/ch/m4th1eu/json/JSONPointer.java
+++ b/src/main/java/ch/m4th1eu/json/JSONPointer.java
@@ -1,7 +1,5 @@
 package ch.m4th1eu.json;
 
-import static java.lang.String.format;
-
 import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
@@ -9,6 +7,8 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
+import static java.lang.String.format;
+
 /*
 Copyright (c) 2002 JSON.org
 
@@ -36,18 +36,18 @@ SOFTWARE.
 /**
  * A JSON Pointer is a simple query language defined for JSON documents by
  * RFC 6901.
- * 
+ * 

* In a nutshell, JSONPointer allows the user to navigate into a JSON document * using strings, and retrieve targeted objects, like a simple form of XPATH. * Path segments are separated by the '/' char, which signifies the root of - * the document when it appears as the first char of the string. Array + * the document when it appears as the first char of the string. Array * elements are navigated using ordinals, counting from 0. JSONPointer strings * may be extended to any arbitrary number of segments. If the navigation * is successful, the matched item is returned. A matched item may be a - * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building + * JSONObject, a JSONArray, or a JSON value. If the JSONPointer string building * fails, an appropriate exception is thrown. If the navigation fails to find - * a match, a JSONPointerException is thrown. - * + * a match, a JSONPointerException is thrown. + * * @author JSON.org * @version 2016-05-14 */ @@ -55,76 +55,6 @@ public class JSONPointer { // used for URL encoding and decoding private static final String ENCODING = "utf-8"; - - /** - * This class allows the user to build a JSONPointer in steps, using - * exactly one segment in each step. - */ - public static class Builder { - - // Segments for the eventual JSONPointer string - private final List refTokens = new ArrayList(); - - /** - * Creates a {@code JSONPointer} instance using the tokens previously set using the - * {@link #append(String)} method calls. - */ - public JSONPointer build() { - return new JSONPointer(this.refTokens); - } - - /** - * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. - * - * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the - * argument of this method MUST NOT be escaped. If you want to query the property called - * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no - * need to escape it as {@code "a~0b"}. - * - * @param token the new token to be appended to the list - * @return {@code this} - * @throws NullPointerException if {@code token} is null - */ - public Builder append(String token) { - if (token == null) { - throw new NullPointerException("token cannot be null"); - } - this.refTokens.add(token); - return this; - } - - /** - * Adds an integer to the reference token list. Although not necessarily, mostly this token will - * denote an array index. - * - * @param arrayIndex the array index to be added to the token list - * @return {@code this} - */ - public Builder append(int arrayIndex) { - this.refTokens.add(String.valueOf(arrayIndex)); - return this; - } - } - - /** - * Static factory method for {@link Builder}. Example usage: - * - *


-     * JSONPointer pointer = JSONPointer.builder()
-     *       .append("obj")
-     *       .append("other~key").append("another/key")
-     *       .append("\"")
-     *       .append(0)
-     *       .build();
-     * 
- * - * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained - * {@link Builder#append(String)} calls. - */ - public static Builder builder() { - return new Builder(); - } - // Segments for the JSONPointer string private final List refTokens; @@ -132,7 +62,7 @@ public class JSONPointer { * Pre-parses and initializes a new {@code JSONPointer} instance. If you want to * evaluate the same JSON Pointer on different JSON documents then it is recommended * to keep the {@code JSONPointer} instances due to performance considerations. - * + * * @param pointer the JSON String or URI Fragment representation of the JSON pointer. * @throws IllegalArgumentException if {@code pointer} is not a valid JSON pointer */ @@ -163,7 +93,7 @@ public class JSONPointer { do { prevSlashIdx = slashIdx + 1; slashIdx = refs.indexOf('/', prevSlashIdx); - if(prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { + if (prevSlashIdx == slashIdx || prevSlashIdx == refs.length()) { // found 2 slashes in a row ( obj//next ) // or single slash at the end of a string ( obj/test/ ) this.refTokens.add(""); @@ -186,6 +116,25 @@ public class JSONPointer { this.refTokens = new ArrayList(refTokens); } + /** + * Static factory method for {@link Builder}. Example usage: + * + *

+     * JSONPointer pointer = JSONPointer.builder()
+     *       .append("obj")
+     *       .append("other~key").append("another/key")
+     *       .append("\"")
+     *       .append(0)
+     *       .build();
+     * 
+ * + * @return a builder instance which can be used to construct a {@code JSONPointer} instance by chained + * {@link Builder#append(String)} calls. + */ + public static Builder builder() { + return new Builder(); + } + private String unescape(String token) { return token.replace("~1", "/").replace("~0", "~") .replace("\\\"", "\"") @@ -196,8 +145,8 @@ public class JSONPointer { * Evaluates this JSON Pointer on the given {@code document}. The {@code document} * is usually a {@link JSONObject} or a {@link JSONArray} instance, but the empty * JSON Pointer ({@code ""}) can be evaluated on any JSON values and in such case the - * returned value will be {@code document} itself. - * + * returned value will be {@code document} itself. + * * @param document the JSON document which should be the subject of querying. * @return the result of the evaluation * @throws JSONPointerException if an error occurs during evaluation @@ -223,7 +172,8 @@ public class JSONPointer { /** * Matches a JSONArray element by ordinal position - * @param current the JSONArray to be evaluated + * + * @param current the JSONArray to be evaluated * @param indexToken the array index in string form * @return the matched object. If no matching item is found a * @throws JSONPointerException is thrown if the index is out of bounds @@ -237,10 +187,10 @@ public class JSONPointer { Integer.valueOf(currentArr.length()))); } try { - return currentArr.get(index); - } catch (JSONException e) { - throw new JSONPointerException("Error reading value at index position " + index, e); - } + return currentArr.get(index); + } catch (JSONException e) { + throw new JSONPointerException("Error reading value at index position " + index, e); + } } catch (NumberFormatException e) { throw new JSONPointerException(format("%s is not an array index", indexToken), e); } @@ -252,8 +202,8 @@ public class JSONPointer { */ @Override public String toString() { - StringBuilder rval = new StringBuilder(""); - for (String token: this.refTokens) { + StringBuilder rval = new StringBuilder(); + for (String token : this.refTokens) { rval.append('/').append(escape(token)); } return rval.toString(); @@ -261,9 +211,10 @@ public class JSONPointer { /** * Escapes path segment values to an unambiguous form. - * The escape char to be inserted is '~'. The chars to be escaped + * The escape char to be inserted is '~'. The chars to be escaped * are ~, which maps to ~0, and /, which maps to ~1. Backslashes * and double quote chars are also escaped. + * * @param token the JSONPointer segment value to be escaped * @return the escaped value for the token */ @@ -289,5 +240,55 @@ public class JSONPointer { throw new RuntimeException(e); } } - + + /** + * This class allows the user to build a JSONPointer in steps, using + * exactly one segment in each step. + */ + public static class Builder { + + // Segments for the eventual JSONPointer string + private final List refTokens = new ArrayList(); + + /** + * Creates a {@code JSONPointer} instance using the tokens previously set using the + * {@link #append(String)} method calls. + */ + public JSONPointer build() { + return new JSONPointer(this.refTokens); + } + + /** + * Adds an arbitrary token to the list of reference tokens. It can be any non-null value. + *

+ * Unlike in the case of JSON string or URI fragment representation of JSON pointers, the + * argument of this method MUST NOT be escaped. If you want to query the property called + * {@code "a~b"} then you should simply pass the {@code "a~b"} string as-is, there is no + * need to escape it as {@code "a~0b"}. + * + * @param token the new token to be appended to the list + * @return {@code this} + * @throws NullPointerException if {@code token} is null + */ + public Builder append(String token) { + if (token == null) { + throw new NullPointerException("token cannot be null"); + } + this.refTokens.add(token); + return this; + } + + /** + * Adds an integer to the reference token list. Although not necessarily, mostly this token will + * denote an array index. + * + * @param arrayIndex the array index to be added to the token list + * @return {@code this} + */ + public Builder append(int arrayIndex) { + this.refTokens.add(String.valueOf(arrayIndex)); + return this; + } + } + } diff --git a/src/main/java/ch/m4th1eu/json/JSONPointerException.java b/src/main/java/ch/m4th1eu/json/JSONPointerException.java index c16ba1b..7335b3f 100644 --- a/src/main/java/ch/m4th1eu/json/JSONPointerException.java +++ b/src/main/java/ch/m4th1eu/json/JSONPointerException.java @@ -27,7 +27,7 @@ SOFTWARE. /** * The JSONPointerException is thrown by {@link JSONPointer} if an error occurs * during evaluating a pointer. - * + * * @author JSON.org * @version 2016-05-13 */ diff --git a/src/main/java/ch/m4th1eu/json/JSONPropertyIgnore.java b/src/main/java/ch/m4th1eu/json/JSONPropertyIgnore.java index 0e9271c..f1dd4f7 100644 --- a/src/main/java/ch/m4th1eu/json/JSONPropertyIgnore.java +++ b/src/main/java/ch/m4th1eu/json/JSONPropertyIgnore.java @@ -24,13 +24,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Documented @Retention(RUNTIME) @Target({METHOD}) @@ -40,4 +40,5 @@ import java.lang.annotation.Target; * present at any level in the class hierarchy, then the method will * not be serialized from the bean into the JSONObject. */ -public @interface JSONPropertyIgnore { } +public @interface JSONPropertyIgnore { +} diff --git a/src/main/java/ch/m4th1eu/json/JSONPropertyName.java b/src/main/java/ch/m4th1eu/json/JSONPropertyName.java index 650df18..53e9ef3 100644 --- a/src/main/java/ch/m4th1eu/json/JSONPropertyName.java +++ b/src/main/java/ch/m4th1eu/json/JSONPropertyName.java @@ -24,13 +24,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import static java.lang.annotation.ElementType.METHOD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.METHOD; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Documented @Retention(RUNTIME) @Target({METHOD}) diff --git a/src/main/java/ch/m4th1eu/json/JSONString.java b/src/main/java/ch/m4th1eu/json/JSONString.java index 384164b..c0e83d7 100644 --- a/src/main/java/ch/m4th1eu/json/JSONString.java +++ b/src/main/java/ch/m4th1eu/json/JSONString.java @@ -1,4 +1,5 @@ package ch.m4th1eu.json; + /** * The JSONString interface allows a toJSONString() * method so that a class can change the behavior of @@ -14,5 +15,5 @@ public interface JSONString { * * @return A strictly syntactically correct JSON text. */ - public String toJSONString(); + String toJSONString(); } diff --git a/src/main/java/ch/m4th1eu/json/JSONStringer.java b/src/main/java/ch/m4th1eu/json/JSONStringer.java index 7a0e5f4..2bd3643 100644 --- a/src/main/java/ch/m4th1eu/json/JSONStringer.java +++ b/src/main/java/ch/m4th1eu/json/JSONStringer.java @@ -53,6 +53,7 @@ import java.io.StringWriter; * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2015-12-09 */ @@ -70,6 +71,7 @@ public class JSONStringer extends JSONWriter { * problem in the construction of the JSON text (such as the calls to * array were not properly balanced with calls to * endArray). + * * @return The JSON text. */ @Override diff --git a/src/main/java/ch/m4th1eu/json/JSONTokener.java b/src/main/java/ch/m4th1eu/json/JSONTokener.java index e14d2cd..a073f66 100644 --- a/src/main/java/ch/m4th1eu/json/JSONTokener.java +++ b/src/main/java/ch/m4th1eu/json/JSONTokener.java @@ -1,11 +1,6 @@ package ch.m4th1eu.json; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; /* Copyright (c) 2002 JSON.org @@ -35,37 +30,54 @@ SOFTWARE. * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse * JSON source strings. + * * @author JSON.org * @version 2014-05-03 */ public class JSONTokener { - /** current read character position on the current line. */ - private long character; - /** flag to indicate if the end of the input has been found. */ - private boolean eof; - /** current read index of the input. */ - private long index; - /** current line of the input. */ - private long line; - /** previous character read from the input. */ - private char previous; - /** Reader for the input. */ + /** + * Reader for the input. + */ private final Reader reader; - /** flag to indicate that a previous character was requested. */ + /** + * current read character position on the current line. + */ + private long character; + /** + * flag to indicate if the end of the input has been found. + */ + private boolean eof; + /** + * current read index of the input. + */ + private long index; + /** + * current line of the input. + */ + private long line; + /** + * previous character read from the input. + */ + private char previous; + /** + * flag to indicate that a previous character was requested. + */ private boolean usePrevious; - /** the number of characters read in the previous line. */ + /** + * the number of characters read in the previous line. + */ private long characterPreviousLine; /** * Construct a JSONTokener from a Reader. The caller must close the Reader. * - * @param reader A reader. + * @param reader A reader. */ public JSONTokener(Reader reader) { this.reader = reader.markSupported() ? reader - : new BufferedReader(reader); + : new BufferedReader(reader); this.eof = false; this.usePrevious = false; this.previous = 0; @@ -78,6 +90,7 @@ public class JSONTokener { /** * Construct a JSONTokener from an InputStream. The caller must close the input stream. + * * @param inputStream The source. */ public JSONTokener(InputStream inputStream) { @@ -88,47 +101,18 @@ public class JSONTokener { /** * Construct a JSONTokener from a string. * - * @param s A source string. + * @param s A source string. */ public JSONTokener(String s) { this(new StringReader(s)); } - - /** - * Back up one character. This provides a sort of lookahead capability, - * so that you can test for a digit or letter before attempting to parse - * the next number or identifier. - * @throws JSONException Thrown if trying to step back more than 1 step - * or if already at the start of the string - */ - public void back() throws JSONException { - if (this.usePrevious || this.index <= 0) { - throw new JSONException("Stepping back two steps is not supported"); - } - this.decrementIndexes(); - this.usePrevious = true; - this.eof = false; - } - - /** - * Decrements the indexes for the {@link #back()} method based on the previous character read. - */ - private void decrementIndexes() { - this.index--; - if(this.previous=='\r' || this.previous == '\n') { - this.line--; - this.character=this.characterPreviousLine ; - } else if(this.character > 0){ - this.character--; - } - } - /** * Get the hex value of a character (base16). + * * @param c A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. */ public static int dehexchar(char c) { if (c >= '0' && c <= '9') { @@ -143,9 +127,39 @@ public class JSONTokener { 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. + * + * @throws JSONException Thrown if trying to step back more than 1 step + * or if already at the start of the string + */ + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.decrementIndexes(); + this.usePrevious = true; + this.eof = false; + } + + /** + * Decrements the indexes for the {@link #back()} method based on the previous character read. + */ + private void decrementIndexes() { + this.index--; + if (this.previous == '\r' || this.previous == '\n') { + this.line--; + this.character = this.characterPreviousLine; + } else if (this.character > 0) { + this.character--; + } + } + /** * Checks if the end of the input has been reached. - * + * * @return true if at the end of the file and we didn't step back */ public boolean end() { @@ -156,12 +170,13 @@ public class JSONTokener { /** * Determine if the source string still contains characters that next() * can consume. + * * @return true if not yet at the end of the source. * @throws JSONException thrown if there is an error stepping forward - * or backward while checking for more data. + * or backward while checking for more data. */ public boolean more() throws JSONException { - if(this.usePrevious) { + if (this.usePrevious) { return true; } try { @@ -171,7 +186,7 @@ public class JSONTokener { } try { // -1 is EOF, but next() can not consume the null character '\0' - if(this.reader.read() <= 0) { + if (this.reader.read() <= 0) { this.eof = true; return false; } @@ -213,21 +228,22 @@ public class JSONTokener { /** * Increments the internal indexes according to the previous character * read and the character passed as the current character. + * * @param c the current character read. */ private void incrementIndexes(int c) { - if(c > 0) { + if (c > 0) { this.index++; - if(c=='\r') { + if (c == '\r') { this.line++; this.characterPreviousLine = this.character; - this.character=0; - }else if (c=='\n') { - if(this.previous != '\r') { + this.character = 0; + } else if (c == '\n') { + if (this.previous != '\r') { this.line++; this.characterPreviousLine = this.character; } - this.character=0; + this.character = 0; } else { this.character++; } @@ -237,6 +253,7 @@ public class JSONTokener { /** * Consume the next character, and check that it matches a specified * character. + * * @param c The character to match. * @return The character. * @throws JSONException if the character does not match. @@ -244,7 +261,7 @@ public class JSONTokener { public char next(char c) throws JSONException { char n = this.next(); if (n != c) { - if(n > 0) { + if (n > 0) { throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); } @@ -257,11 +274,10 @@ public class JSONTokener { /** * Get the next n characters. * - * @param n The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not - * n characters remaining in the source string. + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not + * n characters remaining in the source string. */ public String next(int n) throws JSONException { if (n == 0) { @@ -284,11 +300,12 @@ public class JSONTokener { /** * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. * @throws JSONException Thrown if there is an error reading the source string. - * @return A character, or 0 if there are no more characters. */ public char nextClean() throws JSONException { - for (;;) { + for (; ; ) { char c = this.next(); if (c == 0 || c > ' ') { return c; @@ -302,62 +319,63 @@ public class JSONTokener { * Backslash processing is done. The formal JSON format does not * allow strings in single quotes, but an implementation is allowed to * accept them. + * * @param quote The quoting character, either - * " (double quote) or - * ' (single quote). - * @return A String. + * " (double quote) or + * ' (single quote). + * @return A String. * @throws JSONException Unterminated string. */ public String nextString(char quote) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); switch (c) { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch (c) { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - try { - sb.append((char)Integer.parseInt(this.next(4), 16)); - } catch (NumberFormatException e) { - throw this.syntaxError("Illegal escape.", e); + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + try { + sb.append((char) Integer.parseInt(this.next(4), 16)); + } catch (NumberFormatException e) { + throw this.syntaxError("Illegal escape.", e); + } + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); } break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); + if (c == quote) { + return sb.toString(); + } + sb.append(c); } } } @@ -366,14 +384,15 @@ public class JSONTokener { /** * Get the text up but not including the specified character or the * end of line, whichever comes first. - * @param delimiter A delimiter character. - * @return A string. + * + * @param delimiter A delimiter character. + * @return A string. * @throws JSONException Thrown if there is an error while searching - * for the delimiter + * for the delimiter */ public String nextTo(char delimiter) throws JSONException { StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { char c = this.next(); if (c == delimiter || c == 0 || c == '\n' || c == '\r') { if (c != 0) { @@ -389,15 +408,16 @@ public class JSONTokener { /** * Get the text up but not including one of the specified delimiter * characters or the end of line, whichever comes first. + * * @param delimiters A set of delimiter characters. * @return A string, trimmed. * @throws JSONException Thrown if there is an error while searching - * for the delimiter + * for the delimiter */ public String nextTo(String delimiters) throws JSONException { char c; StringBuilder sb = new StringBuilder(); - for (;;) { + for (; ; ) { c = this.next(); if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { @@ -414,24 +434,24 @@ public class JSONTokener { /** * Get the next value. The value can be a Boolean, Double, Integer, * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * @throws JSONException If syntax error. * * @return An object. + * @throws JSONException If syntax error. */ public Object nextValue() throws JSONException { char c = this.nextClean(); String string; switch (c) { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); } /* @@ -463,11 +483,12 @@ public class JSONTokener { /** * Skip characters until the next character is the requested character. * If the requested character is not found, no characters are skipped. + * * @param to A character to skip to. * @return The requested character, or zero if the requested character * is not found. * @throws JSONException Thrown if there is an error while searching - * for the to character + * for the to character */ public char skipTo(char to) throws JSONException { char c; @@ -501,7 +522,7 @@ public class JSONTokener { * Make a JSONException to signal a syntax error. * * @param message The error message. - * @return A JSONException object, suitable for throwing + * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message) { return new JSONException(message + this.toString()); @@ -510,9 +531,9 @@ public class JSONTokener { /** * Make a JSONException to signal a syntax error. * - * @param message The error message. + * @param message The error message. * @param causedBy The throwable that caused the error. - * @return A JSONException object, suitable for throwing + * @return A JSONException object, suitable for throwing */ public JSONException syntaxError(String message, Throwable causedBy) { return new JSONException(message + this.toString(), causedBy); diff --git a/src/main/java/ch/m4th1eu/json/JSONWriter.java b/src/main/java/ch/m4th1eu/json/JSONWriter.java index b317357..337ee12 100644 --- a/src/main/java/ch/m4th1eu/json/JSONWriter.java +++ b/src/main/java/ch/m4th1eu/json/JSONWriter.java @@ -54,18 +54,16 @@ SOFTWARE. * you. Objects and arrays can be nested up to 200 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. + * * @author JSON.org * @version 2016-08-08 */ public class JSONWriter { private static final int maxdepth = 200; - /** - * The comma flag determines if a comma should be output before the next - * value. + * The object/array stack. */ - private boolean comma; - + private final JSONObject[] stack; /** * The current mode. Values: * 'a' (array), @@ -75,21 +73,19 @@ public class JSONWriter { * 'o' (object). */ protected char mode; - - /** - * The object/array stack. - */ - private final JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - /** * The writer that will receive the output. */ protected Appendable writer; + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + /** + * 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. @@ -102,200 +98,6 @@ public class JSONWriter { this.writer = w; } - /** - * Append a value. - * @param string A string value. - * @return this - * @throws JSONException If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null pointer"); - } - if (this.mode == 'o' || this.mode == 'a') { - try { - if (this.comma && this.mode == 'a') { - this.writer.append(','); - } - this.writer.append(string); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - if (this.mode == 'o') { - this.mode = 'k'; - } - this.comma = true; - return this; - } - 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. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException { - if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * @param m Mode - * @param c Closing character - * @return this - * @throws JSONException If unbalanced. - */ - private JSONWriter end(char m, char c) throws JSONException { - if (this.mode != m) { - throw new JSONException(m == 'a' - ? "Misplaced endArray." - : "Misplaced endObject."); - } - this.pop(m); - try { - this.writer.append(c); - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * @return this - * @throws JSONException If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException { - return this.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. - * @param string A key string. - * @return this - * @throws JSONException If the key is out of place. For example, keys - * do not belong in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException { - if (string == null) { - throw new JSONException("Null key."); - } - if (this.mode == 'k') { - try { - JSONObject topObject = this.stack[this.top - 1]; - // don't use the built in putOnce method to maintain Android support - if(topObject.has(string)) { - throw new JSONException("Duplicate key \"" + string + "\""); - } - topObject.put(string, true); - if (this.comma) { - this.writer.append(','); - } - this.writer.append(JSONObject.quote(string)); - this.writer.append(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch (IOException e) { - // Android as of API 25 does not support this exception constructor - // however we won't worry about it. If an exception is happening here - // it will just throw a "Method not found" exception instead. - 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. - * @return this - * @throws JSONException If the nesting is too deep, or if the object is - * started in the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException { - if (this.mode == 'i') { - this.mode = 'o'; - } - if (this.mode == 'o' || this.mode == 'a') { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - - /** - * Pop an array or object scope. - * @param c The scope to close. - * @throws JSONException If nesting is wrong. - */ - private void pop(char c) throws JSONException { - if (this.top <= 0) { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if (m != c) { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 - ? 'd' - : this.stack[this.top - 1] == null - ? 'a' - : 'k'; - } - - /** - * Push an array or object scope. - * @param jo The scope to open. - * @throws JSONException If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException { - if (this.top >= maxdepth) { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - /** * 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 @@ -311,14 +113,12 @@ public class JSONWriter { *

* Warning: This method assumes that the data structure is acyclical. * - * @param value - * The value to be serialized. + * @param value The value to be serialized. * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. + * object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the value is or contains an invalid number. */ public static String valueToString(Object value) throws JSONException { if (value == null || value.equals(null)) { @@ -339,7 +139,7 @@ public class JSONWriter { if (value instanceof Number) { // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex final String numberAsString = JSONObject.numberToString((Number) value); - if(JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { + if (JSONObject.NUMBER_PATTERN.matcher(numberAsString).matches()) { // Close enough to a JSON number that we will return it unquoted return numberAsString; } @@ -362,15 +162,217 @@ public class JSONWriter { if (value.getClass().isArray()) { return new JSONArray(value).toString(); } - if(value instanceof Enum){ - return JSONObject.quote(((Enum)value).name()); + if (value instanceof Enum) { + return JSONObject.quote(((Enum) value).name()); } return JSONObject.quote(value.toString()); } + /** + * Append a value. + * + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.append(','); + } + this.writer.append(string); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + 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. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + + /** + * End something. + * + * @param m Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char m, char c) throws JSONException { + if (this.mode != m) { + throw new JSONException(m == 'a' + ? "Misplaced endArray." + : "Misplaced endObject."); + } + this.pop(m); + try { + this.writer.append(c); + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + throw new JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.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. + * + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys + * do not belong in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + JSONObject topObject = this.stack[this.top - 1]; + // don't use the built in putOnce method to maintain Android support + if (topObject.has(string)) { + throw new JSONException("Duplicate key \"" + string + "\""); + } + topObject.put(string, true); + if (this.comma) { + this.writer.append(','); + } + this.writer.append(JSONObject.quote(string)); + this.writer.append(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + // Android as of API 25 does not support this exception constructor + // however we won't worry about it. If an exception is happening here + // it will just throw a "Method not found" exception instead. + 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. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is + * started in the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); + + } + + /** + * Pop an array or object scope. + * + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 + ? 'd' + : this.stack[this.top - 1] == null + ? 'a' + : 'k'; + } + + /** + * Push an array or object scope. + * + * @param jo The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } + /** * Append either the value true or the value * false. + * * @param b A boolean. * @return this * @throws JSONException @@ -381,6 +383,7 @@ public class JSONWriter { /** * Append a double value. + * * @param d A double. * @return this * @throws JSONException If the number is not finite. @@ -391,6 +394,7 @@ public class JSONWriter { /** * Append a long value. + * * @param l A long. * @return this * @throws JSONException @@ -402,8 +406,9 @@ public class JSONWriter { /** * Append an object value. + * * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. + * String, JSONObject, or JSONArray, or an object that implements JSONString. * @return this * @throws JSONException If the value is out of sequence. */ diff --git a/src/main/java/ch/m4th1eu/json/Property.java b/src/main/java/ch/m4th1eu/json/Property.java index 14cefa8..635f2d6 100644 --- a/src/main/java/ch/m4th1eu/json/Property.java +++ b/src/main/java/ch/m4th1eu/json/Property.java @@ -29,12 +29,14 @@ import java.util.Properties; /** * Converts a Property file data into JSONObject and back. + * * @author JSON.org * @version 2015-05-05 */ public class Property { /** * Converts a property file object into a JSONObject. The property file object is a table of name value pairs. + * * @param properties java.util.Properties * @return JSONObject * @throws JSONException @@ -45,8 +47,8 @@ public class Property { JSONObject jo = new JSONObject(); if (properties != null && !properties.isEmpty()) { Enumeration enumProperties = properties.propertyNames(); - while(enumProperties.hasMoreElements()) { - String name = (String)enumProperties.nextElement(); + while (enumProperties.hasMoreElements()) { + String name = (String) enumProperties.nextElement(); jo.put(name, properties.getProperty(name)); } } @@ -55,14 +57,15 @@ public class Property { /** * Converts the JSONObject into a property file object. + * * @param jo JSONObject * @return java.util.Properties * @throws JSONException */ - public static Properties toProperties(JSONObject jo) throws JSONException { - Properties properties = new Properties(); + public static Properties toProperties(JSONObject jo) throws JSONException { + Properties properties = new Properties(); if (jo != null) { - // Don't use the new entrySet API to maintain Android support + // Don't use the new entrySet API to maintain Android support for (final String key : jo.keySet()) { Object value = jo.opt(key); if (!JSONObject.NULL.equals(value)) { diff --git a/src/main/java/ch/m4th1eu/json/XML.java b/src/main/java/ch/m4th1eu/json/XML.java index 2d293e2..b078f5a 100644 --- a/src/main/java/ch/m4th1eu/json/XML.java +++ b/src/main/java/ch/m4th1eu/json/XML.java @@ -38,31 +38,49 @@ import java.util.Iterator; @SuppressWarnings("boxing") public class XML { - /** The Character '&'. */ + /** + * The Character '&'. + */ public static final Character AMP = '&'; - /** The Character '''. */ + /** + * The Character '''. + */ public static final Character APOS = '\''; - /** The Character '!'. */ + /** + * The Character '!'. + */ public static final Character BANG = '!'; - /** The Character '='. */ + /** + * The Character '='. + */ public static final Character EQ = '='; - /** The Character '>'. */ + /** + * The Character '>'. + */ public static final Character GT = '>'; - /** The Character '<'. */ + /** + * The Character '<'. + */ public static final Character LT = '<'; - /** The Character '?'. */ + /** + * The Character '?'. + */ public static final Character QUEST = '?'; - /** The Character '"'. */ + /** + * The Character '"'. + */ public static final Character QUOT = '"'; - /** The Character '/'. */ + /** + * The Character '/'. + */ public static final Character SLASH = '/'; /** @@ -79,7 +97,7 @@ public class XML { * which is available in Java8 and above. * * @see http://stackoverflow.com/a/21791059/6030888 + * "http://stackoverflow.com/a/21791059/6030888">http://stackoverflow.com/a/21791059/6030888 */ private static Iterable codePointIterator(final String string) { return new Iterable() { @@ -121,37 +139,36 @@ public class XML { * ' (single quote / apostrophe) is replaced by &apos; *

* - * @param string - * The string to be escaped. + * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuilder sb = new StringBuilder(string.length()); for (final int cp : codePointIterator(string)) { switch (cp) { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - if (mustEscape(cp)) { - sb.append("&#x"); - sb.append(Integer.toHexString(cp)); - sb.append(';'); - } else { - sb.appendCodePoint(cp); - } + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + if (mustEscape(cp)) { + sb.append("&#x"); + sb.append(Integer.toHexString(cp)); + sb.append(';'); + } else { + sb.appendCodePoint(cp); + } } } return sb.toString(); @@ -174,20 +191,19 @@ public class XML { && cp != 0x9 && cp != 0xA && cp != 0xD - ) || !( + ) || !( // valid the range of acceptable characters that aren't control (cp >= 0x20 && cp <= 0xD7FF) - || (cp >= 0xE000 && cp <= 0xFFFD) - || (cp >= 0x10000 && cp <= 0x10FFFF) - ) - ; + || (cp >= 0xE000 && cp <= 0xFFFD) + || (cp >= 0x10000 && cp <= 0x10FFFF) + ) + ; } /** * Removes XML escapes from the string. * - * @param string - * string to remove escapes from + * @param string string to remove escapes from * @return string with converted entities */ public static String unescape(String string) { @@ -218,8 +234,7 @@ public class XML { * Throw an exception if the string contains whitespace. Whitespace is not * allowed in tagNames and attributes. * - * @param string - * A string. + * @param string A string. * @throws JSONException Thrown if the string contains whitespace or is empty. */ public static void noSpace(String string) throws JSONException { @@ -238,12 +253,9 @@ public class XML { /** * Scan the content following the named tag, attaching it to the context. * - * @param x - * The XMLTokener containing the source string. - * @param context - * The JSONObject that will include the new material. - * @param name - * The tag name. + * @param x The XMLTokener containing the source string. + * @param context The JSONObject that will include the new material. + * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ @@ -334,7 +346,7 @@ public class XML { token = null; jsonobject = new JSONObject(); boolean nilAttributeFound = false; - for (;;) { + for (; ; ) { if (token == null) { token = x.nextToken(); } @@ -380,7 +392,7 @@ public class XML { } else if (token == GT) { // Content, between <...> and - for (;;) { + for (; ; ) { token = x.nextContent(); if (token == null) { if (tagName != null) { @@ -481,8 +493,7 @@ public class XML { * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. * - * @param string - * The source string. + * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown if there is an errors while parsing the string */ @@ -519,18 +530,18 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + *

* All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. * - * @param reader The XML source reader. + * @param reader The XML source reader. * @param keepStrings If true, then values will not be coerced into boolean - * or numeric values and will instead be left as strings + * or numeric values and will instead be left as strings * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown if there is an errors while parsing the string */ public static JSONObject toJSONObject(Reader reader, boolean keepStrings) throws JSONException { - if(keepStrings) { + if (keepStrings) { return toJSONObject(reader, XMLParserConfiguration.KEEP_STRINGS); } return toJSONObject(reader, XMLParserConfiguration.ORIGINAL); @@ -546,7 +557,7 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + *

* All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. * @@ -560,7 +571,7 @@ public class XML { XMLTokener x = new XMLTokener(reader); while (x.more()) { x.skipPast("<"); - if(x.more()) { + if (x.more()) { parse(x, jo, null, config); } } @@ -577,14 +588,13 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + *

* All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. * - * @param string - * The source string. + * @param string The source string. * @param keepStrings If true, then values will not be coerced into boolean - * or numeric values and will instead be left as strings + * or numeric values and will instead be left as strings * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown if there is an errors while parsing the string */ @@ -602,12 +612,11 @@ public class XML { * elements are represented as JSONArrays. Content text may be placed in a * "content" member. Comments, prologs, DTDs, and <[ [ ]]> * are ignored. - * + *

* All values are converted as strings, for 1, 01, 29.0 will not be coerced to * numbers but will instead be the exact value as seen in the XML document. * - * @param string - * The source string. + * @param string The source string. * @param config Configuration options for the parser. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException Thrown if there is an errors while parsing the string @@ -619,8 +628,7 @@ public class XML { /** * Convert a JSONObject into a well-formed, element-normal XML string. * - * @param object - * A JSONObject. + * @param object A JSONObject. * @return A string. * @throws JSONException Thrown if there is an error parsing the string */ @@ -631,10 +639,8 @@ public class XML { /** * Convert a JSONObject into a well-formed, element-normal XML string. * - * @param object - * A JSONObject. - * @param tagName - * The optional name of the enclosing tag. + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException Thrown if there is an error parsing the string */ @@ -645,12 +651,9 @@ public class XML { /** * Convert a JSONObject into a well-formed, element-normal XML string. * - * @param object - * A JSONObject. - * @param tagName - * The optional name of the enclosing tag. - * @param config - * Configuration that can control output to XML. + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. + * @param config Configuration that can control output to XML. * @return A string. * @throws JSONException Thrown if there is an error parsing the string */ @@ -687,7 +690,7 @@ public class XML { ja = (JSONArray) value; int jaLength = ja.length(); // don't use the new iterator API to maintain support for Android - for (int i = 0; i < jaLength; i++) { + for (int i = 0; i < jaLength; i++) { if (i > 0) { sb.append('\n'); } @@ -704,7 +707,7 @@ public class XML { ja = (JSONArray) value; int jaLength = ja.length(); // don't use the new iterator API to maintain support for Android - for (int i = 0; i < jaLength; i++) { + for (int i = 0; i < jaLength; i++) { Object val = ja.opt(i); if (val instanceof JSONArray) { sb.append('<'); @@ -740,15 +743,15 @@ public class XML { } - if (object != null && (object instanceof JSONArray || object.getClass().isArray())) { - if(object.getClass().isArray()) { + if (object != null && (object instanceof JSONArray || object.getClass().isArray())) { + if (object.getClass().isArray()) { ja = new JSONArray(object); } else { ja = (JSONArray) object; } int jaLength = ja.length(); // don't use the new iterator API to maintain support for Android - for (int i = 0; i < jaLength; i++) { + for (int i = 0; i < jaLength; i++) { Object val = ja.opt(i); // XML does not have good support for arrays. If an array // appears in a place where XML is lacking, synthesize an @@ -761,7 +764,7 @@ public class XML { string = (object == null) ? "null" : escape(object.toString()); return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName - + ">" + string + ""; + + ">" + string + ""; } } diff --git a/src/main/java/ch/m4th1eu/json/XMLParserConfiguration.java b/src/main/java/ch/m4th1eu/json/XMLParserConfiguration.java index d3f2040..8143b1b 100644 --- a/src/main/java/ch/m4th1eu/json/XMLParserConfiguration.java +++ b/src/main/java/ch/m4th1eu/json/XMLParserConfiguration.java @@ -25,13 +25,17 @@ SOFTWARE. /** * Configuration object for the XML parser. - * @author AylwardJ * + * @author AylwardJ */ public class XMLParserConfiguration { - /** Original Configuration of the XML Parser. */ + /** + * Original Configuration of the XML Parser. + */ public static final XMLParserConfiguration ORIGINAL = new XMLParserConfiguration(); - /** Original configuration of the XML Parser except that values are kept as strings. */ + /** + * Original configuration of the XML Parser except that values are kept as strings. + */ public static final XMLParserConfiguration KEEP_STRINGS = new XMLParserConfiguration(true); /** * When parsing the XML into JSON, specifies if values should be kept as strings (true), or if @@ -53,16 +57,17 @@ public class XMLParserConfiguration { /** * Default parser configuration. Does not keep strings, and the CDATA Tag Name is "content". */ - public XMLParserConfiguration () { + public XMLParserConfiguration() { this(false, "content", false); } /** * Configure the parser string processing and use the default CDATA Tag Name as "content". + * * @param keepStrings true to parse all values as string. - * false to try and convert XML string values into a JSON value. + * false to try and convert XML string values into a JSON value. */ - public XMLParserConfiguration (final boolean keepStrings) { + public XMLParserConfiguration(final boolean keepStrings) { this(keepStrings, "content", false); } @@ -70,21 +75,23 @@ public class XMLParserConfiguration { * Configure the parser string processing to try and convert XML values to JSON values and * use the passed CDATA Tag Name the processing value. Pass null to * disable CDATA processing + * * @param cDataTagNamenull to disable CDATA processing. Any other value - * to use that value as the JSONObject key name to process as CDATA. + * to use that value as the JSONObject key name to process as CDATA. */ - public XMLParserConfiguration (final String cDataTagName) { + public XMLParserConfiguration(final String cDataTagName) { this(false, cDataTagName, false); } /** * Configure the parser to use custom settings. - * @param keepStrings true to parse all values as string. - * false to try and convert XML string values into a JSON value. + * + * @param keepStrings true to parse all values as string. + * false to try and convert XML string values into a JSON value. * @param cDataTagNamenull to disable CDATA processing. Any other value - * to use that value as the JSONObject key name to process as CDATA. + * to use that value as the JSONObject key name to process as CDATA. */ - public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName) { + public XMLParserConfiguration(final boolean keepStrings, final String cDataTagName) { this.keepStrings = keepStrings; this.cDataTagName = cDataTagName; this.convertNilAttributeToNull = false; @@ -92,14 +99,15 @@ public class XMLParserConfiguration { /** * Configure the parser to use custom settings. - * @param keepStrings true to parse all values as string. - * false to try and convert XML string values into a JSON value. - * @param cDataTagName null to disable CDATA processing. Any other value - * to use that value as the JSONObject key name to process as CDATA. + * + * @param keepStrings true to parse all values as string. + * false to try and convert XML string values into a JSON value. + * @param cDataTagName null to disable CDATA processing. Any other value + * to use that value as the JSONObject key name to process as CDATA. * @param convertNilAttributeToNull true to parse values with attribute xsi:nil="true" as null. * false to parse values with attribute xsi:nil="true" as {"xsi:nil":true}. */ - public XMLParserConfiguration (final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) { + public XMLParserConfiguration(final boolean keepStrings, final String cDataTagName, final boolean convertNilAttributeToNull) { this.keepStrings = keepStrings; this.cDataTagName = cDataTagName; this.convertNilAttributeToNull = convertNilAttributeToNull; diff --git a/src/main/java/ch/m4th1eu/json/XMLTokener.java b/src/main/java/ch/m4th1eu/json/XMLTokener.java index 9bd3143..cf0de5f 100644 --- a/src/main/java/ch/m4th1eu/json/XMLTokener.java +++ b/src/main/java/ch/m4th1eu/json/XMLTokener.java @@ -29,28 +29,31 @@ import java.io.Reader; /** * The XMLTokener extends the JSONTokener to provide additional methods * for the parsing of XML texts. + * * @author JSON.org * @version 2015-12-09 */ 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; + /** + * The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; - static { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } /** * Construct an XMLTokener from a Reader. + * * @param r A source reader. */ public XMLTokener(Reader r) { @@ -59,100 +62,16 @@ public class XMLTokener extends JSONTokener { /** * Construct an XMLTokener from a string. + * * @param s A source string. */ public XMLTokener(String s) { super(s); } - /** - * Get the text in the CDATA block. - * @return The string up to the ]]>. - * @throws JSONException If the ]]> is not found. - */ - public String nextCDATA() throws JSONException { - char c; - int i; - StringBuilder sb = new StringBuilder(); - while (more()) { - c = next(); - sb.append(c); - i = sb.length() - 3; - if (i >= 0 && sb.charAt(i) == ']' && - sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { - sb.setLength(i); - return sb.toString(); - } - } - throw syntaxError("Unclosed CDATA"); - } - - - /** - * 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. - * - * @return A string, or a '<' Character, or null if there is no more - * source text. - * @throws JSONException - */ - public Object nextContent() throws JSONException { - char c; - StringBuilder sb; - do { - c = next(); - } while (Character.isWhitespace(c)); - if (c == 0) { - return null; - } - if (c == '<') { - return XML.LT; - } - sb = new StringBuilder(); - for (;;) { - if (c == 0) { - return sb.toString().trim(); - } - if (c == '<') { - back(); - return sb.toString().trim(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - c = next(); - } - } - - - /** - * Return the next entity. These entities are translated to Characters: - * & ' > < ". - * @param ampersand An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException If missing ';' in XML entity. - */ - public Object nextEntity(@SuppressWarnings("unused") char ampersand) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (;;) { - char c = next(); - if (Character.isLetterOrDigit(c) || c == '#') { - sb.append(Character.toLowerCase(c)); - } else if (c == ';') { - break; - } else { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - return unescapeEntity(string); - } - /** * Unescapes an XML entity encoding; + * * @param e entity (only the actual entity value, not the preceding & or ending ; * @return */ @@ -171,25 +90,111 @@ public class XMLTokener extends JSONTokener { // decimal encoded unicode cp = Integer.parseInt(e.substring(1)); } - return new String(new int[] {cp},0,1); - } + return new String(new int[]{cp}, 0, 1); + } Character knownEntity = entity.get(e); - if(knownEntity==null) { + if (knownEntity == null) { // we don't know the entity so keep it encoded return '&' + e + ';'; } return knownEntity.toString(); } + /** + * Get the text in the CDATA block. + * + * @return The string up to the ]]>. + * @throws JSONException If the ]]> is not found. + */ + public String nextCDATA() throws JSONException { + char c; + int i; + StringBuilder sb = new StringBuilder(); + while (more()) { + c = next(); + sb.append(c); + i = sb.length() - 3; + if (i >= 0 && sb.charAt(i) == ']' && + sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + sb.setLength(i); + return sb.toString(); + } + } + throw syntaxError("Unclosed CDATA"); + } + + /** + * 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. + * + * @return A string, or a '<' Character, or null if there is no more + * source text. + * @throws JSONException + */ + public Object nextContent() throws JSONException { + char c; + StringBuilder sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == 0) { + return null; + } + if (c == '<') { + return XML.LT; + } + sb = new StringBuilder(); + for (; ; ) { + if (c == 0) { + return sb.toString().trim(); + } + if (c == '<') { + back(); + return sb.toString().trim(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + c = next(); + } + } + + /** + * Return the next entity. These entities are translated to Characters: + * & ' > < ". + * + * @param ampersand An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException If missing ';' in XML entity. + */ + public Object nextEntity(@SuppressWarnings("unused") char ampersand) throws JSONException { + StringBuilder sb = new StringBuilder(); + for (; ; ) { + char c = next(); + if (Character.isLetterOrDigit(c) || c == '#') { + sb.append(Character.toLowerCase(c)); + } else if (c == ';') { + break; + } else { + throw syntaxError("Missing ';' in XML entity: &" + sb); + } + } + String string = sb.toString(); + return unescapeEntity(string); + } /** * Returns the next XML meta token. This is used for skipping over * and structures. + * * @return Syntax characters (< > / = ! ?) are returned as - * Character, and strings and names are returned as Boolean. We don't care - * what the values actually are. + * Character, and strings and names are returned as Boolean. We don't care + * what the values actually are. * @throws JSONException If a string is not properly closed or if the XML - * is badly structured. + * is badly structured. */ public Object nextMeta() throws JSONException { char c; @@ -198,52 +203,52 @@ public class XMLTokener extends JSONTokener { c = next(); } while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } } - if (c == q) { - return Boolean.TRUE; + default: + for (; ; ) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } } - } - default: - for (;;) { - c = next(); - if (Character.isWhitespace(c)) { - return Boolean.TRUE; - } - switch (c) { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } } } @@ -253,6 +258,7 @@ public class XMLTokener extends JSONTokener { * 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. + * * @return a String or a Character. * @throws JSONException If the XML is not well formed. */ @@ -264,70 +270,70 @@ public class XMLTokener extends JSONTokener { c = next(); } while (Character.isWhitespace(c)); switch (c) { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; // Quoted string - case '"': - case '\'': - q = c; - sb = new StringBuilder(); - for (;;) { - c = next(); - if (c == 0) { - throw syntaxError("Unterminated string"); + case '"': + case '\'': + q = c; + sb = new StringBuilder(); + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } } - if (c == q) { - return sb.toString(); - } - if (c == '&') { - sb.append(nextEntity(c)); - } else { - sb.append(c); - } - } - default: + default: // Name - sb = new StringBuilder(); - for (;;) { - sb.append(c); - c = next(); - if (Character.isWhitespace(c)) { - return sb.toString(); + sb = new StringBuilder(); + for (; ; ) { + sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } } - switch (c) { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } } } @@ -335,6 +341,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. + * * @param to A string to skip past. */ // The Android implementation of JSONTokener has a public method of public void skipPast(String to) @@ -364,7 +371,7 @@ public class XMLTokener extends JSONTokener { /* We will loop, possibly for all of the remaining characters. */ - for (;;) { + for (; ; ) { j = offset; b = true; diff --git a/src/main/java/ch/m4th1eu/richpresence/Main.java b/src/main/java/ch/m4th1eu/richpresence/Main.java index 0437311..0409692 100644 --- a/src/main/java/ch/m4th1eu/richpresence/Main.java +++ b/src/main/java/ch/m4th1eu/richpresence/Main.java @@ -1,10 +1,10 @@ package ch.m4th1eu.richpresence; -import ch.m4th1eu.json.JSONArray; import ch.m4th1eu.json.JSONObject; import ch.m4th1eu.richpresence.events.AdvancedStatusEvent; import ch.m4th1eu.richpresence.events.EventPresence; import ch.m4th1eu.richpresence.proxy.CommonProxy; +import net.minecraft.client.Minecraft; import net.minecraftforge.common.MinecraftForge; import net.minecraftforge.fml.common.Mod; import net.minecraftforge.fml.common.Mod.EventHandler; @@ -29,8 +29,7 @@ public class Main { /** * Variables pour la config */ - public static String applicationId, largeimage, largeimagetext, serveurIP; - public static boolean advancedstatus; + public static String applicationId, largeimage, largeimagetext; public static Logger logger; @@ -38,18 +37,17 @@ public class Main { public Main() { - if (advancedstatus) { - MinecraftForge.EVENT_BUS.register(new AdvancedStatusEvent()); - } + MinecraftForge.EVENT_BUS.register(new AdvancedStatusEvent()); } + @EventHandler public void preInit(FMLPreInitializationEvent event) { logger = event.getModLog(); proxy.preInit(event.getSuggestedConfigurationFile()); - //Configuration + //Configuration event.getModConfigurationDirectory().mkdir(); File config_file = new File(event.getModConfigurationDirectory(), "\\" + Main.MODID + ".json"); if (!config_file.exists()) { @@ -66,29 +64,40 @@ public class Main { try { PrintWriter writer = new PrintWriter(config_file, "UTF-8"); writer.println("{\n" + - " \"application-settings\": [\n" + - " {\n" + - " \"applicationID\": \"601875975533232158\",\n" + - " \"large-image-name\": \"discord_logo\",\n" + - " \"large-image-text\": \"En train de tester ce mod !\"\n" + + " \"_comment\": \"Variables disponibles :\",\n" + + " \"_comment2\": \"%player-name% - Nom du joueur.\",\n" + + " \"_comment3\": \"%server-connected-player% - Nombre de joueur connecté au serveur.\",\n" + + " \"_comment4\": \"%server-max-slot% - Nombre de slots du serveur\",\n" + + " \"server-ip\": \"mc.hypixel.net\",\n" + + " \"server-port\": \"25565\",\n" + + " \"application-settings\": {\n" + + " \"applicationID\": \"601875975533232158\",\n" + + " \"large-image-name\": \"discord_logo\",\n" + + " \"large-image-text\": \"En train de tester ce mod !\"\n" + + " },\n" + + " \"advanced-status-custom\": {\n" + + " \"onJoinServer\": {\n" + + " \"enable\": true,\n" + + " \"message\": \"En jeu.\"\n" + + " },\n" + + " \"onQuitServer\": {\n" + + " \"enable\": true,\n" + + " \"message\": \"Dans le menu principal.\"\n" + + " },\n" + + " \"inPauseMenu\": {\n" + + " \"enable\": true,\n" + + " \"message\": \"Dans le menu pause.\"\n" + + " },\n" + + " \"inMainMenu\": {\n" + + " \"enable\": true,\n" + + " \"message\": \"Dans le menu principal.\"\n" + + " },\n" + + " \"inInventory\": {\n" + + " \"enable\": false,\n" + + " \"message\": \"Dans l'inventaire.\"\n" + " }\n" + - " ],\n" + - " \"advanced-status\": true,\n" + - " \"advanced-status-custom\": [\n" + - " {\n" + - " \"onJoinServer\": {\n" + - " \"message\": \"En jeu.\"\n" + - " },\n" + - " \"onQuitServer\": {\n" + - " \"message\": \"Dans le menu principal.\"\n" + - " },\n" + - " \"inPauseMenu\": {\n" + - " \"message\": \"Dans le menu pause\"\n" + - " }\n" + - " }\n" + - " ]\n" + - "}\n" + - "\n"); + " }\n" + + "}"); writer.close(); } catch (FileNotFoundException e) { e.printStackTrace(); @@ -102,23 +111,24 @@ public class Main { applicationId = config.getJSONObject("application-settings").getString("applicationID"); largeimage = config.getJSONObject("application-settings").getString("large-image-name"); - largeimagetext = config.getJSONObject("application-settings").getString("large-image-text"); + largeimagetext = Utils.replaceArgsString(config.getJSONObject("application-settings").getString("large-image-text")); + - advancedstatus = config.getBoolean("advanced-status"); } @EventHandler public void init(FMLInitializationEvent event) { + JSONObject config = new JSONObject(Utils.readFileToString(new File(Minecraft.getMinecraft().mcDataDir, "\\config\\" + Main.MODID + ".json"))); proxy.init(); rpcClient = new EventPresence(); - proxy.rpcinit(); - if (advancedstatus) { - proxy.rpcupdate("Dans le menu.", null); - } else { - proxy.rpcupdate("", null); + proxy.rpcinit(); + if (config.getJSONObject("advanced-status-custom").getJSONObject("inMainMenu").getBoolean("enable")) { + proxy.rpcupdate(config.getJSONObject("advanced-status-custom").getJSONObject("inMainMenu").getString("message"), null, false); + } else { + proxy.rpcupdate("", null, false); } } diff --git a/src/main/java/ch/m4th1eu/richpresence/Utils.java b/src/main/java/ch/m4th1eu/richpresence/Utils.java index f853088..89fe763 100644 --- a/src/main/java/ch/m4th1eu/richpresence/Utils.java +++ b/src/main/java/ch/m4th1eu/richpresence/Utils.java @@ -1,8 +1,13 @@ package ch.m4th1eu.richpresence; -import java.io.BufferedReader; -import java.io.File; -import java.io.FileReader; +import ch.m4th1eu.json.JSONObject; +import net.minecraft.client.Minecraft; +import net.minecraft.network.INetHandler; + +import java.io.*; +import java.net.URL; +import java.net.URLConnection; +import java.nio.charset.Charset; public class Utils { @@ -27,4 +32,91 @@ public class Utils { return "ERROR"; } } + + + /** + * @author Nathanael + */ + public static String readTextFromURL(String url) throws IOException { + URL urlObject; + URLConnection uc; + StringBuilder parsedContentFromUrl = new StringBuilder(); + urlObject = new URL(url); + uc = urlObject.openConnection(); + uc.connect(); + uc = urlObject.openConnection(); + uc.addRequestProperty("User-Agent", + "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); + uc.getInputStream(); + InputStream is = uc.getInputStream(); + BufferedReader in = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8"))); + + int ch; + while ((ch = in.read()) != -1) { + parsedContentFromUrl.append((char) ch); + } + return parsedContentFromUrl.toString(); + } + + /** + * @author M4TH1EU_ + */ + public static String replaceArgsString(String variable) { + File config_file = new File(Minecraft.getMinecraft().mcDataDir, "\\config\\" + Main.MODID + ".json"); + JSONObject config = new JSONObject(Utils.readFileToString(config_file)); + + String serverip = config.getString("server-ip"); + String serverport = config.getString("server-port"); + + try { + variable = variable.replaceAll("%player-name%", Minecraft.getMinecraft().getSession().getUsername()); + variable = variable.replaceAll("%server-connected-player%", readTextFromURL("https://minecraft-api.com/api/ping/playeronline.php?ip=" + serverip + "&port=" + serverport)); + variable = variable.replaceAll("%server-max-slot%", readTextFromURL("https://minecraft-api.com/api/ping/maxplayer.php?ip=" + serverip + "&port=" + serverport)); + } catch (Exception e) { + } + + return variable; + } + + public static void updateStatus(int id) { + Thread t = new Thread(() -> { + JSONObject config = new JSONObject(Utils.readFileToString(new File(Minecraft.getMinecraft().mcDataDir, "\\config\\" + Main.MODID + ".json"))); + JSONObject onQuitServer = config.getJSONObject("advanced-status-custom").getJSONObject("onQuitServer"); + JSONObject onJoinServer = config.getJSONObject("advanced-status-custom").getJSONObject("onJoinServer"); + JSONObject inPauseMenu = config.getJSONObject("advanced-status-custom").getJSONObject("inPauseMenu"); + JSONObject inMainMenu = config.getJSONObject("advanced-status-custom").getJSONObject("inMainMenu"); + JSONObject inInventory = config.getJSONObject("advanced-status-custom").getJSONObject("inInventory"); + + switch (id) { + case 0: + Main.proxy.rpcupdate(Utils.replaceArgsString(config.getJSONObject("advanced-status-custom").getJSONObject("inMainMenu").getString("message")), null, false); + break; + case 1: + Main.proxy.rpcupdate(Utils.replaceArgsString(onJoinServer.getString("message")), null, false); + break; + case 2: + Main.proxy.rpcupdate(Utils.replaceArgsString(onQuitServer.getString("message")), null, false); + break; + case 3: + Main.proxy.rpcupdate(Utils.replaceArgsString(inPauseMenu.getString("message")), null, false); + break; + case 4: + Main.proxy.rpcupdate(Utils.replaceArgsString(inMainMenu.getString("message")), null, false); + break; + case 5: + Main.proxy.rpcupdate(Utils.replaceArgsString(inInventory.getString("message")), null, false); + break; + case 6: + Main.proxy.rpcupdate(Utils.replaceArgsString(config.getJSONObject("advanced-status-custom").getJSONObject("onJoinServer").getString("message")), null, false); + break; + default: + break; + } + }); + + t.start(); + + + } } + diff --git a/src/main/java/ch/m4th1eu/richpresence/events/AdvancedStatusEvent.java b/src/main/java/ch/m4th1eu/richpresence/events/AdvancedStatusEvent.java index f77fb2a..7e6723d 100644 --- a/src/main/java/ch/m4th1eu/richpresence/events/AdvancedStatusEvent.java +++ b/src/main/java/ch/m4th1eu/richpresence/events/AdvancedStatusEvent.java @@ -5,7 +5,9 @@ import ch.m4th1eu.richpresence.Main; import ch.m4th1eu.richpresence.Utils; import net.minecraft.client.Minecraft; import net.minecraft.client.gui.GuiIngameMenu; -import net.minecraft.server.MinecraftServer; +import net.minecraft.client.gui.GuiMainMenu; +import net.minecraft.client.gui.inventory.GuiInventory; +import net.minecraft.entity.player.EntityPlayerMP; import net.minecraftforge.client.event.GuiOpenEvent; import net.minecraftforge.fml.client.FMLClientHandler; import net.minecraftforge.fml.common.Mod; @@ -24,28 +26,52 @@ public class AdvancedStatusEvent { JSONObject config = new JSONObject(Utils.readFileToString(config_file)); @SubscribeEvent - public void onServerJoin(FMLNetworkEvent.ClientConnectedToServerEvent event) { - if (Main.advancedstatus) { - Main.proxy.rpcupdate(config.getJSONArray("advanced-status-custom").getJSONObject(0).getString("message"), null); + public void onJoinServer(FMLNetworkEvent.ClientConnectedToServerEvent event) { + JSONObject onJoinServer = config.getJSONObject("advanced-status-custom").getJSONObject("onJoinServer"); + + if (onJoinServer.getBoolean("enable")) { + Utils.updateStatus(1); } } @SubscribeEvent public void onQuitServer(FMLNetworkEvent.ClientDisconnectionFromServerEvent event) { - if (Main.advancedstatus) { + JSONObject onQuitServer = config.getJSONObject("advanced-status-custom").getJSONObject("onQuitServer"); - Main.proxy.rpcupdate(config.getJSONArray("advanced-status-custom").getJSONObject(1).getString("message"), null); + if (onQuitServer.getBoolean("enable")) { + Utils.updateStatus(1); } } @SubscribeEvent public void onGuiOpen(GuiOpenEvent event) { - if (Main.advancedstatus) { + + JSONObject inPauseMenu = config.getJSONObject("advanced-status-custom").getJSONObject("inPauseMenu"); + JSONObject inMainMenu = config.getJSONObject("advanced-status-custom").getJSONObject("inMainMenu"); + JSONObject inInventory = config.getJSONObject("advanced-status-custom").getJSONObject("inInventory"); + + if (inPauseMenu.getBoolean("enable")) { if (event.getGui() instanceof GuiIngameMenu) { - Main.proxy.rpcupdate(config.getJSONArray("advanced-status-custom").getJSONObject(2).getString("message"), null); + Utils.updateStatus(3); + } + } + + if (inMainMenu.getBoolean("enable")) { + if (event.getGui() instanceof GuiMainMenu) { + Utils.updateStatus(4); + } + } + + if (inInventory.getBoolean("enable")) { + if (event.getGui() instanceof GuiInventory) { + Utils.updateStatus(5); + } + } + + if (event.getGui() == null) { + if (config.getJSONObject("advanced-status-custom").getJSONObject("onJoinServer").getBoolean("enable")) { + Utils.updateStatus(6); } } } - - } diff --git a/src/main/java/ch/m4th1eu/richpresence/events/EventPresence.java b/src/main/java/ch/m4th1eu/richpresence/events/EventPresence.java index 815700f..1529b63 100644 --- a/src/main/java/ch/m4th1eu/richpresence/events/EventPresence.java +++ b/src/main/java/ch/m4th1eu/richpresence/events/EventPresence.java @@ -12,17 +12,13 @@ public class EventPresence { private static Thread callbackRunner; - public synchronized static final void init() { + public synchronized static void init() { DiscordEventHandlers handlers = new DiscordEventHandlers(); DiscordRPC.discordInitialize(Main.applicationId, handlers, true, null); if (EventPresence.callbackRunner == null) { (EventPresence.callbackRunner = new Thread(() -> { while (!Thread.currentThread().isInterrupted()) { DiscordRPC.discordRunCallbacks(); - try { - Thread.sleep(100L); - } catch (InterruptedException ex) { - } } return; }, "RPC-Callback-Handler")).start(); @@ -30,14 +26,16 @@ public class EventPresence { Main.logger.info("EventPresence has been started."); } - public static final void updatePresence(String details, String action) { + public synchronized static void updatePresence(String details, String action, Boolean changeTime) { DiscordRichPresence presence = new DiscordRichPresence(); presence.largeImageKey = Main.largeimage; presence.largeImageText = Main.largeimagetext; if (details != null) { presence.details = details; - presence.startTimestamp = System.currentTimeMillis() / 1000L; + if (changeTime) { + presence.startTimestamp = System.currentTimeMillis() / 1000L; + } } else if (action != null) { presence.state = action; } diff --git a/src/main/java/ch/m4th1eu/richpresence/proxy/ClientProxy.java b/src/main/java/ch/m4th1eu/richpresence/proxy/ClientProxy.java index 9f80453..3f5e048 100644 --- a/src/main/java/ch/m4th1eu/richpresence/proxy/ClientProxy.java +++ b/src/main/java/ch/m4th1eu/richpresence/proxy/ClientProxy.java @@ -28,7 +28,7 @@ public class ClientProxy extends CommonProxy { } @Override - public void rpcupdate(String details, String action) { - EventPresence.updatePresence(details, action); + public void rpcupdate(String details, String action, Boolean changeTime) { + EventPresence.updatePresence(details, action, changeTime); } } diff --git a/src/main/java/ch/m4th1eu/richpresence/proxy/CommonProxy.java b/src/main/java/ch/m4th1eu/richpresence/proxy/CommonProxy.java index 0053bae..e32c2e8 100644 --- a/src/main/java/ch/m4th1eu/richpresence/proxy/CommonProxy.java +++ b/src/main/java/ch/m4th1eu/richpresence/proxy/CommonProxy.java @@ -19,7 +19,7 @@ public class CommonProxy { public void rpcinit() { } - public void rpcupdate(String details, String action) { + public void rpcupdate(String details, String action, Boolean changeTime) { } }