diff --git a/moe-json/pom.xml b/moe-json/pom.xml index d77416e..02b6021 100644 --- a/moe-json/pom.xml +++ b/moe-json/pom.xml @@ -12,11 +12,23 @@ dxt.moe.json jar + + + gitea + https://git.daxii.org/api/packages/libzero/maven + + + dxt.moe dxt.moe.main - ${project.parent.version} + v1-SNAPSHOT + + + org.json + json + 20260814 diff --git a/moe-json/src/main/java/dxt/moe/codec/json/JSONCodec.java b/moe-json/src/main/java/dxt/moe/codec/json/JsonCodec.java similarity index 89% rename from moe-json/src/main/java/dxt/moe/codec/json/JSONCodec.java rename to moe-json/src/main/java/dxt/moe/codec/json/JsonCodec.java index c822b28..9cfafb3 100644 --- a/moe-json/src/main/java/dxt/moe/codec/json/JSONCodec.java +++ b/moe-json/src/main/java/dxt/moe/codec/json/JsonCodec.java @@ -22,7 +22,7 @@ import dxt.moe.codec.MoeEncoder; * @author indroneel */ -public class JSONCodec implements MoeCodec { +public class JsonCodec implements MoeCodec { @Override public String getFormat() { @@ -31,11 +31,11 @@ public class JSONCodec implements MoeCodec { @Override public MoeDecoder decoder() { - return new JSONDecoder(); + return new JsonDecoder(); } @Override public MoeEncoder encoder() { - return new JSONEncoder(); + return new JsonEncoder(); } } diff --git a/moe-json/src/main/java/dxt/moe/codec/json/JSONDecoder.java b/moe-json/src/main/java/dxt/moe/codec/json/JsonDecoder.java similarity index 87% rename from moe-json/src/main/java/dxt/moe/codec/json/JSONDecoder.java rename to moe-json/src/main/java/dxt/moe/codec/json/JsonDecoder.java index 59ec8ac..9a77525 100644 --- a/moe-json/src/main/java/dxt/moe/codec/json/JSONDecoder.java +++ b/moe-json/src/main/java/dxt/moe/codec/json/JsonDecoder.java @@ -24,6 +24,7 @@ import dxt.moe.model.SimpleData; import org.json.JSONArray; import org.json.JSONObject; +import java.io.IOException; import java.io.InputStream; import java.math.BigDecimal; import java.math.BigInteger; @@ -35,12 +36,15 @@ import java.util.logging.Logger; * @author indroneel */ -public class JSONDecoder implements MoeDecoder { +public class JsonDecoder implements MoeDecoder { - private static final Logger L = Logger.getLogger(JSONDecoder.class.getName()); + private static final Logger L = Logger.getLogger(JsonDecoder.class.getName()); private byte[] jsonData; + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeDecoder + @Override public void setSource(byte[] data) throws CodecException { jsonData = data; @@ -48,7 +52,16 @@ public class JSONDecoder implements MoeDecoder { @Override public void setSource(InputStream input) throws CodecException { - + if (input == null) { + throw new CodecException("json", "Input stream is null."); + } + try { + setSource(input.readAllBytes()); + } + catch (IOException exep) { + throw new CodecException("json", + "Error reading input stream: " + exep.getMessage(), exep); + } } @Override diff --git a/moe-json/src/main/java/dxt/moe/codec/json/JsonEncoder.java b/moe-json/src/main/java/dxt/moe/codec/json/JsonEncoder.java new file mode 100644 index 0000000..6a43594 --- /dev/null +++ b/moe-json/src/main/java/dxt/moe/codec/json/JsonEncoder.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) DuxTechnica + * + * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not + * use this file except in compliance with the License. You may obtain a copy of the License by + * contacting: + * + * Dux Technica, contact@duxtechnica.com + * + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dxt.moe.codec.json; + +import dxt.moe.codec.MoeEncoder; +import dxt.moe.model.AnyData; +import dxt.moe.model.LinearData; +import dxt.moe.model.MappedData; +import dxt.moe.model.SimpleData; +import org.json.JSONObject; + +import java.util.LinkedList; +import java.util.List; + +/** + * @author indroneel + */ + +public class JsonEncoder implements MoeEncoder { + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeEncoder + + @Override + public byte[] convert(AnyData data) { + return convert(data, false); + } + + @Override + public byte[] convert(AnyData data, boolean pretty) { + JSONObject jobj = null; + if(data.asMapped() != null) { + MappedData mdata = data.asMapped(); + jobj = convertMappedData(mdata); + } + if(jobj != null) { + if(pretty) { + return jobj.toString(4).getBytes(); + } + else { + return jobj.toString().getBytes(); + } + } + return new byte[0]; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Helper methods + + private JSONObject convertMappedData(MappedData mdata) { + if(mdata == null) { + return null; + } + + JSONObject jobj = new JSONObject(); + for (String key : mdata.getKeys()) { + AnyData ndata = mdata.get(key); + if (ndata == null) { + continue; + } + + Object item = convertNested(ndata); + if (item != null) { + jobj.put(key, item); + } + } + return jobj; + } + + private List convertCollectionData(LinearData ldata) { + if(ldata == null) { + return null; + } + LinkedList list = new LinkedList<>(); + for(int i=0; i < ldata.size(); i++) { + AnyData ndata = ldata.get(i); + if (ndata == null) { + continue; + } + + Object item = convertNested(ndata); + if (item != null) { + list.add(item); + } + } + return list; + } + + private Object convertNested(AnyData ndata) { + if(ndata.asSimple() != null) { + SimpleData nsdata = ndata.asSimple(); + if(nsdata.getBoolean() != null) { + return nsdata.getBoolean(); + } + else if(nsdata.getString() != null) { + return nsdata.getString(); + } + else if(nsdata.getNumber() != null) { + Number nval = nsdata.getNumber(); + if(nval instanceof Byte || nval instanceof Short + || nval instanceof Integer || nval instanceof Long) { + return nval.longValue(); + } + else if(nval instanceof Float || nval instanceof Double) { + return nval.doubleValue(); + } + else { + return nval.toString(); + } + } + } + + if(ndata.asLinear() != null) { + LinearData nldata = ndata.asLinear(); + return convertCollectionData(nldata); + } + + if(ndata.asMapped() != null) { + MappedData nmdata = ndata.asMapped(); + return convertMappedData(nmdata); + } + return null; + } +} diff --git a/moe-json/src/main/java/org/json/JSONArray.java b/moe-json/src/main/java/org/json/JSONArray.java deleted file mode 100644 index f7deb1d..0000000 --- a/moe-json/src/main/java/org/json/JSONArray.java +++ /dev/null @@ -1,1961 +0,0 @@ -package org.json; - -/* -Public Domain. - */ - -import java.io.IOException; -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; - - -/** - * A JSONArray is an ordered sequence of values. Its external text form is a - * string wrapped in square brackets with commas separating the values. The - * internal form is an object having get and opt - * methods for accessing the values by index, and put methods for - * adding or replacing values. The values can be any of these types: - * Boolean, JSONArray, JSONObject, - * Number, String, or the - * JSONObject.NULL object. - *

- * The constructor can convert a JSON text into a Java object. The - * toString method converts to JSON text. - *

- * A get method returns a value if one can be found, and throws an - * exception if one cannot be found. An opt method returns a - * default value instead of throwing an exception, and so is useful for - * obtaining optional values. - *

- * The generic get() and opt() methods return an - * object which you can cast or query for type. There are also typed - * get and opt methods that do type checking and type - * coercion for you. - *

- * The texts produced by the toString methods strictly conform to - * JSON syntax rules. The constructors are more forgiving in the texts they will - * accept: - *

- * - * @author JSON.org - * @version 2016-08/15 - */ -public class JSONArray extends JSONBase implements Iterable { - - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; - - /** - * Construct an empty JSONArray. - */ - public JSONArray() { - myArrayList = new ArrayList(); - } - - //TODO: Remove dead code - /** - * Construct a JSONArray from a JSONTokener. - * - * @param jtok A JSONTokener - * @throws JSONException If there is a syntax error. - */ - //TODO: Remove dead code - /* - public JSONArray(JSONTokener jtok) throws JSONException { - this(jtok, jtok.getJsonParserConfiguration()); - } - */ - - //TODO: Remove dead code - /** - * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration. - * The supplied configuration applies to all values during construction, - * including nested objects and arrays. The tokener's original configuration - * is restored afterward, even if parsing fails. - * - * @param jtok A JSONTokener instance from which the JSONArray is constructed. - * @param pconfig A JSONParserConfiguration instance that controls the behavior of the parser. - * @throws JSONException If a syntax error occurs during the construction of the JSONArray. - */ - //TODO: Remove dead code - /* - public JSONArray(JSONTokener jtok, JSONParserConfiguration pconfig) throws JSONException { - this(jtok, pconfig, true); - } - */ - - /** - * Constructs a JSONArray from a JSONTokener and a JSONParserConfiguration, for internal use.
- * Never call this instead of using withStrictMode(boolean). - * - * @param jtok A JSONTokener instance from which the JSONArray is constructed. - * @param pconfig A JSONParserConfiguration instance that controls the behavior of the parser. - * @param isInitial A boolean that determines whether this array is the root. - * @throws JSONException If a syntax error occurs during the construction of the JSONArray. - */ - JSONArray(JSONTokener jtok, JSONParserConfiguration pconfig, boolean isInitial) throws JSONException { - this(); - JSONParserConfiguration oconfig = jtok.getJsonParserConfiguration(); - jtok.setJsonParserConfigurationInternal(pconfig); - try { - if (jtok.nextClean() != '[') { - throw jtok.syntaxError("A JSONArray text must start with '['"); - } - - char nextChar = jtok.nextClean(); - if (nextChar == 0) { - // array is unclosed. No ']' found, instead EOF - throw jtok.syntaxError("Expected a ',' or ']'"); - } else if (nextChar == ',' && pconfig.isStrictMode()) { - throw jtok.syntaxError("Array content starts with a ','"); - } - if (nextChar != ']') { - jtok.back(); - for (; ; ) { - if (jtok.nextClean() == ',') { - jtok.back(); - this.myArrayList.add(Null.TYPE); - } else { - jtok.back(); - this.myArrayList.add(jtok.nextValue()); - } - if (checkForSyntaxError(jtok, pconfig, isInitial)) - return; - } - } else { - if (isInitial && pconfig.isStrictMode() && jtok.nextClean() != 0) { - throw jtok.syntaxError("Strict mode error: Unparsed characters found at end of input text"); - } - } - } finally { - jtok.setJsonParserConfigurationInternal(oconfig); - } - } - - //TODO: Remove dead code - /** - * 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. - */ - //TODO: Remove dead code - /* - public JSONArray(String source) throws JSONException { - this(source, new JSONParserConfiguration()); - } - */ - - //TODO: Remove dead code - /** - * Construct a JSONArray from a source JSON text. - * - * @param source A string that begins with [ (left - * bracket) and ends with ] - *  (right bracket). - * @param jsonParserConfiguration the parser config object - * @throws JSONException If there is a syntax error. - */ - //TODO: Remove dead code - /* - public JSONArray(String source, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - this(new JSONTokener(source, jsonParserConfiguration), jsonParserConfiguration); - } - */ - - /** - * Construct a JSONArray from a Collection. - * - * @param collection A Collection. - */ - public JSONArray(Collection collection) { - this(collection, 0, new JSONParserConfiguration()); - } - - /** - * Construct a JSONArray from a Collection. - * - * @param collection A Collection. - * @param jsonParserConfiguration Configuration object for the JSON parser - */ - public JSONArray(Collection collection, JSONParserConfiguration jsonParserConfiguration) { - this(collection, 0, jsonParserConfiguration); - } - - /** - * Construct a JSONArray from a collection with recursion depth. - * - * @param collection A Collection. - * @param recursionDepth Variable for tracking the count of nested object creations. - * @param jsonParserConfiguration Configuration object for the JSON parser - */ - JSONArray(Collection collection, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - if (recursionDepth > jsonParserConfiguration.getMaxNestingDepth()) { - throw new JSONException("JSONArray has reached recursion depth limit of " + jsonParserConfiguration.getMaxNestingDepth()); - } - if (collection == null) { - this.myArrayList = new ArrayList(); - } else { - this.myArrayList = new ArrayList(collection.size()); - this.addAll(collection, true, recursionDepth, jsonParserConfiguration); - } - } - - /** - * Construct a JSONArray from an Iterable. This is a shallow copy. - * - * @param iter A Iterable collection. - */ - public JSONArray(Iterable iter) { - this(); - if (iter == null) { - return; - } - this.addAll(iter, true); - } - - /** - * Construct a JSONArray from another JSONArray. This is a shallow copy. - * - * @param array A array. - */ - public JSONArray(JSONArray array) { - if (array == null) { - this.myArrayList = new ArrayList(); - } else { - // shallow copy directly the internal array lists as any wrapping - // should have been done already in the original JSONArray - this.myArrayList = new ArrayList(array.myArrayList); - } - } - - /** - * 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. - */ - public JSONArray(Object array) throws JSONException { - this(); - if (!array.getClass().isArray()) { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } - this.addAll(array, true, 0); - } - - /** - * Construct a JSONArray with the specified initial capacity. - * - * @param initialCapacity the initial capacity of the JSONArray. - * @throws JSONException If the initial capacity is negative. - */ - public JSONArray(int initialCapacity) throws JSONException { - if (initialCapacity < 0) { - throw new JSONException( - "JSONArray initial capacity cannot be negative."); - } - this.myArrayList = new ArrayList(initialCapacity); - } - - /** - * Create a new JSONException in a common format for incorrect conversions. - * - * @param idx index of the item - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. - */ - private static JSONException wrongValueFormatException( - int idx, - String valueType, - Object value, - Throwable cause) { - if (value == null) { - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (null)." - , cause); - } - // don't try to toString collections or known object types that could be large. - if (value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + ")." - , cause); - } - return new JSONException( - "JSONArray[" + idx + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")." - , cause); - } - - /** - * Convenience function. Checks for JSON syntax error. - * - * @param x A JSONTokener instance from which the JSONArray is constructed. - * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. - * @param isInitial Boolean indicating position of char - * @return true if a syntax error has occurred, otherwise false - */ - private boolean checkForSyntaxError(JSONTokener x, JSONParserConfiguration jsonParserConfiguration, boolean isInitial) { - char nextChar; - 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) { - // array is unclosed. No ']' found, instead EOF - throw x.syntaxError("Expected a ',' or ']'"); - } - if (nextChar == ']') { - // trailing commas are not allowed in strict mode - if (jsonParserConfiguration.isStrictMode()) { - throw x.syntaxError("Strict mode error: Expected another array element"); - } - return true; - } - if (nextChar == ',') { - // Consecutive commas are not allowed in strict mode. - // Otherwise, the tokener is backed up, and a null object is inserted by the calling code. - if (jsonParserConfiguration.isStrictMode()) { - throw x.syntaxError("Strict mode error: Expected a valid array element"); - } - } - x.back(); - break; - case - ']': - if (isInitial && jsonParserConfiguration.isStrictMode() && - x.nextClean() != 0) { - throw x.syntaxError("Strict mode error: Unparsed characters found at end of input text"); - } - return true; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - return false; - } - - @Override - public Iterator iterator() { - return this.myArrayList.iterator(); - } - - /** - * Get the object value associated with an index. - * - * @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. - */ - public Object get(int index) throws JSONException { - Object object = this.opt(index); - if (object == null) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } - - /** - * Get the boolean value associated with an index. The string values "true" - * and "false" are converted to boolean. - * - * @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. - */ - public boolean getBoolean(int index) throws JSONException { - Object object = this.get(index); - if (Boolean.FALSE.equals(object) - || (object instanceof String && "false".equalsIgnoreCase((String) object))) { - return false; - } else if (Boolean.TRUE.equals(object) - || (object instanceof String && "true".equalsIgnoreCase((String) object))) { - return true; - } - throw wrongValueFormatException(index, "boolean", object, null); - } - - /** - * Get the double value associated with an index. - * - * @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. - */ - public double getDouble(int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof Number) { - return ((Number) object).doubleValue(); - } - try { - return Double.parseDouble(object.toString()); - } catch ( - Exception e) { - throw wrongValueFormatException(index, "double", object, e); - } - } - - /** - * Get the float value associated with a key. - * - * @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. - */ - public float getFloat(int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof Number) { - return ((Number) object).floatValue(); - } - try { - return Float.parseFloat(object.toString()); - } catch ( - Exception e) { - throw wrongValueFormatException(index, "float", object, e); - } - } - - /** - * Get the Number value associated with a key. - * - * @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. - */ - public Number getNumber(int index) throws JSONException { - Object object = this.get(index); - try { - if (object instanceof Number) { - return (Number) object; - } - return JSONUtils.stringToNumber(object.toString()); - } catch ( - Exception e) { - throw wrongValueFormatException(index, "number", object, e); - } - } - - /** - * 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. - * @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. - */ - public > E getEnum(Class clazz, int index) throws JSONException { - E val = optEnum(clazz, index); - 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 wrongValueFormatException(index, "enum of type " - + JSONUtils.quote(clazz.getSimpleName()), opt(index), null); - } - return val; - } - - /** - * Get the BigDecimal value associated with an index. If the value is float - * or double, 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. - * @return The value. - * @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 { - Object object = this.get(index); - BigDecimal val = JSONUtils.objectToBigDecimal(object, null); - if (val == null) { - throw wrongValueFormatException(index, "BigDecimal", object, null); - } - return val; - } - - /** - * Get the BigInteger value associated with an index. - * - * @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. - */ - public BigInteger getBigInteger(int index) throws JSONException { - return this.getBigInteger(index, new JSONParserConfiguration()); - } - - /** - * Get the BigInteger value associated with an index. - * - * @param index The index must be between 0 and length() - 1. - * @param jsonParserConfiguration A configuration whose {@code maxNumberLength} bounds the number of - * decimal digits in the returned integer. Values exceeding this length - * are treated as unconvertible. Pass a configuration with - * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable - * this check. - * @return The value. - * @throws JSONException If the key is not found or if the value cannot be converted - * to a BigInteger. - */ - public BigInteger getBigInteger(int index, JSONParserConfiguration jsonParserConfiguration) - throws JSONException { - Object object = this.get(index); - BigInteger val = JSONUtils.objectToBigInteger(object, null, jsonParserConfiguration); - if (val == null) { - throw wrongValueFormatException(index, "BigInteger", object, null); - } - return val; - } - - /** - * Get the int value associated with an index. - * - * @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. - */ - public int getInt(int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof Number) { - return ((Number) object).intValue(); - } - try { - return Integer.parseInt(object.toString()); - } catch ( - Exception e) { - throw wrongValueFormatException(index, "int", object, e); - } - } - - /** - * Get the JSONArray associated with an index. - * - * @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 - */ - public JSONArray getJSONArray(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONArray) { - return (JSONArray) object; - } - throw wrongValueFormatException(index, "JSONArray", object, null); - } - - /** - * Get the JSONObject associated with an index. - * - * @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 - */ - public JSONObject getJSONObject(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof JSONObject) { - return (JSONObject) object; - } - throw wrongValueFormatException(index, "JSONObject", object, null); - } - - /** - * Get the long value associated with an index. - * - * @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. - */ - public long getLong(int index) throws JSONException { - final Object object = this.get(index); - if (object instanceof Number) { - return ((Number) object).longValue(); - } - try { - return Long.parseLong(object.toString()); - } catch ( - Exception e) { - throw wrongValueFormatException(index, "long", object, e); - } - } - - /** - * Get the string associated with an index. - * - * @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. - */ - public String getString(int index) throws JSONException { - Object object = this.get(index); - if (object instanceof String) { - return (String) object; - } - throw wrongValueFormatException(index, "String", object, null); - } - - /** - * Determine if the value is null. - * - * @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) { - return Null.TYPE.equals(this.opt(index)); - } - - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. Warning: - * This method assumes that the data structure is acyclical. - * - * @param separator A string that will be inserted between the elements. - * @return a string. - * @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))); - - for (int i = 1; i < len; i++) { - sb.append(separator) - .append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } - - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() { - return this.myArrayList.size(); - } - - /** - * Removes all of the elements from this JSONArray. - * The JSONArray will be empty after this call returns. - */ - public void clear() { - this.myArrayList.clear(); - } - - /** - * 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. - * @return An object value, or null if there is no object at that index. - */ - public Object opt(int index) { - return (index < 0 || index >= this.length()) ? null : this.myArrayList - .get(index); - } - - /** - * Get the optional boolean value associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) { - return this.optBoolean(index, false); - } - - /** - * Get the optional boolean value associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @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) { - try { - return this.getBoolean(index); - } catch ( - Exception e) { - return defaultValue; - } - } - - /** - * Get the optional Boolean object associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index The index must be between 0 and length() - 1. - * @return The truth. - */ - public Boolean optBooleanObject(int index) { - return this.optBooleanObject(index, false); - } - - /** - * Get the optional Boolean object associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue A boolean default. - * @return The truth. - */ - public Boolean optBooleanObject(int index, Boolean defaultValue) { - try { - return this.getBoolean(index); - } catch ( - Exception e) { - return defaultValue; - } - } - - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) { - return this.optDouble(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index subscript - * @param defaultValue The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - - /** - * Get the optional Double object associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The object. - */ - public Double optDoubleObject(int index) { - return this.optDoubleObject(index, Double.NaN); - } - - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index subscript - * @param defaultValue The default object. - * @return The object. - */ - public Double optDoubleObject(int index, Double defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - - /** - * Get the optional float value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public float optFloat(int index) { - return this.optFloat(index, Float.NaN); - } - - /** - * Get the optional float 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 subscript - * @param defaultValue The default value. - * @return The value. - */ - public float optFloat(int index, float defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.floatValue(); - } - - /** - * Get the optional Float object associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The object. - */ - public Float optFloatObject(int index) { - return this.optFloatObject(index, Float.NaN); - } - - /** - * Get the optional Float object 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 subscript - * @param defaultValue The default object. - * @return The object. - */ - public Float optFloatObject(int index, Float defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.floatValue(); - } - - /** - * Get the optional int value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) { - return this.optInt(index, 0); - } - - /** - * Get the optional int value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @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) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * Get the optional Integer object associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The object. - */ - public Integer optIntegerObject(int index) { - return this.optIntegerObject(index, 0); - } - - /** - * Get the optional Integer object 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 object. - * @return The object. - */ - public Integer optIntegerObject(int index, Integer defaultValue) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - - /** - * 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. - * @return The enum value at the index location or null if not found - */ - public > E optEnum(Class clazz, int index) { - return this.optEnum(clazz, index, null); - } - - /** - * 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 - * @return The enum value at the index location or defaultValue if - * the value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, int index, E defaultValue) { - try { - Object val = this.opt(index); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } catch ( IllegalArgumentException | NullPointerException e) { - return defaultValue; - } - } - - /** - * 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. - * @return The value. - */ - public BigInteger optBigInteger(int index, BigInteger defaultValue) { - return this.optBigInteger(index, defaultValue, new JSONParserConfiguration()); - } - - /** - * 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 jsonParserConfiguration A configuration whose {@code maxNumberLength} bounds the number of - * decimal digits in the returned integer. Values exceeding this length - * are treated as unconvertible and {@code defaultValue} is returned. - * Pass a configuration with - * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable - * this check. - * @return The value. - */ - public BigInteger optBigInteger(int index, BigInteger defaultValue, - JSONParserConfiguration jsonParserConfiguration) { - Object val = this.opt(index); - return JSONUtils.objectToBigInteger(val, defaultValue, jsonParserConfiguration); - } - - /** - * 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 {@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. - * @return The value. - */ - public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { - Object val = this.opt(index); - return JSONUtils.objectToBigDecimal(val, defaultValue); - } - - /** - * Get the optional JSONArray associated with an index. Null is returned if - * there is no value at that index or if the value is not a JSONArray. - * - * @param index The index must be between 0 and length() - 1. - * @return A JSONArray value. - */ - public JSONArray optJSONArray(int index) { - return this.optJSONArray(index, null); - } - - /** - * Get the optional JSONArray associated with an index. The defaultValue is returned if - * there is no value at that index or if the value is not a JSONArray. - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default. - * @return A JSONArray value. - */ - public JSONArray optJSONArray(int index, JSONArray defaultValue) { - Object object = this.opt(index); - return object instanceof JSONArray ? (JSONArray) object : defaultValue; - } - - /** - * Get the optional JSONObject associated with an index. Null is returned if - * there is no value at that index or if the value is not a JSONObject. - * - * @param index The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) { - return this.optJSONObject(index, null); - } - - /** - * Get the optional JSONObject associated with an index. The defaultValue is returned if - * there is no value at that index or if the value is not a JSONObject. - * - * @param index The index must be between 0 and length() - 1. - * @param defaultValue The default. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index, JSONObject defaultValue) { - Object object = this.opt(index); - return object instanceof JSONObject ? (JSONObject) object : defaultValue; - } - - /** - * Get the optional long value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) { - return this.optLong(index, 0); - } - - /** - * Get the optional long value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @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) { - final Number val = this.optNumber(index, null); - if (val == null) { - return defaultValue; - } - return val.longValue(); - } - - /** - * Get the optional Long object associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index The index must be between 0 and length() - 1. - * @return The object. - */ - public Long optLongObject(int index) { - return this.optLongObject(index, 0L); - } - - /** - * Get the optional Long object 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 object. - * @return The object. - */ - public Long optLongObject(int index, Long defaultValue) { - final Number val = this.optNumber(index, null); - 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 index The index must be between 0 and length() - 1. - * @return An object which is the value. - */ - public Number optNumber(int index) { - return this.optNumber(index, null); - } - - /** - * Get an optional {@link Number} value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number ({@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. - * @return An object which is the value. - */ - public Number optNumber(int index, Number defaultValue) { - Object val = this.opt(index); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (val instanceof Number) { - return (Number) val; - } - - if (val instanceof String) { - try { - return JSONUtils.stringToNumber((String) val); - } catch ( - Exception e) { - return defaultValue; - } - } - return defaultValue; - } - - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is converted to a string. - * - * @param index The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) { - return this.optString(index, ""); - } - - /** - * 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. - * @return A String value. - */ - public String optString(int index, String defaultValue) { - Object object = this.opt(index); - return Null.TYPE.equals(object) ? defaultValue : object - .toString(); - } - - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value A boolean value. - * @return this. - */ - public JSONArray put(boolean value) { - return this.put(value ? Boolean.TRUE : Boolean.FALSE); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param value A Collection value. - * @return this. - * @throws JSONException If the value is non-finite number. - */ - public JSONArray put(Collection value) { - return this.put(new JSONArray(value)); - } - - /** - * Append a double value. This increases the array's length by one. - * - * @param value A double value. - * @return this. - * @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. - * @return this. - * @throws JSONException if the value is not finite. - */ - public JSONArray put(float value) throws JSONException { - return this.put(Float.valueOf(value)); - } - - /** - * Append an int value. This increases the array's length by one. - * - * @param value An int value. - * @return this. - */ - public JSONArray put(int value) { - return this.put(Integer.valueOf(value)); - } - - /** - * Append an long value. This increases the array's length by one. - * - * @param value A long value. - * @return this. - */ - public JSONArray put(long value) { - return this.put(Long.valueOf(value)); - } - - /** - * Put a value in the JSONArray, where the value will be a JSONObject which - * is produced from a Map. - * - * @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 - */ - public JSONArray put(Map value) { - return this.put(new JSONObject(value)); - } - - /** - * 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 - * Null.TYPE object. - * @return this. - * @throws JSONException If the value is non-finite number. - */ - public JSONArray put(Object value) { - JSONUtils.testValidity(value); - this.myArrayList.add(value); - return this; - } - - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index The subscript. - * @param value A boolean value. - * @return this. - * @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); - } - - /** - * 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. - * @return this. - * @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)); - } - - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @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. - */ - public JSONArray put(int index, double value) throws JSONException { - return this.put(index, Double.valueOf(value)); - } - - /** - * Put or replace a float value. If the index is greater 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 float value. - * @return this. - * @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)); - } - - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index The subscript. - * @param value An int value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException { - return this.put(index, Integer.valueOf(value)); - } - - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index The subscript. - * @param value A long value. - * @return this. - * @throws JSONException If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException { - return this.put(index, Long.valueOf(value)); - } - - /** - * 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. - * @return reference to self - * @throws JSONException If the index is negative or if 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, new JSONParserConfiguration())); - return this; - } - - /** - * 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 jsonParserConfiguration Configuration object for the JSON parser - * @return reference to self - * @throws JSONException If the index is negative or if the value is an invalid - * number. - */ - public JSONArray put(int index, Map value, JSONParserConfiguration jsonParserConfiguration) throws JSONException { - this.put(index, new JSONObject(value, jsonParserConfiguration)); - return this; - } - - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @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 value is an invalid - * number. - */ - public JSONArray put(int index, Object value) throws JSONException { - if (index < 0) { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if (index < this.length()) { - JSONUtils.testValidity(value); - this.myArrayList.set(index, value); - return this; - } - if (index == this.length()) { - // simple append - return this.put(value); - } - // if we are inserting past the length, we want to grow the array all at once - // instead of incrementally. - this.myArrayList.ensureCapacity(index + 1); - while (index != this.length()) { - // we don't need to test validity of NULL objects - this.myArrayList.add(Null.TYPE); - } - return this.put(value); - } - - /** - * Put a collection's elements in to the JSONArray. - * - * @param collection A Collection. - * @return this. - */ - public JSONArray putAll(Collection collection) { - this.addAll(collection, false); - return this; - } - - /** - * Put an Iterable's elements in to the JSONArray. - * - * @param iter An Iterable. - * @return this. - */ - public JSONArray putAll(Iterable iter) { - this.addAll(iter, false); - return this; - } - - /** - * Put a JSONArray's elements in to the JSONArray. - * - * @param array A JSONArray. - * @return this. - */ - public JSONArray putAll(JSONArray array) { - // directly copy the elements from the source array to this one - // as all wrapping should have been done already in the source. - this.myArrayList.addAll(array.myArrayList); - return this; - } - - /** - * Put an array's elements in to the JSONArray. - * - * @param array Array. If the parameter passed is null, or not an array or Iterable, an - * exception will be thrown. - * @return this. - * @throws JSONException If not an array, JSONArray, Iterable or if an value is non-finite number. - * @throws NullPointerException Thrown if the array parameter is null. - */ - public JSONArray putAll(Object array) throws JSONException { - this.addAll(array, false); - return this; - } - - /** - * 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: - *
-	 * [
-	 *     {"b":"c"}
-	 * ]
-	 * 
- * and this JSONPointer string: - *
-	 * "/0/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 - * match it to an item within this JSONArray. For example, given a - * JSONArray initialized with this document: - *
-	 * [
-	 *     {"b":"c"}
-	 * ]
-	 * 
- * and this JSONPointer: - *
-	 * "/0/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)); - } - - /** - * 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 - */ - public Object optQuery(JSONPointer jsonPointer) { - try { - return jsonPointer.queryFrom(this); - } catch ( - JSONPointerException e) { - return null; - } - } - - /** - * Remove an index and close the hole. - * - * @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. - */ - public Object remove(int index) { - return index >= 0 && index < this.length() - ? this.myArrayList.remove(index) - : null; - } - - /** - * Determine if two JSONArrays are similar. - * They must contain similar sequences. - * - * @param other The other JSONArray - * @return true if they are equal - */ - public boolean similar(Object other) { - if (!(other instanceof JSONArray)) { - return false; - } - int len = this.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; - } - if (valueThis == null) { - return false; - } - if (!isSimilar(valueThis, valueOther)) { - return false; - } - } - return true; - } - - /** - * Convenience function; checks for object similarity - * - * @param valueThis Initial object to compare - * @param valueOther Comparison object - * @return boolean - */ - private boolean isSimilar(Object valueThis, Object valueOther) { - if (valueThis instanceof JSONObject) { - if (!((JSONObject) valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof JSONArray) { - if (!((JSONArray) valueThis).similar(valueOther)) { - return false; - } - } else if (valueThis instanceof Number && valueOther instanceof Number) { - if (!JSONUtils.isNumberSimilar((Number) valueThis, (Number) valueOther)) { - return false; - } - } else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { - if (!((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString())) { - return false; - } - } else if (!valueThis.equals(valueOther)) { - return false; - } - return true; - } - - /** - * Produce a JSONObject by combining a JSONArray of names with the values of - * this JSONArray. - * - * @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. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException { - if (names == null || names.isEmpty() || this.isEmpty()) { - return null; - } - JSONObject jo = new JSONObject(names.length()); - for (int i = 0; i < names.length(); i += 1) { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } - - /** - * Make a JSON text of this JSONArray. For compactness, no unnecessary - * whitespace is added. If it is not possible to produce a syntactically - * correct JSON text then null will be returned instead. This could occur if - * the array contains an invalid number. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @return a printable, displayable, transmittable representation of the - * array. - */ - @Override - public String toString() { - try { - return this.toString(0); - } catch ( - Exception e) { - return null; - } - } - - /** - * Make a pretty-printed JSON text of this JSONArray. - * - *

If

 {@code 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
-	 * [
-	 * 1,
-	 * "value 2",
-	 * 3
-	 * ]
-	 * }
- *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @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). - * @throws JSONException if a called function fails - */ - @SuppressWarnings("resource") - public String toString(int indentFactor) throws JSONException { - // each value requires a comma, so multiply the count by 2 - // We don't want to oversize the initial capacity - int initialSize = myArrayList.size() * 2; - Writer sw = new StringBuilderWriter(Math.max(initialSize, 16)); - return this.write(sw, indentFactor, 0).toString(); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @param writer the writer object - * @return The writer. - * @throws JSONException if a called function fails - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - /** - * Write the contents of the JSONArray as JSON text to a writer. - * - *

If

{@code 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
-	 * [
-	 * 1,
-	 * "value 2",
-	 * 3
-	 * ]
-	 * }
- *

- * 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. - * @return The writer. - * @throws JSONException if a called function fails or unable to write - */ - @SuppressWarnings("resource") - public Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean needsComma = false; - int length = this.length(); - writer.write('['); - - if (length == 1) { - writeArrayAttempt(writer, indentFactor, indent, 0); - } else if (length != 0) { - final int newIndent = indent + indentFactor; - - for (int i = 0; i < length; i += 1) { - if (needsComma) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, newIndent); - writeArrayAttempt(writer, indentFactor, newIndent, i); - needsComma = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch ( - IOException e) { - throw new JSONException(e); - } - } - - /** - * Convenience function. Attempts to write - * - * @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 i Index in array to be added - */ - private void writeArrayAttempt(Writer writer, int indentFactor, int indent, int i) { - try { - JSONObject.writeValue(writer, this.myArrayList.get(i), - indentFactor, indent); - } catch ( - Exception e) { - throw new JSONException("Unable to write JSONArray value at index: " + i, e); - } - } - - /** - * Returns a java.util.List containing all of the elements in this array. - * If an element in the array is a JSONArray or JSONObject it will also - * be converted to a List and a Map respectively. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a java.util.List containing the elements of this array - */ - public List toList() { - List results = new ArrayList(this.myArrayList.size()); - for (Object element : this.myArrayList) { - if (element == null || Null.TYPE.equals(element)) { - results.add(null); - } else if (element instanceof JSONArray) { - results.add(((JSONArray) element).toList()); - } else if (element instanceof JSONObject) { - results.add(((JSONObject) element).toMap()); - } else { - results.add(element); - } - } - return results; - } - - /** - * Check if JSONArray is empty. - * - * @return true if JSONArray is empty, otherwise false. - */ - public boolean isEmpty() { - return this.myArrayList.isEmpty(); - } - - /** - * Add a collection's elements to the JSONArray. - * - * @param collection A Collection. - * @param wrap {@code true} to call {@link JSONWrapper#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth Variable for tracking the count of nested object creations. - */ - private void addAll(Collection collection, boolean wrap, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - this.myArrayList.ensureCapacity(this.myArrayList.size() + collection.size()); - if (wrap) { - for (Object o : collection) { - this.put(wrapper.wrap(o, recursionDepth + 1, jsonParserConfiguration)); - } - } else { - for (Object o : collection) { - this.put(o); - } - } - } - - /** - * Add an Iterable's elements to the JSONArray. - * - * @param iter An Iterable. - * @param wrap {@code true} to call {@link JSONWrapper#wrap(Object)} for each item, - * {@code false} to add the items directly - */ - private void addAll(Iterable iter, boolean wrap) { - if (wrap) { - for (Object o : iter) { - this.put(wrapper.wrap(o)); - } - } else { - for (Object o : iter) { - this.put(o); - } - } - } - - /** - * Add an array's elements to the JSONArray. - * - * @param array Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap {@code true} to call {@link JSONWrapper#wrap(Object)} for each item, - * {@code false} to add the items directly - * @throws JSONException If not an array or if an array value is non-finite number. - */ - private void addAll(Object array, boolean wrap) throws JSONException { - this.addAll(array, wrap, 0); - } - - /** - * Add an array's elements to the JSONArray. - * - * @param array Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap {@code true} to call {@link JSONWrapper#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth Variable for tracking the count of nested object creations. - */ - private void addAll(Object array, boolean wrap, int recursionDepth) { - addAll(array, wrap, recursionDepth, new JSONParserConfiguration()); - } - - /** - * Add an array's elements to the JSONArray. - * ` - * - * @param array Array. If the parameter passed is null, or not an array, - * JSONArray, Collection, or Iterable, an exception will be - * thrown. - * @param wrap {@code true} to call {@link JSONWrapper#wrap(Object)} for each item, - * {@code false} to add the items directly - * @param recursionDepth Variable for tracking the count of nested object creations. - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @throws JSONException If not an array or if an array value is non-finite number. - * @throws NullPointerException Thrown if the array parameter is null. - */ - - private void addAll(Object array, boolean wrap, int recursionDepth, JSONParserConfiguration pconfig) throws JSONException { - if (array.getClass().isArray()) { - int length = Array.getLength(array); - this.myArrayList.ensureCapacity(this.myArrayList.size() + length); - if (wrap) { - for (int i = 0; i < length; i += 1) { - this.put(wrapper.wrap(Array.get(array, i), recursionDepth + 1, pconfig)); - } - } else { - for (int i = 0; i < length; i += 1) { - this.put(Array.get(array, i)); - } - } - } - else if (array instanceof JSONArray) { - // use the built in array list `addAll` as all object - // wrapping should have been completed in the original - // JSONArray - this.myArrayList.addAll(((JSONArray) array).myArrayList); - } - else if (array instanceof Collection) { - this.addAll((Collection) array, wrap, recursionDepth, pconfig); - } - else if (array instanceof Iterable) { - this.addAll((Iterable) array, wrap); - } - else { - throw new JSONException( - "JSONArray initial value should be a string or collection or array."); - } - } -} diff --git a/moe-json/src/main/java/org/json/JSONException.java b/moe-json/src/main/java/org/json/JSONException.java deleted file mode 100644 index 4b80f76..0000000 --- a/moe-json/src/main/java/org/json/JSONException.java +++ /dev/null @@ -1,52 +0,0 @@ -package org.json; - -/* -Public Domain. - */ - -/** - * The JSONException is thrown by the JSON.org classes when things are amiss. - * - * @author JSON.org - * @version 2015-12-09 - */ - -public class JSONException extends RuntimeException { - -/** - * Serialization ID - */ - - private static final long serialVersionUID = 0; - -/** - * Constructs a JSONException with an explanatory message. - * - * @param message Detail about the reason for the exception. - */ - - public JSONException(final String message) { - super(message); - } - -/** - * Constructs a JSONException with an explanatory message and 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); - } - -/** - * Constructs a new JSONException with the specified cause. - * - * @param cause The cause. - */ - - public JSONException(final Throwable cause) { - super(cause.getMessage(), cause); - } -} diff --git a/moe-json/src/main/java/org/json/JSONObject.java b/moe-json/src/main/java/org/json/JSONObject.java deleted file mode 100644 index f6d498f..0000000 --- a/moe-json/src/main/java/org/json/JSONObject.java +++ /dev/null @@ -1,2530 +0,0 @@ -package org.json; - -/* -Public Domain. -*/ - -import java.io.IOException; -import java.io.Writer; -import java.lang.reflect.Field; -import java.lang.reflect.GenericArrayType; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -/** - * A JSONObject is an unordered collection of name/value pairs. Its external form is a string - * wrapped in curly braces with colons between the names and values, and commas between the values - * and names. The internal form is an object having get and opt methods - * for accessing the values by name, and put methods for adding or replacing values by - * name. The values can be any of these types: Boolean, JSONArray, - * JSONObject, Number, String, or the - * JSONObject.NULL object. A JSONObject constructor can be used to convert an external - * form JSON text into an internal form whose values can be retrieved with the get and - * opt methods, or to convert values into a JSON text using the put and - * toString methods. A get method returns a value if one can be found, and - * throws an exception if one cannot be found. An opt method returns a default value - * instead of throwing an exception, and so is useful for obtaining optional values. - *

- * The generic get() and opt() methods return an object, which you can - * cast or query for type. There are also typed get and opt methods that - * do type checking and type coercion for you. The opt methods differ from the get methods in that - * they do not throw. Instead, they return a specified value, such as null. - *

- * The put methods add or replace values in an object. For example, - * - *

- * myString = new JSONObject()
- *         .put("JSON", "Hello, World!").toString();
- * 
- * - * produces the string {"JSON": "Hello, World"}. - *

- * The texts produced by the toString methods strictly conform to the JSON syntax - * rules. The constructors are more forgiving in the texts they will accept: - *

    - *
  • An extra , (comma) may appear just before the closing - * brace.
  • - *
  • Strings may be quoted with ' (single quote).
  • - *
  • Strings do not need to be quoted at all if they do not begin with a quote or single quote, - * and if they do not contain leading or trailing spaces, and if they do not contain any of these - * characters: { } [ ] / \ : , # and if they do not look like numbers and if they are - * not the reserved words true, false, or null.
  • - *
- * - * @author JSON.org - * @version 2016-08-15 - */ - -public class JSONObject extends JSONBase { - -/** - * The map where the JSONObject's properties are kept. - */ - - private final Map map; - -//TODO: Remove dead code -/* - * Retrieves the type of the underlying Map in this class. - * - * @return The class object representing the type of the underlying Map. - */ - - //TODO: Remove dead code - /* - public Class getMapType() { - return map.getClass(); - } - */ - -/** - * Construct an empty JSONObject. - */ - - public JSONObject() { - // 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 retrieval based on associative access. - // Therefore, an implementation mustn't rely on the order of the item. - - this.map = new HashMap(); - } - -/** - * Construct a JSONObject from a subset of another JSONObject. An array of strings is used to - * identify the keys that should be copied. Missing keys are ignored. - * - * @param jo A JSONObject. - * @param names An array of strings. - */ - - public JSONObject(JSONObject jo, String ... names) { - this(names.length); - for (String name : names) { - try { - this.putOnce(name, jo.opt(name)); - } - catch (Exception ignore) { // exception thrown for missing key - } - } - } - -/** - * Construct a JSONObject from a JSONTokener. - * - * @param jtok 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 jtok) throws JSONException { - this(jtok, jtok.getJsonParserConfiguration()); - } - -/** - * Construct a JSONObject from a JSONTokener with custom json parse configurations. The supplied - * configuration applies to all values during construction, including nested objects and arrays. The - * tokener's original configuration is restored afterward, even if parsing fails. - * - * @param jtok A JSONTokener object containing the source string. - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @throws JSONException If there is a syntax error in the source string or a duplicated key. - */ - - public JSONObject(JSONTokener jtok, JSONParserConfiguration pconfig) throws JSONException { - this(jtok, pconfig, true); - } - -/** - * Construct a JSONObject from a JSONTokener with custom json parse configurations, for internal - * use. Never call this instead of using withStrictMode(boolean). - * - * @param jtok A JSONTokener object containing the source string. - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @param isInitial A boolean that determines whether this object is the root. - * @throws JSONException If there is a syntax error in the source string or a duplicated key. - */ - - JSONObject(JSONTokener jtok, JSONParserConfiguration pconfig, boolean isInitial) - throws JSONException { - this(); - JSONParserConfiguration originalConfiguration = jtok.getJsonParserConfiguration(); - jtok.setJsonParserConfigurationInternal(pconfig); - try { - if (jtok.nextClean() != '{') { - throw jtok.syntaxError("A JSONObject text must begin with '{'"); - } - for (;;) { - if (parseJSONObject(jtok, pconfig, isInitial)) { - return; - } - } - } - finally { - jtok.setJsonParserConfigurationInternal(originalConfiguration); - } - } - -/** - * Parses entirety of JSON object - * - * @param jtok Parses text as tokens - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @param isInitial True if start of document, else false - * @return True if done building object, else false - */ - - private boolean parseJSONObject( - JSONTokener jtok, JSONParserConfiguration pconfig, boolean isInitial) { - Object obj; - String key; - boolean doneParsing = false; - char c = jtok.nextClean(); - - switch (c) { - case 0: - throw jtok.syntaxError("A JSONObject text must end with '}'"); - case '}': - if (isInitial && pconfig.isStrictMode() && jtok.nextClean() != 0) { - throw jtok.syntaxError("Strict mode error: Unparsed characters found at end " + - "of input text"); - } - return true; - default: - obj = jtok.nextSimpleValue(c); - key = obj.toString(); - } - - checkKeyForStrictMode(jtok, pconfig, obj); - - // The key is followed by ':'. - c = jtok.nextClean(); - if (c != ':') { - throw jtok.syntaxError("Expected a ':' after a key"); - } - - // Use syntaxError(..) to include error location - if (key != null) { - // Check if key exists - boolean keyExists = this.opt(key) != null; - if (keyExists && !pconfig.isOverwriteDuplicateKey()) { - throw jtok.syntaxError("Duplicate key \"" + key + "\""); - } - - Object value = jtok.nextValue(); - // Only add value if non-null - if (value != null) { - this.put(key, value); - } - } - - // Pairs are separated by ','. - if (parseEndOfKeyValuePair(jtok, pconfig, isInitial)) { - doneParsing = true; - } - - return doneParsing; - } - -/** - * Checks for valid end of key:value pair - * @param jtok Parses text as tokens - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @param isInitial True if end of JSON object, else false - * @return True if end of JSON object, else false - */ - - private static boolean parseEndOfKeyValuePair( - JSONTokener jtok, JSONParserConfiguration pconfig, boolean isInitial) { - switch (jtok.nextClean()) { - case ';': - // In strict mode semicolon is not a valid separator - if (pconfig.isStrictMode()) { - throw jtok.syntaxError("Strict mode error: Invalid character ';' found"); - } - break; - case ',': - if (jtok.nextClean() == '}') { - // trailing commas are not allowed in strict mode - if (pconfig.isStrictMode()) { - throw jtok.syntaxError( - "Strict mode error: Expected another object element"); - } - // End of JSON object - return true; - } - if (jtok.end()) { - throw jtok.syntaxError("A JSONObject text must end with '}'"); - } - jtok.back(); - break; - case '}': - if (isInitial && pconfig.isStrictMode() && jtok.nextClean() != 0) { - throw jtok.syntaxError( - "Strict mode error: Unparsed characters found at end of input text"); - } - // End of JSON object - return true; - default: - throw jtok.syntaxError("Expected a ',' or '}'"); - } - // Not at end of JSON object - return false; - } - -/** - * Throws error if key violates strictMode - * @param jtok Parses text as tokens - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @param obj Value to be checked - */ - - private static void checkKeyForStrictMode( - JSONTokener jtok, JSONParserConfiguration pconfig, Object obj) { - if (pconfig != null && pconfig.isStrictMode()) { - if(obj instanceof Boolean) { - throw jtok.syntaxError(String.format( - "Strict mode error: key '%s' cannot be boolean", obj.toString())); - } - if(obj == Null.TYPE) { - throw jtok.syntaxError(String.format( - "Strict mode error: key '%s' cannot be null", obj.toString())); - } - if(obj instanceof Number) { - throw jtok.syntaxError(String.format( - "Strict mode error: key '%s' cannot be number", obj.toString())); - } - } - } - -/** - * 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 - */ - - public JSONObject(Map m) { - this(m, 0, new JSONParserConfiguration()); - } - -/** - * Construct a JSONObject from a Map with custom json parse configurations. - * - * @param m A map object that can be used to initialize the contents of the JSONObject. - * @param pconfig Variable to pass parser custom configuration for json parsing. - */ - - public JSONObject(Map m, JSONParserConfiguration pconfig) { - this(m, 0, pconfig); - } - -/** - * Construct a JSONObject from a map with recursion depth. - */ - - public JSONObject(Map m, int recursionDepth, JSONParserConfiguration pconfig) { - if (recursionDepth > pconfig.getMaxNestingDepth()) { - throw new JSONException( - "JSONObject has reached recursion depth limit of " + pconfig.getMaxNestingDepth()); - } - 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."); - } - final Object value = e.getValue(); - if (value != null || pconfig.isUseNativeNulls()) { - JSONUtils.testValidity(value); - this.map.put(String.valueOf(e.getKey()), - wrapper.wrap(value, recursionDepth + 1, pconfig)); - } - } - } - } - -/** - * 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. - */ - - public JSONObject(String source) throws JSONException { - this(source, new JSONParserConfiguration()); - } - -/** - * Construct a JSONObject from a source JSON text string with custom json parse configurations. - * This is the most commonly used JSONObject constructor. - * - * @param source A string beginning with { (left brace) and ending - * with }  (right brace). - * @param pconfig Variable to pass parser custom configuration for json parsing. - * @exception JSONException If there is a syntax error in the source string or a duplicated key. - */ - - public JSONObject(String source, JSONParserConfiguration pconfig) throws JSONException { - this(new JSONTokener(source, pconfig), pconfig); - } - -/** - * 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){ - 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 { - JSONUtils.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 { - JSONUtils.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 wrongValueFormatException(key, "JSONArray", null, null); - } - return this; - } - -/** - * Produce a string from a double. The string "null" will be returned if the number is not finite. - * - * @param d A double. - * @return A String. - */ - - public static String doubleToString(double d) { - if (Double.isInfinite(d) || Double.isNaN(d)) { - return "null"; - } - - // Shave off trailing zeros and decimal point, if possible. - String string = Double.toString(d); - // idx = 0 case is covered by behavior of Double.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 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[" + JSONUtils.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 wrongValueFormatException(key, "enum of type " - + JSONUtils.quote(clazz.getSimpleName()), opt(key), null); - } - 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 (Boolean.FALSE.equals(object) - || (object instanceof String && "false".equalsIgnoreCase((String) object))) { - return false; - } else if (Boolean.TRUE.equals(object) - || (object instanceof String && "true".equalsIgnoreCase((String) object))) { - return true; - } - throw wrongValueFormatException(key, "Boolean", object, null); - } - -/** - * 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 { - return this.getBigInteger(key, new JSONParserConfiguration()); - } - -/** - * Get the BigInteger value associated with a key. - * - * @param key A key string. - * @param pconfig A configuration whose {@code maxNumberLength} bounds the number of decimal digits - * in the returned integer. Values exceeding this length are treated as unconvertible. Pass a - * configuration with {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable this - * check. - * - * @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, JSONParserConfiguration pconfig) - throws JSONException { - Object object = this.get(key); - BigInteger ret = JSONUtils.objectToBigInteger(object, null, pconfig); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigInteger", object, null); - } - -/** - * Get the BigDecimal value associated with a key. If the value is float or double, 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 = JSONUtils.objectToBigDecimal(object, null); - if (ret != null) { - return ret; - } - throw wrongValueFormatException(key, "BigDecimal", object, null); - } - -/** - * 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 { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).doubleValue(); - } - try { - return Double.parseDouble(object.toString()); - } - catch (Exception e) { - throw wrongValueFormatException(key, "double", object, e); - } - } - -/** - * 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 { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).floatValue(); - } - try { - return Float.parseFloat(object.toString()); - } - catch (Exception e) { - throw wrongValueFormatException(key, "float", object, e); - } - } - -/** - * 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 JSONUtils.stringToNumber(object.toString()); - } - catch (Exception e) { - throw wrongValueFormatException(key, "number", object, 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 { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).intValue(); - } - try { - return Integer.parseInt(object.toString()); - } - catch (Exception e) { - throw wrongValueFormatException(key, "int", object, e); - } - } - -/** - * 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 wrongValueFormatException(key, "JSONArray", object, null); - } - -/** - * 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 wrongValueFormatException(key, "JSONObject", object, null); - } - -/** - * 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 { - final Object object = this.get(key); - if(object instanceof Number) { - return ((Number)object).longValue(); - } - try { - return Long.parseLong(object.toString()); - } - catch (Exception e) { - throw wrongValueFormatException(key, "long", object, e); - } - } - -/** - * Get an array of field names from a JSONObject. - * - * @param jo JSON object - * @return An array of field names, or null if there are no names. - */ - - public static String[] getNames(JSONObject jo) { - if (jo.isEmpty()) { - return null; - } - return jo.keySet().toArray(new String[jo.length()]); - } - -/** - * Get an array of public field names from an Object. - * - * @param object object to read - * @return An array of field names, or null if there are no names. - */ - - public static String[] getNames(Object object) { - if (object == null) { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if (length == 0) { - return null; - } - String[] names = new String[length]; - for (int i = 0; i < length; i += 1) { - names[i] = fields[i].getName(); - } - return names; - } - -/** - * Get the string associated with a key. - * - * @param key A key string. - * @return A string which is the value. - * @throws JSONException if there is no string value for the key. - */ - - public String getString(String key) throws JSONException { - Object object = this.get(key); - if (object instanceof String) { - return (String) object; - } - throw wrongValueFormatException(key, "string", object, null); - } - -/** - * Determine if the JSONObject contains a specific key. - * - * @param key A key string. - * @return true if the key exists in the JSONObject. - */ - - public boolean has(String key) { - return this.map.containsKey(key); - } - -/** - * Increment a property of a JSONObject. If there is no such property, create one with a value of 1 - * (Integer). If there is such a property, and if it is an Integer, Long, Double, Float, BigInteger, - * or BigDecimal then add one to it. No overflow bounds checking is performed, so callers should - * initialize the key prior to this call with an appropriate type that can handle the maximum - * expected value. - * - * @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. - */ - - public JSONObject increment(String key) throws JSONException { - Object value = this.opt(key); - switch (value) { - case - null -> this.put(key, 1); - case - Integer i -> this.put(key, i + 1); - case - Long l -> this.put(key, l + 1L); - case - BigInteger bigInteger -> this.put(key, bigInteger.add(BigInteger.ONE)); - case - Float v -> this.put(key, v + 1.0f); - case - Double v -> this.put(key, v + 1.0d); - case - BigDecimal bigDecimal -> this.put(key, bigDecimal.add(BigDecimal.ONE)); - default -> - throw new JSONException("Unable to increment [" + JSONUtils.quote(key) + "]."); - } - return this; - } - -/** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key A key string. - * @return true if there is no value associated with the key or if the value is the Null.TYPE - * object. - */ - - public boolean isNull(String key) { - return Null.TYPE.equals(this.opt(key)); - } - -/** - * 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. - */ - - public Iterator keys() { - return this.keySet().iterator(); - } - -/** - * 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. - */ - - public Set keySet() { - return this.map.keySet(); - } - -/** - * 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 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 - */ - - protected Set> entrySet() { - return this.map.entrySet(); - } - -/** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - - public int length() { - return this.map.size(); - } - -/** - * Removes all of the elements from this JSONObject. The JSONObject will be empty after this call - * returns. - */ - - public void clear() { - this.map.clear(); - } - -/** - * Check if JSONObject is empty. - * - * @return true if JSONObject is empty, otherwise false. - */ - - public boolean isEmpty() { - return this.map.isEmpty(); - } - -/** - * Produce a JSONArray containing the names of the elements of this JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject is empty. - */ - - public JSONArray names() { - if(this.map.isEmpty()) { - return null; - } - return new JSONArray(this.map.keySet()); - } - -/** - * Get an optional value associated with a key. - * - * @param key A key string. - * @return An object which is the value, or null if there is no value. - */ - - public Object opt(String key) { - return key == null ? null : this.map.get(key); - } - -/** - * 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 or null if not found - */ - - public > E optEnum(Class clazz, String key) { - return this.optEnum(clazz, key, null); - } - -/** - * 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 - * @return The enum value associated with the key or defaultValue if the value is not found or - * cannot be assigned to clazz - */ - - public > E optEnum(Class clazz, String key, E defaultValue) { - try { - Object val = this.opt(key); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (clazz.isAssignableFrom(val.getClass())) { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } - catch ( - IllegalArgumentException | NullPointerException e) { - return defaultValue; - } - } - -/** - * 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. - * @return The truth. - */ - - public boolean optBoolean(String key) { - return this.optBoolean(key, false); - } - -/** - * Get an optional boolean associated with a key. It returns the defaultValue if there is no such - * key, or if it is not a Boolean or the String "true" or "false" (case-insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - - public boolean optBoolean(String key, boolean defaultValue) { - Object val = this.opt(key); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (val instanceof Boolean){ - return (Boolean) val; - } - try { - // we'll use the get anyway because it does string conversion. - return this.getBoolean(key); - } - catch (Exception e) { - return defaultValue; - } - } - -/** - * Get an optional boolean object 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. - * @return The truth. - */ - - public Boolean optBooleanObject(String key) { - return this.optBooleanObject(key, false); - } - -/** - * Get an optional boolean object associated with a key. It returns the defaultValue if there is no - * such key, or if it is not a Boolean or the String "true" or "false" (case-insensitive). - * - * @param key A key string. - * @param defaultValue The default. - * @return The truth. - */ - - public Boolean optBooleanObject(String key, Boolean defaultValue) { - Object val = this.opt(key); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (val instanceof Boolean){ - return (Boolean) val; - } - try { - // we'll use the get anyway because it does string conversion. - return this.getBoolean(key); - } - catch (Exception e) { - return defaultValue; - } - } - -/** - * Get an optional BigDecimal 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. If the value is float or double, then 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. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { - Object val = this.opt(key); - return JSONUtils.objectToBigDecimal(val, 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. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) { - return this.optBigInteger(key, defaultValue, new JSONParserConfiguration()); - } - -/** - * 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 pconfig A configuration whose {@code maxNumberLength} bounds the number of decimal digits - * in the returned integer. Values exceeding this length are treated as unconvertible and - * {@code defaultValue} is returned. Pass a configuration with - * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable this check. - * @return An object which is the value. - */ - - public BigInteger optBigInteger(String key, BigInteger defaultValue, - JSONParserConfiguration pconfig) { - Object val = this.opt(key); - return JSONUtils.objectToBigInteger(val, defaultValue, pconfig); - } - -/** - * 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. - * @return An object which is the value. - */ - - public double optDouble(String key) { - return this.optDouble(key, Double.NaN); - } - -/** - * Get an optional double associated with a key, or the defaultValue if there is no such key or if - * its value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public double optDouble(String key, double defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - -/** - * Get an optional Double object 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. - * @return An object which is the value. - */ - - public Double optDoubleObject(String key) { - return this.optDoubleObject(key, Double.NaN); - } - -/** - * Get an optional Double object 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. - * @return An object which is the value. - */ - - public Double optDoubleObject(String key, Double defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.doubleValue(); - } - -/** - * Get the optional float value associated with an index. NaN is returned if there is no value for - * the index, or if the value is not a number and cannot be converted to a number. - * - * @param key A key string. - * @return The value. - */ - - public float optFloat(String key) { - return this.optFloat(key, Float.NaN); - } - -/** - * Get the optional float 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 key A key string. - * @param defaultValue The default value. - * @return The value. - */ - - public float optFloat(String key, float defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.floatValue(); - } - -/** - * Get the optional Float object associated with an index. NaN is returned if there is no value for - * the index, or if the value is not a number and cannot be converted to a number. - * - * @param key A key string. - * @return The object. - */ - - public Float optFloatObject(String key) { - return this.optFloatObject(key, Float.NaN); - } - -/** - * Get the optional Float object 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 key A key string. - * @param defaultValue The default object. - * @return The object. - */ - - public Float optFloatObject(String key, Float defaultValue) { - Number val = this.optNumber(key); - if (val == null) { - return defaultValue; - } - return val.floatValue(); - } - -/** - * Get an optional int value associated with a key, or zero if there is no such key or if the value - * is not a number. If the value is a string, an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @return An object which is the value. - */ - - public int optInt(String key) { - return this.optInt(key, 0); - } - -/** - * Get an optional int value associated with a key, or the default if there is no such key or if the - * value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public int optInt(String key, int defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - -/** - * Get an optional Integer object associated with a key, or zero if there is no such key or if the - * value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @return An object which is the value. - */ - - public Integer optIntegerObject(String key) { - return this.optIntegerObject(key, 0); - } - -/** - * Get an optional Integer object associated with a key, or the default if there is no such key or - * if the value is not a number. If the value is a string, an attempt will be made to evaluate it as - * a number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public Integer optIntegerObject(String key, Integer defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - return val.intValue(); - } - -/** - * 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. - * @return A JSONArray which is the value. - */ - - public JSONArray optJSONArray(String key) { - return this.optJSONArray(key, null); - } - -/** - * Get an optional JSONArray associated with a key, or the default if there is no such key, or if - * its value is not a JSONArray. - * - * @param key A key string. - * @param defaultValue The default. - * @return A JSONArray which is the value. - */ - - public JSONArray optJSONArray(String key, JSONArray defaultValue) { - Object object = this.opt(key); - return object instanceof JSONArray ? (JSONArray) object : defaultValue; - } - -/** - * 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. - * @return A JSONObject which is the value. - */ - - public JSONObject optJSONObject(String key) { return this.optJSONObject(key, null); } - -/** - * Get an optional JSONObject associated with a key, or the default if there is no such key or if - * the value is not a JSONObject. - * - * @param key A key string. - * @param defaultValue The default. - * @return An JSONObject which is the value. - */ - - public JSONObject optJSONObject(String key, JSONObject defaultValue) { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : defaultValue; - } - -/** - * Get an optional long value associated with a key, or zero if there is no such key or if the value - * is not a number. If the value is a string, an attempt will be made to evaluate it as a number. - * - * @param key A key string. - * @return An object which is the value. - */ - - public long optLong(String key) { - return this.optLong(key, 0); - } - -/** - * Get an optional long value associated with a key, or the default if there is no such key or if - * the value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public long optLong(String key, long defaultValue) { - final Number val = this.optNumber(key, null); - if (val == null) { - return defaultValue; - } - - return val.longValue(); - } - -/** - * Get an optional Long object associated with a key, or zero if there is no such key or if the - * value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @return An object which is the value. - */ - - public Long optLongObject(String key) { - return this.optLongObject(key, 0L); - } - -/** - * Get an optional Long object associated with a key, or the default if there is no such key or if - * the value is not a number. If the value is a string, an attempt will be made to evaluate it as a - * number. - * - * @param key A key string. - * @param defaultValue The default. - * @return An object which is the value. - */ - - public Long optLongObject(String key, Long defaultValue) { - final Number val = this.optNumber(key, null); - 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. - * @return An object which is the value. - */ - - public Number optNumber(String key) { - return this.optNumber(key, null); - } - -/** - * Get an optional {@link Number} value associated with a key, or the default if there is no such - * key or if the value is not a number. If the value is a string, an attempt will be made to - * evaluate it as a number. 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. - * @return An object which is the value. - */ - - public Number optNumber(String key, Number defaultValue) { - Object val = this.opt(key); - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (val instanceof Number){ - return (Number) val; - } - - try { - return JSONUtils.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. - * @return A string which is the value. - */ - - public String optString(String key) { - return this.optString(key, ""); - } - -/** - * 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. - * @return A string which is the value. - */ - - public String optString(String key, String defaultValue) { - Object object = this.opt(key); - return Null.TYPE.equals(object) ? defaultValue : object.toString(); - } - -/** - * Put a key/boolean pair in the JSONObject. - * - * @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. - */ - - public JSONObject put(String key, boolean value) throws JSONException { - return this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - } - -/** - * 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. - * @return this. - * @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)); - } - -/** - * Put a key/double pair in the JSONObject. - * - * @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. - */ - - 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. - * @return this. - * @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)); - } - -/** - * Put a key/int pair in the JSONObject. - * - * @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. - */ - - public JSONObject put(String key, int value) throws JSONException { - return this.put(key, Integer.valueOf(value)); - } - -/** - * Put a key/long pair in the JSONObject. - * - * @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. - */ - - public JSONObject put(String key, long value) throws JSONException { - return this.put(key, Long.valueOf(value)); - } - -/** - * 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. - * @return this. - * @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)); - } - -/** - * 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 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. - */ - - public JSONObject put(String key, Object value) throws JSONException { - if (key == null) { - throw new NullPointerException("Null key."); - } - if (value != null) { - JSONUtils.testValidity(value); - this.map.put(key, value); - } - else { - this.remove(key); - } - return this; - } - -/** - * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null, and - * only if there is not already a member with that name. - * - * @param key key to insert into - * @param value value to insert - * @return this. - * @throws JSONException if the key is a duplicate - */ - - public JSONObject putOnce(String key, Object value) throws JSONException { - if (key != null && value != null) { - if (this.opt(key) != null) { - throw new JSONException("Duplicate key \"" + key + "\""); - } - return this.put(key, value); - } - return this; - } - -/** - * Put a key/value pair in the JSONObject, but only if the key and the value are both non-null. - * - * @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. - */ - - public JSONObject putOpt(String key, Object value) throws JSONException { - if (key != null && value != null) { - return this.put(key, value); - } - return this; - } - -/** - * 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: - *

- * {
- *     "a":{"b":"c"}
- * }
- * 
- * 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 match it to an item within this JSONObject. For - * example, given a JSONObject initialized with this document: - *
- * {
- *     "a":{"b":"c"}
- * }
- * 
- * 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)); - } - -/** - * 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 - */ - - public Object optQuery(JSONPointer jsonPointer) { - try { - return jsonPointer.queryFrom(this); - } - catch (JSONPointerException e) { - return null; - } - } - -/** - * Remove a name and its value, if present. - * - * @param key The name to be removed. - * @return The value that was associated with the name, or null if there was no value. - */ - - public Object remove(String key) { - return this.map.remove(key); - } - -/** - * Determine if two JSONObjects are similar. They must contain the same set of names which must be - * associated with similar values. - * - * @param other The other JSONObject - * @return true if they are equal - */ - - public boolean similar(Object other) { - try { - if (!(other instanceof JSONObject)) { - return false; - } - if (!this.keySet().equals(((JSONObject)other).keySet())) { - return false; - } - return checkSimilarEntries(other); - } - catch (Exception e) { - return false; - } - } - - private boolean checkSimilarEntries(Object other) { - for (final Entry entry : this.entrySet()) { - String name = entry.getKey(); - Object valueThis = entry.getValue(); - Object valueOther = ((JSONObject)other).get(name); - if(valueThis == valueOther) { - continue; - } - if(valueThis == null) { - return false; - } - - if (!checkObjectType(valueThis, valueOther)) { - return false; - } - } - return true; - } - -/** - * Convenience function. Compares types of two objects. - * - * @param valueThis Object whose type is being checked - * @param valueOther Reference object - * @return true if match, else false - */ - - private boolean checkObjectType(Object valueThis, Object valueOther) { - if (valueThis instanceof JSONObject) { - return ((JSONObject)valueThis).similar(valueOther); - } - else if (valueThis instanceof JSONArray) { - return ((JSONArray)valueThis).similar(valueOther); - } - else if (valueThis instanceof Number && valueOther instanceof Number) { - return JSONUtils.isNumberSimilar((Number)valueThis, (Number)valueOther); - } - else if (valueThis instanceof JSONString && valueOther instanceof JSONString) { - return ((JSONString) valueThis).toJSONString().equals(((JSONString) valueOther).toJSONString()); - } - else if (!valueThis.equals(valueOther)) { - return false; - } - return true; - } - - -/** - * 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. - * @return A JSONArray of values. - * @throws JSONException If any of the values are non-finite numbers. - */ - - public JSONArray toJSONArray(JSONArray names) throws JSONException { - if (names == null || names.isEmpty()) { - return null; - } - JSONArray ja = new JSONArray(); - for (int i = 0; i < names.length(); i += 1) { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - -/** - * Make a JSON text of this JSONObject. For compactness, no whitespace is added. If this would not - * result in a syntactically correct JSON text, then null will be returned instead. - *

- * 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). - */ - - @Override - public String toString() { - try { - return this.toString(0); - } - catch (Exception e) { - return null; - } - } - -/** - * Make a pretty-printed JSON text of this JSONObject. - * - *

If

{@code 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:

{@code {
- *  "key1": 1,
- *  "key2": "value 2",
- *  "key3": 3
- * }}
- *

- * Warning: This method assumes that the data structure is acyclical. - * - * - * @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. - */ - - public String toString(int indentFactor) throws JSONException { - // 6 characters are the minimum to serialise a key value pair e.g.: "k":1, - // and we don't want to oversize the initial capacity - int initialSize = map.size() * 6; - Writer w = new StringBuilderWriter(Math.max(initialSize, 16)); - return this.write(w, indentFactor, 0).toString(); - } - - /** - * 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 - */ - - // TODO: Uncomment later - /* - public static Object wrap(Object object) { - return wrap(object, null); - } - */ - - /** - * 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 - * @param recursionDepth - * Variable for tracking the count of nested object creations. - * @param jsonParserConfiguration - * Variable to pass parser custom configuration for json parsing. - * @return The wrapped value - */ - - // TODO: Uncomment later - /* - static Object wrap(Object object, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - return wrap(object, null, recursionDepth, jsonParserConfiguration); - } - - private static Object wrap(Object object, Set objectsRecord) { - return wrap(object, objectsRecord, 0, new JSONParserConfiguration()); - } - */ - - // TODO: Uncomment later - /* - private static Object wrap(Object object, Set objectsRecord, int recursionDepth, JSONParserConfiguration jsonParserConfiguration) { - try { - if (Null.TYPE.equals(object)) { - return Null.TYPE; - } - if (object instanceof JSONObject || object instanceof JSONArray - || object instanceof JSONString || object instanceof String - || 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 BigInteger || object instanceof BigDecimal - || object instanceof Enum) { - return object; - } - - if (object instanceof Collection) { - Collection coll = (Collection) object; - return new JSONArray(coll, recursionDepth, jsonParserConfiguration); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map) { - Map map = (Map) object; - return new JSONObject(map, recursionDepth, jsonParserConfiguration); - } - 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(); - } - if (objectsRecord != null) { - return new JSONObject(object, objectsRecord); - } - return new JSONObject(object); - } - catch (JSONException exception) { - throw exception; - } 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. - * - * @param writer the writer object - * @return The writer. - * @throws JSONException if a called function has an error - */ - public Writer write(Writer writer) throws JSONException { - return this.write(writer, 0, 0); - } - - static 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) { - // may throw an exception - processJsonStringToWriteValue(writer, value); - } else if (value instanceof String) { - // assuming most values are Strings, so testing it early - JSONUtils.quote(value.toString(), writer); - return writer; - } else if (value instanceof Number) { - // may throw an exception - processNumberToWriteValue(writer, (Number) value); - } else if (value instanceof Boolean) { - writer.write(value.toString()); - } else if (value instanceof Enum) { - writer.write(JSONUtils.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 { - JSONUtils.quote(value.toString(), writer); - } - return writer; - } - - /** - * Convenience function to reduce cog complexity of calling method; writes value if string is valid - * @param writer Object doing the writing - * @param value Value to be written - * @throws IOException if something goes wrong - */ - private static void processJsonStringToWriteValue(Writer writer, Object value) throws IOException { - // JSONString must be checked first, so it can overwrite behaviour of other types below - Object o; - try { - o = ((JSONString) value).toJSONString(); - } catch (Exception e) { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : JSONUtils.quote(value.toString())); - } - - /** - * Convenience function to reduce cog complexity of calling method; writes value if number is valid - * @param writer Object doing the writing - * @param value Value to be written - * @throws IOException if something goes wrong - */ - private static void processNumberToWriteValue(Writer writer, Number value) throws IOException { - // not all Numbers may match actual JSON Numbers. i.e. fractions or Imaginary - final String numberAsString = JSONUtils.numberToString(value); - if(JSONUtils.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 - JSONUtils.quote(numberAsString, 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

{@code 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:

{@code {
-	 *  "key1": 1,
-	 *  "key2": "value 2",
-	 *  "key3": 3
-	 * }}
- *

- * 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. - * @return The writer. - * @throws JSONException if a called function has an error or a write error - * occurs - */ - - public Writer write(Writer writer, int indentFactor, int indent) - throws JSONException { - try { - boolean needsComma = false; - final int length = this.length(); - writer.write('{'); - - if (length == 1) { - final Entry entry = this.entrySet().iterator().next(); - final String key = entry.getKey(); - writer.write(JSONUtils.quote(key)); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - // might throw an exception - attemptWriteValue(writer, indentFactor, indent, entry, key); - } else if (length != 0) { - writeContent(writer, indentFactor, indent, needsComma); - } - writer.write('}'); - return writer; - } catch (IOException exception) { - throw new JSONException(exception); - } - } - - /** - * Convenience function. Writer attempts to write formatted content - * @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 needsComma - * Boolean flag indicating a comma is needed - * @throws IOException - * If something goes wrong - */ - private void writeContent(Writer writer, int indentFactor, int indent, boolean needsComma) throws IOException { - final int newIndent = indent + indentFactor; - for (final Entry entry : this.entrySet()) { - if (needsComma) { - writer.write(','); - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, newIndent); - final String key = entry.getKey(); - writer.write(JSONUtils.quote(key)); - writer.write(':'); - if (indentFactor > 0) { - writer.write(' '); - } - attemptWriteValue(writer, indentFactor, newIndent, entry, key); - needsComma = true; - } - if (indentFactor > 0) { - writer.write('\n'); - } - indent(writer, indent); - } - - /** - * Convenience function. Writer attempts to write a value. - * @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 entry - * Contains the value being written - * @param key - * Identifies the value - * @throws JSONException if a called function has an error or a write error - * occurs - - */ - private static void attemptWriteValue(Writer writer, int indentFactor, int indent, Entry entry, String key) { - try{ - writeValue(writer, entry.getValue(), indentFactor, indent); - } catch (Exception e) { - throw new JSONException("Unable to write JSONObject value for key: " + key, e); - } - } - - /** - * Returns a java.util.Map containing all of the entries in this object. - * If an entry in the object is a JSONArray or JSONObject it will also - * be converted. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a java.util.Map containing the entries of this object - */ - public Map toMap() { - Map results = new HashMap(); - for (Entry entry : this.entrySet()) { - Object value; - if (entry.getValue() == null || Null.TYPE.equals(entry.getValue())) { - value = null; - } else if (entry.getValue() instanceof JSONObject) { - value = ((JSONObject) entry.getValue()).toMap(); - } else if (entry.getValue() instanceof JSONArray) { - value = ((JSONArray) entry.getValue()).toList(); - } else { - value = entry.getValue(); - } - results.put(entry.getKey(), value); - } - return results; - } - - /** - * Create a new JSONException in a common format for incorrect conversions. - * @param key name of the key - * @param valueType the type of value being coerced to - * @param cause optional cause of the coercion failure - * @return JSONException that can be thrown. - */ - private JSONException wrongValueFormatException( - String key, - String valueType, - Object value, - Throwable cause) { - if(value == null) { - - return new JSONException( - "JSONObject[" + JSONUtils.quote(key) + "] is not a " + valueType + " (null)." - , cause); - } - // don't try to toString collections or known object types that could be large. - if(value instanceof Map || value instanceof Iterable || value instanceof JSONObject) { - return new JSONException( - "JSONObject[" + JSONUtils.quote(key) + "] is not a " + valueType + " (" + value.getClass() + ")." - , cause); - } - return new JSONException( - "JSONObject[" + JSONUtils.quote(key) + "] is not a " + valueType + " (" + value.getClass() + " : " + value + ")." - , cause); - } - - - /** - * Helper method to extract the raw Class from Type. - */ - private Class getRawType(Type type) { - if (type instanceof Class) { - return (Class) type; - } else if (type instanceof ParameterizedType) { - return (Class) ((ParameterizedType) type).getRawType(); - } else if (type instanceof GenericArrayType) { - return Object[].class; // Simplified handling for arrays - } - return Object.class; // Fallback - } - - /** - * Extracts the element Type for a Collection Type. - */ - private Type getElementType(Type type) { - if (type instanceof ParameterizedType) { - Type[] args = ((ParameterizedType) type).getActualTypeArguments(); - return args.length > 0 ? args[0] : Object.class; - } - return Object.class; - } - - /** - * Extracts the key and value Types for a Map Type. - */ - private Type[] getMapTypes(Type type) { - if (type instanceof ParameterizedType) { - Type[] args = ((ParameterizedType) type).getActualTypeArguments(); - if (args.length == 2) { - return args; - } - } - return new Type[]{Object.class, Object.class}; // Default: String keys, Object values - } - - - //TODO: Remove code - /** - * Deserializes a JSON string into an instance of the specified class. - * - *

This method attempts to map JSON key-value pairs to the corresponding fields - * of the given class. It supports basic data types including int, double, float, - * long, and boolean (as well as their boxed counterparts). The class must have a - * no-argument constructor, and the field names in the class must match the keys - * in the JSON string. - * - * @param the type of the object to return - * @param jsonString json in string format - * @param clazz the class of the object to be returned - * @return an instance of Object T with fields populated from the JSON string - */ - //TODO: Remove code - /* - public static T fromJson(String jsonString, Class clazz) { - JSONObject jsonObject = new JSONObject(jsonString); - return jsonObject.fromJson(clazz); - } - */ - - - - /** - * Deserializes a JSON string into an instance of the specified class. - * - *

This method attempts to map JSON key-value pairs to the corresponding fields - * of the given class. It supports basic data types including {@code int}, {@code double}, - * {@code float}, {@code long}, and {@code boolean}, as well as their boxed counterparts. - * The target class must have a no-argument constructor, and its field names must match - * the keys in the JSON string. Static fields are ignored. - * - *

Note: Only classes that are explicitly supported and registered within - * the {@code JSONObject} context can be deserialized. If the provided class is not among those, - * this method will not be able to deserialize it. This ensures that only a limited and - * controlled set of types can be instantiated from JSON for safety and predictability. - * - * @param clazz the class of the object to be returned - * @param the type of the object - * @return an instance of type {@code T} with fields populated from the JSON string - * @throws IllegalArgumentException if the class is not supported for deserialization - */ - @SuppressWarnings("unchecked") - public T fromJson(Class clazz) { - try { - T obj = clazz.getDeclaredConstructor().newInstance(); - for (Field field : clazz.getDeclaredFields()) { - if (Modifier.isStatic(field.getModifiers())) { - continue; - } - field.setAccessible(true); - String fieldName = field.getName(); - if (has(fieldName)) { - Object value = get(fieldName); - Type fieldType = field.getGenericType(); - Object convertedValue = convertValue(value, fieldType); - field.set(obj, convertedValue); - } - } - return obj; - } catch (NoSuchMethodException e) { - throw new JSONException("No no-arg constructor for class: " + clazz.getName(), e); - } catch (Exception e) { - throw new JSONException("Failed to instantiate or set field for class: " + clazz.getName(), e); - } - } - - /** - * Recursively converts a value to the target Type, handling nested generics for Collections and Maps. - */ - private Object convertValue(Object value, Type targetType) throws JSONException { - if (value == null) { - return null; - } - - Class rawType = getRawType(targetType); - - // Direct assignment - if (rawType.isAssignableFrom(value.getClass())) { - return value; - } - - if (rawType == int.class || rawType == Integer.class) { - return ((Number) value).intValue(); - } else if (rawType == double.class || rawType == Double.class) { - return ((Number) value).doubleValue(); - } else if (rawType == float.class || rawType == Float.class) { - return ((Number) value).floatValue(); - } else if (rawType == long.class || rawType == Long.class) { - return ((Number) value).longValue(); - } else if (rawType == boolean.class || rawType == Boolean.class) { - return value; - } else if (rawType == String.class) { - return value; - } else if (rawType == BigDecimal.class) { - return new BigDecimal((String) value); - } else if (rawType == BigInteger.class) { - return new BigInteger((String) value); - } - - // Enum conversion - if (rawType.isEnum() && value instanceof String) { - return stringToEnum(rawType, (String) value); - } - - // Collection handling (e.g., List>>) - if (Collection.class.isAssignableFrom(rawType)) { - if (value instanceof JSONArray) { - Type elementType = getElementType(targetType); - return fromJsonArray((JSONArray) value, rawType, elementType); - } - } - // Map handling (e.g., Map>) - else if (Map.class.isAssignableFrom(rawType) && value instanceof JSONObject) { - Type[] mapTypes = getMapTypes(targetType); - Type keyType = mapTypes[0]; - Type valueType = mapTypes[1]; - return convertToMap((JSONObject) value, keyType, valueType, rawType); - } - // POJO handling (including custom classes like Tuple) - else if (!rawType.isPrimitive() && !rawType.isEnum() && value instanceof JSONObject) { - // Recurse with the raw class for POJO deserialization - return ((JSONObject) value).fromJson(rawType); - } - - // Fallback - return value.toString(); - } - - /** - * Converts a JSONObject to a Map with the specified generic key and value Types. - * Supports nested types via recursive convertValue. - */ - private Map convertToMap(JSONObject jsonMap, Type keyType, Type valueType, Class mapType) throws JSONException { - try { - @SuppressWarnings("unchecked") - Map createdMap = new HashMap(); - - for (Object keyObj : jsonMap.keySet()) { - String keyStr = (String) keyObj; - Object mapValue = jsonMap.get(keyStr); - // Convert key (e.g., String to Integer for Map) - Object convertedKey = convertValue(keyStr, keyType); - // Convert value recursively (handles nesting) - Object convertedValue = convertValue(mapValue, valueType); - createdMap.put(convertedKey, convertedValue); - } - return createdMap; - } catch (Exception e) { - throw new JSONException("Failed to convert JSONObject to Map: " + mapType.getName(), e); - } - } - - /** - * Converts a String to an Enum value. - * The unchecked warning is suppressed when casting valueOf() to E - * @param enumClass enum class - * @param value value of enum - * @param type of enum - */ - @SuppressWarnings("unchecked") - private E stringToEnum(Class enumClass, String value) throws JSONException { - try { - @SuppressWarnings("unchecked") - Class enumType = (Class) enumClass; - Method valueOfMethod = enumType.getMethod("valueOf", String.class); - return (E) valueOfMethod.invoke(null, value); - } catch (Exception e) { - throw new JSONException("Failed to convert string to enum: " + value + " for " + enumClass.getName(), e); - } - } - - /** - * Deserializes a JSONArray into a Collection, supporting nested generics. - * Uses recursive convertValue for elements. - */ - @SuppressWarnings("unchecked") - private Collection fromJsonArray(JSONArray jsonArray, Class collectionType, Type elementType) throws JSONException { - try { - Collection collection = getCollection(collectionType); - - for (int i = 0; i < jsonArray.length(); i++) { - Object jsonElement = jsonArray.get(i); - // Recursively convert each element using the full element Type (handles nesting) - Object convertedValue = convertValue(jsonElement, elementType); - collection.add((T) convertedValue); - } - return collection; - } catch (Exception e) { - throw new JSONException("Failed to convert JSONArray to Collection: " + collectionType.getName(), e); - } - } - - /** - * Creates and returns a new instance of a supported {@link Collection} implementation - * based on the specified collection type. - *

- * This method currently supports the following collection types: - *

    - *
  • {@code List.class}
  • - *
  • {@code ArrayList.class}
  • - *
  • {@code Set.class}
  • - *
  • {@code HashSet.class}
  • - *
- * If the provided type does not match any of the supported types, a {@link JSONException} - * is thrown. - * - * @param collectionType the {@link Class} object representing the desired collection type - * @return a new empty instance of the specified collection type - * @throws JSONException if the specified type is not a supported collection type - */ - private Collection getCollection(Class collectionType) throws JSONException { - if (collectionType == List.class || collectionType == ArrayList.class) { - return new ArrayList(); - } else if (collectionType == Set.class || collectionType == HashSet.class) { - return new HashSet(); - } else { - throw new JSONException("Unsupported Collection type: " + collectionType.getName()); - } - } -} diff --git a/moe-json/src/main/java/org/json/JSONParserConfiguration.java b/moe-json/src/main/java/org/json/JSONParserConfiguration.java deleted file mode 100644 index fa8f42f..0000000 --- a/moe-json/src/main/java/org/json/JSONParserConfiguration.java +++ /dev/null @@ -1,164 +0,0 @@ -package org.json; - -/** - * Configuration object for the JSON parser. The configuration is immutable. - */ - -public class JSONParserConfiguration extends ParserConfiguration { - -/** - * Used to indicate whether to overwrite duplicate key or not. - */ - - private boolean overwriteDuplicateKey; - -/** - * Used to indicate whether to convert java null values to JSONObject.NULL or ignoring the entry - * when converting java maps. - */ - - private boolean useNativeNulls; - -/** - * This flag, when set to true, instructs the parser to enforce strict mode when parsing JSON text. - * Garbage chars at the end of the doc, unquoted string, and single-quoted strings are all disallowed. - */ - - private boolean strictMode; - -/** - * Configuration with the default values. - */ - - public JSONParserConfiguration() { - super(); - this.overwriteDuplicateKey = false; - // DO NOT DELETE THE FOLLOWING LINE -- it is used for strictMode testing - // this.strictMode = true; - } - - @Override - protected JSONParserConfiguration clone() { - JSONParserConfiguration clone = new JSONParserConfiguration(); - clone.overwriteDuplicateKey = overwriteDuplicateKey; - clone.strictMode = strictMode; - clone.maxNestingDepth = maxNestingDepth; - clone.keepStrings = keepStrings; - clone.useNativeNulls = useNativeNulls; - return clone; - } - -/** - * Defines the maximum nesting depth that the parser will descend before throwing an exception - * when parsing a map into JSONObject or parsing a {@link java.util.Collection} instance into - * JSONArray. The default max nesting depth is 512, which means the parser will throw a JsonException - * if the maximum depth is reached. - * - * @param maxNestingDepth the maximum nesting depth allowed to the JSON parser - * @return The existing configuration will not be modified. A new configuration is returned. - */ - - @SuppressWarnings("unchecked") - @Override - public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) { - JSONParserConfiguration clone = this.clone(); - clone.maxNestingDepth = maxNestingDepth; - return clone; - } - -/** - * Controls the parser's behavior when meeting duplicate keys. - * If set to false, the parser will throw a JSONException when meeting a duplicate key. - * Or the duplicate key's value will be overwritten. - * - * @param overwriteDuplicateKey defines should the parser overwrite duplicate keys. - * @return The existing configuration will not be modified. A new configuration is returned. - */ - - public JSONParserConfiguration withOverwriteDuplicateKey(final boolean overwriteDuplicateKey) { - JSONParserConfiguration clone = this.clone(); - clone.overwriteDuplicateKey = overwriteDuplicateKey; - return clone; - } - -/** - * Controls the parser's behavior when meeting Java null values while converting maps. - * If set to true, the parser will put a JSONObject.NULL into the resulting JSONObject. - * Or the map entry will be ignored. - * - * @param useNativeNulls defines if the parser should convert null values in Java maps - * @return The existing configuration will not be modified. A new configuration is returned. - */ - - public JSONParserConfiguration withUseNativeNulls(final boolean useNativeNulls) { - JSONParserConfiguration clone = this.clone(); - clone.useNativeNulls = useNativeNulls; - return clone; - } - -/** - * Sets the strict mode configuration for the JSON parser with default true value - *

- * When strict mode is enabled, the parser will throw a JSONException if it encounters an invalid character - * immediately following the final ']' character in the input. This is useful for ensuring strict adherence to the - * JSON syntax, as any characters after the final closing bracket of a JSON array are considered invalid. - * - * @return a new JSONParserConfiguration instance with the updated strict mode setting - */ - - public JSONParserConfiguration withStrictMode() { - return withStrictMode(true); - } - -/** - * Sets the strict mode configuration for the JSON parser. - *

- * When strict mode is enabled, the parser will throw a JSONException if it encounters an invalid character - * immediately following the final ']' character in the input. This is useful for ensuring strict adherence to the - * JSON syntax, as any characters after the final closing bracket of a JSON array are considered invalid. - * - * @param mode a boolean value indicating whether strict mode should be enabled or not - * @return a new JSONParserConfiguration instance with the updated strict mode setting - */ - - public JSONParserConfiguration withStrictMode(final boolean mode) { - JSONParserConfiguration clone = this.clone(); - clone.strictMode = mode; - return clone; - } - -/** - * The parser's behavior when meeting duplicate keys, controls whether the parser should - * overwrite duplicate keys or not. - * - * @return The overwriteDuplicateKey configuration value. - */ - - public boolean isOverwriteDuplicateKey() { - return overwriteDuplicateKey; - } - -/** - * The parser's behavior when meeting a null value in a java map, controls whether the parser should - * write a JSON entry with a null value (isUseNativeNulls() == true) - * or ignore that map entry (isUseNativeNulls() == false). - * - * @return The useNativeNulls configuration value. - */ - - public boolean isUseNativeNulls() { - return useNativeNulls; - } - - -/** - * The parser throws an Exception when strict mode is true and tries to parse invalid JSON characters. - * Otherwise, the parser is more relaxed and might tolerate some invalid characters. - * - * @return the current strict mode setting. - */ - - public boolean isStrictMode() { - return strictMode; - } -} diff --git a/moe-json/src/main/java/org/json/JSONPointer.java b/moe-json/src/main/java/org/json/JSONPointer.java deleted file mode 100644 index 44940e3..0000000 --- a/moe-json/src/main/java/org/json/JSONPointer.java +++ /dev/null @@ -1,315 +0,0 @@ -package org.json; - -import java.io.UnsupportedEncodingException; -import java.net.URLDecoder; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/* -Public Domain. -*/ - -/** - * 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 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 fails, an appropriate exception is thrown. If the navigation fails to find a - * match, a JSONPointerException is thrown. - * - * @author JSON.org - * @version 2016-05-14 - */ - -public class JSONPointer { - - // used for URL encoding and decoding - private static final String ENCODING = "utf-8"; - // Segments for the JSONPointer string - private final List refTokens; - -/** - * 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 - */ - - public JSONPointer(final String pointer) { - if (pointer == null) { - throw new NullPointerException("pointer cannot be null"); - } - if (pointer.isEmpty() || "#".equals(pointer)) { - this.refTokens = Collections.emptyList(); - return; - } - String refs; - if (pointer.startsWith("#/")) { - refs = pointer.substring(2); - try { - // URI fragments preserve plus signs rather than treating them as form-encoded spaces. - refs = URLDecoder.decode(refs.replace("+", "%2B"), ENCODING); - } catch ( - UnsupportedEncodingException e) { - throw new RuntimeException(e); - } - } - else if (pointer.startsWith("/")) { - refs = pointer.substring(1); - } - else { - throw new IllegalArgumentException("a JSON pointer should start with '/' or '#/'"); - } - this.refTokens = new ArrayList(); - int slashIdx = -1; - int prevSlashIdx = 0; - do { - prevSlashIdx = slashIdx + 1; - slashIdx = refs.indexOf('/', prevSlashIdx); - 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(""); - } - else if (slashIdx >= 0) { - final String token = refs.substring(prevSlashIdx, slashIdx); - this.refTokens.add(unescape(token)); - } - else { - // last item after separator, or no separator at all. - final String token = refs.substring(prevSlashIdx); - this.refTokens.add(unescape(token)); - } - } - while (slashIdx >= 0); - // using split does not take into account consecutive separators or "ending nulls" - // for (String token : refs.split("/")) { - // this.refTokens.add(unescape(token)); - // } - } - -/** - * Constructs a new JSONPointer instance with the provided list of reference tokens. - * - * @param refTokens A list of strings representing the reference tokens for the JSON Pointer. Each - * token identifies a step in the path to the targeted value. - */ - - public JSONPointer(List refTokens) { - 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(); - } - -/** - * @see rfc6901 section 3 - */ - - private static String unescape(String token) { - return token.replace("~1", "/").replace("~0", "~"); - } - -/** - * Matches a JSONArray element by ordinal position - * - * @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 - */ - - private static Object readByIndexToken(Object current, String indexToken) throws JSONPointerException { - try { - int index = Integer.parseInt(indexToken); - JSONArray currentArr = (JSONArray) current; - if (index >= currentArr.length()) { - throw new JSONPointerException(String.format( - "index %s is out of bounds - the array has %d elements", - indexToken, - currentArr.length())); - } - try { - return currentArr.get(index); - } - catch ( - JSONException e) { - throw new JSONPointerException("Error reading value at index position " + index, e); - } - } - catch ( - NumberFormatException e) { - throw new JSONPointerException(String.format( - "%s is not an array index", indexToken), e); - } - } - -/** - * Escapes path segment values to an unambiguous form. The escape char to be inserted is '~'. The - * chars to be escaped are ~, which maps to ~0, and /, which maps to ~1. - * - * @param token the JSONPointer segment value to be escaped - * @return the escaped value for the token - * @see rfc6901 section 3 - */ - - private static String escape(String token) { - return token.replace("~", "~0") - .replace("/", "~1"); - } - -/** - * 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. - * - * @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 - */ - - public Object queryFrom(Object document) throws JSONPointerException { - if (this.refTokens.isEmpty()) { - return document; - } - Object current = document; - for (String token : this.refTokens) { - if (current instanceof JSONObject) { - current = ((JSONObject) current).opt(token); - } - else if (current instanceof JSONArray) { - current = readByIndexToken(current, token); - } - else { - throw new JSONPointerException(String.format( - "value [%s] is not an array or object therefore its key %s cannot be resolved", - current, token)); - } - } - return current; - } - -/** - * Returns a string representing the JSONPointer path value using string representation - */ - - @Override - public String toString() { - StringBuilder rval = new StringBuilder(); - for (String token : this.refTokens) { - rval.append('/').append(escape(token)); - } - return rval.toString(); - } - -/** - * Returns a string representing the JSONPointer path value using URI fragment identifier - * representation - * - * @return a uri fragment string - */ - - public String toURIFragment() { - try { - StringBuilder rval = new StringBuilder("#"); - for (String token : this.refTokens) { - rval.append('/').append(URLEncoder.encode(escape(token), ENCODING).replace("+", "%20")); - } - return rval.toString(); - } - catch ( - UnsupportedEncodingException e) { - 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(); - -/** - * Constructs a new Builder object. - */ - - public Builder() { - } - - /** - * Creates a {@code JSONPointer} instance using the tokens previously set using the - * {@link #append(String)} method calls. - * - * @return a JSONPointer object - */ - - 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/moe-json/src/main/java/org/json/JSONPointerException.java b/moe-json/src/main/java/org/json/JSONPointerException.java deleted file mode 100644 index c855b57..0000000 --- a/moe-json/src/main/java/org/json/JSONPointerException.java +++ /dev/null @@ -1,42 +0,0 @@ -package org.json; - -/* -Public Domain. -*/ - -import java.io.Serial; - -/** - * The JSONPointerException is thrown by {@link JSONPointer} if an error occurs during evaluating a - * pointer. - * - * @author JSON.org - * @version 2016-05-13 - */ - -public class JSONPointerException extends JSONException { - - @Serial - private static final long serialVersionUID = 8872944667561856751L; - -/** - * Constructs a new JSONPointerException with the specified error message. - * - * @param message The detail message describing the reason for the exception. - */ - - public JSONPointerException(String message) { - super(message); - } - -/** - * Constructs a new JSONPointerException with the specified error message and cause. - * - * @param message The detail message describing the reason for the exception. - * @param cause The cause of the exception. - */ - - public JSONPointerException(String message, Throwable cause) { - super(message, cause); - } -} diff --git a/moe-json/src/main/java/org/json/JSONString.java b/moe-json/src/main/java/org/json/JSONString.java deleted file mode 100644 index 4f9f04f..0000000 --- a/moe-json/src/main/java/org/json/JSONString.java +++ /dev/null @@ -1,24 +0,0 @@ -package org.json; - -/* -Public Domain. - */ - -/** - * The JSONString interface allows a toJSONString() method so that a class - * can change the behavior of JSONObject.toString(), JSONArray.toString(), - * and JSONWriter.value(Object). The toJSONString method will - * be used instead of the default behavior of using the Object's toString() method and - * quoting the result. - */ - -public interface JSONString { - -/** - * The toJSONString method allows a class to produce its own JSON serialization. - * - * @return A strictly syntactically correct JSON text. - */ - - public String toJSONString(); -} diff --git a/moe-json/src/main/java/org/json/JSONTokener.java b/moe-json/src/main/java/org/json/JSONTokener.java deleted file mode 100644 index b72e652..0000000 --- a/moe-json/src/main/java/org/json/JSONTokener.java +++ /dev/null @@ -1,682 +0,0 @@ -package org.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.nio.charset.Charset; - -/* -Public Domain. - */ - -/** - * 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 { - /** - * Reader for the input. - */ - private final Reader reader; - /** - * 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. - */ - private long characterPreviousLine; - - // access to this object is required for strict mode checking - private JSONParserConfiguration jsonParserConfiguration; - - /** - * Construct a JSONTokener from a Reader. The caller must close the Reader. - * - * @param reader the source. - */ - public JSONTokener(Reader reader) { - this(reader, new JSONParserConfiguration()); - } - - /** - * Construct a JSONTokener from a Reader with a given JSONParserConfiguration. The caller must close the Reader. - * - * @param reader the source. - * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. - * - */ - public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguration) { - this.jsonParserConfiguration = jsonParserConfiguration; - this.reader = reader.markSupported() - ? reader - : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.characterPreviousLine = 0; - this.line = 1; - } - - /** - * Construct a JSONTokener from an InputStream. The caller must close the input stream. - * - * @param inputStream The source. - */ - public JSONTokener(InputStream inputStream) { - this(inputStream, new JSONParserConfiguration()); - } - - /** - * Construct a JSONTokener from an InputStream. The caller must close the input stream. - * - * @param inputStream The source. - * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. - */ - public JSONTokener(InputStream inputStream, JSONParserConfiguration jsonParserConfiguration) { - this(new InputStreamReader(inputStream, Charset.forName("UTF-8")), jsonParserConfiguration); - } - - - /** - * Construct a JSONTokener from a string. - * - * @param source A source string. - */ - public JSONTokener(String source) { - this(new StringReader(source)); - } - - /** - * Construct a JSONTokener from an InputStream. The caller must close the input stream. - * - * @param source The source. - * @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser. - */ - public JSONTokener(String source, JSONParserConfiguration jsonParserConfiguration) { - this(new StringReader(source), jsonParserConfiguration); - } - - /** - * 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. - */ - public static int dehexchar(char c) { - if (c >= '0' && c <= '9') { - return c - '0'; - } - if (c >= 'A' && c <= 'F') { - return c - ('A' - 10); - } - if (c >= 'a' && c <= 'f') { - return c - ('a' - 10); - } - return -1; - } - - /** - * Getter - * - * @return jsonParserConfiguration - */ - public JSONParserConfiguration getJsonParserConfiguration() { - return jsonParserConfiguration; - } - - /** - * Setter - * - * @param jsonParserConfiguration new value for jsonParserConfiguration - * @deprecated method should not be used - */ - @Deprecated - public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) { - setJsonParserConfigurationInternal(jsonParserConfiguration); - } - - void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfiguration) { - this.jsonParserConfiguration = jsonParserConfiguration; - } - - /** - * 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() { - return this.eof && !this.usePrevious; - } - - - /** - * Determine if the source string still contains characters that next() - * can consume. - * - * @return true if not yet at the end of the source. - * @throws JSONException thrown if there is an error stepping forward - * or backward while checking for more data. - */ - public boolean more() throws JSONException { - if (this.usePrevious) { - return true; - } - try { - this.reader.mark(1); - } catch ( - IOException e) { - throw new JSONException("Unable to preserve stream position", e); - } - try { - // -1 is EOF, but next() can not consume the null character '\0' - if (this.reader.read() <= 0) { - this.eof = true; - return false; - } - this.reader.reset(); - } catch ( - IOException e) { - throw new JSONException("Unable to read the next character from the stream", e); - } - return true; - } - - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - * @throws JSONException Thrown if there is an error reading the source string. - */ - public char next() throws JSONException { - int c; - if (this.usePrevious) { - this.usePrevious = false; - c = this.previous; - } else { - try { - c = this.reader.read(); - } catch ( - IOException exception) { - throw new JSONException(exception); - } - } - if (c <= 0) { // End of stream - this.eof = true; - return 0; - } - this.incrementIndexes(c); - this.previous = (char) c; - return this.previous; - } - - /** - * Get the last character read from the input or '\0' if nothing has been read yet. - * - * @return the last character read from the input. - */ - protected char getPrevious() { - return this.previous; - } - - /** - * 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) { - this.index++; - if (c == '\r') { - this.line++; - this.characterPreviousLine = this.character; - this.character = 0; - } else if (c == '\n') { - if (this.previous != '\r') { - this.line++; - this.characterPreviousLine = this.character; - } - this.character = 0; - } else { - this.character++; - } - } - } - - /** - * 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. - */ - public char next(char c) throws JSONException { - char n = this.next(); - if (n != c) { - if (n > 0) { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + - n + "'"); - } - throw this.syntaxError("Expected '" + c + "' and instead saw ''"); - } - return n; - } - - - /** - * 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. - */ - public String next(int n) throws JSONException { - if (n == 0) { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while (pos < n) { - chars[pos] = this.next(); - if (this.end()) { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - - /** - * 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. - */ - public char nextClean() throws JSONException { - for (; ; ) { - char c = this.next(); - if (c == 0 || c > ' ') { - return c; - } - } - } - - - /** - * Return the characters up to the next close quote character. - * Backslash processing is done. The formal JSON format does not - * allow strings in single quotes, but an implementation is allowed to - * accept them. - * - * @param quote The quoting character, either - * " (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 (; ; ) { - c = this.next(); - switch (c) { - case - 0: - case - '\n': - case - '\r': - throw this.syntaxError("Unterminated string. " + - "Character with int code " + (int) c + " is not allowed within a quoted 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': - String next = this.next(4); - try { - sb.append((char) Integer.parseInt(next, 16)); - } catch ( - NumberFormatException e) { - throw this.syntaxError("Illegal escape. " + - "\\u must be followed by a 4 digit hexadecimal number. \\" + next + " is not valid.", e); - } - break; - case - '"': - case - '\'': - case - '\\': - case - '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape. Escape sequence \\" + c + " is not valid."); - } - break; - default: - if (c == quote) { - return sb.toString(); - } - sb.append(c); - } - } - } - - - /** - * Get the text up but not including the specified character or the - * end of line, whichever comes first. - * - * @param delimiter A delimiter character. - * @return A string. - * @throws JSONException Thrown if there is an error while searching - * for the delimiter - */ - public String nextTo(char delimiter) throws JSONException { - StringBuilder sb = new StringBuilder(); - for (; ; ) { - char c = this.next(); - if (c == delimiter || c == 0 || c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * 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 - */ - public String nextTo(String delimiters) throws JSONException { - char c; - StringBuilder sb = new StringBuilder(); - for (; ; ) { - c = this.next(); - if (delimiters.indexOf(c) >= 0 || c == 0 || - c == '\n' || c == '\r') { - if (c != 0) { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * - * @return An object. - * @throws JSONException If syntax error. - */ - public Object nextValue() throws JSONException { - char c = this.nextClean(); - switch (c) { - case - '{': - this.back(); - try { - return new JSONObject(this, jsonParserConfiguration, false); - } catch ( - StackOverflowError e) { - throw new JSONException("JSON Array or Object depth too large to process.", e); - } - case - '[': - this.back(); - try { - return new JSONArray(this, jsonParserConfiguration, false); - } catch ( - StackOverflowError e) { - throw new JSONException("JSON Array or Object depth too large to process.", e); - } - } - return nextSimpleValue(c); - } - - Object nextSimpleValue(char c) { - String string; - - // Strict mode only allows strings with explicit double quotes - if (jsonParserConfiguration != null && - jsonParserConfiguration.isStrictMode() && - c == '\'') { - throw this.syntaxError("Strict mode error: Single quoted strings are not allowed"); - } - switch (c) { - case - '"': - case - '\'': - return this.nextString(c); - } - - /* - * Handle unquoted text. This could be the values true, false, or - * null, or it can be a number. An implementation (such as this one) - * is allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuilder sb = new StringBuilder(); - while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { - sb.append(c); - c = this.next(); - } - if (!this.eof) { - this.back(); - } - - string = sb.toString().trim(); - if ("".equals(string)) { - throw this.syntaxError("Missing value"); - } else if (jsonParserConfiguration != null && - jsonParserConfiguration.isStrictMode() && string.endsWith(".")) { - throw this.syntaxError(String.format("Strict mode error: Value '%s' ends with dot", string)); - } - Object obj = JSONUtils.stringToValue(string, jsonParserConfiguration); - // if obj is a boolean, look at string - if (jsonParserConfiguration != null && - jsonParserConfiguration.isStrictMode()) { - if (obj instanceof Boolean && !"true".equals(string) && !"false".equals(string)) { - // Strict mode only allows lowercase true or false - throw this.syntaxError(String.format("Strict mode error: Value '%s' is not lowercase boolean", obj)); - } else if (obj == Null.TYPE && !"null".equals(string)) { - // Strict mode only allows lowercase null - throw this.syntaxError(String.format("Strict mode error: Value '%s' is not lowercase null", obj)); - } else if (obj instanceof String) { - // Strict mode only allows strings with explicit double quotes - throw this.syntaxError(String.format("Strict mode error: Value '%s' is not surrounded by quotes", obj)); - } - } - return obj; - } - - - /** - * 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 - */ - public char skipTo(char to) throws JSONException { - char c; - try { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do - { - c = this.next(); - if (c == 0) { - // in some readers, reset() may throw an exception if - // the remaining portion of the input is greater than - // the mark size (1,000,000 above). - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return 0; - } - } while (c != to); - this.reader.mark(1); - } catch ( - IOException exception) { - throw new JSONException(exception); - } - this.back(); - return c; - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) { - return new JSONException(message + this.toString()); - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message The error message. - * @param causedBy The throwable that caused the error. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message, Throwable causedBy) { - return new JSONException(message + this.toString(), causedBy); - } - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - @Override - public String toString() { - return " at " + this.index + " [character " + this.character + " line " + - this.line + "]"; - } - - /** - * Closes the underlying reader, releasing any resources associated with it. - * - * @throws IOException If an I/O error occurs while closing the reader. - */ - public void close() throws IOException { - if (reader != null) { - reader.close(); - } - } -} diff --git a/moe-json/src/main/java/org/json/JSONUtils.java b/moe-json/src/main/java/org/json/JSONUtils.java deleted file mode 100644 index 0bee1c3..0000000 --- a/moe-json/src/main/java/org/json/JSONUtils.java +++ /dev/null @@ -1,552 +0,0 @@ -/* - * Copyright (c) DuxTechnica - * - * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not - * use this file except in compliance with the License. You may obtain a copy of the License by - * contacting: - * - * Dux Technica, contact@duxtechnica.com - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.json; - -import java.io.IOException; -import java.io.Writer; -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.regex.Pattern; - -public final class JSONUtils { - -/** - * 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+)?"); - -/** - * 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(); - // idx = 0 case is covered by behavior of .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; - } - -/** - * 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 instanceof Number && !numberIsFinite((Number) o)) { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } - - public static boolean numberIsFinite(Number n) { - if (n instanceof Double && (((Double) n).isInfinite() || ((Double) n).isNaN())) { - return false; - } - else if (n instanceof Float && (((Float) n).isInfinite() || ((Float) n).isNaN())) { - return false; - } - return true; - } - -/** - * 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) { - if (string == null || string.isEmpty()) { - return "\"\""; - } - Writer sw = new StringBuilderWriter(string.length() + 2); - try { - return quote(string, sw).toString(); - } - catch ( - IOException ignored) { - // will never happen - we are writing to a string writer - return ""; - } - } - -/** - * Quotes a string and appends the result to a given Writer. - * - * @param string The input string to be quoted. - * @param w The Writer to which the quoted string will be appended. - * @return The same Writer instance after appending the quoted string. - * @throws IOException If an I/O error occurs while writing to the Writer. - */ - - public static Writer quote(String string, Writer w) throws IOException { - if (string == null || string.isEmpty()) { - w.write("\"\""); - return w; - } - - char b; - char c = 0; - 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: - writeAsHex(w, c); - } - } - w.write('"'); - return w; - } - -/** - * Convenience method to reduce cognitive complexity of quote() - * - * @param w The Writer to which the quoted string will be appended. - * @param c Character to write - * @throws IOException - */ - - private static void writeAsHex(Writer w, char c) throws IOException { - String hhhh; - 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); - } - } - - /** - * Compares two numbers to see if they are similar. - * - * If either of the numbers are Double or Float instances, then they are checked to have - * a finite value. If either value is not finite (NaN or ±infinity), then this - * function will always return false. If both numbers are finite, they are first checked - * to be the same type and implement {@link Comparable}. If they do, then the actual - * {@link Comparable#compareTo(Object)} is called. If they are not the same type, or don't - * implement Comparable, then they are converted to {@link BigDecimal}s. Finally the - * BigDecimal values are compared using {@link BigDecimal#compareTo(BigDecimal)}. - * - * @param l the Left value to compare. Can not be null. - * @param r the right value to compare. Can not be null. - * @return true if the numbers are similar, false otherwise. - */ - - static boolean isNumberSimilar(Number l, Number r) { - if (!numberIsFinite(l) || !numberIsFinite(r)) { - // non-finite numbers are never similar - return false; - } - - // if the classes are the same and implement Comparable - // then use the built in compare first. - if(l.getClass().equals(r.getClass()) && l instanceof Comparable) { - @SuppressWarnings({ "rawtypes", "unchecked" }) - int compareTo = ((Comparable)l).compareTo(r); - return compareTo==0; - } - - // BigDecimal should be able to handle all of our number types that we support through - // documentation. Convert to BigDecimal first, then use the Compare method to - // decide equality. - final BigDecimal lBigDecimal = objectToBigDecimal(l, null, false); - final BigDecimal rBigDecimal = objectToBigDecimal(r, null, false); - if (lBigDecimal == null || rBigDecimal == null) { - return false; - } - return lBigDecimal.compareTo(rBigDecimal) == 0; - } - -/** - * @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) { - return objectToBigDecimal(val, defaultValue, true); - } - -/** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @param exact When true, then {@link Double} and {@link Float} values will be - * converted exactly. When false, they will be converted to {@link String} values - * before converting to {@link BigDecimal}. - * @return BigDecimal conversion of the original value, or the defaultValue if unable to convert. - */ - - static BigDecimal objectToBigDecimal(Object val, BigDecimal defaultValue, boolean exact) { - if (Null.TYPE.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) { - if (!numberIsFinite((Number)val)) { - return defaultValue; - } - if (exact) { - return new BigDecimal(((Number)val).doubleValue()); - } - // use the string constructor so that we maintain "nice" values for doubles and floats - // the double constructor will translate doubles to "exact" values instead of the likely - // intended representation - return new BigDecimal(val.toString()); - } - 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) { - return objectToBigInteger(val, defaultValue, new JSONParserConfiguration()); - } - - /** - * @param val value to convert - * @param defaultValue default value to return is the conversion doesn't work or is null. - * @param jsonParserConfiguration parser configuration whose {@code maxNumberLength} - * bounds the number of decimal digits in the resulting integer. Values whose - * integer part would exceed this length are treated as unconvertible and - * {@code defaultValue} is returned. Pass a configuration with - * {@link ParserConfiguration#UNDEFINED_MAXIMUM_NUMBER_LENGTH} to disable this check. - * @return BigInteger conversion of the original value, or the defaultValue if unable - * to convert. - */ - static BigInteger objectToBigInteger(Object val, BigInteger defaultValue, - JSONParserConfiguration jsonParserConfiguration) { - if (Null.TYPE.equals(val)) { - return defaultValue; - } - if (jsonParserConfiguration == null) { - jsonParserConfiguration = new JSONParserConfiguration(); - } - final int maxNumberLength = jsonParserConfiguration.getMaxNumberLength(); - if (val instanceof BigInteger){ - return (BigInteger) val; - } - if (val instanceof BigDecimal){ - BigDecimal bd = (BigDecimal) val; - // Same ceiling as the parse-time maxNumberLength guard: refuse to - // materialise an integer whose decimal representation would exceed - // maxNumberLength digits. Prevents DoS via short exponent literals - // like 1e100000000 (CVE-2026-59171, see issue #1063). - if (maxNumberLength != ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH - && (long) bd.precision() - bd.scale() > maxNumberLength) { - return defaultValue; - } - return bd.toBigInteger(); - } - if (val instanceof Double || val instanceof Float){ - if (!numberIsFinite((Number)val)) { - return defaultValue; - } - return BigDecimal.valueOf(((Number) val).doubleValue()).toBigInteger(); - } - if (val instanceof Long || val instanceof Integer - || val instanceof Short || val instanceof Byte){ - return BigInteger.valueOf(((Number) val).longValue()); - } - return attemptConversionToBigInteger(val, defaultValue, maxNumberLength); - } - - /** - * Convenience method to attempt conversion of value to BigInteger. - * Added to reduce complexity of objectToBigInteger() - * @param val the value to be converted - * @param defaultValue the default value to use if conversion is not attempted or fails - * @param maxNumberLength the max length allowed for BigIntegers - * @return the converted value, or the defaultValue - */ - private static BigInteger attemptConversionToBigInteger(Object val, BigInteger defaultValue, int maxNumberLength) { - // 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)) { - BigDecimal bd = new BigDecimal(valStr); - if (maxNumberLength != ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH - && (long) bd.precision() - bd.scale() > maxNumberLength) { - return defaultValue; - } - return bd.toBigInteger(); - } - return new BigInteger(valStr); - } catch (Exception e) { - return defaultValue; - } - } - - /** - * 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); - } - - - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * Warning! stringToValue(String) uses the default max number length. If you want to override it, - * use a suitable initialized JSONParserConfiguration and the method: stringToValue(String, JSONParserConfiguration). - * - * @param str 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 str) { - return stringToValue(str, new JSONParserConfiguration()); - } - - /** - * 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. - * @param jsonParserConfiguration the parser config - * @return A simple JSON value. If the string represents a number that is too large, - * a string will be returned. - * @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, JSONParserConfiguration jsonParserConfiguration) { - 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 Null.TYPE; - } - - /* - * 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 (jsonParserConfiguration == null) { - jsonParserConfiguration = new JSONParserConfiguration(); - } - // user declines max number checking - if (jsonParserConfiguration.getMaxNumberLength() == ParserConfiguration.UNDEFINED_MAXIMUM_NUMBER_LENGTH) { - return stringToNumber(string); - } - if (string.length() <= jsonParserConfiguration.getMaxNumberLength()) { - return stringToNumber(string); - } - } catch (Exception ignore) { - // Do nothing - } - } - return string; - } - - /** - * 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)) { - return getNumber(val, initial); - } - // block items like 00 01 etc. Java number parsers treat these as Octal. - checkForInvalidNumberFormat(val, initial); - // integer representation. - // This will narrow any values to the smallest reasonable Object representation - // (Integer, Long, or BigInteger) - - // BigInteger down conversion: We use a similar bitLength 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. - 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."); - } - - /** - * Convenience function. Block items like 00 01 etc. Java number parsers treat these as Octal. - * @param val value to convert - * @param initial first char of val - * @throws NumberFormatException if numbers are not formatted correctly - */ - private static void checkForInvalidNumberFormat(String val, char initial) { - if(initial == '0' && val.length() > 1) { - char at1 = val.charAt(1); - if(at1 >= '0' && at1 <= '9') { - throw new NumberFormatException("val ["+ val +"] is not a valid number."); - } - } else if (initial == '-' && val.length() > 2) { - char at1 = val.charAt(1); - char at2 = val.charAt(2); - if(at1 == '0' && at2 >= '0' && at2 <= '9') { - throw new NumberFormatException("val ["+ val +"] is not a valid number."); - } - } - } - - /** - * Convenience function. Handles val if it is a number - * @param val value to convert - * @param initial first char of val - * @return val as a BigDecimal - */ - private static Number getNumber(String val, char initial) { - // Use a BigDecimal all the time so we keep the original - // representation. BigDecimal doesn't support -0.0, ensure we - // keep that by forcing a decimal. - try { - BigDecimal bd = new BigDecimal(val); - if(initial == '-' && BigDecimal.ZERO.compareTo(bd)==0) { - return Double.valueOf(-0.0); - } - return bd; - } catch (NumberFormatException retryAsDouble) { - // this is to support "Hex Floats" like this: 0x1.0P-1074 - try { - Double d = Double.valueOf(val); - if(d.isNaN() || d.isInfinite()) { - throw new NumberFormatException("val ["+ val +"] is not a valid number."); - } - return d; - } catch (NumberFormatException ignore) { - throw new NumberFormatException("val ["+ val +"] is not a valid number."); - } - } - } -} diff --git a/moe-json/src/main/java/org/json/JSONWrapper.java b/moe-json/src/main/java/org/json/JSONWrapper.java deleted file mode 100644 index 006c58b..0000000 --- a/moe-json/src/main/java/org/json/JSONWrapper.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (c) DuxTechnica - * - * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not - * use this file except in compliance with the License. You may obtain a copy of the License by - * contacting: - * - * Dux Technica, contact@duxtechnica.com - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.json; - -import java.math.BigDecimal; -import java.math.BigInteger; -import java.util.Collection; -import java.util.Map; - -public class JSONWrapper { - - public Object wrap(Object object) { - return wrap(object, 0, new JSONParserConfiguration()); - } - - public Object wrap(Object object, int recursionDepth, JSONParserConfiguration pconfig) { - try { - if (Null.TYPE.equals(object)) { - return Null.TYPE; - } - if (object instanceof JSONObject || object instanceof JSONArray - || object instanceof JSONString || object instanceof String - || 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 BigInteger || object instanceof BigDecimal - || object instanceof Enum) { - return object; - } - - if (object instanceof Collection coll) { - return new JSONArray(coll, recursionDepth, pconfig); - } - if (object.getClass().isArray()) { - return new JSONArray(object); - } - if (object instanceof Map map) { - return new JSONObject(map, recursionDepth, pconfig); - } - return null; - } - catch (JSONException exception) { - throw exception; - } - catch (Exception exception) { - return null; - } - } -} diff --git a/moe-json/src/main/java/org/json/JSONWriter.java b/moe-json/src/main/java/org/json/JSONWriter.java deleted file mode 100644 index d025865..0000000 --- a/moe-json/src/main/java/org/json/JSONWriter.java +++ /dev/null @@ -1,409 +0,0 @@ -package org.json; - -import java.io.IOException; -import java.util.Collection; -import java.util.Map; - -/* -Public Domain. -*/ - -/** - * JSONWriter provides a quick and convenient way of producing JSON text. The texts produced - * strictly conform to JSON syntax rules. No whitespace is added, so the results are ready for - * transmission or storage. Each instance of JSONWriter can produce one JSON text. - *

- * A JSONWriter instance provides a value method for appending values to the text, and - * a key method for adding keys before values in objects. There are array - * and endArray methods that make and bound array values, and object and - * endObject methods which make and bound object values. All of these methods return - * the JSONWriter instance, permitting a cascade style. For example,

- * new JSONWriter(myWriter)
- *     .object()
- *         .key("JSON")
- *         .value("Hello, World!")
- *     .endObject();
which writes
- * {"JSON":"Hello, World!"}
- *

- * The first method called must be array or object. There are no methods - * for adding commas or colons. JSONWriter adds them for 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 object/array stack. - */ - - private final JSONObject[] stack; - -/** - * The current mode. Values: - * 'a' (array), - * 'd' (done), - * 'i' (initial), - * 'k' (key), - * 'o' (object). - */ - - protected char mode; - -/** - * 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. - * - * @param w an appendable object - */ - - public JSONWriter(Appendable w) { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - -/** - * Make a JSON text of an Object value. If the object has a 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 { - if (value == null || value.equals(null)) { - return "null"; - } - if (value instanceof JSONString) { - String object; - try { - object = ((JSONString) value).toJSONString(); - } - catch (Exception e) { - throw new JSONException(e); - } - if (object != null) { - return object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if (value instanceof Number) { - // not all Numbers may match actual JSON Numbers. i.e. Fractions or Complex - final String numberAsString = JSONUtils.numberToString((Number) value); - if (JSONUtils.NUMBER_PATTERN.matcher(numberAsString).matches()) { - // Close enough to a JSON number that we will return it unquoted - return numberAsString; - } - // The Number value is not a valid JSON number. - // Instead we will quote it as a string - return JSONUtils.quote(numberAsString); - } - if (value instanceof Boolean || value instanceof JSONObject - || value instanceof JSONArray) { - return value.toString(); - } - if (value instanceof Map) { - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if (value instanceof Collection) { - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if (value.getClass().isArray()) { - return new JSONArray(value).toString(); - } - if (value instanceof Enum) { - return JSONUtils.quote(((Enum) value).name()); - } - return JSONUtils.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(JSONUtils.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 if a called function has an error - */ - public JSONWriter value(boolean b) throws JSONException { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * - * @param d A double. - * @return this - * @throws JSONException If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException { - return this.value(Double.valueOf(d)); - } - - /** - * Append a long value. - * - * @param l A long. - * @return this - * @throws JSONException if a called function has an error - */ - public JSONWriter value(long l) throws JSONException { - return this.append(Long.toString(l)); - } - - - /** - * Append an object value. - * - * @param object The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements JSONString. - * @return this - * @throws JSONException If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException { - return this.append(valueToString(object)); - } -} diff --git a/moe-json/src/main/java/org/json/Null.java b/moe-json/src/main/java/org/json/Null.java deleted file mode 100644 index 6fe861c..0000000 --- a/moe-json/src/main/java/org/json/Null.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Copyright (c) DuxTechnica - * - * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not - * use this file except in compliance with the License. You may obtain a copy of the License by - * contacting: - * - * Dux Technica, contact@duxtechnica.com - * - * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, - * either express or implied. See the License for the specific language governing permissions and - * limitations under the License. - */ - -package org.json; - -/** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, whilst Java's null is - * equivalent to the value that JavaScript calls undefined. - */ - -public final class Null { - -/** - * 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 Null object or null. - */ - - @Override - @SuppressWarnings("lgtm[java/unchecked-cast-in-equals]") - 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"; - } - -/** - * 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 TYPE = new Null(); -} diff --git a/moe-json/src/main/java/org/json/ParserConfiguration.java b/moe-json/src/main/java/org/json/ParserConfiguration.java deleted file mode 100644 index e2625d9..0000000 --- a/moe-json/src/main/java/org/json/ParserConfiguration.java +++ /dev/null @@ -1,179 +0,0 @@ -package org.json; -/* -Public Domain. -*/ - -/** - * Configuration base object for parsers. The configuration is immutable. - */ -@SuppressWarnings({""}) -public class ParserConfiguration { - /** - * Used to indicate there's no defined limit to the maximum nesting depth when parsing a document. - */ - public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1; - - /** - * Used to indicate there's no defined limit to the maximum number length - */ - public static final int UNDEFINED_MAXIMUM_NUMBER_LENGTH = -1; - - /** - * The default maximum nesting depth when parsing a document. - */ - public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512; - - /** - * The default max number length - */ - public static final int DEFAULT_MAX_NUMBER_LENGTH = 1000; - - /** - * Specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string). - */ - protected boolean keepStrings; - - /** - * The maximum nesting depth when parsing an object. - */ - protected int maxNestingDepth; - - /** - * The max number of chars for any number. Exceeding this limit will cause the value to be converted to a string - */ - protected int maxNumberLength; - - /** - * Constructs a new ParserConfiguration with default settings. - */ - public ParserConfiguration() { - this.keepStrings = false; - this.maxNestingDepth = DEFAULT_MAXIMUM_NESTING_DEPTH; - this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH; - } - - /** - * Constructs a new ParserConfiguration with the specified settings. Use the with* methods instead of calling this ctor. - * - * @param keepStrings A boolean indicating whether to preserve strings during parsing. - * @param maxNestingDepth An integer representing the maximum allowed nesting depth. - * @deprecated Use the with*() methods instead - */ - @Deprecated - protected ParserConfiguration(final boolean keepStrings, final int maxNestingDepth) { - this.keepStrings = keepStrings; - this.maxNestingDepth = maxNestingDepth; - this.maxNumberLength = DEFAULT_MAX_NUMBER_LENGTH; - } - - /** - * Provides a new instance of the same configuration. - */ - @Override - protected ParserConfiguration clone() { - // future modifications to this method should always ensure a "deep" - // clone in the case of collections. i.e. if a Map is added as a configuration - // item, a new map instance should be created and if possible each value in the - // map should be cloned as well. If the values of the map are known to also - // be immutable, then a shallow clone of the map is acceptable. - ParserConfiguration parserConfiguration = new ParserConfiguration(); - parserConfiguration.keepStrings = this.keepStrings; - parserConfiguration.maxNestingDepth = this.maxNestingDepth; - parserConfiguration.maxNumberLength = this.maxNumberLength; - return parserConfiguration; - } - - /** - * When parsing the XML into JSONML, specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string). - * - * @return The keepStrings configuration value. - */ - public boolean isKeepStrings() { - return this.keepStrings; - } - - /** - * When parsing the XML into JSONML, specifies if values should be kept as strings (true), or if - * they should try to be guessed into JSON values (numeric, boolean, string) - * - * @param newVal new value to use for the keepStrings configuration option. - * @param the type of the configuration object - * @return The existing configuration will not be modified. A new configuration is returned. - */ - @SuppressWarnings("unchecked") - public T withKeepStrings(final boolean newVal) { - T newConfig = (T) this.clone(); - newConfig.keepStrings = newVal; - return newConfig; - } - - /** - * The maximum nesting depth that the parser will descend before throwing an exception - * when parsing an object (e.g. Map, Collection) into JSON-related objects. - * - * @return the maximum nesting depth set for this configuration - */ - public int getMaxNestingDepth() { - return maxNestingDepth; - } - - /** - * Defines the maximum nesting depth that the parser will descend before throwing an exception - * when parsing an object (e.g. Map, Collection) into JSON-related objects. - * The default max nesting depth is 512, which means the parser will throw a JsonException if - * the maximum depth is reached. - * Using any negative value as a parameter is equivalent to setting no limit to the nesting depth, - * which means the parses will go as deep as the maximum call stack size allows. - * - * @param maxNestingDepth the maximum nesting depth allowed to the XML parser - * @param the type of the configuration object - * @return The existing configuration will not be modified. A new configuration is returned. - */ - @SuppressWarnings("unchecked") - public T withMaxNestingDepth(int maxNestingDepth) { - T newConfig = (T) this.clone(); - - if (maxNestingDepth > UNDEFINED_MAXIMUM_NESTING_DEPTH) { - newConfig.maxNestingDepth = maxNestingDepth; - } else { - newConfig.maxNestingDepth = UNDEFINED_MAXIMUM_NESTING_DEPTH; - } - - return newConfig; - } - - - /** - * The maximum number length that the parser will allow - * - * @return the maximum number lengtj set for this configuration - */ - public int getMaxNumberLength() { - return maxNumberLength; - } - - /** - * Defines the maximum number length that the parser will allow - * Using any negative value as a parameter is equivalent to setting no limit to the length - * which means any size number is allowed - * - * @param maxNumberLength the maximum number length allowed - * @param the type of the configuration object - * @return The existing configuration will not be modified. A new configuration is returned. - */ - @SuppressWarnings("unchecked") - public T withMaxNumberLength(int maxNumberLength) { - T newConfig = (T) this.clone(); - - if (maxNumberLength > UNDEFINED_MAXIMUM_NUMBER_LENGTH) { - newConfig.maxNumberLength = maxNumberLength; - } else { - newConfig.maxNumberLength = UNDEFINED_MAXIMUM_NUMBER_LENGTH; - } - - return newConfig; - } - -} diff --git a/moe-json/src/main/java/org/json/StringBuilderWriter.java b/moe-json/src/main/java/org/json/StringBuilderWriter.java deleted file mode 100644 index 6d50789..0000000 --- a/moe-json/src/main/java/org/json/StringBuilderWriter.java +++ /dev/null @@ -1,96 +0,0 @@ -package org.json; - -import java.io.IOException; -import java.io.Writer; - -/** - * Performance optimised alternative for {@link java.io.StringWriter} using internally a - * {@link StringBuilder} instead of a {@link StringBuffer}. - */ - -public class StringBuilderWriter extends Writer { - - private final StringBuilder builder; - -/** - * Create a new string builder writer using the default initial string-builder buffer size. - */ - - public StringBuilderWriter() { - builder = new StringBuilder(); - lock = builder; - } - -/** - * Create a new string builder writer using the specified initial string-builder buffer size. - * - * @param initialSize The number of {@code char} values that will fit into this buffer before it is - * automatically expanded - * @throws IllegalArgumentException If {@code initialSize} is negative - */ - - public StringBuilderWriter(int initialSize) { - builder = new StringBuilder(initialSize); - lock = builder; - } - - @Override - public void write(int c) { - builder.append((char) c); - } - - @Override - public void write(char[] cbuf, int offset, int length) { - if ((offset < 0) || (offset > cbuf.length) || (length < 0) || - ((offset + length) > cbuf.length) || ((offset + length) < 0)) { - throw new IndexOutOfBoundsException(); - } - else if (length == 0) { - return; - } - builder.append(cbuf, offset, length); - } - - @Override - public void write(String str) { - builder.append(str); - } - - @Override - public void write(String str, int offset, int length) { - builder.append(str, offset, offset + length); - } - - @Override - public StringBuilderWriter append(CharSequence csq) { - write(String.valueOf(csq)); - return this; - } - - @Override - public StringBuilderWriter append(CharSequence csq, int start, int end) { - if (csq == null) { - csq = "null"; - } - return append(csq.subSequence(start, end)); - } - - @Override - public StringBuilderWriter append(char c) { - write(c); - return this; - } - - @Override - public String toString() { - return builder.toString(); - } - - @Override - public void flush() { - } - - @Override - public void close() throws IOException { - } -} diff --git a/moe-json/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec b/moe-json/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec index b86762b..8fb1c80 100644 --- a/moe-json/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec +++ b/moe-json/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec @@ -12,4 +12,4 @@ # limitations under the License. # -dxt.moe.codec.json.JSONCodec \ No newline at end of file +dxt.moe.codec.json.JsonCodec \ No newline at end of file diff --git a/moe-main/src/main/java/dxt/moe/lib/MoeImpl.java b/moe-main/src/main/java/dxt/moe/lib/MoeImpl.java index 78ada12..31b633d 100644 --- a/moe-main/src/main/java/dxt/moe/lib/MoeImpl.java +++ b/moe-main/src/main/java/dxt/moe/lib/MoeImpl.java @@ -43,17 +43,13 @@ public class MoeImpl extends Moe { private final static Map codecs; static { - if (L.isLoggable(Level.FINE)) { - L.fine("loading MOE codecs"); - } + L.fine(() -> "loading MOE codecs"); codecs = new HashMap<>(); ServiceLoader codecs = ServiceLoader.load(MoeCodec.class); for (MoeCodec codec : codecs) { String format = codec.getFormat(); MoeImpl.codecs.put(format.toLowerCase(), codec); - if (L.isLoggable(Level.FINE)) { - L.fine(String.format("%s -> %s", format, codec.getClass().getName())); - } + L.fine(() -> String.format("%s -> %s", format, codec.getClass().getName())); } } diff --git a/moe-json/src/main/java/org/json/JSONBase.java b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlCodec.java similarity index 57% rename from moe-json/src/main/java/org/json/JSONBase.java rename to moe-toml/src/main/java/dxt/moe/codec/toml/TomlCodec.java index fd681b8..143cb8f 100644 --- a/moe-json/src/main/java/org/json/JSONBase.java +++ b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlCodec.java @@ -12,13 +12,30 @@ * limitations under the License. */ -package org.json; +package dxt.moe.codec.toml; -public class JSONBase { +import dxt.moe.codec.MoeCodec; +import dxt.moe.codec.MoeDecoder; +import dxt.moe.codec.MoeEncoder; - protected JSONWrapper wrapper; +/** + * @author indroneel + */ - protected JSONBase() { - wrapper = new JSONWrapper(); +public class TomlCodec implements MoeCodec { + + @Override + public String getFormat() { + return "toml"; + } + + @Override + public MoeDecoder decoder() { + return new TomlDecoder(); + } + + @Override + public MoeEncoder encoder() { + return new TomlEncoder(); } } diff --git a/moe-toml/src/main/java/dxt/moe/codec/toml/TomlDecoder.java b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlDecoder.java new file mode 100644 index 0000000..f644c7b --- /dev/null +++ b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlDecoder.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) DuxTechnica + * + * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not + * use this file except in compliance with the License. You may obtain a copy of the License by + * contacting: + * + * Dux Technica, contact@duxtechnica.com + * + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dxt.moe.codec.toml; + +import dxt.moe.app.CodecException; +import dxt.moe.app.Moe; +import dxt.moe.codec.MoeDecoder; +import dxt.moe.model.AnyData; + +import java.io.InputStream; +import java.util.List; +import java.util.logging.Logger; + +/** + * @author indroneel + */ + +public class TomlDecoder implements MoeDecoder { + + private static final Logger L = Logger.getLogger(TomlDecoder.class.getName()); + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeDecoder + + @Override + public void setSource(byte[] data) throws CodecException { + + } + + @Override + public void setSource(InputStream input) throws CodecException { + + } + + @Override + public AnyData decode(List options) throws CodecException { + return null; + } +} diff --git a/moe-json/src/main/java/dxt/moe/codec/json/JSONEncoder.java b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlEncoder.java similarity index 78% rename from moe-json/src/main/java/dxt/moe/codec/json/JSONEncoder.java rename to moe-toml/src/main/java/dxt/moe/codec/toml/TomlEncoder.java index 88b178f..c1557dd 100644 --- a/moe-json/src/main/java/dxt/moe/codec/json/JSONEncoder.java +++ b/moe-toml/src/main/java/dxt/moe/codec/toml/TomlEncoder.java @@ -12,7 +12,7 @@ * limitations under the License. */ -package dxt.moe.codec.json; +package dxt.moe.codec.toml; import dxt.moe.codec.MoeEncoder; import dxt.moe.model.AnyData; @@ -21,7 +21,10 @@ import dxt.moe.model.AnyData; * @author indroneel */ -public class JSONEncoder implements MoeEncoder { +public class TomlEncoder implements MoeEncoder { + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeEncoder @Override public byte[] convert(AnyData data) { diff --git a/moe-toml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec b/moe-toml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec new file mode 100644 index 0000000..be5f6e8 --- /dev/null +++ b/moe-toml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec @@ -0,0 +1,15 @@ +# +# Copyright (c) DuxTechnica +# +# Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not +# use this file except in compliance with the License. You may obtain a copy of the License by +# contacting: +# +# Dux Technica, contact@duxtechnica.com +# +# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +# either express or implied. See the License for the specific language governing permissions and +# limitations under the License. +# + +dxt.moe.codec.toml.TomlCodec \ No newline at end of file diff --git a/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlCodec.java b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlCodec.java new file mode 100644 index 0000000..005786d --- /dev/null +++ b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlCodec.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) DuxTechnica + * + * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not + * use this file except in compliance with the License. You may obtain a copy of the License by + * contacting: + * + * Dux Technica, contact@duxtechnica.com + * + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dxt.moe.codec.yaml; + +import dxt.moe.codec.MoeCodec; +import dxt.moe.codec.MoeDecoder; +import dxt.moe.codec.MoeEncoder; + +/** + * YamlCodec is an implementation of the MoeCodec interface for YAML format. + * + * @author indroneel + */ + +public class YamlCodec implements MoeCodec { + + @Override + public String getFormat() { + return "yaml"; + } + + @Override + public MoeDecoder decoder() { + return new YamlDecoder(); + } + + @Override + public MoeEncoder encoder() { + return new YamlEncoder(); + } +} diff --git a/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlDecoder.java b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlDecoder.java new file mode 100644 index 0000000..06a6e78 --- /dev/null +++ b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlDecoder.java @@ -0,0 +1,196 @@ +/* + * Copyright (c) DuxTechnica + * + * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not + * use this file except in compliance with the License. You may obtain a copy of the License by + * contacting: + * + * Dux Technica, contact@duxtechnica.com + * + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dxt.moe.codec.yaml; + +import dxt.moe.app.CodecException; +import dxt.moe.app.Moe; +import dxt.moe.codec.MoeDecoder; +import dxt.moe.model.AnyData; +import dxt.moe.model.LinearData; +import dxt.moe.model.MappedData; +import dxt.moe.model.SimpleData; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.SequenceNode; +import org.yaml.snakeyaml.nodes.Tag; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.util.List; +import java.util.Locale; +import java.util.logging.Logger; + +/** + * @author indroneel + */ + +public class YamlDecoder implements MoeDecoder { + + private static final Logger L = Logger.getLogger(YamlDecoder.class.getName()); + + private Reader reader; + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeDecoder + + @Override + public void setSource(byte[] data) throws CodecException { + reader = new InputStreamReader(new ByteArrayInputStream(data)); + L.fine(() -> "byte array set as source"); + } + + @Override + public void setSource(InputStream input) throws CodecException { + reader = new InputStreamReader(input); + L.fine(() -> "input stream set as source"); + } + + @Override + public AnyData decode(List options) throws CodecException { + L.fine(() -> "converting from yaml"); + Yaml yaml = new Yaml(); + Node node = yaml.compose(reader); + if(node == null) { + return null; + } + if(node instanceof MappingNode) { + return new AnyData(convertMappedData((MappingNode) node, options)); + } + return null; + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Helper methods + + private MappedData convertMappedData(MappingNode mapNode, + List options) throws CodecException { + MappedData mapData = new MappedData(); + for(NodeTuple tuple : mapNode.getValue()) { + ScalarNode snode = (ScalarNode) tuple.getKeyNode(); + String keyStr = options.contains(Moe.Options.ANYCASE) + ? snode.getValue().toLowerCase(Locale.getDefault()) + : snode.getValue(); + + Node valueNode = tuple.getValueNode(); + if(valueNode instanceof ScalarNode svnode) { + String valueStr = svnode.getValue(); + + if(svnode.getTag().equals(Tag.BOOL)) { + SimpleData itemData = new SimpleData(Boolean.valueOf(valueStr)); + mapData.put(keyStr, new AnyData(itemData)); + } + else if(svnode.getTag().equals(Tag.FLOAT)) { + try { + SimpleData itemData = new SimpleData(Double.valueOf(valueStr)); + mapData.put(keyStr, new AnyData(itemData)); + } + catch(Exception exep) { + throw new CodecException("yaml", + "Error converting float value: " + valueStr, exep); + } + } + else if(svnode.getTag().equals(Tag.INT)) { + try { + SimpleData itemData = new SimpleData(Long.valueOf(valueStr)); + mapData.put(keyStr, new AnyData(itemData)); + } + catch(Exception exep) { + throw new CodecException("yaml", + "Error converting int value: " + valueStr, exep); + } + } + else if(svnode.getTag().equals(Tag.STR)) { + SimpleData itemData = new SimpleData(valueStr); + mapData.put(keyStr, new AnyData(itemData)); + } + else { + L.info(() -> "unhandled tag in scalar node: " + svnode.getTag().getValue()); + } + } + else if(valueNode instanceof SequenceNode) { + LinearData itemData = convertLinearData((SequenceNode) valueNode, options); + mapData.put(keyStr, new AnyData(itemData)); + } + else if(valueNode instanceof MappingNode) { + MappedData itemData = convertMappedData((MappingNode) valueNode, options); + mapData.put(keyStr, new AnyData(itemData)); + } + else { + L.warning(() -> String.format("no suitable conversion found for node: %s", keyStr)); + } + } + return mapData; + } + + private LinearData convertLinearData(SequenceNode seqNode, + List options) throws CodecException { + LinearData linData = new LinearData(); + for (Node valueNode : seqNode.getValue()) { + if (valueNode instanceof ScalarNode) { + ScalarNode svnode = (ScalarNode) valueNode; + String valueStr = svnode.getValue(); + + if(svnode.getTag().equals(Tag.BOOL)) { + SimpleData itemData = new SimpleData(Boolean.valueOf(valueStr)); + linData.add(new AnyData(itemData)); + } + else if(svnode.getTag().equals(Tag.FLOAT)) { + try { + SimpleData itemData = new SimpleData(Double.valueOf(valueStr)); + linData.add(new AnyData(itemData)); + } + catch(Exception exep) { + throw new CodecException("yaml", + "Error converting float value: " + valueStr, exep); + } + } + else if(svnode.getTag().equals(Tag.INT)) { + try { + SimpleData itemData = new SimpleData(Long.valueOf(valueStr)); + linData.add(new AnyData(itemData)); + } + catch(Exception exep) { + throw new CodecException("yaml", + "Error converting int value: " + valueStr, exep); + } + } + else if(svnode.getTag().equals(Tag.STR)) { + SimpleData itemData = new SimpleData(valueStr); + linData.add(new AnyData(itemData)); + } + else { + L.info(() -> "unhandled tag in scalar node: " + svnode.getTag().getValue()); + } + } + else if (valueNode instanceof SequenceNode) { + LinearData itemData = convertLinearData((SequenceNode) valueNode, options); + linData.add(new AnyData(itemData)); + } + else if (valueNode instanceof MappingNode) { + MappedData itemData = convertMappedData((MappingNode) valueNode, options); + linData.add(new AnyData(itemData)); + } + else { + L.warning(() -> "no suitable conversion found for node: " + valueNode.toString()); + } + } + return linData; + } +} diff --git a/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlEncoder.java b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlEncoder.java new file mode 100644 index 0000000..7edc943 --- /dev/null +++ b/moe-yaml/src/main/java/dxt/moe/codec/yaml/YamlEncoder.java @@ -0,0 +1,169 @@ +/* + * Copyright (c) DuxTechnica + * + * Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not + * use this file except in compliance with the License. You may obtain a copy of the License by + * contacting: + * + * Dux Technica, contact@duxtechnica.com + * + * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, + * either express or implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +package dxt.moe.codec.yaml; + +import dxt.moe.app.CodecException; +import dxt.moe.codec.MoeEncoder; +import dxt.moe.model.AnyData; +import dxt.moe.model.LinearData; +import dxt.moe.model.MappedData; +import dxt.moe.model.SimpleData; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.Node; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.ScalarNode; +import org.yaml.snakeyaml.nodes.SequenceNode; +import org.yaml.snakeyaml.nodes.Tag; + +import java.io.ByteArrayOutputStream; +import java.io.OutputStreamWriter; +import java.math.BigDecimal; +import java.math.BigInteger; +import java.util.LinkedList; +import java.util.List; + +/** + * @author indroneel + */ + +public class YamlEncoder implements MoeEncoder { + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Methods of interface MoeEncoder + + @Override + public byte[] convert(AnyData data) throws CodecException { + return convert(data, false); + } + + @Override + public byte[] convert(AnyData data, boolean pretty) throws CodecException { + if(data.asMapped() == null) { + return new byte[0]; + } + + Node node = convertMappedData(data.asMapped()); + Yaml yaml = new Yaml(); + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + yaml.serialize(node, new OutputStreamWriter(buffer)); + if(pretty) { + + } + else { + + } + return buffer.toByteArray(); + } + + //////////////////////////////////////////////////////////////////////////////////////////////// + // Helper methods + + private MappingNode convertMappedData(MappedData mapData) { + List tuples = new LinkedList<>(); + + for(String key: mapData.getKeys()) { + //create the key node + ScalarNode knode = new ScalarNode(Tag.STR, key, null, null, + DumperOptions.ScalarStyle.LITERAL); + + AnyData itemData = mapData.get(key); + + if(itemData.asSimple() != null) { + SimpleData sdata = itemData.asSimple(); + if(sdata.getBoolean() != null) { + ScalarNode vnode = new ScalarNode(Tag.BOOL, sdata.getBoolean().toString(), + null, null, DumperOptions.ScalarStyle.PLAIN); + tuples.add(new NodeTuple(knode, vnode)); + } + else if(sdata.getNumber() != null) { + Number nval = sdata.getNumber(); + if(nval instanceof Byte || nval instanceof Short || nval instanceof Integer + || nval instanceof Long || nval instanceof BigInteger) { + ScalarNode vnode = new ScalarNode(Tag.INT, nval.toString(), null, null, + DumperOptions.ScalarStyle.PLAIN); + tuples.add(new NodeTuple(knode, vnode)); + } + else if(nval instanceof Float || nval instanceof Double + || nval instanceof BigDecimal) { + ScalarNode vnode = new ScalarNode(Tag.FLOAT, nval.toString(), null, null, + DumperOptions.ScalarStyle.PLAIN); + tuples.add(new NodeTuple(knode, vnode)); + } + } + else if(sdata.getString() != null) { + ScalarNode vnode = new ScalarNode(Tag.STR, sdata.getString(), + null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED); + tuples.add(new NodeTuple(knode, vnode)); + } + } + else if(itemData.asLinear() != null) { + Node vnode = convertLinearData(itemData.asLinear()); + tuples.add(new NodeTuple(knode, vnode)); + } + else if(itemData.asMapped() != null) { + Node vnode = convertMappedData(itemData.asMapped()); + tuples.add(new NodeTuple(knode, vnode)); + } + } + return new MappingNode(Tag.MAP, tuples, DumperOptions.FlowStyle.AUTO); + } + + private SequenceNode convertLinearData(LinearData linData) { + List nodeList = new LinkedList<>(); + for(int i=0; i < linData.size(); i++) { + AnyData itemData = linData.get(i); + + if(itemData.asSimple() != null) { + SimpleData sdata = itemData.asSimple(); + if(sdata.getBoolean() != null) { + ScalarNode vnode = new ScalarNode(Tag.BOOL, sdata.getBoolean().toString(), + null, null, DumperOptions.ScalarStyle.PLAIN); + nodeList.add(vnode); + } + else if(sdata.getNumber() != null) { + Number nval = sdata.getNumber(); + if(nval instanceof Byte || nval instanceof Short || nval instanceof Integer + || nval instanceof Long || nval instanceof BigInteger) { + ScalarNode vnode = new ScalarNode(Tag.INT, nval.toString(), null, null, + DumperOptions.ScalarStyle.PLAIN); + nodeList.add(vnode); + } + else if(nval instanceof Float || nval instanceof Double + || nval instanceof BigDecimal) { + ScalarNode vnode = new ScalarNode(Tag.FLOAT, nval.toString(), null, null, + DumperOptions.ScalarStyle.PLAIN); + nodeList.add(vnode); + } + } + else if(sdata.getString() != null) { + ScalarNode vnode = new ScalarNode(Tag.STR, sdata.getString(), + null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED); + nodeList.add(vnode); + } + } + else if(itemData.asLinear() != null) { + Node vnode = convertLinearData(itemData.asLinear()); + nodeList.add(vnode); + } + else if(itemData.asMapped() != null) { + Node vnode = convertMappedData(itemData.asMapped()); + nodeList.add(vnode); + } + } + return new SequenceNode(Tag.SEQ, nodeList, DumperOptions.FlowStyle.AUTO); + } +} diff --git a/moe-yaml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec b/moe-yaml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec new file mode 100644 index 0000000..1e888ac --- /dev/null +++ b/moe-yaml/src/main/resources/META-INF/services/dxt.moe.codec.MoeCodec @@ -0,0 +1,15 @@ +# +# Copyright (c) DuxTechnica +# +# Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not +# use this file except in compliance with the License. You may obtain a copy of the License by +# contacting: +# +# Dux Technica, contact@duxtechnica.com +# +# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, +# either express or implied. See the License for the specific language governing permissions and +# limitations under the License. +# + +dxt.moe.codec.yaml.YamlCodec \ No newline at end of file