code complete for yaml transformation

This commit is contained in:
2026-11-13 23:07:29 +05:30
parent c59ee0067a
commit a91f72ffd2
28 changed files with 687 additions and 7155 deletions
+13 -1
View File
@@ -12,11 +12,23 @@
<artifactId>dxt.moe.json</artifactId>
<packaging>jar</packaging>
<repositories>
<repository>
<id>gitea</id>
<url>https://git.daxii.org/api/packages/libzero/maven</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>dxt.moe</groupId>
<artifactId>dxt.moe.main</artifactId>
<version>${project.parent.version}</version>
<version>v1-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20260814</version>
</dependency>
</dependencies>
</project>
@@ -22,7 +22,7 @@ import dxt.moe.codec.MoeEncoder;
* @author indroneel
*/
public class JSONCodec implements MoeCodec {
public class JsonCodec implements MoeCodec {
@Override
public String getFormat() {
@@ -31,11 +31,11 @@ public class JSONCodec implements MoeCodec {
@Override
public MoeDecoder decoder() {
return new JSONDecoder();
return new JsonDecoder();
}
@Override
public MoeEncoder encoder() {
return new JSONEncoder();
return new JsonEncoder();
}
}
@@ -24,6 +24,7 @@ import dxt.moe.model.SimpleData;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
@@ -35,12 +36,15 @@ import java.util.logging.Logger;
* @author indroneel
*/
public class JSONDecoder implements MoeDecoder {
public class JsonDecoder implements MoeDecoder {
private static final Logger L = Logger.getLogger(JSONDecoder.class.getName());
private static final Logger L = Logger.getLogger(JsonDecoder.class.getName());
private byte[] jsonData;
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeDecoder
@Override
public void setSource(byte[] data) throws CodecException {
jsonData = data;
@@ -48,7 +52,16 @@ public class JSONDecoder implements MoeDecoder {
@Override
public void setSource(InputStream input) throws CodecException {
if (input == null) {
throw new CodecException("json", "Input stream is null.");
}
try {
setSource(input.readAllBytes());
}
catch (IOException exep) {
throw new CodecException("json",
"Error reading input stream: " + exep.getMessage(), exep);
}
}
@Override
@@ -0,0 +1,136 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package dxt.moe.codec.json;
import dxt.moe.codec.MoeEncoder;
import dxt.moe.model.AnyData;
import dxt.moe.model.LinearData;
import dxt.moe.model.MappedData;
import dxt.moe.model.SimpleData;
import org.json.JSONObject;
import java.util.LinkedList;
import java.util.List;
/**
* @author indroneel
*/
public class JsonEncoder implements MoeEncoder {
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeEncoder
@Override
public byte[] convert(AnyData data) {
return convert(data, false);
}
@Override
public byte[] convert(AnyData data, boolean pretty) {
JSONObject jobj = null;
if(data.asMapped() != null) {
MappedData mdata = data.asMapped();
jobj = convertMappedData(mdata);
}
if(jobj != null) {
if(pretty) {
return jobj.toString(4).getBytes();
}
else {
return jobj.toString().getBytes();
}
}
return new byte[0];
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private JSONObject convertMappedData(MappedData mdata) {
if(mdata == null) {
return null;
}
JSONObject jobj = new JSONObject();
for (String key : mdata.getKeys()) {
AnyData ndata = mdata.get(key);
if (ndata == null) {
continue;
}
Object item = convertNested(ndata);
if (item != null) {
jobj.put(key, item);
}
}
return jobj;
}
private List<Object> convertCollectionData(LinearData ldata) {
if(ldata == null) {
return null;
}
LinkedList<Object> list = new LinkedList<>();
for(int i=0; i < ldata.size(); i++) {
AnyData ndata = ldata.get(i);
if (ndata == null) {
continue;
}
Object item = convertNested(ndata);
if (item != null) {
list.add(item);
}
}
return list;
}
private Object convertNested(AnyData ndata) {
if(ndata.asSimple() != null) {
SimpleData nsdata = ndata.asSimple();
if(nsdata.getBoolean() != null) {
return nsdata.getBoolean();
}
else if(nsdata.getString() != null) {
return nsdata.getString();
}
else if(nsdata.getNumber() != null) {
Number nval = nsdata.getNumber();
if(nval instanceof Byte || nval instanceof Short
|| nval instanceof Integer || nval instanceof Long) {
return nval.longValue();
}
else if(nval instanceof Float || nval instanceof Double) {
return nval.doubleValue();
}
else {
return nval.toString();
}
}
}
if(ndata.asLinear() != null) {
LinearData nldata = ndata.asLinear();
return convertCollectionData(nldata);
}
if(ndata.asMapped() != null) {
MappedData nmdata = ndata.asMapped();
return convertMappedData(nmdata);
}
return null;
}
}
File diff suppressed because it is too large Load Diff
@@ -1,52 +0,0 @@
package org.json;
/*
Public Domain.
*/
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
* @author JSON.org
* @version 2015-12-09
*/
public class JSONException extends RuntimeException {
/**
* Serialization ID
*/
private static final long serialVersionUID = 0;
/**
* Constructs a JSONException with an explanatory message.
*
* @param message Detail about the reason for the exception.
*/
public JSONException(final String message) {
super(message);
}
/**
* Constructs a JSONException with an explanatory message and cause.
*
* @param message Detail about the reason for the exception.
* @param cause The cause.
*/
public JSONException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructs a new JSONException with the specified cause.
*
* @param cause The cause.
*/
public JSONException(final Throwable cause) {
super(cause.getMessage(), cause);
}
}
File diff suppressed because it is too large Load Diff
@@ -1,164 +0,0 @@
package org.json;
/**
* Configuration object for the JSON parser. The configuration is immutable.
*/
public class JSONParserConfiguration extends ParserConfiguration {
/**
* Used to indicate whether to overwrite duplicate key or not.
*/
private boolean overwriteDuplicateKey;
/**
* Used to indicate whether to convert java null values to JSONObject.NULL or ignoring the entry
* when converting java maps.
*/
private boolean useNativeNulls;
/**
* This flag, when set to true, instructs the parser to enforce strict mode when parsing JSON text.
* Garbage chars at the end of the doc, unquoted string, and single-quoted strings are all disallowed.
*/
private boolean strictMode;
/**
* Configuration with the default values.
*/
public JSONParserConfiguration() {
super();
this.overwriteDuplicateKey = false;
// DO NOT DELETE THE FOLLOWING LINE -- it is used for strictMode testing
// this.strictMode = true;
}
@Override
protected JSONParserConfiguration clone() {
JSONParserConfiguration clone = new JSONParserConfiguration();
clone.overwriteDuplicateKey = overwriteDuplicateKey;
clone.strictMode = strictMode;
clone.maxNestingDepth = maxNestingDepth;
clone.keepStrings = keepStrings;
clone.useNativeNulls = useNativeNulls;
return clone;
}
/**
* Defines the maximum nesting depth that the parser will descend before throwing an exception
* when parsing a map into JSONObject or parsing a {@link java.util.Collection} instance into
* JSONArray. The default max nesting depth is 512, which means the parser will throw a JsonException
* if the maximum depth is reached.
*
* @param maxNestingDepth the maximum nesting depth allowed to the JSON parser
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
@Override
public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) {
JSONParserConfiguration clone = this.clone();
clone.maxNestingDepth = maxNestingDepth;
return clone;
}
/**
* Controls the parser's behavior when meeting duplicate keys.
* If set to false, the parser will throw a JSONException when meeting a duplicate key.
* Or the duplicate key's value will be overwritten.
*
* @param overwriteDuplicateKey defines should the parser overwrite duplicate keys.
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withOverwriteDuplicateKey(final boolean overwriteDuplicateKey) {
JSONParserConfiguration clone = this.clone();
clone.overwriteDuplicateKey = overwriteDuplicateKey;
return clone;
}
/**
* Controls the parser's behavior when meeting Java null values while converting maps.
* If set to true, the parser will put a JSONObject.NULL into the resulting JSONObject.
* Or the map entry will be ignored.
*
* @param useNativeNulls defines if the parser should convert null values in Java maps
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withUseNativeNulls(final boolean useNativeNulls) {
JSONParserConfiguration clone = this.clone();
clone.useNativeNulls = useNativeNulls;
return clone;
}
/**
* Sets the strict mode configuration for the JSON parser with default true value
* <p>
* 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.
* <p>
* 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 <code>overwriteDuplicateKey</code> 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 (<code>isUseNativeNulls() == true</code>)
* or ignore that map entry (<code>isUseNativeNulls() == false</code>).
*
* @return The <code>useNativeNulls</code> 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;
}
}
@@ -1,315 +0,0 @@
package org.json;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
Public Domain.
*/
/**
* A JSON Pointer is a simple query language defined for JSON documents by
* <a href="https://tools.ietf.org/html/rfc6901">RFC 6901</a>.
* <p>
* 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<String> 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<String>();
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<String> refTokens) {
this.refTokens = new ArrayList<String>(refTokens);
}
/**
* Static factory method for {@link Builder}. Example usage:
*
* <pre><code>
* JSONPointer pointer = JSONPointer.builder()
* .append("obj")
* .append("other~key").append("another/key")
* .append("\"")
* .append(0)
* .build();
* </code></pre>
*
* @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 <a href="https://tools.ietf.org/html/rfc6901#section-3">rfc6901 section 3</a>
*/
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 <a href="https://tools.ietf.org/html/rfc6901#section-3">rfc6901 section 3</a>
*/
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<String> refTokens = new ArrayList<String>();
/**
* 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.
* <p>
* 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;
}
}
}
@@ -1,42 +0,0 @@
package org.json;
/*
Public Domain.
*/
import java.io.Serial;
/**
* The JSONPointerException is thrown by {@link JSONPointer} if an error occurs during evaluating a
* pointer.
*
* @author JSON.org
* @version 2016-05-13
*/
public class JSONPointerException extends JSONException {
@Serial
private static final long serialVersionUID = 8872944667561856751L;
/**
* Constructs a new JSONPointerException with the specified error message.
*
* @param message The detail message describing the reason for the exception.
*/
public JSONPointerException(String message) {
super(message);
}
/**
* Constructs a new JSONPointerException with the specified error message and cause.
*
* @param message The detail message describing the reason for the exception.
* @param cause The cause of the exception.
*/
public JSONPointerException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,24 +0,0 @@
package org.json;
/*
Public Domain.
*/
/**
* The <code>JSONString</code> interface allows a <code>toJSONString()</code> method so that a class
* can change the behavior of <code>JSONObject.toString()</code>, <code>JSONArray.toString()</code>,
* and <code>JSONWriter.value(</code>Object<code>)</code>. The <code>toJSONString</code> method will
* be used instead of the default behavior of using the Object's <code>toString()</code> method and
* quoting the result.
*/
public interface JSONString {
/**
* The <code>toJSONString</code> method allows a class to produce its own JSON serialization.
*
* @return A strictly syntactically correct JSON text.
*/
public String toJSONString();
}
@@ -1,682 +0,0 @@
package org.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
/*
Public Domain.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from
* it. It is used by the JSONObject and JSONArray constructors to parse
* JSON source strings.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONTokener {
/**
* Reader for the input.
*/
private final Reader reader;
/**
* current read character position on the current line.
*/
private long character;
/**
* flag to indicate if the end of the input has been found.
*/
private boolean eof;
/**
* current read index of the input.
*/
private long index;
/**
* current line of the input.
*/
private long line;
/**
* previous character read from the input.
*/
private char previous;
/**
* flag to indicate that a previous character was requested.
*/
private boolean usePrevious;
/**
* the number of characters read in the previous line.
*/
private long characterPreviousLine;
// access to this object is required for strict mode checking
private JSONParserConfiguration jsonParserConfiguration;
/**
* Construct a JSONTokener from a Reader. The caller must close the Reader.
*
* @param reader the source.
*/
public JSONTokener(Reader reader) {
this(reader, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from a Reader with a given JSONParserConfiguration. The caller must close the Reader.
*
* @param reader the source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*
*/
public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration;
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.characterPreviousLine = 0;
this.line = 1;
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param inputStream The source.
*/
public JSONTokener(InputStream inputStream) {
this(inputStream, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param inputStream The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(InputStream inputStream, JSONParserConfiguration jsonParserConfiguration) {
this(new InputStreamReader(inputStream, Charset.forName("UTF-8")), jsonParserConfiguration);
}
/**
* Construct a JSONTokener from a string.
*
* @param source A source string.
*/
public JSONTokener(String source) {
this(new StringReader(source));
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param source The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(String source, JSONParserConfiguration jsonParserConfiguration) {
this(new StringReader(source), jsonParserConfiguration);
}
/**
* Get the hex value of a character (base16).
*
* @param c A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
/**
* Getter
*
* @return jsonParserConfiguration
*/
public JSONParserConfiguration getJsonParserConfiguration() {
return jsonParserConfiguration;
}
/**
* Setter
*
* @param jsonParserConfiguration new value for jsonParserConfiguration
* @deprecated method should not be used
*/
@Deprecated
public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) {
setJsonParserConfigurationInternal(jsonParserConfiguration);
}
void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration;
}
/**
* Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse
* the next number or identifier.
*
* @throws JSONException Thrown if trying to step back more than 1 step
* or if already at the start of the string
*/
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.decrementIndexes();
this.usePrevious = true;
this.eof = false;
}
/**
* Decrements the indexes for the {@link #back()} method based on the previous character read.
*/
private void decrementIndexes() {
this.index--;
if (this.previous == '\r' || this.previous == '\n') {
this.line--;
this.character = this.characterPreviousLine;
} else if (this.character > 0) {
this.character--;
}
}
/**
* Checks if the end of the input has been reached.
*
* @return true if at the end of the file and we didn't step back
*/
public boolean end() {
return this.eof && !this.usePrevious;
}
/**
* Determine if the source string still contains characters that next()
* can consume.
*
* @return true if not yet at the end of the source.
* @throws JSONException thrown if there is an error stepping forward
* or backward while checking for more data.
*/
public boolean more() throws JSONException {
if (this.usePrevious) {
return true;
}
try {
this.reader.mark(1);
} catch (
IOException e) {
throw new JSONException("Unable to preserve stream position", e);
}
try {
// -1 is EOF, but next() can not consume the null character '\0'
if (this.reader.read() <= 0) {
this.eof = true;
return false;
}
this.reader.reset();
} catch (
IOException e) {
throw new JSONException("Unable to read the next character from the stream", e);
}
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
* @throws JSONException Thrown if there is an error reading the source string.
*/
public char next() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (
IOException exception) {
throw new JSONException(exception);
}
}
if (c <= 0) { // End of stream
this.eof = true;
return 0;
}
this.incrementIndexes(c);
this.previous = (char) c;
return this.previous;
}
/**
* Get the last character read from the input or '\0' if nothing has been read yet.
*
* @return the last character read from the input.
*/
protected char getPrevious() {
return this.previous;
}
/**
* Increments the internal indexes according to the previous character
* read and the character passed as the current character.
*
* @param c the current character read.
*/
private void incrementIndexes(int c) {
if (c > 0) {
this.index++;
if (c == '\r') {
this.line++;
this.characterPreviousLine = this.character;
this.character = 0;
} else if (c == '\n') {
if (this.previous != '\r') {
this.line++;
this.characterPreviousLine = this.character;
}
this.character = 0;
} else {
this.character++;
}
}
}
/**
* Consume the next character, and check that it matches a specified
* character.
*
* @param c The character to match.
* @return The character.
* @throws JSONException if the character does not match.
*/
public char next(char c) throws JSONException {
char n = this.next();
if (n != c) {
if (n > 0) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" +
n + "'");
}
throw this.syntaxError("Expected '" + c + "' and instead saw ''");
}
return n;
}
/**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @throws JSONException Substring bounds error if there are not
* n characters remaining in the source string.
*/
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
*
* @return A character, or 0 if there are no more characters.
* @throws JSONException Thrown if there is an error reading the source string.
*/
public char nextClean() throws JSONException {
for (; ; ) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
}
/**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
* allow strings in single quotes, but an implementation is allowed to
* accept them.
*
* @param quote The quoting character, either
* <code>"</code>&nbsp;<small>(double quote)</small> or
* <code>'</code>&nbsp;<small>(single quote)</small>.
* @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();
}
}
}
@@ -1,552 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* 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 &lt;/, producing &lt;\/, 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 &#177;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 <code>null</code>.
* @param r the right value to compare. Can not be <code>null</code>.
* @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 <code>true</code>, then {@link Double} and {@link Float} values will be
* converted exactly. When <code>false</code>, 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.");
}
}
}
}
@@ -1,62 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* 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;
}
}
}
@@ -1,409 +0,0 @@
package org.json;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/*
Public Domain.
*/
/**
* JSONWriter provides a quick and convenient way of producing JSON text. The texts produced
* strictly conform to JSON syntax rules. No whitespace is added, so the results are ready for
* transmission or storage. Each instance of JSONWriter can produce one JSON text.
* <p>
* A JSONWriter instance provides a <code>value</code> method for appending values to the text, and
* a <code>key</code> method for adding keys before values in objects. There are <code>array</code>
* and <code>endArray</code> methods that make and bound array values, and <code>object</code> and
* <code>endObject</code> methods which make and bound object values. All of these methods return
* the JSONWriter instance, permitting a cascade style. For example, <pre>
* new JSONWriter(myWriter)
* .object()
* .key("JSON")
* .value("Hello, World!")
* .endObject();</pre> which writes <pre>
* {"JSON":"Hello, World!"}</pre>
* <p>
* The first method called must be <code>array</code> or <code>object</code>. There are no methods
* for adding commas or colons. JSONWriter adds them for you. Objects and arrays can be nested up to
* 200 levels deep.
* <p>
* 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.
* <p>
* 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
* <code>{</code>&nbsp;<small>(left brace)</small> and ending with <code>}</code>&nbsp;<small>(right
* brace)</small>.
* @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
* <code>endArray</code> will be appended to this array. The
* <code>endArray</code> method must be called to mark the array's end.
*
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* 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
* <code>array</code>.
*
* @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
* <code>object</code>.
*
* @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
* <code>endObject</code> will be appended to this object. The
* <code>endObject</code> method must be called to mark the object's end.
*
* @return this
* @throws JSONException If the nesting is too deep, or if the object is
* started in the wrong place (for example as a key or after the end of the
* 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 <code>true</code> or the value
* <code>false</code>.
*
* @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));
}
}
-66
View File
@@ -1,66 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* 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 <code>NULL</code> object than to use
* Java's <code>null</code> value. <code>JSONObject.NULL.equals(null)</code> returns
* <code>true</code>. <code>JSONObject.NULL.toString()</code> returns <code>"null"</code>.
*/
public static final Object TYPE = new Null();
}
@@ -1,179 +0,0 @@
package org.json;
/*
Public Domain.
*/
/**
* Configuration base object for parsers. The configuration is immutable.
*/
@SuppressWarnings({""})
public class ParserConfiguration {
/**
* Used to indicate there's no defined limit to the maximum nesting depth when parsing a document.
*/
public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1;
/**
* Used to indicate there's no defined limit to the maximum number length
*/
public static final int UNDEFINED_MAXIMUM_NUMBER_LENGTH = -1;
/**
* The default maximum nesting depth when parsing a document.
*/
public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512;
/**
* The default max number length
*/
public static final int DEFAULT_MAX_NUMBER_LENGTH = 1000;
/**
* Specifies if values should be kept as strings (<code>true</code>), 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 (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string).
*
* @return The <code>keepStrings</code> configuration value.
*/
public boolean isKeepStrings() {
return this.keepStrings;
}
/**
* When parsing the XML into JSONML, specifies if values should be kept as strings (<code>true</code>), or if
* they should try to be guessed into JSON values (numeric, boolean, string)
*
* @param newVal new value to use for the <code>keepStrings</code> configuration option.
* @param <T> the type of the configuration object
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
public <T extends ParserConfiguration> 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 <T> the type of the configuration object
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
public <T extends ParserConfiguration> 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 <T> the type of the configuration object
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
public <T extends ParserConfiguration> 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;
}
}
@@ -1,96 +0,0 @@
package org.json;
import java.io.IOException;
import java.io.Writer;
/**
* Performance optimised alternative for {@link java.io.StringWriter} using internally a
* {@link StringBuilder} instead of a {@link StringBuffer}.
*/
public class StringBuilderWriter extends Writer {
private final StringBuilder builder;
/**
* Create a new string builder writer using the default initial string-builder buffer size.
*/
public StringBuilderWriter() {
builder = new StringBuilder();
lock = builder;
}
/**
* Create a new string builder writer using the specified initial string-builder buffer size.
*
* @param initialSize The number of {@code char} values that will fit into this buffer before it is
* automatically expanded
* @throws IllegalArgumentException If {@code initialSize} is negative
*/
public StringBuilderWriter(int initialSize) {
builder = new StringBuilder(initialSize);
lock = builder;
}
@Override
public void write(int c) {
builder.append((char) c);
}
@Override
public void write(char[] cbuf, int offset, int length) {
if ((offset < 0) || (offset > cbuf.length) || (length < 0) ||
((offset + length) > cbuf.length) || ((offset + length) < 0)) {
throw new IndexOutOfBoundsException();
}
else if (length == 0) {
return;
}
builder.append(cbuf, offset, length);
}
@Override
public void write(String str) {
builder.append(str);
}
@Override
public void write(String str, int offset, int length) {
builder.append(str, offset, offset + length);
}
@Override
public StringBuilderWriter append(CharSequence csq) {
write(String.valueOf(csq));
return this;
}
@Override
public StringBuilderWriter append(CharSequence csq, int start, int end) {
if (csq == null) {
csq = "null";
}
return append(csq.subSequence(start, end));
}
@Override
public StringBuilderWriter append(char c) {
write(c);
return this;
}
@Override
public String toString() {
return builder.toString();
}
@Override
public void flush() {
}
@Override
public void close() throws IOException {
}
}
@@ -12,4 +12,4 @@
# limitations under the License.
#
dxt.moe.codec.json.JSONCodec
dxt.moe.codec.json.JsonCodec
@@ -43,17 +43,13 @@ public class MoeImpl extends Moe {
private final static Map<String, MoeCodec> codecs;
static {
if (L.isLoggable(Level.FINE)) {
L.fine("loading MOE codecs");
}
L.fine(() -> "loading MOE codecs");
codecs = new HashMap<>();
ServiceLoader<MoeCodec> codecs = ServiceLoader.load(MoeCodec.class);
for (MoeCodec codec : codecs) {
String format = codec.getFormat();
MoeImpl.codecs.put(format.toLowerCase(), codec);
if (L.isLoggable(Level.FINE)) {
L.fine(String.format("%s -> %s", format, codec.getClass().getName()));
}
L.fine(() -> String.format("%s -> %s", format, codec.getClass().getName()));
}
}
@@ -12,13 +12,30 @@
* limitations under the License.
*/
package org.json;
package dxt.moe.codec.toml;
public class JSONBase {
import dxt.moe.codec.MoeCodec;
import dxt.moe.codec.MoeDecoder;
import dxt.moe.codec.MoeEncoder;
protected JSONWrapper wrapper;
/**
* @author indroneel
*/
protected JSONBase() {
wrapper = new JSONWrapper();
public class TomlCodec implements MoeCodec {
@Override
public String getFormat() {
return "toml";
}
@Override
public MoeDecoder decoder() {
return new TomlDecoder();
}
@Override
public MoeEncoder encoder() {
return new TomlEncoder();
}
}
@@ -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, [email protected]
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package dxt.moe.codec.toml;
import dxt.moe.app.CodecException;
import dxt.moe.app.Moe;
import dxt.moe.codec.MoeDecoder;
import dxt.moe.model.AnyData;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class TomlDecoder implements MoeDecoder {
private static final Logger L = Logger.getLogger(TomlDecoder.class.getName());
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeDecoder
@Override
public void setSource(byte[] data) throws CodecException {
}
@Override
public void setSource(InputStream input) throws CodecException {
}
@Override
public AnyData decode(List<Moe.Options> options) throws CodecException {
return null;
}
}
@@ -12,7 +12,7 @@
* limitations under the License.
*/
package dxt.moe.codec.json;
package dxt.moe.codec.toml;
import dxt.moe.codec.MoeEncoder;
import dxt.moe.model.AnyData;
@@ -21,7 +21,10 @@ import dxt.moe.model.AnyData;
* @author indroneel
*/
public class JSONEncoder implements MoeEncoder {
public class TomlEncoder implements MoeEncoder {
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeEncoder
@Override
public byte[] convert(AnyData data) {
@@ -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, [email protected]
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions and
# limitations under the License.
#
dxt.moe.codec.toml.TomlCodec
@@ -0,0 +1,43 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package dxt.moe.codec.yaml;
import dxt.moe.codec.MoeCodec;
import dxt.moe.codec.MoeDecoder;
import dxt.moe.codec.MoeEncoder;
/**
* YamlCodec is an implementation of the MoeCodec interface for YAML format.
*
* @author indroneel
*/
public class YamlCodec implements MoeCodec {
@Override
public String getFormat() {
return "yaml";
}
@Override
public MoeDecoder decoder() {
return new YamlDecoder();
}
@Override
public MoeEncoder encoder() {
return new YamlEncoder();
}
}
@@ -0,0 +1,196 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package dxt.moe.codec.yaml;
import dxt.moe.app.CodecException;
import dxt.moe.app.Moe;
import dxt.moe.codec.MoeDecoder;
import dxt.moe.model.AnyData;
import dxt.moe.model.LinearData;
import dxt.moe.model.MappedData;
import dxt.moe.model.SimpleData;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.List;
import java.util.Locale;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class YamlDecoder implements MoeDecoder {
private static final Logger L = Logger.getLogger(YamlDecoder.class.getName());
private Reader reader;
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeDecoder
@Override
public void setSource(byte[] data) throws CodecException {
reader = new InputStreamReader(new ByteArrayInputStream(data));
L.fine(() -> "byte array set as source");
}
@Override
public void setSource(InputStream input) throws CodecException {
reader = new InputStreamReader(input);
L.fine(() -> "input stream set as source");
}
@Override
public AnyData decode(List<Moe.Options> options) throws CodecException {
L.fine(() -> "converting from yaml");
Yaml yaml = new Yaml();
Node node = yaml.compose(reader);
if(node == null) {
return null;
}
if(node instanceof MappingNode) {
return new AnyData(convertMappedData((MappingNode) node, options));
}
return null;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private MappedData convertMappedData(MappingNode mapNode,
List<Moe.Options> options) throws CodecException {
MappedData mapData = new MappedData();
for(NodeTuple tuple : mapNode.getValue()) {
ScalarNode snode = (ScalarNode) tuple.getKeyNode();
String keyStr = options.contains(Moe.Options.ANYCASE)
? snode.getValue().toLowerCase(Locale.getDefault())
: snode.getValue();
Node valueNode = tuple.getValueNode();
if(valueNode instanceof ScalarNode svnode) {
String valueStr = svnode.getValue();
if(svnode.getTag().equals(Tag.BOOL)) {
SimpleData itemData = new SimpleData(Boolean.valueOf(valueStr));
mapData.put(keyStr, new AnyData(itemData));
}
else if(svnode.getTag().equals(Tag.FLOAT)) {
try {
SimpleData itemData = new SimpleData(Double.valueOf(valueStr));
mapData.put(keyStr, new AnyData(itemData));
}
catch(Exception exep) {
throw new CodecException("yaml",
"Error converting float value: " + valueStr, exep);
}
}
else if(svnode.getTag().equals(Tag.INT)) {
try {
SimpleData itemData = new SimpleData(Long.valueOf(valueStr));
mapData.put(keyStr, new AnyData(itemData));
}
catch(Exception exep) {
throw new CodecException("yaml",
"Error converting int value: " + valueStr, exep);
}
}
else if(svnode.getTag().equals(Tag.STR)) {
SimpleData itemData = new SimpleData(valueStr);
mapData.put(keyStr, new AnyData(itemData));
}
else {
L.info(() -> "unhandled tag in scalar node: " + svnode.getTag().getValue());
}
}
else if(valueNode instanceof SequenceNode) {
LinearData itemData = convertLinearData((SequenceNode) valueNode, options);
mapData.put(keyStr, new AnyData(itemData));
}
else if(valueNode instanceof MappingNode) {
MappedData itemData = convertMappedData((MappingNode) valueNode, options);
mapData.put(keyStr, new AnyData(itemData));
}
else {
L.warning(() -> String.format("no suitable conversion found for node: %s", keyStr));
}
}
return mapData;
}
private LinearData convertLinearData(SequenceNode seqNode,
List<Moe.Options> options) throws CodecException {
LinearData linData = new LinearData();
for (Node valueNode : seqNode.getValue()) {
if (valueNode instanceof ScalarNode) {
ScalarNode svnode = (ScalarNode) valueNode;
String valueStr = svnode.getValue();
if(svnode.getTag().equals(Tag.BOOL)) {
SimpleData itemData = new SimpleData(Boolean.valueOf(valueStr));
linData.add(new AnyData(itemData));
}
else if(svnode.getTag().equals(Tag.FLOAT)) {
try {
SimpleData itemData = new SimpleData(Double.valueOf(valueStr));
linData.add(new AnyData(itemData));
}
catch(Exception exep) {
throw new CodecException("yaml",
"Error converting float value: " + valueStr, exep);
}
}
else if(svnode.getTag().equals(Tag.INT)) {
try {
SimpleData itemData = new SimpleData(Long.valueOf(valueStr));
linData.add(new AnyData(itemData));
}
catch(Exception exep) {
throw new CodecException("yaml",
"Error converting int value: " + valueStr, exep);
}
}
else if(svnode.getTag().equals(Tag.STR)) {
SimpleData itemData = new SimpleData(valueStr);
linData.add(new AnyData(itemData));
}
else {
L.info(() -> "unhandled tag in scalar node: " + svnode.getTag().getValue());
}
}
else if (valueNode instanceof SequenceNode) {
LinearData itemData = convertLinearData((SequenceNode) valueNode, options);
linData.add(new AnyData(itemData));
}
else if (valueNode instanceof MappingNode) {
MappedData itemData = convertMappedData((MappingNode) valueNode, options);
linData.add(new AnyData(itemData));
}
else {
L.warning(() -> "no suitable conversion found for node: " + valueNode.toString());
}
}
return linData;
}
}
@@ -0,0 +1,169 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [email protected]
*
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*/
package dxt.moe.codec.yaml;
import dxt.moe.app.CodecException;
import dxt.moe.codec.MoeEncoder;
import dxt.moe.model.AnyData;
import dxt.moe.model.LinearData;
import dxt.moe.model.MappedData;
import dxt.moe.model.SimpleData;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.nodes.MappingNode;
import org.yaml.snakeyaml.nodes.Node;
import org.yaml.snakeyaml.nodes.NodeTuple;
import org.yaml.snakeyaml.nodes.ScalarNode;
import org.yaml.snakeyaml.nodes.SequenceNode;
import org.yaml.snakeyaml.nodes.Tag;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.LinkedList;
import java.util.List;
/**
* @author indroneel
*/
public class YamlEncoder implements MoeEncoder {
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface MoeEncoder
@Override
public byte[] convert(AnyData data) throws CodecException {
return convert(data, false);
}
@Override
public byte[] convert(AnyData data, boolean pretty) throws CodecException {
if(data.asMapped() == null) {
return new byte[0];
}
Node node = convertMappedData(data.asMapped());
Yaml yaml = new Yaml();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
yaml.serialize(node, new OutputStreamWriter(buffer));
if(pretty) {
}
else {
}
return buffer.toByteArray();
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private MappingNode convertMappedData(MappedData mapData) {
List<NodeTuple> tuples = new LinkedList<>();
for(String key: mapData.getKeys()) {
//create the key node
ScalarNode knode = new ScalarNode(Tag.STR, key, null, null,
DumperOptions.ScalarStyle.LITERAL);
AnyData itemData = mapData.get(key);
if(itemData.asSimple() != null) {
SimpleData sdata = itemData.asSimple();
if(sdata.getBoolean() != null) {
ScalarNode vnode = new ScalarNode(Tag.BOOL, sdata.getBoolean().toString(),
null, null, DumperOptions.ScalarStyle.PLAIN);
tuples.add(new NodeTuple(knode, vnode));
}
else if(sdata.getNumber() != null) {
Number nval = sdata.getNumber();
if(nval instanceof Byte || nval instanceof Short || nval instanceof Integer
|| nval instanceof Long || nval instanceof BigInteger) {
ScalarNode vnode = new ScalarNode(Tag.INT, nval.toString(), null, null,
DumperOptions.ScalarStyle.PLAIN);
tuples.add(new NodeTuple(knode, vnode));
}
else if(nval instanceof Float || nval instanceof Double
|| nval instanceof BigDecimal) {
ScalarNode vnode = new ScalarNode(Tag.FLOAT, nval.toString(), null, null,
DumperOptions.ScalarStyle.PLAIN);
tuples.add(new NodeTuple(knode, vnode));
}
}
else if(sdata.getString() != null) {
ScalarNode vnode = new ScalarNode(Tag.STR, sdata.getString(),
null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED);
tuples.add(new NodeTuple(knode, vnode));
}
}
else if(itemData.asLinear() != null) {
Node vnode = convertLinearData(itemData.asLinear());
tuples.add(new NodeTuple(knode, vnode));
}
else if(itemData.asMapped() != null) {
Node vnode = convertMappedData(itemData.asMapped());
tuples.add(new NodeTuple(knode, vnode));
}
}
return new MappingNode(Tag.MAP, tuples, DumperOptions.FlowStyle.AUTO);
}
private SequenceNode convertLinearData(LinearData linData) {
List<Node> nodeList = new LinkedList<>();
for(int i=0; i < linData.size(); i++) {
AnyData itemData = linData.get(i);
if(itemData.asSimple() != null) {
SimpleData sdata = itemData.asSimple();
if(sdata.getBoolean() != null) {
ScalarNode vnode = new ScalarNode(Tag.BOOL, sdata.getBoolean().toString(),
null, null, DumperOptions.ScalarStyle.PLAIN);
nodeList.add(vnode);
}
else if(sdata.getNumber() != null) {
Number nval = sdata.getNumber();
if(nval instanceof Byte || nval instanceof Short || nval instanceof Integer
|| nval instanceof Long || nval instanceof BigInteger) {
ScalarNode vnode = new ScalarNode(Tag.INT, nval.toString(), null, null,
DumperOptions.ScalarStyle.PLAIN);
nodeList.add(vnode);
}
else if(nval instanceof Float || nval instanceof Double
|| nval instanceof BigDecimal) {
ScalarNode vnode = new ScalarNode(Tag.FLOAT, nval.toString(), null, null,
DumperOptions.ScalarStyle.PLAIN);
nodeList.add(vnode);
}
}
else if(sdata.getString() != null) {
ScalarNode vnode = new ScalarNode(Tag.STR, sdata.getString(),
null, null, DumperOptions.ScalarStyle.DOUBLE_QUOTED);
nodeList.add(vnode);
}
}
else if(itemData.asLinear() != null) {
Node vnode = convertLinearData(itemData.asLinear());
nodeList.add(vnode);
}
else if(itemData.asMapped() != null) {
Node vnode = convertMappedData(itemData.asMapped());
nodeList.add(vnode);
}
}
return new SequenceNode(Tag.SEQ, nodeList, DumperOptions.FlowStyle.AUTO);
}
}
@@ -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, [email protected]
#
# This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
# either express or implied. See the License for the specific language governing permissions and
# limitations under the License.
#
dxt.moe.codec.yaml.YamlCodec