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/JSONBase.java b/moe-json/src/main/java/org/json/JSONBase.java
new file mode 100644
index 0000000..fd681b8
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONBase.java
@@ -0,0 +1,24 @@
+/*
+ * 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;
+
+public class JSONBase {
+
+ protected JSONWrapper wrapper;
+
+ protected JSONBase() {
+ wrapper = new JSONWrapper();
+ }
+}
diff --git a/moe-json/src/main/java/org/json/JSONException.java b/moe-json/src/main/java/org/json/JSONException.java
new file mode 100644
index 0000000..4b80f76
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONException.java
@@ -0,0 +1,52 @@
+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
new file mode 100644
index 0000000..f6d498f
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONObject.java
@@ -0,0 +1,2530 @@
+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 extends Map> 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
new file mode 100644
index 0000000..fa8f42f
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONParserConfiguration.java
@@ -0,0 +1,164 @@
+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
new file mode 100644
index 0000000..44940e3
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONPointer.java
@@ -0,0 +1,315 @@
+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
new file mode 100644
index 0000000..c855b57
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONPointerException.java
@@ -0,0 +1,42 @@
+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
new file mode 100644
index 0000000..4f9f04f
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONString.java
@@ -0,0 +1,24 @@
+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
new file mode 100644
index 0000000..b72e652
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONTokener.java
@@ -0,0 +1,682 @@
+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
new file mode 100644
index 0000000..0bee1c3
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONUtils.java
@@ -0,0 +1,552 @@
+/*
+ * 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
new file mode 100644
index 0000000..006c58b
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONWrapper.java
@@ -0,0 +1,62 @@
+/*
+ * 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
new file mode 100644
index 0000000..d025865
--- /dev/null
+++ b/moe-json/src/main/java/org/json/JSONWriter.java
@@ -0,0 +1,409 @@
+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
new file mode 100644
index 0000000..6fe861c
--- /dev/null
+++ b/moe-json/src/main/java/org/json/Null.java
@@ -0,0 +1,66 @@
+/*
+ * 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
new file mode 100644
index 0000000..e2625d9
--- /dev/null
+++ b/moe-json/src/main/java/org/json/ParserConfiguration.java
@@ -0,0 +1,179 @@
+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
new file mode 100644
index 0000000..6d50789
--- /dev/null
+++ b/moe-json/src/main/java/org/json/StringBuilderWriter.java
@@ -0,0 +1,96 @@
+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/daxi.moe.codec.MoeCodec b/moe-json/src/main/resources/META-INF/services/daxi.moe.codec.MoeCodec
new file mode 100644
index 0000000..0c2953d
--- /dev/null
+++ b/moe-json/src/main/resources/META-INF/services/daxi.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.
+#
+
+daxi.moe.codec.json.JSONCodec
\ No newline at end of file
diff --git a/moe-main/pom.xml b/moe-main/pom.xml
index 48cea1f..9faa8ca 100644
--- a/moe-main/pom.xml
+++ b/moe-main/pom.xml
@@ -12,4 +12,12 @@
daxi.moe.main
jar
+
+
+ daxi.moe
+ daxi.moe.api
+ ${project.parent.version}
+
+
+
diff --git a/moe-main/src/main/java/daxi/moe/codec/mem/MemDecoder.java b/moe-main/src/main/java/daxi/moe/codec/mem/MemDecoder.java
index c36c9fa..0f8002e 100644
--- a/moe-main/src/main/java/daxi/moe/codec/mem/MemDecoder.java
+++ b/moe-main/src/main/java/daxi/moe/codec/mem/MemDecoder.java
@@ -14,6 +14,7 @@
package daxi.moe.codec.mem;
+import daxi.moe.app.CodecException;
import daxi.moe.app.Moe;
import daxi.moe.codec.MoeDecoder;
import daxi.moe.model.AnyData;
@@ -21,20 +22,24 @@ import daxi.moe.model.AnyData;
import java.io.InputStream;
import java.util.List;
+/**
+ * @author indroneel
+ */
+
public class MemDecoder implements MoeDecoder {
@Override
- public void setSource(byte[] data) {
+ public void setSource(byte[] data) throws CodecException {
}
@Override
- public void setSource(InputStream input) {
+ public void setSource(InputStream input) throws CodecException {
}
@Override
- public AnyData decode(List options) {
+ public AnyData decode(List options) throws CodecException {
return null;
}
}
diff --git a/moe-main/src/main/java/daxi/moe/lib/MoeImpl.java b/moe-main/src/main/java/daxi/moe/lib/MoeImpl.java
index 340c99f..d7f51cb 100644
--- a/moe-main/src/main/java/daxi/moe/lib/MoeImpl.java
+++ b/moe-main/src/main/java/daxi/moe/lib/MoeImpl.java
@@ -18,12 +18,21 @@ import daxi.moe.app.External;
import daxi.moe.app.Internal;
import daxi.moe.app.Moe;
import daxi.moe.codec.MoeCodec;
+import daxi.moe.lib.mod2obj.ExternalImpl;
+import daxi.moe.lib.obj2mod.InternalImpl;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
+ * The only implementation of {@link Moe}.
+ *
* @author indroneel
*/
@@ -79,4 +88,4 @@ public class MoeImpl extends Moe {
}
return this;
}
-}
\ No newline at end of file
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JLinearImpl.java b/moe-main/src/main/java/daxi/moe/lib/m2j/M2JLinearImpl.java
deleted file mode 100644
index 7c39403..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JLinearImpl.java
+++ /dev/null
@@ -1,45 +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 daxi.moe.lib.m2j;
-
-import daxi.moe.lib.transform.M2JGlobals;
-import daxi.moe.lib.transform.M2JLinear;
-import daxi.moe.lib.transform.M2JStatus;
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * The only implementation of the {@link M2JLinear} interface.
- *
- * @author indroneel
- */
-
-public class M2JLinearImpl implements M2JLinear {
-
- private final M2JGlobals globals;
-
- public M2JLinearImpl(M2JGlobals globals) {
- this.globals = globals;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Methods of interface M2JLinear
-
- @Override
- public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
- return M2JStatus.NOT_VALID;
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMappedImpl.java b/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMappedImpl.java
deleted file mode 100644
index c85aa7d..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMappedImpl.java
+++ /dev/null
@@ -1,45 +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 daxi.moe.lib.m2j;
-
-import daxi.moe.lib.transform.M2JGlobals;
-import daxi.moe.lib.transform.M2JMapped;
-import daxi.moe.lib.transform.M2JStatus;
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * The only implementation of the {@link M2JMapped} interface.
- *
- * @author indroneel
- */
-
-public class M2JMappedImpl implements M2JMapped {
-
- private final M2JGlobals globals;
-
- public M2JMappedImpl(M2JGlobals globals) {
- this.globals = globals;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Methods of interface M2JMapped
-
- @Override
- public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
- return M2JStatus.NOT_VALID;
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMethod.java b/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMethod.java
deleted file mode 100644
index d71ebac..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JMethod.java
+++ /dev/null
@@ -1,206 +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 daxi.moe.lib.m2j;
-
-import daxi.moe.app.MapFrom;
-
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.lang.reflect.Parameter;
-import java.lang.reflect.ParameterizedType;
-import java.lang.reflect.Type;
-import java.lang.reflect.TypeVariable;
-
-/**
- * Contains information about a method on the target Java object. The method and the information
- * can be used to transform some portions of internal data model and populate the containing object.
- *
- * @author indroneel
- */
-
-public class M2JMethod {
-
- private boolean valid = false;
- private boolean setter = false;
- private boolean linAdder = false;
- private boolean mapAdder = false;
- private String mapFromKey = null;
- private Class> paramType = null;
-
-/**
- * Constructs the object around transforming method . The contained method may or may not be valid
- * for transformation, depending on the method's signature and annotations.
- *
- * @param method the method to be encapsulated
- */
-
- public M2JMethod(Method method) {
-
- MapFrom mapFrom = method.getAnnotation(MapFrom.class);
- if(mapFrom == null) {
- // If the method does not have the @MapFrom annotation, it is not valid for
- // transformation
- return;
- }
- // populate the mapFromKey field with the value of the @MapFrom annotation
- mapFromKey = mapFrom.value();
- if(mapFromKey == null || mapFromKey.isBlank()) {
- // If the @MapFrom annotation does not have a valid key, it is not valid for
- // transformation
- return;
- }
-
- int mod = method.getModifiers();
- if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
- // If the method is abstract, static, or not private, it is not valid for transformation
- return;
- }
- if(method.getReturnType() != Void.TYPE) {
- // If the method does not return void, it is not valid for transformation
- return;
- }
-
- Parameter[] params = method.getParameters();
-
- // Check if the method name starts with "_set" and has more than 4 characters
- if(method.getName().startsWith("_set") && method.getName().length() > 4) {
- if(params.length != 1) {
- // If the method name starts with "_set" but does not have exactly one parameter, it
- // is not valid for transformation
- return;
- }
-
- Type type = params[0].getParameterizedType();
- if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
- // If the parameter type is a type variable or a parameterized type, it is not valid
- // for transformation
- return;
- }
- paramType = params[0].getType();
- if(paramType.isArray()) {
- // If the parameter type is an array, it is not valid for transformation
- return;
- }
-
- valid = true;
- setter = true;
- }
- // Check if the method name starts with "_add" and has more than 4 characters
- else if(method.getName().startsWith("_add") && method.getName().length() > 4) {
- if(params.length ==1 ) {
- Type type = params[0].getParameterizedType();
- if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
- // If the parameter type is a type variable or a parameterized type, it is not
- // valid for transformation
- return;
- }
- paramType = params[0].getType();
- if(paramType.isArray()) {
- // If the parameter type is an array, it is not valid for transformation
- return;
- }
- valid = true;
- linAdder = true;
- }
- else if(params.length == 2) {
- if(params[0].getType() != String.class) {
- // If the first parameter type is not String, it is not valid for transformation
- return;
- }
- Type type = params[1].getParameterizedType();
- if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
- // If the second parameter type is a type variable or a parameterized type, it
- // is not valid for transformation
- return;
- }
- paramType = params[1].getType();
- if(paramType.isArray()) {
- // If the second parameter type is an array, it is not valid for transformation
- return;
- }
- valid = true;
- mapAdder = true;
- }
- }
- }
-
-/**
- * Returns whether the method is valid for transformation.
- *
- * @return true if the method is valid for transformation, false otherwise.
- */
-
- boolean isValid() {
- return valid;
- }
-
-/**
- * Returns whether the method is a setter. A setter is a method that takes a single parameter and
- * sets it to the containing object.
- *
- * @return true if the method is a setter, false otherwise
- */
-
- boolean isSetter() {
- return setter;
- }
-
-/**
- * Returns whether the method is a linear adder. A linear adder is a method that takes a single
- * parameter and adds it to the containing object. The adder method is called multiple times, once
- * for each value to be added.
- *
- * @return true if the method is a linear adder, false otherwise
- */
-
- boolean isLinearAdder() {
- return linAdder;
- }
-
-/**
- * Returns whether the method is a mapped adder. A mapped adder is a method that takes two
- * parameters, the first being a String key and the second being the value to be added. The library
- * will use the key to determine which portion of the data model is mapped to the method. The adder
- * method is called multiple times, once for each key-value pair to be added.
- *
- * @return true if the method is a mapped adder, false otherwise
- */
-
- boolean isMappedAdder() {
- return mapAdder;
- }
-
-/**
- * Returns the key from the @MapFrom annotation. The library will use this key to determine which
- * portion of the data model is mapped to the method.
- *
- * @return the key from the @MapFrom annotation
- */
-
- String getMapFromKey() {
- return mapFromKey;
- }
-
-/**
- * Returns the parameter type of the method. The library will use this type to determine how to
- * convert the data model item into the appropriate Java type.
- *
- * @return the parameter type of the method
- */
-
- Class> getParamType() {
- return paramType;
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JObjectImpl.java b/moe-main/src/main/java/daxi/moe/lib/m2j/M2JObjectImpl.java
deleted file mode 100644
index bf237b2..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JObjectImpl.java
+++ /dev/null
@@ -1,145 +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 daxi.moe.lib.m2j;
-
-import daxi.moe.app.MapFrom;
-import daxi.moe.lib.transform.M2JGlobals;
-import daxi.moe.lib.transform.M2JLinear;
-import daxi.moe.lib.transform.M2JMapped;
-import daxi.moe.lib.transform.M2JObject;
-import daxi.moe.lib.transform.M2JSimple;
-import daxi.moe.lib.transform.M2JStatus;
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Constructor;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * The only implementation of the {@link M2JObject} interface.
- *
- * @author indroneel
- */
-
-public class M2JObjectImpl implements M2JObject {
-
- private static final Logger L = Logger.getLogger(M2JObjectImpl.class.getName());
-
- private final M2JGlobals globals;
-
- public M2JObjectImpl(M2JGlobals globals) {
- this.globals = globals;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Methods of interface M2JObject
-
- @Override
- public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
- return null;
- }
-
- @Override
- public T convert(MappedData data, Class targetType) {
- if(data == null || targetType == null) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Invalid arguments: data=" + data + ", targetType=" + targetType);
- }
- return null;
- }
- List methods = new LinkedList<>();
- collateAllMethods(targetType, methods);
- if(methods.isEmpty()) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("No suitable methods found in targetType: " + targetType);
- }
- return null;
- }
-
- T target;
- try {
- Constructor ctor = targetType.getConstructor();
- target = ctor.newInstance();
- }
- catch(Exception exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.log(Level.WARNING, exep.getMessage(), exep);
- }
- return null;
- }
-
- for(Method method : methods) {
- M2JStatus m2jStat = transformImpl(data, target, method);
- if(m2jStat == M2JStatus.ERROR) {
- return null;
- }
- }
-
- return target;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Helper methods
-
- private void collateAllMethods(Class> type, List methodList) {
- if(type.getClassLoader() == null) {
- // Skip system classes
- return;
- }
-
- for (Method method : type.getDeclaredMethods()) {
- if (!Modifier.isStatic(method.getModifiers())) {
- MapFrom ann = method.getAnnotation(MapFrom.class);
- if (ann != null && !ann.value().isBlank()) {
- methodList.add(method);
- }
- }
- }
-
- if (type.getSuperclass() != null) {
- collateAllMethods(type.getSuperclass(), methodList);
- }
- }
-
- private M2JStatus transformImpl(MappedData data, Object targetObj, Method targetMthd) {
- M2JSimple m2jSim = globals.getM2JSimple();
- M2JStatus m2jStat = m2jSim.convert(data, targetObj, targetMthd);
- if(m2jStat != M2JStatus.NOT_VALID) {
- // here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
- return m2jStat;
- }
-
- M2JLinear m2jLin = globals.getM2JLinear();
- m2jStat = m2jLin.convert(data, targetObj, targetMthd);
- if(m2jStat != M2JStatus.NOT_VALID) {
- // here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
- return m2jStat;
- }
-
- M2JMapped m2jMap = globals.getM2JMapped();
- m2jStat = m2jMap.convert(data, targetObj, targetMthd);
- if(m2jStat != M2JStatus.NOT_VALID) {
- // here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
- return m2jStat;
- }
-
- // here: m2jStat == M2JStatus.NOT_VALID
- return convert(data, targetObj, targetMthd);
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JSimpleImpl.java b/moe-main/src/main/java/daxi/moe/lib/m2j/M2JSimpleImpl.java
deleted file mode 100644
index 536a878..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/m2j/M2JSimpleImpl.java
+++ /dev/null
@@ -1,337 +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 daxi.moe.lib.m2j;
-
-import daxi.moe.lib.transform.M2JGlobals;
-import daxi.moe.lib.transform.M2JSimple;
-import daxi.moe.lib.transform.M2JStatus;
-import daxi.moe.model.AnyData;
-import daxi.moe.model.MappedData;
-import daxi.moe.model.SimpleData;
-
-import java.lang.reflect.Method;
-import java.math.BigDecimal;
-import java.math.BigInteger;
-import java.util.Locale;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-/**
- * The only implementation of the {@link daxi.moe.lib.transform.M2JSimple} interface.
- *
- * @author indroneel
- */
-
-public class M2JSimpleImpl implements M2JSimple {
-
- private static final Logger L = Logger.getLogger(M2JSimpleImpl.class.getName());
-
- private final M2JGlobals globals;
-
- public M2JSimpleImpl(M2JGlobals globals) {
- this.globals = globals;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Methods of interface M2JSimple
-
- @Override
- public M2JStatus convert(MappedData data, Object target, Method method) {
-
- M2JMethod m2jMthd = new M2JMethod(method);
- if(!m2jMthd.isValid() || !m2jMthd.isSetter()) {
- return M2JStatus.NOT_VALID;
- }
-
- Class> paramType = m2jMthd.getParamType();
- if(!isSupportedParamType(paramType)) {
- return M2JStatus.NOT_VALID;
- }
-
- String key = m2jMthd.getMapFromKey();
- if(!data.contains(key)) {
- return M2JStatus.NOT_VALID;
- }
-
- AnyData adata = data.get(key);
- SimpleData sdata = adata.asSimple();
- if(sdata == null) {
- return M2JStatus.NOT_VALID;
- }
-
- Object paramVal = null;
-
- if(paramType == String.class) {
- paramVal = sdata.getString();
- }
- else if(paramType == BigInteger.class) {
- paramVal = getBigIntegerValue(sdata);
- }
- else if(paramType == BigDecimal.class) {
- paramVal = getBigDecimalValue(sdata);
- }
- else if(paramType == byte.class || paramType == Byte.class) {
- paramVal = getByteValue(sdata);
- }
- else if(paramType == short.class || paramType == Short.class) {
- paramVal = getShortValue(sdata);
- }
- else if(paramType == int.class || paramType == Integer.class) {
- paramVal = getIntegerValue(sdata);
- }
- else if(paramType == long.class || paramType == Long.class) {
- paramVal = getLongValue(sdata);
- }
- else if(paramType == float.class || paramType == Float.class) {
- paramVal = getFloatValue(sdata);
- }
- else if(paramType == double.class || paramType == Double.class) {
- paramVal = getDoubleValue(sdata);
- }
- else if(paramType == boolean.class || paramType == Boolean.class) {
- paramVal = getBooleanValue(sdata);
- }
-
- if(paramVal == null) {
- return M2JStatus.NOT_VALID;
- }
-
- try {
- method.setAccessible(true);
- method.invoke(target, paramVal);
- method.setAccessible(false);
- }
- catch (ReflectiveOperationException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.log(Level.WARNING, exep.getMessage(), exep);
- }
- return M2JStatus.ERROR;
- }
- return M2JStatus.SUCCESS;
- }
-
- ////////////////////////////////////////////////////////////////////////////////////////////////
- // Helper methods
-
- private boolean isSupportedParamType(Class> paramType) {
- return paramType == String.class
- || paramType == BigInteger.class
- || paramType == BigDecimal.class
- || Number.class.isAssignableFrom(paramType)
- || paramType == byte.class
- || paramType == short.class
- || paramType == int.class
- || paramType == long.class
- || paramType == float.class
- || paramType == double.class
- || paramType == boolean.class
- || paramType == Boolean.class;
- }
-
- private BigInteger getBigIntegerValue(SimpleData data) {
- BigInteger paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = new BigInteger(Long.toString(nval.longValue()));
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = new BigInteger(sval);
- }
- catch(Exception exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to BigInteger");
- }
- }
- }
- }
- return paramVal;
- }
-
- private BigDecimal getBigDecimalValue(SimpleData data) {
- BigDecimal paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = new BigDecimal(nval.toString());
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = new BigDecimal(sval);
- }
- catch(Exception exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to BigDecimal");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Byte getByteValue(SimpleData data) {
- Byte paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.byteValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Byte.parseByte(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to byte");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Short getShortValue(SimpleData data) {
- Short paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.shortValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Short.parseShort(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to short");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Integer getIntegerValue(SimpleData data) {
- Integer paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.intValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Integer.parseInt(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to integer");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Long getLongValue(SimpleData data) {
- Long paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.longValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Long.parseLong(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to long");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Float getFloatValue(SimpleData data) {
- Float paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.floatValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Float.parseFloat(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to float");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Double getDoubleValue(SimpleData data) {
- Double paramVal = null;
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.doubleValue();
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- try {
- paramVal = Double.parseDouble(sval);
- }
- catch(NumberFormatException exep) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("Unable to convert string [" + sval + "] to double");
- }
- }
- }
- }
- return paramVal;
- }
-
- private Boolean getBooleanValue(SimpleData data) {
- Boolean paramVal = data.getBoolean();
- if(paramVal != null) {
- return paramVal;
- }
-
- Number nval = data.getNumber();
- if(nval != null) {
- paramVal = nval.intValue() != 0;
- }
- else {
- String sval = data.getString();
- if(sval != null) {
- paramVal = Boolean.parseBoolean(sval.toLowerCase(Locale.getDefault()));
- }
- }
- return paramVal;
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankLinear.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankLinear.java
new file mode 100644
index 0000000..9d167a3
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankLinear.java
@@ -0,0 +1,82 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+/**
+ * A BlankLinear is a Setter method that has a blank data key. It is used to set the value of a
+ * property on an object, but does not have a specific data key associated with it.
+ *
+ * @author indroneel
+ */
+
+public class BlankLinear extends FromMethod {
+
+ private final Class> inType;
+
+ public BlankLinear(Method method) throws IllegalArgumentException {
+ super(method);
+
+ if(!getDataKey().isBlank()) {
+ // If the data key is not blank, it is not a blank linear method
+ throw new IllegalArgumentException();
+ }
+
+ Parameter[] params = method.getParameters();
+ if(params.length != 1) {
+ // If the method does not have exactly one parameter, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+
+ Type type = params[0].getParameterizedType();
+ if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
+ // If the parameter type is a type variable or a parameterized type, it is not valid
+ // for conversion
+ throw new IllegalArgumentException();
+ }
+ inType = params[0].getType();
+ if(inType.isArray()) {
+ // If the parameter type is an array, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of base class FromMethod
+
+ @Override
+ public Class> getInputType() {
+ return inType;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s(%s)", getMethod().getName(), inType.getName());
+ }
+
+ public static BlankLinear of(Method method) {
+ try {
+ return new BlankLinear(method);
+ }
+ catch (IllegalArgumentException exep) {
+ return null;
+ }
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankMapped.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankMapped.java
new file mode 100644
index 0000000..34c82d0
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/BlankMapped.java
@@ -0,0 +1,81 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+public class BlankMapped extends FromMethod {
+
+ private final Class> inType;
+
+ public BlankMapped(Method method) throws IllegalArgumentException {
+ super(method);
+
+ if(!getDataKey().isBlank()) {
+ // If the data key is not blank, it is not a blank mapped method
+ throw new IllegalArgumentException();
+ }
+
+ Parameter[] params = method.getParameters();
+ if(params.length != 2) {
+ // If the method does not have exactly two parameters, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+
+ if(params[0].getType() != String.class) {
+ // If the first parameter is not of type String, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+
+ Type type = params[1].getParameterizedType();
+ if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
+ // If the second parameter type is a type variable or a parameterized type, it
+ // is not valid for transformation
+ throw new IllegalArgumentException();
+ }
+ inType = params[1].getType();
+ if(inType.isArray()) {
+ // If the parameter type is an array, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of base class FromMethod
+
+ @Override
+ public Class> getInputType() {
+ return inType;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s(%s)", getMethod().getName(), inType.getName());
+ }
+
+ public static BlankMapped of(Method method) {
+ try {
+ return new BlankMapped(method);
+ }
+ catch (IllegalArgumentException exep) {
+ return null;
+ }
+ }
+
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/ExternalImpl.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/ExternalImpl.java
similarity index 61%
rename from moe-main/src/main/java/daxi/moe/lib/ExternalImpl.java
rename to moe-main/src/main/java/daxi/moe/lib/mod2obj/ExternalImpl.java
index 6c78cb6..acb4175 100644
--- a/moe-main/src/main/java/daxi/moe/lib/ExternalImpl.java
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/ExternalImpl.java
@@ -10,30 +10,20 @@
* 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 daxi.moe.lib;
+package daxi.moe.lib.mod2obj;
import daxi.moe.app.External;
import daxi.moe.app.Moe;
+import daxi.moe.app.MoeException;
import daxi.moe.codec.MoeCodec;
import daxi.moe.codec.MoeDecoder;
-import daxi.moe.lib.m2j.M2JLinearImpl;
-import daxi.moe.lib.m2j.M2JMappedImpl;
-import daxi.moe.lib.m2j.M2JObjectImpl;
-import daxi.moe.lib.m2j.M2JSimpleImpl;
-import daxi.moe.lib.transform.M2JGlobals;
-import daxi.moe.lib.transform.M2JLinear;
-import daxi.moe.lib.transform.M2JMapped;
-import daxi.moe.lib.transform.M2JObject;
-import daxi.moe.lib.transform.M2JSimple;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import java.io.InputStream;
import java.util.List;
-import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -46,24 +36,13 @@ public class ExternalImpl implements External {
private final MoeDecoder decoder;
private final List options;
- private final M2JGlobals globals;
+ private final Populators populators;
private AnyData model;
- ExternalImpl(MoeCodec codec, List options) {
+ public ExternalImpl(MoeCodec codec, List options) {
decoder = codec.decoder();
-
this.options = options;
-
- globals = new M2JGlobals(options);
- M2JSimple m2jSim = new M2JSimpleImpl(globals);
- globals.setM2J(m2jSim);
- M2JLinear m2jLin = new M2JLinearImpl(globals);
- globals.setM2J(m2jLin);
- M2JMapped m2jMap = new M2JMappedImpl(globals);
- globals.setM2J(m2jMap);
- M2JObject m2jObj = new M2JObjectImpl(globals);
- globals.setM2J(m2jObj);
-
+ populators = new Populators(options);
model = new AnyData(new MappedData());
}
@@ -71,7 +50,7 @@ public class ExternalImpl implements External {
// Methods of interface External
@Override
- public External from(InputStream in) {
+ public External from(InputStream in) throws MoeException {
decoder.setSource(in);
model = decoder.decode(options);
if(model == null) {
@@ -81,7 +60,7 @@ public class ExternalImpl implements External {
}
@Override
- public External from(byte[] data) {
+ public External from(byte[] data) throws MoeException {
decoder.setSource(data);
model = decoder.decode(options);
if(model == null) {
@@ -101,19 +80,18 @@ public class ExternalImpl implements External {
}
@Override
- public T convert(Class type) {
+ public T convert(Class type) throws MoeException {
MappedData data = model.asMapped();
if(data == null) {
- if(L.isLoggable(Level.WARNING)) {
- L.warning("input data model does not contain MappedData as root element");
- }
+ L.warning(() -> "input data model does not contain MappedData as root element");
return null;
}
- return globals.getM2JObject().convert(data, type);
+ Object retObj = populators.getMapped().create(new AnyData(data), type);
+ return type.cast(retObj);
}
@Override
- public T convert(String path, Class type) {
+ public T convert(String path, Class type) throws MoeException {
return null;
}
}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/FromMethod.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/FromMethod.java
new file mode 100644
index 0000000..3dc0be0
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/FromMethod.java
@@ -0,0 +1,88 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.MapFrom;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+
+/**
+ * Represents a method that is used to convert a nested data model item into a Java object. The
+ * method must be private, non-static, and return void. The method must also be annotated with the
+ * {@link MapFrom} annotation, which specifies the data key that is used to identify the nested data
+ * in the model.
+ *
+ * @author indroneel
+ */
+
+public abstract class FromMethod {
+
+ private final Method method;
+ private final String dataKey;
+
+ protected FromMethod(Method method) {
+ this.method = method;
+ MapFrom mapping = method.getAnnotation(MapFrom.class);
+ if(mapping == null) {
+ // If the method does not have the @Mapping annotation, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+ // populate the dataKey field with the value of the @Mapping annotation
+ dataKey = mapping.value().trim();
+
+ if(method.getReturnType() != Void.TYPE) {
+ // If the method does not return void, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+
+ int mod = method.getModifiers();
+ // If the method is abstract, static, or not private, it is not valid for conversion
+ if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
+ throw new IllegalArgumentException();
+ }
+ }
+
+/**
+ * Returns the data key associated with this method. The data key is used to identify the nested
+ * data in the model that will be converted.
+ *
+ * @return the data key
+ */
+
+ public final String getDataKey() {
+ return dataKey;
+ }
+
+/**
+ * Returns the method that this FromMethod instance represents. The method is used to set the
+ * value of the converted data in the target object.
+ *
+ * @return the method that is used to convert the data
+ */
+
+ public final Method getMethod() {
+ return method;
+ }
+
+/**
+ * Returns the input type that the method accepts. The library will use this type to determine how
+ * to convert the data model item into the appropriate (Java) input type.
+ *
+ * @return the input type of the method
+ */
+
+ public abstract Class> getInputType();
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/LinearPopulator.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/LinearPopulator.java
new file mode 100644
index 0000000..b869afe
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/LinearPopulator.java
@@ -0,0 +1,160 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.LinearData;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class LinearPopulator implements Populator {
+
+ private static final Logger L = Logger.getLogger(LinearPopulator.class.getName());
+
+ private final Populators populators;
+
+ public LinearPopulator(Populators populators) {
+ this.populators = populators;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Populator
+
+ @Override
+ public Object create(AnyData data, Class> targetType) throws ConvertException {
+ LinearData ldata = data.asLinear();
+ if(ldata == null || targetType == null) {
+ L.warning(() -> "Invalid arguments: data=" + ldata + ", targetType=" + targetType);
+ return null;
+ }
+
+ TargetEntity entity = new TargetEntity(targetType);
+ L.finest(() -> entity.dumpInfo());
+
+ if(entity.hasSetters()) {
+ L.warning(() -> "Target type has setters, need only blank linear: " + targetType);
+ return null;
+ }
+
+ BlankLinear blinear = entity.getBlankLinear();
+ if(blinear == null) {
+ L.warning(() -> "Target type does not have a blank linear method: " + targetType);
+ return null;
+ }
+
+ Object target;
+ try {
+ // Attempt to create a new instance of the target type using its public and default
+ // constructor
+ Constructor> ctor = targetType.getConstructor();
+ target = ctor.newInstance();
+ }
+ catch(NoSuchMethodException exep) {
+ if(L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ return null;
+ }
+ catch(Exception exep) {
+ throw new ConvertException(targetType.getName(), "",
+ "Error invoking default constructor - " + exep.getMessage(), exep);
+ }
+
+ Status status = populateImpl(data, target, blinear.getMethod(), blinear.getInputType());
+
+ if(status != Status.SUCCESS) {
+ L.warning(() -> "Failed to populate target object: " + targetType);
+ return null;
+ }
+ return target;
+ }
+
+ @Override
+ public Status populate(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+ // note: the check for linear data is done in the populateImpl method, so we don't need to
+ // do it here
+
+ // for each item in the linear data, we will try to populate the target object using the
+ // corresponding setter method with the given data key.
+
+ Setter setter = entity.getSetter(dataKey);
+ if(setter == null) {
+ return Status.NOT_VALID;
+ }
+
+ return populateImpl(data, targetObj, setter.getMethod(), setter.getInputType());
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private Status populateImpl(AnyData data,
+ Object targetObj, Method method,
+ Class> popType) throws ConvertException {
+ LinearData ldata = data.asLinear();
+ if(ldata == null) {
+ return Status.NOT_VALID;
+ }
+
+ Status retstat = Status.NOT_VALID;
+ for(int pos=0; pos String.format("Cannot set using: %s:%s",
+ targetObj.getClass().getName(), method.getName()));
+ continue;
+ }
+
+ try {
+ method.setAccessible(true);
+ method.invoke(targetObj, setterVal);
+ method.setAccessible(false);
+ retstat = Status.SUCCESS;
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), method.getName(),
+ "Error invoking setter for linear data item - " + exep.getMessage(), exep);
+ }
+ }
+ return retstat;
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/MappedPopulator.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/MappedPopulator.java
new file mode 100644
index 0000000..1acbc8b
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/MappedPopulator.java
@@ -0,0 +1,182 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.MappedData;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class MappedPopulator implements Populator {
+
+ private static final Logger L = Logger.getLogger(MappedPopulator.class.getName());
+
+ private final Populators populators;
+
+ public MappedPopulator(Populators populators) {
+ this.populators = populators;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Populator
+
+ @Override
+ public Object create(AnyData data, Class> targetType) throws ConvertException {
+ MappedData mdata = data.asMapped();
+ if(mdata == null || targetType == null) {
+ L.warning(() -> "Invalid arguments: data=" + mdata + ", targetType=" + targetType);
+ return null;
+ }
+
+ TargetEntity entity = new TargetEntity(targetType);
+ if (L.isLoggable(Level.FINEST)) {
+ L.finest(entity.dumpInfo());
+ }
+
+ if(entity.isInvalid()) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.warning("Target type is not valid: " + targetType);
+ }
+ return null;
+ }
+
+ Object target;
+ try {
+ // Attempt to create a new instance of the target type using its public and default
+ // constructor
+ Constructor> ctor = targetType.getConstructor();
+ target = ctor.newInstance();
+ }
+ catch(NoSuchMethodException exep) {
+ if(L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ return null;
+ }
+ catch(Exception exep) {
+ throw new ConvertException(targetType.getName(), "",
+ "Error invoking default constructor - " + exep.getMessage(), exep);
+ }
+
+ for(String dataKey : mdata.getKeys()) {
+ AnyData nestedData = mdata.get(dataKey);
+ if (nestedData == null) {
+ continue; // this should not happen, but just in case
+ }
+
+ Status status = Status.NOT_VALID;
+
+ if(nestedData.asSimple() != null) {
+ status = populators.getSimple().populate(nestedData, dataKey, entity, target);
+ }
+ else if(nestedData.asLinear() != null) {
+ status = populators.getLinear().populate(nestedData, dataKey, entity, target);
+ }
+ else if(nestedData.asMapped() != null) {
+ status = populate(nestedData, dataKey, entity, target);
+ }
+
+ if(status != Status.SUCCESS) {
+ L.info(() -> String.format("key = %s, type = %s Cannot set or add", dataKey,
+ target.getClass().getName()));
+ }
+ }
+ return target;
+ }
+
+ @Override
+ public Status populate(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+ MappedData mdata = data.asMapped();
+ if(mdata == null) {
+ return Status.NOT_VALID;
+ }
+
+ if(entity.hasSetters()) {
+ return doSetter(data, dataKey, entity, targetObj);
+ }
+ else {
+ return doBlankMap(data, dataKey, entity, targetObj);
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private Status doSetter(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+ Setter setter = entity.getSetter(dataKey);
+ if(setter == null) {
+ return Status.NOT_VALID;
+ }
+
+ Object paramVal = create(data, setter.getInputType());
+ if(paramVal == null) {
+ return Status.NOT_VALID;
+ }
+
+ Method method = setter.getMethod();
+ try {
+ method.setAccessible(true);
+ method.invoke(targetObj, paramVal);
+ method.setAccessible(false);
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), method.getName(),
+ "Error invoking setter - " + exep.getMessage(), exep);
+ }
+ return Status.SUCCESS;
+ }
+
+ private Status doBlankMap(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+
+ BlankMapped bmapped = entity.getBlankMapped();
+ if(bmapped == null) {
+ return Status.NOT_VALID;
+ }
+
+ Object paramVal = create(data, bmapped.getInputType());
+ if(paramVal == null) {
+ return Status.NOT_VALID;
+ }
+
+ Method method = bmapped.getMethod();
+ try {
+ method.setAccessible(true);
+ method.invoke(targetObj, dataKey, paramVal);
+ method.setAccessible(false);
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), method.getName(),
+ "Error invoking blank mapped method - " + exep.getMessage(), exep);
+ }
+ return Status.SUCCESS;
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populator.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populator.java
new file mode 100644
index 0000000..f3ec4d9
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populator.java
@@ -0,0 +1,52 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+
+/**
+ * @author indroneel
+ */
+
+public interface Populator {
+
+/**
+ * Converts an {@link AnyData} to an object of the specified target type. The anydata encapsulates
+ * any one of a simple, linear or mapped data.
+ *
+ * @param data one of a simple, linear or mapped data to convert
+ * @param targetType the target type to convert to
+ * @return an object of the specified target type
+ * @throws ConvertException if the conversion fails
+ */
+
+ Object create(AnyData data, Class> targetType) throws ConvertException;
+
+/**
+ * Populates a target Java object using any data by invoking the provided method on the object. The
+ * anydata encapsulates any one of a simple, linear or mapped data.
+ *
+ * @param data one of a simple, linear or mapped data
+ * @param dataKey The key associated with the any data.
+ * @param entity the target entity that encapsulates the target object and the method to invoke
+ * @param targetObj the target Java object to populate
+ * @return a {@link Status} indicating the result of the population operation
+ * @throws ConvertException if the population operation fails
+ */
+
+ Status populate(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException;
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populators.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populators.java
new file mode 100644
index 0000000..28dd2b5
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Populators.java
@@ -0,0 +1,55 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.Moe;
+
+import java.util.List;
+
+/**
+ * @author indroneel
+ */
+
+public class Populators {
+
+ private final List options;
+
+ private final Populator simple;
+ private final Populator linear;
+ private final Populator mapped;
+
+ public Populators(List options) {
+ this.options = options;
+ simple = new SimplePopulator();
+ linear = new LinearPopulator(this);
+ mapped = new MappedPopulator(this);
+ }
+
+ public boolean hasOption(Moe.Options opt) {
+ return options.contains(opt);
+ }
+
+ public Populator getSimple() {
+ return simple;
+ }
+
+ public Populator getLinear() {
+ return linear;
+ }
+
+ public Populator getMapped() {
+ return mapped;
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/Setter.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Setter.java
new file mode 100644
index 0000000..2fc977c
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Setter.java
@@ -0,0 +1,92 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Parameter;
+import java.lang.reflect.ParameterizedType;
+import java.lang.reflect.Type;
+import java.lang.reflect.TypeVariable;
+
+/**
+ * A Setter is a method that takes a single input parameter and returns void. It is used to set the
+ * value of a property on an object.
+ *
+ * @author indroneel
+ */
+
+public class Setter extends FromMethod {
+
+ private final Class> inType;
+
+ protected Setter(Method method) throws IllegalArgumentException {
+ super(method);
+
+ if(getDataKey().isBlank()) {
+ // If the data key is blank, it is not a setter method
+ throw new IllegalArgumentException();
+ }
+
+ Parameter[] params = method.getParameters();
+ if(params.length != 1) {
+ // If the method does not have exactly one parameter, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+
+ Type type = params[0].getParameterizedType();
+ if(type instanceof TypeVariable> || type instanceof ParameterizedType) {
+ // If the parameter type is a type variable or a parameterized type, it is not valid
+ // for conversion
+ throw new IllegalArgumentException();
+ }
+ inType = params[0].getType();
+ if(inType.isArray()) {
+ // If the parameter type is an array, it is not valid for conversion
+ throw new IllegalArgumentException();
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of base class FromMethod
+
+ @Override
+ public Class> getInputType() {
+ return inType;
+ }
+
+ @Override
+ public String toString() {
+ return String.format("%s(%s)", getMethod().getName(), inType.getName());
+ }
+
+/**
+ * Returns a Setter object if the provided method is valid for conversion, or null if it is
+ * not valid.
+ *
+ * @param method the method to be checked
+ * @return the Setter instance or null if the method does not meet valid setter semantics
+ */
+
+ public static Setter of(Method method) {
+ try {
+ return new Setter(method);
+ }
+ catch (IllegalArgumentException exep) {
+ return null;
+ }
+ }
+
+
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/SimplePopulator.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/SimplePopulator.java
new file mode 100644
index 0000000..ef8672c
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/SimplePopulator.java
@@ -0,0 +1,347 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.SimpleData;
+
+import java.lang.reflect.Method;
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.util.Locale;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class SimplePopulator implements Populator {
+
+ private static final Logger L = Logger.getLogger(SimplePopulator.class.getName());
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Populator
+
+ @Override
+ public Object create(AnyData data, Class> targetType) throws ConvertException {
+ SimpleData sdata = data.asSimple();
+ if(sdata == null) {
+ return null;
+ }
+
+ Object targetObj = null;
+ if(targetType == String.class) {
+ targetObj = sdata.getString();
+ }
+
+ if(targetType == BigInteger.class) {
+ targetObj = getBigIntegerValue(sdata);
+ }
+
+ if(targetType == BigDecimal.class) {
+ targetObj = getBigDecimalValue(sdata);
+ }
+
+ if(targetType == byte.class || targetType == Byte.class) {
+ targetObj = getByteValue(sdata);
+ }
+
+ if(targetType == short.class || targetType == Short.class) {
+ targetObj = getShortValue(sdata);
+ }
+
+ if(targetType == int.class || targetType == Integer.class) {
+ targetObj = getIntegerValue(sdata);
+ }
+
+ if(targetType == long.class || targetType == Long.class) {
+ targetObj = getLongValue(sdata);
+ }
+
+ if(targetType == float.class || targetType == Float.class) {
+ targetObj = getFloatValue(sdata);
+ }
+
+ if(targetType == double.class || targetType == Double.class) {
+ targetObj = getDoubleValue(sdata);
+ }
+
+ if(targetType == boolean.class || targetType == Boolean.class) {
+ targetObj = getBooleanValue(sdata);
+ }
+
+ return targetObj;
+ }
+
+ @Override
+ public Status populate(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+ SimpleData sdata = data.asSimple();
+ if(sdata == null) {
+ return Status.NOT_VALID;
+ }
+ if(entity.hasSetters()) {
+ return doSetter(data, dataKey, entity, targetObj);
+ }
+ else {
+ return doBlankMap(data, dataKey, entity, targetObj);
+ }
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private BigInteger getBigIntegerValue(SimpleData data) {
+ String strVal = data.getString();
+ if(strVal == null) {
+ Number nval = data.getNumber();
+ if(nval != null) {
+ strVal = nval.toString();
+ }
+ }
+ if(strVal != null) {
+ strVal = strVal.split("\\.")[0];
+ try {
+ return new BigInteger(strVal);
+ }
+ catch(Exception exep) {
+ if(L.isLoggable(Level.WARNING)) {
+ L.warning(() -> "Unable to convert [" + data + "] to BigInteger");
+ }
+ }
+ }
+ return null;
+ }
+
+ private BigDecimal getBigDecimalValue(SimpleData data) {
+ String strVal = data.getString();
+ if(strVal == null) {
+ Number nval = data.getNumber();
+ if(nval != null) {
+ strVal = nval.toString();
+ }
+ }
+ if(strVal != null) {
+ try {
+ return new BigDecimal(strVal);
+ }
+ catch(Exception exep) {
+ if(L.isLoggable(Level.WARNING)) {
+ L.warning(() -> "Unable to convert [" + data + "] to BigDecimal");
+ }
+ }
+ }
+ return null;
+ }
+
+ private Byte getByteValue(SimpleData data) {
+ Byte paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.byteValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Byte.parseByte(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to byte");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Short getShortValue(SimpleData data) {
+ Short paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.shortValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Short.parseShort(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to short");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Integer getIntegerValue(SimpleData data) {
+ Integer paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.intValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Integer.parseInt(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to integer");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Long getLongValue(SimpleData data) {
+ Long paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.longValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Long.parseLong(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to long");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Float getFloatValue(SimpleData data) {
+ Float paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.floatValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Float.parseFloat(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to float");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Double getDoubleValue(SimpleData data) {
+ Double paramVal = null;
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.doubleValue();
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ try {
+ paramVal = Double.parseDouble(sval);
+ }
+ catch(NumberFormatException exep) {
+ L.warning(() -> "Unable to convert string [" + sval + "] to double");
+ }
+ }
+ }
+ return paramVal;
+ }
+
+ private Boolean getBooleanValue(SimpleData data) {
+ Boolean paramVal = data.getBoolean();
+ if(paramVal != null) {
+ return paramVal;
+ }
+
+ Number nval = data.getNumber();
+ if(nval != null) {
+ paramVal = nval.intValue() != 0;
+ }
+ else {
+ String sval = data.getString();
+ if(sval != null) {
+ paramVal = Boolean.parseBoolean(sval.toLowerCase(Locale.getDefault()));
+ }
+ }
+ return paramVal;
+ }
+
+ private Status doSetter(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+ Setter setter = entity.getSetter(dataKey);
+ if(setter == null) {
+ return Status.NOT_VALID;
+ }
+
+ Object paramVal = create(data, setter.getInputType());
+
+ if(paramVal == null) {
+ return Status.NOT_VALID;
+ }
+
+ Method method = setter.getMethod();
+ try {
+ method.setAccessible(true);
+ method.invoke(targetObj, paramVal);
+ method.setAccessible(false);
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), method.getName(),
+ "Error invoking setter - " + exep.getMessage(), exep);
+ }
+ return Status.SUCCESS;
+ }
+
+ private Status doBlankMap(AnyData data, String dataKey,
+ TargetEntity entity, Object targetObj) throws ConvertException {
+
+ BlankMapped bmapped = entity.getBlankMapped();
+ if(bmapped == null) {
+ return Status.NOT_VALID;
+ }
+
+ Object paramVal = create(data, bmapped.getInputType());
+ if(paramVal == null) {
+ return Status.NOT_VALID;
+ }
+
+ Method method = bmapped.getMethod();
+ try {
+ method.setAccessible(true);
+ method.invoke(targetObj, dataKey, paramVal);
+ method.setAccessible(false);
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), method.getName(),
+ "Error invoking blank mapped method - " + exep.getMessage(), exep);
+ }
+ return Status.SUCCESS;
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JStatus.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Status.java
similarity index 68%
rename from moe-main/src/main/java/daxi/moe/lib/transform/M2JStatus.java
rename to moe-main/src/main/java/daxi/moe/lib/mod2obj/Status.java
index 44f5dea..774c0e9 100644
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JStatus.java
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/Status.java
@@ -12,17 +12,25 @@
* limitations under the License.
*/
-package daxi.moe.lib.transform;
+package daxi.moe.lib.mod2obj;
/**
- * Defines the possible statuses for a transformation. The transformation can be from the model data
- * to Java objects or vice versa.
+ * Reports whether a converter could handle the supplied data and whether conversion succeeded.
*
* @author indroneel
*/
-public enum M2JStatus {
+public enum Status {
+
+/**
+ * The converter did not handle the supplied data.
+ */
+
NOT_VALID,
- SUCCESS,
- ERROR
+
+/**
+ * The conversion completed successfully.
+ */
+
+ SUCCESS
}
diff --git a/moe-main/src/main/java/daxi/moe/lib/mod2obj/TargetEntity.java b/moe-main/src/main/java/daxi/moe/lib/mod2obj/TargetEntity.java
new file mode 100644
index 0000000..9edf4bc
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/mod2obj/TargetEntity.java
@@ -0,0 +1,137 @@
+/*
+ * 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 daxi.moe.lib.mod2obj;
+
+import daxi.moe.app.ConvertException;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.logging.Logger;
+
+/**
+ * A TargetEntity is a representation of a target class that can be populated with data from a
+ * model. It contains information about the setters and blank methods available in the target class.
+ *
+ * @author indroneel
+ */
+
+public class TargetEntity {
+
+ private static final Logger L = Logger.getLogger(TargetEntity.class.getName());
+
+ private final Class> targetType;
+ private final Map setters;
+ private BlankLinear blankLinear;
+ private BlankMapped blankMapped;
+
+ public TargetEntity(Class> targetType) throws ConvertException {
+ this.targetType = targetType;
+ setters = new HashMap<>();
+ collateAllMethods(targetType);
+ }
+
+ //TODO: remove dead code
+ /*
+ public TargetEntity(Object targetObj) throws ConvertException {
+ this(targetObj.getClass());
+ }
+ */
+
+ public boolean isInvalid() {
+ return setters.isEmpty() && blankLinear == null && blankMapped == null;
+ }
+
+ public boolean hasSetters() {
+ return !setters.isEmpty();
+ }
+
+ public Setter getSetter(String dataKey) {
+ return setters.get(dataKey);
+ }
+
+ public BlankLinear getBlankLinear() {
+ return blankLinear;
+ }
+
+ public BlankMapped getBlankMapped() {
+ return blankMapped;
+ }
+
+ public String dumpInfo() {
+ StringBuilder sb = new StringBuilder();
+ sb.append(String.format("TargetEntity: %s\n", targetType.getName()));
+ sb.append("=== START DUMP ===\n");
+ sb.append("Setters:\n");
+ for (Map.Entry entry : setters.entrySet()) {
+ sb.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\n");
+ }
+ sb.append("BlankLinear: ").append(blankLinear).append("\n");
+ sb.append("BlankMapped: ").append(blankMapped).append("\n");
+ sb.append("=== END DUMP ===\n");
+ return sb.toString();
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private void collateAllMethods(Class> type) throws ConvertException {
+
+ if(type.getClassLoader() == null) {
+ // Skip system classes
+ return;
+ }
+
+ for (Method method : type.getDeclaredMethods()) {
+ Setter sm = Setter.of(method);
+ if(sm != null) {
+ if(setters.containsKey(sm.getDataKey())) {
+ throw new ConvertException(type.getName(), sm.getMethod().getName(),
+ "Duplicate setter for data key: " + sm.getDataKey(), null);
+ }
+ setters.put(sm.getDataKey(), sm);
+ continue;
+ }
+
+ //else
+ BlankLinear bkl = BlankLinear.of(method);
+ if(bkl != null) {
+ if(blankLinear == null) {
+ blankLinear = bkl;
+ }
+ else {
+ throw new ConvertException(type.getName(), bkl.getMethod().getName(),
+ "Duplicate blank linear method: " + bkl.getMethod().getName(), null);
+ }
+ }
+
+ //else
+ BlankMapped bkm = BlankMapped.of(method);
+ if(bkm != null) {
+ if(blankMapped == null) {
+ blankMapped = bkm;
+ }
+ else {
+ throw new ConvertException(type.getName(), bkm.getMethod().getName(),
+ "Duplicate blank mapped method: " + bkm.getMethod().getName(), null);
+ }
+ }
+ }
+
+ if (type.getSuperclass() != null) {
+ collateAllMethods(type.getSuperclass());
+ }
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/InternalImpl.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/InternalImpl.java
similarity index 62%
rename from moe-main/src/main/java/daxi/moe/lib/InternalImpl.java
rename to moe-main/src/main/java/daxi/moe/lib/obj2mod/InternalImpl.java
index cfada6d..953389a 100644
--- a/moe-main/src/main/java/daxi/moe/lib/InternalImpl.java
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/InternalImpl.java
@@ -10,24 +10,22 @@
* 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 daxi.moe.lib;
+package daxi.moe.lib.obj2mod;
import daxi.moe.app.Internal;
import daxi.moe.app.Moe;
+import daxi.moe.app.MoeException;
import daxi.moe.codec.MoeCodec;
import daxi.moe.codec.MoeEncoder;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
-import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
/**
- *
* @author indroneel
*/
@@ -38,21 +36,26 @@ public class InternalImpl implements Internal {
private final MoeEncoder encoder;
private final List options;
- //private final M2JGlobals globals;
+ private final Retrievers retrievers;
private AnyData model;
- InternalImpl(MoeCodec provider, List options) {
- encoder = provider.encoder();
+ public InternalImpl(MoeCodec codec, List options) {
+ encoder = codec.encoder();
this.options = options;
-
- //globals = new M2JGlobals(options);
-
+ retrievers = new Retrievers(options);
model = new AnyData(new MappedData());
}
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Internal
+
@Override
- public Internal from(Object obj) {
+ public Internal from(Object obj) throws MoeException {
+ Retriever retriever = retrievers.getRetriever(obj);
+ if(retriever != null) {
+ model = retriever.transform(obj);
+ }
return this;
}
@@ -62,12 +65,12 @@ public class InternalImpl implements Internal {
}
@Override
- public byte[] convert() throws IOException {
- return new byte[0];
+ public byte[] convert() throws MoeException {
+ return encoder.convert(model, false);
}
@Override
- public byte[] convert(boolean pretty) throws IOException {
- return new byte[0];
+ public byte[] convert(boolean pretty) throws MoeException {
+ return encoder.convert(model, pretty);
}
}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/LinearRetriever.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/LinearRetriever.java
new file mode 100644
index 0000000..ec892d4
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/LinearRetriever.java
@@ -0,0 +1,88 @@
+/*
+ * 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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.LinearData;
+
+import java.lang.reflect.Array;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class LinearRetriever implements Retriever {
+
+ private static final Logger L = Logger.getLogger(LinearRetriever.class.getName());
+
+ private final Retrievers retrievers;
+
+ public LinearRetriever(Retrievers retrievers) {
+ this.retrievers = retrievers;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Retriever
+
+ @Override
+ public boolean supports(Object targetObj) {
+ Class> tcls = targetObj.getClass();
+ return Collection.class.isAssignableFrom(tcls) || tcls.isArray();
+ }
+
+ @Override
+ public AnyData transform(Object targetObj) throws ConvertException {
+ Class> tcls = targetObj.getClass();
+
+ LinearData ldata = new LinearData();
+ if(Collection.class.isAssignableFrom(tcls)) {
+ for (Object item : (Collection>) targetObj) {
+ AnyData idata = transformItem(item);
+ if (idata != null) {
+ ldata.add(idata);
+ }
+ }
+ }
+ else if(tcls.isArray()) {
+ Class> compType = tcls.getComponentType();
+ int length = Array.getLength(targetObj);
+ for(int i = 0; i < length; i++) {
+ AnyData idata = transformItem(Array.get(targetObj, i));
+ if(idata != null) {
+ ldata.add(idata);
+ }
+ }
+ }
+ return new AnyData(ldata);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private AnyData transformItem(Object item) throws ConvertException {
+ Retriever retriever = retrievers.getRetriever(item);
+ if(retriever != null) {
+ return retriever.transform(item);
+ }
+ else {
+ L.warning(() -> "Unsupported item - " + item.getClass().getName());
+ return null;
+ }
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/MappedRetriever.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/MappedRetriever.java
new file mode 100644
index 0000000..38b20ab
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/MappedRetriever.java
@@ -0,0 +1,112 @@
+/*
+ * 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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.MappedData;
+
+import java.lang.reflect.Method;
+import java.util.Collection;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class MappedRetriever implements Retriever {
+
+ private static final Logger L = Logger.getLogger(MappedRetriever.class.getName());
+
+ private final Retrievers retrievers;
+
+ public MappedRetriever(Retrievers retrievers) {
+ this.retrievers = retrievers;
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Retriever
+
+ @Override
+ public boolean supports(Object targetObj) {
+ Class> tcls = targetObj.getClass();
+ if(tcls.getClassLoader() == null) {
+ // This is a system class, we don't support it.
+ return false;
+ }
+ /*
+ if(targetObj instanceof String
+ || targetObj instanceof Number || targetObj instanceof Boolean) {
+ // This is a String, Number, or Boolean, we don't support it.
+ return false;
+ }
+ if(Collection.class.isAssignableFrom(tcls)) {
+ // This is a Collection, we don't support it.
+ return false;
+ }
+ */
+
+ if(tcls.isArray()) {
+ // This is an array, we don't support it.
+ return false;
+ }
+ return true;
+ }
+
+ @Override
+ public AnyData transform(Object targetObj) throws ConvertException {
+
+ SourceEntity sent = new SourceEntity(targetObj);
+ Set dataKeys = sent.getDataKeys();
+ if(dataKeys == null || dataKeys.isEmpty()) {
+ return null;
+ }
+
+ MappedData mdata = new MappedData();
+
+ for(String dataKey : dataKeys) {
+ ToMethod tm = sent.getToMethod(dataKey);
+ Method mthd = tm.getMethod();
+ Object retVal = null;
+ final Class> rtnType = tm.getReturnType();
+ try {
+ mthd.setAccessible(true);
+ retVal = mthd.invoke(targetObj);
+ mthd.setAccessible(false);
+ }
+ catch (ReflectiveOperationException exep) {
+ if (L.isLoggable(Level.WARNING)) {
+ L.log(Level.WARNING, exep.getMessage(), exep);
+ }
+ throw new ConvertException(targetObj.getClass().getName(), mthd.getName(),
+ "Error invoking getter - " + exep.getMessage(), exep);
+ }
+
+ Retriever retriever = retrievers.getRetriever(retVal);
+ if(retriever != null) {
+ AnyData adata = retriever.transform(retVal);
+ if(adata != null) {
+ mdata.put(dataKey, adata);
+ }
+ }
+ else {
+ L.warning(() -> "Unsupported return type - " + rtnType.getName());
+ }
+ }
+ return new AnyData(mdata);
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/app/Converter.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/Retriever.java
similarity index 75%
rename from moe-main/src/main/java/daxi/moe/app/Converter.java
rename to moe-main/src/main/java/daxi/moe/lib/obj2mod/Retriever.java
index bb201c9..646ace2 100644
--- a/moe-main/src/main/java/daxi/moe/app/Converter.java
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/Retriever.java
@@ -12,19 +12,18 @@
* limitations under the License.
*/
-package daxi.moe.app;
+package daxi.moe.lib.obj2mod;
+import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
-import java.util.Optional;
-
/**
* @author indroneel
*/
-public interface Converter {
+public interface Retriever {
- T decode(AnyData ad, Class type);
+ boolean supports(Object targetObj);
- Optional encode(Object obj);
+ AnyData transform(Object targetObj) throws ConvertException;
}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/Retrievers.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/Retrievers.java
new file mode 100644
index 0000000..02472b4
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/Retrievers.java
@@ -0,0 +1,49 @@
+/*
+ * 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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.Moe;
+
+import java.util.List;
+
+/**
+ * @author indroneel
+ */
+
+public class Retrievers {
+
+ private final Retriever simple;
+ private final Retriever linear;
+ private final Retriever mapped;
+
+ public Retrievers(List options) {
+ simple = new SimpleRetriever();
+ linear = new LinearRetriever(this);
+ mapped = new MappedRetriever(this);
+ }
+
+ public Retriever getRetriever(Object targetObj) {
+ if(simple.supports(targetObj)) {
+ return simple;
+ }
+ else if(linear.supports(targetObj)) {
+ return linear;
+ }
+ else if(mapped.supports(targetObj)) {
+ return mapped;
+ }
+ return null;
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/SimpleRetriever.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/SimpleRetriever.java
new file mode 100644
index 0000000..9cfebc9
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/SimpleRetriever.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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.ConvertException;
+import daxi.moe.model.AnyData;
+import daxi.moe.model.SimpleData;
+
+/**
+ * @author indroneel
+ */
+
+public class SimpleRetriever implements Retriever {
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Methods of interface Retriever
+
+ @Override
+ public boolean supports(Object targetObj) {
+ return targetObj instanceof String || targetObj instanceof StringBuilder
+ || targetObj instanceof StringBuffer || targetObj instanceof Number
+ || targetObj instanceof Boolean;
+ }
+
+ @Override
+ public AnyData transform(Object targetObj) throws ConvertException {
+ SimpleData sdata = null;
+ if(targetObj instanceof CharSequence) {
+ sdata = new SimpleData(targetObj.toString());
+ }
+ else if(targetObj instanceof Number) {
+ sdata = new SimpleData((Number) targetObj);
+ }
+ else if(targetObj instanceof Boolean) {
+ sdata = new SimpleData((Boolean) targetObj);
+ }
+ return new AnyData(sdata);
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/SourceEntity.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/SourceEntity.java
new file mode 100644
index 0000000..78d5338
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/SourceEntity.java
@@ -0,0 +1,84 @@
+/*
+ * 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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.ConvertException;
+
+import java.lang.reflect.Method;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+import java.util.logging.Logger;
+
+/**
+ * @author indroneel
+ */
+
+public class SourceEntity {
+
+ private static final Logger L = Logger.getLogger(SourceEntity.class.getName());
+
+ private final Class> sourceType;
+ private final Map toMethods;
+
+ public SourceEntity(Class> sourceType) throws ConvertException {
+ this.sourceType = sourceType;
+ toMethods = new HashMap<>();
+ collateAllMethods(sourceType);
+ }
+
+ public SourceEntity(Object srcObj) throws ConvertException {
+ this(srcObj.getClass());
+ }
+
+ public Class> getSourceType() {
+ return sourceType;
+ }
+
+ public Set getDataKeys() {
+ return toMethods.keySet();
+ }
+
+ public ToMethod getToMethod(String dataKey) {
+ return toMethods.get(dataKey);
+ }
+
+ ////////////////////////////////////////////////////////////////////////////////////////////////
+ // Helper methods
+
+ private void collateAllMethods(Class> type) throws ConvertException {
+
+ if(type.getClassLoader() == null) {
+ // Skip system classes
+ return;
+ }
+
+ for (Method method : type.getDeclaredMethods()) {
+ ToMethod tm = ToMethod.of(method);
+ if(tm != null) {
+ if(toMethods.containsKey(tm.getDataKey())) {
+ throw new ConvertException(type.getName(), tm.getMethod().getName(),
+ "Duplicate getters for data key: " + tm.getDataKey(), null);
+ }
+ toMethods.put(tm.getDataKey(), tm);
+ continue;
+ }
+ }
+
+ if (type.getSuperclass() != null) {
+ collateAllMethods(type.getSuperclass());
+ }
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/obj2mod/ToMethod.java b/moe-main/src/main/java/daxi/moe/lib/obj2mod/ToMethod.java
new file mode 100644
index 0000000..00d0e4a
--- /dev/null
+++ b/moe-main/src/main/java/daxi/moe/lib/obj2mod/ToMethod.java
@@ -0,0 +1,86 @@
+/*
+ * 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 daxi.moe.lib.obj2mod;
+
+import daxi.moe.app.MapTo;
+
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.lang.reflect.Parameter;
+
+/**
+ * @author indroneel
+ */
+
+public class ToMethod {
+
+ private final Method method;
+ private final String dataKey;
+ private final Class> returnType;
+
+ public ToMethod(Method method) {
+ this.method = method;
+ MapTo mapping = method.getAnnotation(MapTo.class);
+ if(mapping == null) {
+ // If the method does not have the @MapTo annotation, it is not valid for retrieval
+ throw new IllegalArgumentException();
+ }
+ // populate the dataKey field with the value of the @MapTo annotation
+ dataKey = mapping.value().trim();
+ if(dataKey.isBlank()) {
+ // If the data key is blank, it is not a getter method
+ throw new IllegalArgumentException();
+ }
+
+ int mod = method.getModifiers();
+ // If the method is abstract, static, or not private, it is not valid for retrieval
+ if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
+ throw new IllegalArgumentException();
+ }
+
+ Parameter[] params = method.getParameters();
+ if(params.length > 0) {
+ // If the method takes one or more parameters, it is not valid for retrieval
+ throw new IllegalArgumentException();
+ }
+
+ returnType = method.getReturnType();
+ if(returnType == Void.TYPE) {
+ // If the method returns void, it is not valid for retrieval
+ throw new IllegalArgumentException();
+ }
+ }
+
+ public final String getDataKey() {
+ return dataKey;
+ }
+
+ public final Method getMethod() {
+ return method;
+ }
+
+ public final Class> getReturnType() {
+ return returnType;
+ }
+
+ public static ToMethod of(Method method) {
+ try {
+ return new ToMethod(method);
+ }
+ catch (IllegalArgumentException exep) {
+ return null;
+ }
+ }
+}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JGlobals.java b/moe-main/src/main/java/daxi/moe/lib/transform/M2JGlobals.java
deleted file mode 100644
index ac9417d..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JGlobals.java
+++ /dev/null
@@ -1,76 +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 daxi.moe.lib.transform;
-
-import daxi.moe.app.Moe;
-
-import java.util.List;
-
-/**
- * A registry for model-to-Java transformers as singletons. It also stores options that were set
- * during instatiation of MOE.
- *
- * @author indroneel
- */
-
-public class M2JGlobals {
-
- private final List options;
-
- private M2JSimple simM2j;
- private M2JLinear linM2j;
- private M2JMapped mapM2j;
- private M2JObject objM2j;
-
- public M2JGlobals(List options) {
- this.options = options;
- }
-
- public void setM2J(M2JSimple m2j) {
- simM2j = m2j;
- }
-
- public void setM2J(M2JLinear m2j) {
- linM2j = m2j;
- }
-
- public void setM2J(M2JMapped m2j) {
- mapM2j = m2j;
- }
-
- public void setM2J(M2JObject m2j) {
- objM2j = m2j;
- }
-
- public boolean hasOption(Moe.Options opt) {
- return options.contains(opt);
- }
-
- public M2JSimple getM2JSimple() {
- return simM2j;
- }
-
- public M2JLinear getM2JLinear() {
- return linM2j;
- }
-
- public M2JMapped getM2JMapped() {
- return mapM2j;
- }
-
- public M2JObject getM2JObject() {
- return objM2j;
- }
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JLinear.java b/moe-main/src/main/java/daxi/moe/lib/transform/M2JLinear.java
deleted file mode 100644
index 79b9437..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JLinear.java
+++ /dev/null
@@ -1,41 +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 daxi.moe.lib.transform;
-
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * Defines a marker interface for classes that can be used to populate portions of a Java object
- * with {@link daxi.moe.model.LinearData}.
- *
- * @author indroneel
- */
-
-public interface M2JLinear {
-
-/**
- * Converts a linear data from the given mapped data into the target object using the specified
- * method.
- *
- * @param data The mapped data that contains the linear data to convert.
- * @param targetObj The target object to populate with the converted data.
- * @param targetMthd The method to use for populating the target object.
- * @return The status of the conversion.
- */
-
- M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JMapped.java b/moe-main/src/main/java/daxi/moe/lib/transform/M2JMapped.java
deleted file mode 100644
index 8513a70..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JMapped.java
+++ /dev/null
@@ -1,41 +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 daxi.moe.lib.transform;
-
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * Defines a marker interface for classes that can be used to populate portions of a Java object
- * with {@link daxi.moe.model.MappedData}.
- *
- * @author indroneel
- */
-
-public interface M2JMapped {
-
-/**
- * Converts a nested mapped data contained within a given mapped data into the target object using
- * the specified method.
- *
- * @param data The mapped data that contains the nested mapped data to convert.
- * @param targetObj The target object to populate with the converted data.
- * @param targetMthd The method to use for populating the target object.
- * @return The status of the conversion.
- */
-
- M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JObject.java b/moe-main/src/main/java/daxi/moe/lib/transform/M2JObject.java
deleted file mode 100644
index 88389fc..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JObject.java
+++ /dev/null
@@ -1,49 +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 daxi.moe.lib.transform;
-
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * Defines a marker interface for classes that can be used to convert from
- * {@link daxi.moe.model.MappedData} to a Java object.
- *
- * @author indroneel
- */
-
-public interface M2JObject {
-
-/**
- * Populates a Java object with data from a {@link MappedData} instance using the specified method.
- * @param data the {@link MappedData} instance containing the data to populate the Java object
- * @param targetObj the Java object to populate
- * @param targetMthd the method to use for populating the Java object
- * @return the status of the operation
- */
-
- M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
-
-/**
- * Constructs a Java object of the specified type from the given {@link MappedData} instance.
- * @param data the {@link MappedData} instance containing the data to populate the Java object
- * @param targetType the class of the Java object to construct
- * @param the type of the Java object to construct
- * @return the constructed Java object of the specified type
- */
-
- T convert(MappedData data, Class targetType);
-}
diff --git a/moe-main/src/main/java/daxi/moe/lib/transform/M2JSimple.java b/moe-main/src/main/java/daxi/moe/lib/transform/M2JSimple.java
deleted file mode 100644
index 737e485..0000000
--- a/moe-main/src/main/java/daxi/moe/lib/transform/M2JSimple.java
+++ /dev/null
@@ -1,41 +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 daxi.moe.lib.transform;
-
-import daxi.moe.model.MappedData;
-
-import java.lang.reflect.Method;
-
-/**
- * Defines a marker interface for classes that can be used to populate portions of a Java object
- * with {@link daxi.moe.model.SimpleData}.
- *
- * @author indroneel
- */
-
-public interface M2JSimple {
-
-/**
- * Converts a linear data from the given mapped data into the target object using the specified
- * method.
- *
- * @param data the mapped data that contains the simple data to convert
- * @param targetObj the object to populate
- * @param targetMthd the method to invoke on the target object to set the value
- * @return The status of the conversion.
- */
-
- M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
-}
diff --git a/pom.xml b/pom.xml
index fe33a1b..3034666 100644
--- a/pom.xml
+++ b/pom.xml
@@ -21,6 +21,7 @@
+ moe-api
moe-main
moe-json
moe-yaml