checkpointing

This commit is contained in:
2026-10-31 18:24:58 +05:30
parent c0aa24bc29
commit 44a605dde2
69 changed files with 9412 additions and 1153 deletions
+15
View File
@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>daxi.moe</groupId>
<artifactId>daxi.moe.parent</artifactId>
<version>v1-SNAPSHOT</version>
</parent>
<artifactId>daxi.moe.api</artifactId>
<packaging>jar</packaging>
</project>
@@ -14,26 +14,30 @@
package daxi.moe.app;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Specifies the {@link Converter} implementation used to convert a field to and from
* {@link daxi.moe.model.AnyData}.
*
* @author indroneel
*/
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ConvertUsing {
public class CodecException extends MoeException {
/**
* Returns the converter implementation to use for the annotated field.
*
* @return the converter class
*/
Class<? extends Converter> value();
private final String codecName;
public CodecException(String codecName, String message) {
super(message);
this.codecName = codecName;
}
public CodecException(String codecName, String message, Throwable cause) {
super(message, cause);
this.codecName = codecName;
}
public CodecException(String codecName, Throwable cause) {
super(cause);
this.codecName = codecName;
}
public String getCodecName() {
return codecName;
}
}
@@ -14,25 +14,23 @@
package daxi.moe.app;
public class DecodeException extends Exception {
/**
* Signals a failure while converting data between model classes and plain Java objects.
*
* @author indroneel
*/
public class ConvertException extends MoeException {
private final String type;
private final String method;
public DecodeException(String typeName, String methodName, String message, Throwable cause) {
public ConvertException(String typeName, String methodName, String message, Throwable cause) {
super(message, cause);
this.type = typeName;
this.method = methodName;
}
public DecodeException(String message, Throwable cause) {
this(null, null, message, cause);
}
public DecodeException(Throwable cause) {
this(null, null, null, cause);
}
public String getType() {
return type;
}
@@ -27,15 +27,15 @@ import java.io.InputStream;
public interface External {
External from(InputStream in);
External from(InputStream in) throws MoeException;
External from(byte[] data);
External from(byte[] data) throws MoeException;
boolean hasPath(String path);
AnyData getModel();
<T> T convert(Class<T> type);
<T> T convert(Class<T> type) throws MoeException;
<T> T convert(String path, Class<T> type);
<T> T convert(String path, Class<T> type) throws MoeException;
}
@@ -16,19 +16,20 @@ package daxi.moe.app;
import daxi.moe.model.AnyData;
import java.io.IOException;
/**
* Context for internal data sources, such as a Java object. The data is loaded from these sources,
* and then converted into a byte array.
*
* @author indroneel
*/
public interface Internal {
Internal from(Object obj);
Internal from(Object obj) throws MoeException;
AnyData getModel();
byte[] convert() throws IOException;
byte[] convert() throws MoeException;
byte[] convert(boolean pretty) throws IOException;
byte[] convert(boolean pretty) throws MoeException;
}
@@ -20,6 +20,8 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to specify the source field name in the data model for a method in a class. This is
* used to map data from a data model to a target object.
*
* @author indroneel
*/
@@ -28,5 +30,5 @@ import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
public @interface MapFrom {
String value();
String value() default "";
}
@@ -20,11 +20,15 @@ import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Annotation to specify the target field name in the data model corresponding to the data from a
* method in a Java class. This is used to map data from a source object to a data model.
*
* @author indroneel
*/
@Target({ElementType.FIELD})
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MapTo {
String value() default "";
}
@@ -14,25 +14,49 @@
package daxi.moe.app;
import java.util.Objects;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public abstract class Moe {
private static final Logger L = Logger.getLogger(Moe.class.getName());
/**
* Populates an instance of {@link Moe} with the given options.
*
* @param opts the options to set
* @return the {@link Moe} instance with the given options set
*/
protected abstract Moe options(Options... opts);
/**
* Returns an instance of {@link External} for the given format.
*
* @param format the format to use
* @return an instance of {@link External} for the given format
*/
public abstract External external(String format);
/**
* Returns an instance of {@link Internal} for the given format.
*
* @param format the format to use
* @return an instance of {@link Internal} for the given format
*/
public abstract Internal internal(String format);
/**
* Creates an instance of {@link Moe} using the ServiceLoader mechanism.
*
* @return an instance of {@link Moe} if found, otherwise null
*/
public static Moe create() {
ServiceLoader<Moe> loader = ServiceLoader.load(Moe.class);
try {
@@ -60,10 +84,22 @@ public abstract class Moe {
}
}
/**
* Creates an instance of {@link Moe} using the ServiceLoader mechanism and populates it with the
* given options.
*
* @param opts the options to set
* @return an instance of {@link Moe} with the given options set
*/
public static Moe create(Options... opts) {
return Moe.create().options(opts);
return Objects.requireNonNull(Moe.create()).options(opts);
}
/**
* Defined options for {@link Moe} instances.
*/
public static enum Options {
ANYCASE,
DECODE_IGNORE_MISSING
@@ -0,0 +1,55 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.app;
/**
* The base exception class for all exceptions thrown by the Moe library.
*
* @author indroneel
*/
public class MoeException extends Exception {
/**
* Constructs a new MoeException with the specified detail message.
*
* @param message the detail message
*/
public MoeException(String message) {
super(message);
}
/**
* Constructs a new MoeException with the specified detail message and cause.
*
* @param message the detail message
* @param cause the cause of the exception
*/
public MoeException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs a new MoeException with the specified cause.
*
* @param cause the cause of the exception
*/
public MoeException(Throwable cause) {
super(cause);
}
}
@@ -14,6 +14,7 @@
package daxi.moe.codec;
import daxi.moe.app.CodecException;
import daxi.moe.app.Moe;
import daxi.moe.model.AnyData;
@@ -26,9 +27,9 @@ import java.util.List;
public interface MoeDecoder {
void setSource(byte[] data);
void setSource(byte[] data) throws CodecException;
void setSource(InputStream input);
void setSource(InputStream input) throws CodecException;
AnyData decode(List<Moe.Options> options);
AnyData decode(List<Moe.Options> options) throws CodecException;
}
@@ -14,6 +14,7 @@
package daxi.moe.codec;
import daxi.moe.app.CodecException;
import daxi.moe.model.AnyData;
/**
@@ -21,22 +22,25 @@ import daxi.moe.model.AnyData;
*
* @author indroneel
*/
public interface MoeEncoder {
/**
* Encodes the supplied data using the default formatting.
*
* @param data the data to encode
* @return the encoded data as a byte array
*/
byte[] convert(AnyData data);
/**
* Encodes the supplied data using the default formatting.
*
* @param data the data to encode
* @return the encoded data as a byte array
*/
/**
* Encodes the supplied data, optionally formatting the output for readability.
*
* @param data the data to encode
* @param pretty whether to format the output for readability
* @return the encoded data as a byte array
*/
byte[] convert(AnyData data, boolean pretty);
byte[] convert(AnyData data) throws CodecException;
/**
* Encodes the supplied data, optionally formatting the output for readability.
*
* @param data the data to encode
* @param pretty whether to format the output for readability
* @return the encoded data as a byte array
*/
byte[] convert(AnyData data, boolean pretty) throws CodecException;
}
@@ -15,6 +15,10 @@
package daxi.moe.model;
/**
* A class that can hold any of the three data types: {@link SimpleData}, {@link LinearData}, or
* {@link MappedData}. This class is used to represent a generic data type that can be one of those
* three types.
*
* @author indroneel
*/
@@ -18,6 +18,8 @@ import java.util.LinkedList;
import java.util.List;
/**
* A simple linear data structure that stores a list of {@link AnyData} objects.
*
* @author indroneel
*/
@@ -19,6 +19,8 @@ import java.util.List;
import java.util.Map;
/**
* A simple data structure that maps string keys to {@link AnyData} values.
*
* @author indroneel
*/
@@ -15,6 +15,8 @@
package daxi.moe.model;
/**
* A simple data type that can hold a string, number, or boolean value.
*
* @author indroneel
*/
@@ -53,4 +55,17 @@ public class SimpleData {
public Number getNumber() {
return numVal;
}
public String toString() {
if(strVal != null) {
return "string: " + strVal;
}
if(numVal != null) {
return "number: " + numVal.toString();
}
if(boolVal != null) {
return "boolean: " + boolVal.toString();
}
return "impossible!";
}
}
@@ -0,0 +1,41 @@
/*
* 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 daxi.moe.codec.json;
import daxi.moe.codec.MoeCodec;
import daxi.moe.codec.MoeDecoder;
import daxi.moe.codec.MoeEncoder;
/**
* @author indroneel
*/
public class JSONCodec implements MoeCodec {
@Override
public String getFormat() {
return "json";
}
@Override
public MoeDecoder decoder() {
return new JSONDecoder();
}
@Override
public MoeEncoder encoder() {
return new JSONEncoder();
}
}
@@ -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 daxi.moe.codec.json;
import daxi.moe.app.CodecException;
import daxi.moe.app.Moe;
import daxi.moe.codec.MoeDecoder;
import daxi.moe.model.AnyData;
import daxi.moe.model.LinearData;
import daxi.moe.model.MappedData;
import daxi.moe.model.SimpleData;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class JSONDecoder implements MoeDecoder {
private static final Logger L = Logger.getLogger(JSONDecoder.class.getName());
private byte[] jsonData;
@Override
public void setSource(byte[] data) throws CodecException {
jsonData = data;
}
@Override
public void setSource(InputStream input) throws CodecException {
}
@Override
public AnyData decode(List<Moe.Options> options) throws CodecException {
if (jsonData == null) {
throw new CodecException("json", "No source data set for decoding.");
}
JSONObject rootObj;
try {
rootObj = new JSONObject(new String(jsonData, StandardCharsets.UTF_8));
}
catch (Exception exep) {
throw new CodecException("json", "Error during decoding: " + exep.getMessage(), exep);
}
MappedData rootData = convertObject(rootObj);
return new AnyData(rootData);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private MappedData convertObject(JSONObject obj) throws CodecException {
MappedData mdata = new MappedData();
for (String key : obj.keySet()) {
Object value = obj.get(key);
if (value instanceof String) {
mdata.put(key, new AnyData(new SimpleData((String) value)));
}
else if (value instanceof Integer || value instanceof Long
|| value instanceof Double || value instanceof Float
|| value instanceof Short || value instanceof Byte
|| value instanceof BigDecimal || value instanceof BigInteger) {
mdata.put(key, new AnyData(new SimpleData((Number) value)));
}
else if(value instanceof Boolean bval) {
mdata.put(key, new AnyData(new SimpleData(bval)));
}
else if (value instanceof JSONObject jobj) {
mdata.put(key, new AnyData(convertObject(jobj)));
}
else if (value instanceof JSONArray jarr) {
mdata.put(key, new AnyData(convertArray(key, jarr)));
}
else {
}
}
return mdata;
}
private LinearData convertArray(String key, JSONArray arr)
throws CodecException {
LinearData ldata = new LinearData();
for (int i = 0; i < arr.length(); i++) {
Object value = arr.get(i);
if (value instanceof String) {
ldata.add(new AnyData(new SimpleData((String) value)));
}
else if (value instanceof Integer || value instanceof Long
|| value instanceof Double || value instanceof Float
|| value instanceof Short || value instanceof Byte
|| value instanceof BigDecimal || value instanceof BigInteger) {
ldata.add(new AnyData(new SimpleData((Number) value)));
}
else if(value instanceof Boolean bval) {
ldata.add(new AnyData(new SimpleData(bval)));
}
else if (value instanceof JSONObject jobj) {
ldata.add(new AnyData(convertObject(jobj)));
}
// TODO: This is potentially a dead code, a json array can only contain json objects,
// not json arrays. So this case will never be hit.
else if (value instanceof JSONArray jarr) {
ldata.add(new AnyData(convertArray(key, jarr)));
}
else {
}
}
return ldata;
}
}
@@ -0,0 +1,35 @@
/*
* 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 daxi.moe.codec.json;
import daxi.moe.codec.MoeEncoder;
import daxi.moe.model.AnyData;
/**
* @author indroneel
*/
public class JSONEncoder implements MoeEncoder {
@Override
public byte[] convert(AnyData data) {
return new byte[0];
}
@Override
public byte[] convert(AnyData data, boolean pretty) {
return new byte[0];
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,24 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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;
public class JSONBase {
protected JSONWrapper wrapper;
protected JSONBase() {
wrapper = new JSONWrapper();
}
}
@@ -0,0 +1,52 @@
package org.json;
/*
Public Domain.
*/
/**
* The JSONException is thrown by the JSON.org classes when things are amiss.
*
* @author JSON.org
* @version 2015-12-09
*/
public class JSONException extends RuntimeException {
/**
* Serialization ID
*/
private static final long serialVersionUID = 0;
/**
* Constructs a JSONException with an explanatory message.
*
* @param message Detail about the reason for the exception.
*/
public JSONException(final String message) {
super(message);
}
/**
* Constructs a JSONException with an explanatory message and cause.
*
* @param message Detail about the reason for the exception.
* @param cause The cause.
*/
public JSONException(final String message, final Throwable cause) {
super(message, cause);
}
/**
* Constructs a new JSONException with the specified cause.
*
* @param cause The cause.
*/
public JSONException(final Throwable cause) {
super(cause.getMessage(), cause);
}
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,164 @@
package org.json;
/**
* Configuration object for the JSON parser. The configuration is immutable.
*/
public class JSONParserConfiguration extends ParserConfiguration {
/**
* Used to indicate whether to overwrite duplicate key or not.
*/
private boolean overwriteDuplicateKey;
/**
* Used to indicate whether to convert java null values to JSONObject.NULL or ignoring the entry
* when converting java maps.
*/
private boolean useNativeNulls;
/**
* This flag, when set to true, instructs the parser to enforce strict mode when parsing JSON text.
* Garbage chars at the end of the doc, unquoted string, and single-quoted strings are all disallowed.
*/
private boolean strictMode;
/**
* Configuration with the default values.
*/
public JSONParserConfiguration() {
super();
this.overwriteDuplicateKey = false;
// DO NOT DELETE THE FOLLOWING LINE -- it is used for strictMode testing
// this.strictMode = true;
}
@Override
protected JSONParserConfiguration clone() {
JSONParserConfiguration clone = new JSONParserConfiguration();
clone.overwriteDuplicateKey = overwriteDuplicateKey;
clone.strictMode = strictMode;
clone.maxNestingDepth = maxNestingDepth;
clone.keepStrings = keepStrings;
clone.useNativeNulls = useNativeNulls;
return clone;
}
/**
* Defines the maximum nesting depth that the parser will descend before throwing an exception
* when parsing a map into JSONObject or parsing a {@link java.util.Collection} instance into
* JSONArray. The default max nesting depth is 512, which means the parser will throw a JsonException
* if the maximum depth is reached.
*
* @param maxNestingDepth the maximum nesting depth allowed to the JSON parser
* @return The existing configuration will not be modified. A new configuration is returned.
*/
@SuppressWarnings("unchecked")
@Override
public JSONParserConfiguration withMaxNestingDepth(final int maxNestingDepth) {
JSONParserConfiguration clone = this.clone();
clone.maxNestingDepth = maxNestingDepth;
return clone;
}
/**
* Controls the parser's behavior when meeting duplicate keys.
* If set to false, the parser will throw a JSONException when meeting a duplicate key.
* Or the duplicate key's value will be overwritten.
*
* @param overwriteDuplicateKey defines should the parser overwrite duplicate keys.
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withOverwriteDuplicateKey(final boolean overwriteDuplicateKey) {
JSONParserConfiguration clone = this.clone();
clone.overwriteDuplicateKey = overwriteDuplicateKey;
return clone;
}
/**
* Controls the parser's behavior when meeting Java null values while converting maps.
* If set to true, the parser will put a JSONObject.NULL into the resulting JSONObject.
* Or the map entry will be ignored.
*
* @param useNativeNulls defines if the parser should convert null values in Java maps
* @return The existing configuration will not be modified. A new configuration is returned.
*/
public JSONParserConfiguration withUseNativeNulls(final boolean useNativeNulls) {
JSONParserConfiguration clone = this.clone();
clone.useNativeNulls = useNativeNulls;
return clone;
}
/**
* Sets the strict mode configuration for the JSON parser with default true value
* <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;
}
}
@@ -0,0 +1,315 @@
package org.json;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/*
Public Domain.
*/
/**
* A JSON Pointer is a simple query language defined for JSON documents by
* <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;
}
}
}
@@ -0,0 +1,42 @@
package org.json;
/*
Public Domain.
*/
import java.io.Serial;
/**
* The JSONPointerException is thrown by {@link JSONPointer} if an error occurs during evaluating a
* pointer.
*
* @author JSON.org
* @version 2016-05-13
*/
public class JSONPointerException extends JSONException {
@Serial
private static final long serialVersionUID = 8872944667561856751L;
/**
* Constructs a new JSONPointerException with the specified error message.
*
* @param message The detail message describing the reason for the exception.
*/
public JSONPointerException(String message) {
super(message);
}
/**
* Constructs a new JSONPointerException with the specified error message and cause.
*
* @param message The detail message describing the reason for the exception.
* @param cause The cause of the exception.
*/
public JSONPointerException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -0,0 +1,24 @@
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();
}
@@ -0,0 +1,682 @@
package org.json;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringReader;
import java.nio.charset.Charset;
/*
Public Domain.
*/
/**
* A JSONTokener takes a source string and extracts characters and tokens from
* it. It is used by the JSONObject and JSONArray constructors to parse
* JSON source strings.
*
* @author JSON.org
* @version 2014-05-03
*/
public class JSONTokener {
/**
* Reader for the input.
*/
private final Reader reader;
/**
* current read character position on the current line.
*/
private long character;
/**
* flag to indicate if the end of the input has been found.
*/
private boolean eof;
/**
* current read index of the input.
*/
private long index;
/**
* current line of the input.
*/
private long line;
/**
* previous character read from the input.
*/
private char previous;
/**
* flag to indicate that a previous character was requested.
*/
private boolean usePrevious;
/**
* the number of characters read in the previous line.
*/
private long characterPreviousLine;
// access to this object is required for strict mode checking
private JSONParserConfiguration jsonParserConfiguration;
/**
* Construct a JSONTokener from a Reader. The caller must close the Reader.
*
* @param reader the source.
*/
public JSONTokener(Reader reader) {
this(reader, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from a Reader with a given JSONParserConfiguration. The caller must close the Reader.
*
* @param reader the source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*
*/
public JSONTokener(Reader reader, JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration;
this.reader = reader.markSupported()
? reader
: new BufferedReader(reader);
this.eof = false;
this.usePrevious = false;
this.previous = 0;
this.index = 0;
this.character = 1;
this.characterPreviousLine = 0;
this.line = 1;
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param inputStream The source.
*/
public JSONTokener(InputStream inputStream) {
this(inputStream, new JSONParserConfiguration());
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param inputStream The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(InputStream inputStream, JSONParserConfiguration jsonParserConfiguration) {
this(new InputStreamReader(inputStream, Charset.forName("UTF-8")), jsonParserConfiguration);
}
/**
* Construct a JSONTokener from a string.
*
* @param source A source string.
*/
public JSONTokener(String source) {
this(new StringReader(source));
}
/**
* Construct a JSONTokener from an InputStream. The caller must close the input stream.
*
* @param source The source.
* @param jsonParserConfiguration A JSONParserConfiguration instance that controls the behavior of the parser.
*/
public JSONTokener(String source, JSONParserConfiguration jsonParserConfiguration) {
this(new StringReader(source), jsonParserConfiguration);
}
/**
* Get the hex value of a character (base16).
*
* @param c A character between '0' and '9' or between 'A' and 'F' or
* between 'a' and 'f'.
* @return An int between 0 and 15, or -1 if c was not a hex digit.
*/
public static int dehexchar(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
}
if (c >= 'A' && c <= 'F') {
return c - ('A' - 10);
}
if (c >= 'a' && c <= 'f') {
return c - ('a' - 10);
}
return -1;
}
/**
* Getter
*
* @return jsonParserConfiguration
*/
public JSONParserConfiguration getJsonParserConfiguration() {
return jsonParserConfiguration;
}
/**
* Setter
*
* @param jsonParserConfiguration new value for jsonParserConfiguration
* @deprecated method should not be used
*/
@Deprecated
public void setJsonParserConfiguration(JSONParserConfiguration jsonParserConfiguration) {
setJsonParserConfigurationInternal(jsonParserConfiguration);
}
void setJsonParserConfigurationInternal(JSONParserConfiguration jsonParserConfiguration) {
this.jsonParserConfiguration = jsonParserConfiguration;
}
/**
* Back up one character. This provides a sort of lookahead capability,
* so that you can test for a digit or letter before attempting to parse
* the next number or identifier.
*
* @throws JSONException Thrown if trying to step back more than 1 step
* or if already at the start of the string
*/
public void back() throws JSONException {
if (this.usePrevious || this.index <= 0) {
throw new JSONException("Stepping back two steps is not supported");
}
this.decrementIndexes();
this.usePrevious = true;
this.eof = false;
}
/**
* Decrements the indexes for the {@link #back()} method based on the previous character read.
*/
private void decrementIndexes() {
this.index--;
if (this.previous == '\r' || this.previous == '\n') {
this.line--;
this.character = this.characterPreviousLine;
} else if (this.character > 0) {
this.character--;
}
}
/**
* Checks if the end of the input has been reached.
*
* @return true if at the end of the file and we didn't step back
*/
public boolean end() {
return this.eof && !this.usePrevious;
}
/**
* Determine if the source string still contains characters that next()
* can consume.
*
* @return true if not yet at the end of the source.
* @throws JSONException thrown if there is an error stepping forward
* or backward while checking for more data.
*/
public boolean more() throws JSONException {
if (this.usePrevious) {
return true;
}
try {
this.reader.mark(1);
} catch (
IOException e) {
throw new JSONException("Unable to preserve stream position", e);
}
try {
// -1 is EOF, but next() can not consume the null character '\0'
if (this.reader.read() <= 0) {
this.eof = true;
return false;
}
this.reader.reset();
} catch (
IOException e) {
throw new JSONException("Unable to read the next character from the stream", e);
}
return true;
}
/**
* Get the next character in the source string.
*
* @return The next character, or 0 if past the end of the source string.
* @throws JSONException Thrown if there is an error reading the source string.
*/
public char next() throws JSONException {
int c;
if (this.usePrevious) {
this.usePrevious = false;
c = this.previous;
} else {
try {
c = this.reader.read();
} catch (
IOException exception) {
throw new JSONException(exception);
}
}
if (c <= 0) { // End of stream
this.eof = true;
return 0;
}
this.incrementIndexes(c);
this.previous = (char) c;
return this.previous;
}
/**
* Get the last character read from the input or '\0' if nothing has been read yet.
*
* @return the last character read from the input.
*/
protected char getPrevious() {
return this.previous;
}
/**
* Increments the internal indexes according to the previous character
* read and the character passed as the current character.
*
* @param c the current character read.
*/
private void incrementIndexes(int c) {
if (c > 0) {
this.index++;
if (c == '\r') {
this.line++;
this.characterPreviousLine = this.character;
this.character = 0;
} else if (c == '\n') {
if (this.previous != '\r') {
this.line++;
this.characterPreviousLine = this.character;
}
this.character = 0;
} else {
this.character++;
}
}
}
/**
* Consume the next character, and check that it matches a specified
* character.
*
* @param c The character to match.
* @return The character.
* @throws JSONException if the character does not match.
*/
public char next(char c) throws JSONException {
char n = this.next();
if (n != c) {
if (n > 0) {
throw this.syntaxError("Expected '" + c + "' and instead saw '" +
n + "'");
}
throw this.syntaxError("Expected '" + c + "' and instead saw ''");
}
return n;
}
/**
* Get the next n characters.
*
* @param n The number of characters to take.
* @return A string of n characters.
* @throws JSONException Substring bounds error if there are not
* n characters remaining in the source string.
*/
public String next(int n) throws JSONException {
if (n == 0) {
return "";
}
char[] chars = new char[n];
int pos = 0;
while (pos < n) {
chars[pos] = this.next();
if (this.end()) {
throw this.syntaxError("Substring bounds error");
}
pos += 1;
}
return new String(chars);
}
/**
* Get the next char in the string, skipping whitespace.
*
* @return A character, or 0 if there are no more characters.
* @throws JSONException Thrown if there is an error reading the source string.
*/
public char nextClean() throws JSONException {
for (; ; ) {
char c = this.next();
if (c == 0 || c > ' ') {
return c;
}
}
}
/**
* Return the characters up to the next close quote character.
* Backslash processing is done. The formal JSON format does not
* allow strings in single quotes, but an implementation is allowed to
* accept them.
*
* @param quote The quoting character, either
* <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();
}
}
}
@@ -0,0 +1,552 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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.");
}
}
}
}
@@ -0,0 +1,62 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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;
}
}
}
@@ -0,0 +1,409 @@
package org.json;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;
/*
Public Domain.
*/
/**
* JSONWriter provides a quick and convenient way of producing JSON text. The texts produced
* strictly conform to JSON syntax rules. No whitespace is added, so the results are ready for
* transmission or storage. Each instance of JSONWriter can produce one JSON text.
* <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
@@ -0,0 +1,66 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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();
}
@@ -0,0 +1,179 @@
package org.json;
/*
Public Domain.
*/
/**
* Configuration base object for parsers. The configuration is immutable.
*/
@SuppressWarnings({""})
public class ParserConfiguration {
/**
* Used to indicate there's no defined limit to the maximum nesting depth when parsing a document.
*/
public static final int UNDEFINED_MAXIMUM_NESTING_DEPTH = -1;
/**
* Used to indicate there's no defined limit to the maximum number length
*/
public static final int UNDEFINED_MAXIMUM_NUMBER_LENGTH = -1;
/**
* The default maximum nesting depth when parsing a document.
*/
public static final int DEFAULT_MAXIMUM_NESTING_DEPTH = 512;
/**
* The default max number length
*/
public static final int DEFAULT_MAX_NUMBER_LENGTH = 1000;
/**
* Specifies if values should be kept as strings (<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;
}
}
@@ -0,0 +1,96 @@
package org.json;
import java.io.IOException;
import java.io.Writer;
/**
* Performance optimised alternative for {@link java.io.StringWriter} using internally a
* {@link StringBuilder} instead of a {@link StringBuffer}.
*/
public class StringBuilderWriter extends Writer {
private final StringBuilder builder;
/**
* Create a new string builder writer using the default initial string-builder buffer size.
*/
public StringBuilderWriter() {
builder = new StringBuilder();
lock = builder;
}
/**
* Create a new string builder writer using the specified initial string-builder buffer size.
*
* @param initialSize The number of {@code char} values that will fit into this buffer before it is
* automatically expanded
* @throws IllegalArgumentException If {@code initialSize} is negative
*/
public StringBuilderWriter(int initialSize) {
builder = new StringBuilder(initialSize);
lock = builder;
}
@Override
public void write(int c) {
builder.append((char) c);
}
@Override
public void write(char[] cbuf, int offset, int length) {
if ((offset < 0) || (offset > cbuf.length) || (length < 0) ||
((offset + length) > cbuf.length) || ((offset + length) < 0)) {
throw new IndexOutOfBoundsException();
}
else if (length == 0) {
return;
}
builder.append(cbuf, offset, length);
}
@Override
public void write(String str) {
builder.append(str);
}
@Override
public void write(String str, int offset, int length) {
builder.append(str, offset, offset + length);
}
@Override
public StringBuilderWriter append(CharSequence csq) {
write(String.valueOf(csq));
return this;
}
@Override
public StringBuilderWriter append(CharSequence csq, int start, int end) {
if (csq == null) {
csq = "null";
}
return append(csq.subSequence(start, end));
}
@Override
public StringBuilderWriter append(char c) {
write(c);
return this;
}
@Override
public String toString() {
return builder.toString();
}
@Override
public void flush() {
}
@Override
public void close() throws IOException {
}
}
@@ -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.
#
daxi.moe.codec.json.JSONCodec
+8
View File
@@ -12,4 +12,12 @@
<artifactId>daxi.moe.main</artifactId>
<packaging>jar</packaging>
<dependencies>
<dependency>
<groupId>daxi.moe</groupId>
<artifactId>daxi.moe.api</artifactId>
<version>${project.parent.version}</version>
</dependency>
</dependencies>
</project>
@@ -14,6 +14,7 @@
package daxi.moe.codec.mem;
import daxi.moe.app.CodecException;
import daxi.moe.app.Moe;
import daxi.moe.codec.MoeDecoder;
import daxi.moe.model.AnyData;
@@ -21,20 +22,24 @@ import daxi.moe.model.AnyData;
import java.io.InputStream;
import java.util.List;
/**
* @author indroneel
*/
public class MemDecoder implements MoeDecoder {
@Override
public void setSource(byte[] data) {
public void setSource(byte[] data) throws CodecException {
}
@Override
public void setSource(InputStream input) {
public void setSource(InputStream input) throws CodecException {
}
@Override
public AnyData decode(List<Moe.Options> options) {
public AnyData decode(List<Moe.Options> options) throws CodecException {
return null;
}
}
@@ -18,12 +18,21 @@ import daxi.moe.app.External;
import daxi.moe.app.Internal;
import daxi.moe.app.Moe;
import daxi.moe.codec.MoeCodec;
import daxi.moe.lib.mod2obj.ExternalImpl;
import daxi.moe.lib.obj2mod.InternalImpl;
import java.util.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The only implementation of {@link Moe}.
*
* @author indroneel
*/
@@ -79,4 +88,4 @@ public class MoeImpl extends Moe {
}
return this;
}
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.m2j;
import daxi.moe.lib.transform.M2JGlobals;
import daxi.moe.lib.transform.M2JLinear;
import daxi.moe.lib.transform.M2JStatus;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* The only implementation of the {@link M2JLinear} interface.
*
* @author indroneel
*/
public class M2JLinearImpl implements M2JLinear {
private final M2JGlobals globals;
public M2JLinearImpl(M2JGlobals globals) {
this.globals = globals;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface M2JLinear
@Override
public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
return M2JStatus.NOT_VALID;
}
}
@@ -1,45 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.m2j;
import daxi.moe.lib.transform.M2JGlobals;
import daxi.moe.lib.transform.M2JMapped;
import daxi.moe.lib.transform.M2JStatus;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* The only implementation of the {@link M2JMapped} interface.
*
* @author indroneel
*/
public class M2JMappedImpl implements M2JMapped {
private final M2JGlobals globals;
public M2JMappedImpl(M2JGlobals globals) {
this.globals = globals;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface M2JMapped
@Override
public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
return M2JStatus.NOT_VALID;
}
}
@@ -1,206 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.m2j;
import daxi.moe.app.MapFrom;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
/**
* Contains information about a method on the target Java object. The method and the information
* can be used to transform some portions of internal data model and populate the containing object.
*
* @author indroneel
*/
public class M2JMethod {
private boolean valid = false;
private boolean setter = false;
private boolean linAdder = false;
private boolean mapAdder = false;
private String mapFromKey = null;
private Class<?> paramType = null;
/**
* Constructs the object around transforming method . The contained method may or may not be valid
* for transformation, depending on the method's signature and annotations.
*
* @param method the method to be encapsulated
*/
public M2JMethod(Method method) {
MapFrom mapFrom = method.getAnnotation(MapFrom.class);
if(mapFrom == null) {
// If the method does not have the @MapFrom annotation, it is not valid for
// transformation
return;
}
// populate the mapFromKey field with the value of the @MapFrom annotation
mapFromKey = mapFrom.value();
if(mapFromKey == null || mapFromKey.isBlank()) {
// If the @MapFrom annotation does not have a valid key, it is not valid for
// transformation
return;
}
int mod = method.getModifiers();
if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
// If the method is abstract, static, or not private, it is not valid for transformation
return;
}
if(method.getReturnType() != Void.TYPE) {
// If the method does not return void, it is not valid for transformation
return;
}
Parameter[] params = method.getParameters();
// Check if the method name starts with "_set" and has more than 4 characters
if(method.getName().startsWith("_set") && method.getName().length() > 4) {
if(params.length != 1) {
// If the method name starts with "_set" but does not have exactly one parameter, it
// is not valid for transformation
return;
}
Type type = params[0].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the parameter type is a type variable or a parameterized type, it is not valid
// for transformation
return;
}
paramType = params[0].getType();
if(paramType.isArray()) {
// If the parameter type is an array, it is not valid for transformation
return;
}
valid = true;
setter = true;
}
// Check if the method name starts with "_add" and has more than 4 characters
else if(method.getName().startsWith("_add") && method.getName().length() > 4) {
if(params.length ==1 ) {
Type type = params[0].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the parameter type is a type variable or a parameterized type, it is not
// valid for transformation
return;
}
paramType = params[0].getType();
if(paramType.isArray()) {
// If the parameter type is an array, it is not valid for transformation
return;
}
valid = true;
linAdder = true;
}
else if(params.length == 2) {
if(params[0].getType() != String.class) {
// If the first parameter type is not String, it is not valid for transformation
return;
}
Type type = params[1].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the second parameter type is a type variable or a parameterized type, it
// is not valid for transformation
return;
}
paramType = params[1].getType();
if(paramType.isArray()) {
// If the second parameter type is an array, it is not valid for transformation
return;
}
valid = true;
mapAdder = true;
}
}
}
/**
* Returns whether the method is valid for transformation.
*
* @return true if the method is valid for transformation, false otherwise.
*/
boolean isValid() {
return valid;
}
/**
* Returns whether the method is a setter. A setter is a method that takes a single parameter and
* sets it to the containing object.
*
* @return true if the method is a setter, false otherwise
*/
boolean isSetter() {
return setter;
}
/**
* Returns whether the method is a linear adder. A linear adder is a method that takes a single
* parameter and adds it to the containing object. The adder method is called multiple times, once
* for each value to be added.
*
* @return true if the method is a linear adder, false otherwise
*/
boolean isLinearAdder() {
return linAdder;
}
/**
* Returns whether the method is a mapped adder. A mapped adder is a method that takes two
* parameters, the first being a String key and the second being the value to be added. The library
* will use the key to determine which portion of the data model is mapped to the method. The adder
* method is called multiple times, once for each key-value pair to be added.
*
* @return true if the method is a mapped adder, false otherwise
*/
boolean isMappedAdder() {
return mapAdder;
}
/**
* Returns the key from the @MapFrom annotation. The library will use this key to determine which
* portion of the data model is mapped to the method.
*
* @return the key from the @MapFrom annotation
*/
String getMapFromKey() {
return mapFromKey;
}
/**
* Returns the parameter type of the method. The library will use this type to determine how to
* convert the data model item into the appropriate Java type.
*
* @return the parameter type of the method
*/
Class<?> getParamType() {
return paramType;
}
}
@@ -1,145 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.m2j;
import daxi.moe.app.MapFrom;
import daxi.moe.lib.transform.M2JGlobals;
import daxi.moe.lib.transform.M2JLinear;
import daxi.moe.lib.transform.M2JMapped;
import daxi.moe.lib.transform.M2JObject;
import daxi.moe.lib.transform.M2JSimple;
import daxi.moe.lib.transform.M2JStatus;
import daxi.moe.model.MappedData;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The only implementation of the {@link M2JObject} interface.
*
* @author indroneel
*/
public class M2JObjectImpl implements M2JObject {
private static final Logger L = Logger.getLogger(M2JObjectImpl.class.getName());
private final M2JGlobals globals;
public M2JObjectImpl(M2JGlobals globals) {
this.globals = globals;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface M2JObject
@Override
public M2JStatus convert(MappedData data, Object targetObj, Method targetMthd) {
return null;
}
@Override
public <T> T convert(MappedData data, Class<T> targetType) {
if(data == null || targetType == null) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Invalid arguments: data=" + data + ", targetType=" + targetType);
}
return null;
}
List<Method> methods = new LinkedList<>();
collateAllMethods(targetType, methods);
if(methods.isEmpty()) {
if(L.isLoggable(Level.WARNING)) {
L.warning("No suitable methods found in targetType: " + targetType);
}
return null;
}
T target;
try {
Constructor<T> ctor = targetType.getConstructor();
target = ctor.newInstance();
}
catch(Exception exep) {
if(L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
return null;
}
for(Method method : methods) {
M2JStatus m2jStat = transformImpl(data, target, method);
if(m2jStat == M2JStatus.ERROR) {
return null;
}
}
return target;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private void collateAllMethods(Class<?> type, List<Method> methodList) {
if(type.getClassLoader() == null) {
// Skip system classes
return;
}
for (Method method : type.getDeclaredMethods()) {
if (!Modifier.isStatic(method.getModifiers())) {
MapFrom ann = method.getAnnotation(MapFrom.class);
if (ann != null && !ann.value().isBlank()) {
methodList.add(method);
}
}
}
if (type.getSuperclass() != null) {
collateAllMethods(type.getSuperclass(), methodList);
}
}
private M2JStatus transformImpl(MappedData data, Object targetObj, Method targetMthd) {
M2JSimple m2jSim = globals.getM2JSimple();
M2JStatus m2jStat = m2jSim.convert(data, targetObj, targetMthd);
if(m2jStat != M2JStatus.NOT_VALID) {
// here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
return m2jStat;
}
M2JLinear m2jLin = globals.getM2JLinear();
m2jStat = m2jLin.convert(data, targetObj, targetMthd);
if(m2jStat != M2JStatus.NOT_VALID) {
// here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
return m2jStat;
}
M2JMapped m2jMap = globals.getM2JMapped();
m2jStat = m2jMap.convert(data, targetObj, targetMthd);
if(m2jStat != M2JStatus.NOT_VALID) {
// here: m2jStat == M2JStatus.SUCCESS or m2jStat == M2JStatus.ERROR
return m2jStat;
}
// here: m2jStat == M2JStatus.NOT_VALID
return convert(data, targetObj, targetMthd);
}
}
@@ -1,337 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.m2j;
import daxi.moe.lib.transform.M2JGlobals;
import daxi.moe.lib.transform.M2JSimple;
import daxi.moe.lib.transform.M2JStatus;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import daxi.moe.model.SimpleData;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* The only implementation of the {@link daxi.moe.lib.transform.M2JSimple} interface.
*
* @author indroneel
*/
public class M2JSimpleImpl implements M2JSimple {
private static final Logger L = Logger.getLogger(M2JSimpleImpl.class.getName());
private final M2JGlobals globals;
public M2JSimpleImpl(M2JGlobals globals) {
this.globals = globals;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface M2JSimple
@Override
public M2JStatus convert(MappedData data, Object target, Method method) {
M2JMethod m2jMthd = new M2JMethod(method);
if(!m2jMthd.isValid() || !m2jMthd.isSetter()) {
return M2JStatus.NOT_VALID;
}
Class<?> paramType = m2jMthd.getParamType();
if(!isSupportedParamType(paramType)) {
return M2JStatus.NOT_VALID;
}
String key = m2jMthd.getMapFromKey();
if(!data.contains(key)) {
return M2JStatus.NOT_VALID;
}
AnyData adata = data.get(key);
SimpleData sdata = adata.asSimple();
if(sdata == null) {
return M2JStatus.NOT_VALID;
}
Object paramVal = null;
if(paramType == String.class) {
paramVal = sdata.getString();
}
else if(paramType == BigInteger.class) {
paramVal = getBigIntegerValue(sdata);
}
else if(paramType == BigDecimal.class) {
paramVal = getBigDecimalValue(sdata);
}
else if(paramType == byte.class || paramType == Byte.class) {
paramVal = getByteValue(sdata);
}
else if(paramType == short.class || paramType == Short.class) {
paramVal = getShortValue(sdata);
}
else if(paramType == int.class || paramType == Integer.class) {
paramVal = getIntegerValue(sdata);
}
else if(paramType == long.class || paramType == Long.class) {
paramVal = getLongValue(sdata);
}
else if(paramType == float.class || paramType == Float.class) {
paramVal = getFloatValue(sdata);
}
else if(paramType == double.class || paramType == Double.class) {
paramVal = getDoubleValue(sdata);
}
else if(paramType == boolean.class || paramType == Boolean.class) {
paramVal = getBooleanValue(sdata);
}
if(paramVal == null) {
return M2JStatus.NOT_VALID;
}
try {
method.setAccessible(true);
method.invoke(target, paramVal);
method.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if(L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
return M2JStatus.ERROR;
}
return M2JStatus.SUCCESS;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private boolean isSupportedParamType(Class<?> paramType) {
return paramType == String.class
|| paramType == BigInteger.class
|| paramType == BigDecimal.class
|| Number.class.isAssignableFrom(paramType)
|| paramType == byte.class
|| paramType == short.class
|| paramType == int.class
|| paramType == long.class
|| paramType == float.class
|| paramType == double.class
|| paramType == boolean.class
|| paramType == Boolean.class;
}
private BigInteger getBigIntegerValue(SimpleData data) {
BigInteger paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = new BigInteger(Long.toString(nval.longValue()));
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = new BigInteger(sval);
}
catch(Exception exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to BigInteger");
}
}
}
}
return paramVal;
}
private BigDecimal getBigDecimalValue(SimpleData data) {
BigDecimal paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = new BigDecimal(nval.toString());
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = new BigDecimal(sval);
}
catch(Exception exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to BigDecimal");
}
}
}
}
return paramVal;
}
private Byte getByteValue(SimpleData data) {
Byte paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.byteValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Byte.parseByte(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to byte");
}
}
}
}
return paramVal;
}
private Short getShortValue(SimpleData data) {
Short paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.shortValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Short.parseShort(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to short");
}
}
}
}
return paramVal;
}
private Integer getIntegerValue(SimpleData data) {
Integer paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.intValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Integer.parseInt(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to integer");
}
}
}
}
return paramVal;
}
private Long getLongValue(SimpleData data) {
Long paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.longValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Long.parseLong(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to long");
}
}
}
}
return paramVal;
}
private Float getFloatValue(SimpleData data) {
Float paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.floatValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Float.parseFloat(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to float");
}
}
}
}
return paramVal;
}
private Double getDoubleValue(SimpleData data) {
Double paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.doubleValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Double.parseDouble(sval);
}
catch(NumberFormatException exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning("Unable to convert string [" + sval + "] to double");
}
}
}
}
return paramVal;
}
private Boolean getBooleanValue(SimpleData data) {
Boolean paramVal = data.getBoolean();
if(paramVal != null) {
return paramVal;
}
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.intValue() != 0;
}
else {
String sval = data.getString();
if(sval != null) {
paramVal = Boolean.parseBoolean(sval.toLowerCase(Locale.getDefault()));
}
}
return paramVal;
}
}
@@ -0,0 +1,82 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
/**
* A BlankLinear is a Setter method that has a blank data key. It is used to set the value of a
* property on an object, but does not have a specific data key associated with it.
*
* @author indroneel
*/
public class BlankLinear extends FromMethod {
private final Class<?> inType;
public BlankLinear(Method method) throws IllegalArgumentException {
super(method);
if(!getDataKey().isBlank()) {
// If the data key is not blank, it is not a blank linear method
throw new IllegalArgumentException();
}
Parameter[] params = method.getParameters();
if(params.length != 1) {
// If the method does not have exactly one parameter, it is not valid for conversion
throw new IllegalArgumentException();
}
Type type = params[0].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the parameter type is a type variable or a parameterized type, it is not valid
// for conversion
throw new IllegalArgumentException();
}
inType = params[0].getType();
if(inType.isArray()) {
// If the parameter type is an array, it is not valid for conversion
throw new IllegalArgumentException();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of base class FromMethod
@Override
public Class<?> getInputType() {
return inType;
}
@Override
public String toString() {
return String.format("%s(%s)", getMethod().getName(), inType.getName());
}
public static BlankLinear of(Method method) {
try {
return new BlankLinear(method);
}
catch (IllegalArgumentException exep) {
return null;
}
}
}
@@ -0,0 +1,81 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
public class BlankMapped extends FromMethod {
private final Class<?> inType;
public BlankMapped(Method method) throws IllegalArgumentException {
super(method);
if(!getDataKey().isBlank()) {
// If the data key is not blank, it is not a blank mapped method
throw new IllegalArgumentException();
}
Parameter[] params = method.getParameters();
if(params.length != 2) {
// If the method does not have exactly two parameters, it is not valid for conversion
throw new IllegalArgumentException();
}
if(params[0].getType() != String.class) {
// If the first parameter is not of type String, it is not valid for conversion
throw new IllegalArgumentException();
}
Type type = params[1].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the second parameter type is a type variable or a parameterized type, it
// is not valid for transformation
throw new IllegalArgumentException();
}
inType = params[1].getType();
if(inType.isArray()) {
// If the parameter type is an array, it is not valid for conversion
throw new IllegalArgumentException();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of base class FromMethod
@Override
public Class<?> getInputType() {
return inType;
}
@Override
public String toString() {
return String.format("%s(%s)", getMethod().getName(), inType.getName());
}
public static BlankMapped of(Method method) {
try {
return new BlankMapped(method);
}
catch (IllegalArgumentException exep) {
return null;
}
}
}
@@ -10,30 +10,20 @@
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package daxi.moe.lib;
package daxi.moe.lib.mod2obj;
import daxi.moe.app.External;
import daxi.moe.app.Moe;
import daxi.moe.app.MoeException;
import daxi.moe.codec.MoeCodec;
import daxi.moe.codec.MoeDecoder;
import daxi.moe.lib.m2j.M2JLinearImpl;
import daxi.moe.lib.m2j.M2JMappedImpl;
import daxi.moe.lib.m2j.M2JObjectImpl;
import daxi.moe.lib.m2j.M2JSimpleImpl;
import daxi.moe.lib.transform.M2JGlobals;
import daxi.moe.lib.transform.M2JLinear;
import daxi.moe.lib.transform.M2JMapped;
import daxi.moe.lib.transform.M2JObject;
import daxi.moe.lib.transform.M2JSimple;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import java.io.InputStream;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
@@ -46,24 +36,13 @@ public class ExternalImpl implements External {
private final MoeDecoder decoder;
private final List<Moe.Options> options;
private final M2JGlobals globals;
private final Populators populators;
private AnyData model;
ExternalImpl(MoeCodec codec, List<Moe.Options> options) {
public ExternalImpl(MoeCodec codec, List<Moe.Options> options) {
decoder = codec.decoder();
this.options = options;
globals = new M2JGlobals(options);
M2JSimple m2jSim = new M2JSimpleImpl(globals);
globals.setM2J(m2jSim);
M2JLinear m2jLin = new M2JLinearImpl(globals);
globals.setM2J(m2jLin);
M2JMapped m2jMap = new M2JMappedImpl(globals);
globals.setM2J(m2jMap);
M2JObject m2jObj = new M2JObjectImpl(globals);
globals.setM2J(m2jObj);
populators = new Populators(options);
model = new AnyData(new MappedData());
}
@@ -71,7 +50,7 @@ public class ExternalImpl implements External {
// Methods of interface External
@Override
public External from(InputStream in) {
public External from(InputStream in) throws MoeException {
decoder.setSource(in);
model = decoder.decode(options);
if(model == null) {
@@ -81,7 +60,7 @@ public class ExternalImpl implements External {
}
@Override
public External from(byte[] data) {
public External from(byte[] data) throws MoeException {
decoder.setSource(data);
model = decoder.decode(options);
if(model == null) {
@@ -101,19 +80,18 @@ public class ExternalImpl implements External {
}
@Override
public <T> T convert(Class<T> type) {
public <T> T convert(Class<T> type) throws MoeException {
MappedData data = model.asMapped();
if(data == null) {
if(L.isLoggable(Level.WARNING)) {
L.warning("input data model does not contain MappedData as root element");
}
L.warning(() -> "input data model does not contain MappedData as root element");
return null;
}
return globals.getM2JObject().convert(data, type);
Object retObj = populators.getMapped().create(new AnyData(data), type);
return type.cast(retObj);
}
@Override
public <T> T convert(String path, Class<T> type) {
public <T> T convert(String path, Class<T> type) throws MoeException {
return null;
}
}
@@ -0,0 +1,88 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.MapFrom;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
/**
* Represents a method that is used to convert a nested data model item into a Java object. The
* method must be private, non-static, and return void. The method must also be annotated with the
* {@link MapFrom} annotation, which specifies the data key that is used to identify the nested data
* in the model.
*
* @author indroneel
*/
public abstract class FromMethod {
private final Method method;
private final String dataKey;
protected FromMethod(Method method) {
this.method = method;
MapFrom mapping = method.getAnnotation(MapFrom.class);
if(mapping == null) {
// If the method does not have the @Mapping annotation, it is not valid for conversion
throw new IllegalArgumentException();
}
// populate the dataKey field with the value of the @Mapping annotation
dataKey = mapping.value().trim();
if(method.getReturnType() != Void.TYPE) {
// If the method does not return void, it is not valid for conversion
throw new IllegalArgumentException();
}
int mod = method.getModifiers();
// If the method is abstract, static, or not private, it is not valid for conversion
if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
throw new IllegalArgumentException();
}
}
/**
* Returns the data key associated with this method. The data key is used to identify the nested
* data in the model that will be converted.
*
* @return the data key
*/
public final String getDataKey() {
return dataKey;
}
/**
* Returns the method that this FromMethod instance represents. The method is used to set the
* value of the converted data in the target object.
*
* @return the method that is used to convert the data
*/
public final Method getMethod() {
return method;
}
/**
* Returns the input type that the method accepts. The library will use this type to determine how
* to convert the data model item into the appropriate (Java) input type.
*
* @return the input type of the method
*/
public abstract Class<?> getInputType();
}
@@ -0,0 +1,160 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.LinearData;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class LinearPopulator implements Populator {
private static final Logger L = Logger.getLogger(LinearPopulator.class.getName());
private final Populators populators;
public LinearPopulator(Populators populators) {
this.populators = populators;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Populator
@Override
public Object create(AnyData data, Class<?> targetType) throws ConvertException {
LinearData ldata = data.asLinear();
if(ldata == null || targetType == null) {
L.warning(() -> "Invalid arguments: data=" + ldata + ", targetType=" + targetType);
return null;
}
TargetEntity entity = new TargetEntity(targetType);
L.finest(() -> entity.dumpInfo());
if(entity.hasSetters()) {
L.warning(() -> "Target type has setters, need only blank linear: " + targetType);
return null;
}
BlankLinear blinear = entity.getBlankLinear();
if(blinear == null) {
L.warning(() -> "Target type does not have a blank linear method: " + targetType);
return null;
}
Object target;
try {
// Attempt to create a new instance of the target type using its public and default
// constructor
Constructor<?> ctor = targetType.getConstructor();
target = ctor.newInstance();
}
catch(NoSuchMethodException exep) {
if(L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
return null;
}
catch(Exception exep) {
throw new ConvertException(targetType.getName(), "<init>",
"Error invoking default constructor - " + exep.getMessage(), exep);
}
Status status = populateImpl(data, target, blinear.getMethod(), blinear.getInputType());
if(status != Status.SUCCESS) {
L.warning(() -> "Failed to populate target object: " + targetType);
return null;
}
return target;
}
@Override
public Status populate(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
// note: the check for linear data is done in the populateImpl method, so we don't need to
// do it here
// for each item in the linear data, we will try to populate the target object using the
// corresponding setter method with the given data key.
Setter setter = entity.getSetter(dataKey);
if(setter == null) {
return Status.NOT_VALID;
}
return populateImpl(data, targetObj, setter.getMethod(), setter.getInputType());
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private Status populateImpl(AnyData data,
Object targetObj, Method method,
Class<?> popType) throws ConvertException {
LinearData ldata = data.asLinear();
if(ldata == null) {
return Status.NOT_VALID;
}
Status retstat = Status.NOT_VALID;
for(int pos=0; pos<ldata.size(); pos++) {
AnyData itemData = ldata.get(pos);
if (itemData == null) {
continue; // this should not happen, but just in case
}
Object setterVal = null;
if(itemData.asSimple() != null) {
setterVal = populators.getSimple().create(itemData, popType);
}
else if(itemData.asLinear() != null) {
setterVal = populators.getLinear().create(itemData, popType);
}
else if(itemData.asMapped() != null) {
setterVal = populators.getMapped().create(itemData, popType);
}
if(setterVal == null) {
L.info(() -> String.format("Cannot set using: %s:%s",
targetObj.getClass().getName(), method.getName()));
continue;
}
try {
method.setAccessible(true);
method.invoke(targetObj, setterVal);
method.setAccessible(false);
retstat = Status.SUCCESS;
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), method.getName(),
"Error invoking setter for linear data item - " + exep.getMessage(), exep);
}
}
return retstat;
}
}
@@ -0,0 +1,182 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class MappedPopulator implements Populator {
private static final Logger L = Logger.getLogger(MappedPopulator.class.getName());
private final Populators populators;
public MappedPopulator(Populators populators) {
this.populators = populators;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Populator
@Override
public Object create(AnyData data, Class<?> targetType) throws ConvertException {
MappedData mdata = data.asMapped();
if(mdata == null || targetType == null) {
L.warning(() -> "Invalid arguments: data=" + mdata + ", targetType=" + targetType);
return null;
}
TargetEntity entity = new TargetEntity(targetType);
if (L.isLoggable(Level.FINEST)) {
L.finest(entity.dumpInfo());
}
if(entity.isInvalid()) {
if (L.isLoggable(Level.WARNING)) {
L.warning("Target type is not valid: " + targetType);
}
return null;
}
Object target;
try {
// Attempt to create a new instance of the target type using its public and default
// constructor
Constructor<?> ctor = targetType.getConstructor();
target = ctor.newInstance();
}
catch(NoSuchMethodException exep) {
if(L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
return null;
}
catch(Exception exep) {
throw new ConvertException(targetType.getName(), "<init>",
"Error invoking default constructor - " + exep.getMessage(), exep);
}
for(String dataKey : mdata.getKeys()) {
AnyData nestedData = mdata.get(dataKey);
if (nestedData == null) {
continue; // this should not happen, but just in case
}
Status status = Status.NOT_VALID;
if(nestedData.asSimple() != null) {
status = populators.getSimple().populate(nestedData, dataKey, entity, target);
}
else if(nestedData.asLinear() != null) {
status = populators.getLinear().populate(nestedData, dataKey, entity, target);
}
else if(nestedData.asMapped() != null) {
status = populate(nestedData, dataKey, entity, target);
}
if(status != Status.SUCCESS) {
L.info(() -> String.format("key = %s, type = %s Cannot set or add", dataKey,
target.getClass().getName()));
}
}
return target;
}
@Override
public Status populate(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
MappedData mdata = data.asMapped();
if(mdata == null) {
return Status.NOT_VALID;
}
if(entity.hasSetters()) {
return doSetter(data, dataKey, entity, targetObj);
}
else {
return doBlankMap(data, dataKey, entity, targetObj);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private Status doSetter(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
Setter setter = entity.getSetter(dataKey);
if(setter == null) {
return Status.NOT_VALID;
}
Object paramVal = create(data, setter.getInputType());
if(paramVal == null) {
return Status.NOT_VALID;
}
Method method = setter.getMethod();
try {
method.setAccessible(true);
method.invoke(targetObj, paramVal);
method.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), method.getName(),
"Error invoking setter - " + exep.getMessage(), exep);
}
return Status.SUCCESS;
}
private Status doBlankMap(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
BlankMapped bmapped = entity.getBlankMapped();
if(bmapped == null) {
return Status.NOT_VALID;
}
Object paramVal = create(data, bmapped.getInputType());
if(paramVal == null) {
return Status.NOT_VALID;
}
Method method = bmapped.getMethod();
try {
method.setAccessible(true);
method.invoke(targetObj, dataKey, paramVal);
method.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), method.getName(),
"Error invoking blank mapped method - " + exep.getMessage(), exep);
}
return Status.SUCCESS;
}
}
@@ -0,0 +1,52 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
/**
* @author indroneel
*/
public interface Populator {
/**
* Converts an {@link AnyData} to an object of the specified target type. The anydata encapsulates
* any one of a simple, linear or mapped data.
*
* @param data one of a simple, linear or mapped data to convert
* @param targetType the target type to convert to
* @return an object of the specified target type
* @throws ConvertException if the conversion fails
*/
Object create(AnyData data, Class<?> targetType) throws ConvertException;
/**
* Populates a target Java object using any data by invoking the provided method on the object. The
* anydata encapsulates any one of a simple, linear or mapped data.
*
* @param data one of a simple, linear or mapped data
* @param dataKey The key associated with the any data.
* @param entity the target entity that encapsulates the target object and the method to invoke
* @param targetObj the target Java object to populate
* @return a {@link Status} indicating the result of the population operation
* @throws ConvertException if the population operation fails
*/
Status populate(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException;
}
@@ -0,0 +1,55 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.Moe;
import java.util.List;
/**
* @author indroneel
*/
public class Populators {
private final List<Moe.Options> options;
private final Populator simple;
private final Populator linear;
private final Populator mapped;
public Populators(List<Moe.Options> options) {
this.options = options;
simple = new SimplePopulator();
linear = new LinearPopulator(this);
mapped = new MappedPopulator(this);
}
public boolean hasOption(Moe.Options opt) {
return options.contains(opt);
}
public Populator getSimple() {
return simple;
}
public Populator getLinear() {
return linear;
}
public Populator getMapped() {
return mapped;
}
}
@@ -0,0 +1,92 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
/**
* A Setter is a method that takes a single input parameter and returns void. It is used to set the
* value of a property on an object.
*
* @author indroneel
*/
public class Setter extends FromMethod {
private final Class<?> inType;
protected Setter(Method method) throws IllegalArgumentException {
super(method);
if(getDataKey().isBlank()) {
// If the data key is blank, it is not a setter method
throw new IllegalArgumentException();
}
Parameter[] params = method.getParameters();
if(params.length != 1) {
// If the method does not have exactly one parameter, it is not valid for conversion
throw new IllegalArgumentException();
}
Type type = params[0].getParameterizedType();
if(type instanceof TypeVariable<?> || type instanceof ParameterizedType) {
// If the parameter type is a type variable or a parameterized type, it is not valid
// for conversion
throw new IllegalArgumentException();
}
inType = params[0].getType();
if(inType.isArray()) {
// If the parameter type is an array, it is not valid for conversion
throw new IllegalArgumentException();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of base class FromMethod
@Override
public Class<?> getInputType() {
return inType;
}
@Override
public String toString() {
return String.format("%s(%s)", getMethod().getName(), inType.getName());
}
/**
* Returns a Setter object if the provided method is valid for conversion, or null if it is
* not valid.
*
* @param method the method to be checked
* @return the Setter instance or null if the method does not meet valid setter semantics
*/
public static Setter of(Method method) {
try {
return new Setter(method);
}
catch (IllegalArgumentException exep) {
return null;
}
}
}
@@ -0,0 +1,347 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.SimpleData;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class SimplePopulator implements Populator {
private static final Logger L = Logger.getLogger(SimplePopulator.class.getName());
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Populator
@Override
public Object create(AnyData data, Class<?> targetType) throws ConvertException {
SimpleData sdata = data.asSimple();
if(sdata == null) {
return null;
}
Object targetObj = null;
if(targetType == String.class) {
targetObj = sdata.getString();
}
if(targetType == BigInteger.class) {
targetObj = getBigIntegerValue(sdata);
}
if(targetType == BigDecimal.class) {
targetObj = getBigDecimalValue(sdata);
}
if(targetType == byte.class || targetType == Byte.class) {
targetObj = getByteValue(sdata);
}
if(targetType == short.class || targetType == Short.class) {
targetObj = getShortValue(sdata);
}
if(targetType == int.class || targetType == Integer.class) {
targetObj = getIntegerValue(sdata);
}
if(targetType == long.class || targetType == Long.class) {
targetObj = getLongValue(sdata);
}
if(targetType == float.class || targetType == Float.class) {
targetObj = getFloatValue(sdata);
}
if(targetType == double.class || targetType == Double.class) {
targetObj = getDoubleValue(sdata);
}
if(targetType == boolean.class || targetType == Boolean.class) {
targetObj = getBooleanValue(sdata);
}
return targetObj;
}
@Override
public Status populate(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
SimpleData sdata = data.asSimple();
if(sdata == null) {
return Status.NOT_VALID;
}
if(entity.hasSetters()) {
return doSetter(data, dataKey, entity, targetObj);
}
else {
return doBlankMap(data, dataKey, entity, targetObj);
}
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private BigInteger getBigIntegerValue(SimpleData data) {
String strVal = data.getString();
if(strVal == null) {
Number nval = data.getNumber();
if(nval != null) {
strVal = nval.toString();
}
}
if(strVal != null) {
strVal = strVal.split("\\.")[0];
try {
return new BigInteger(strVal);
}
catch(Exception exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning(() -> "Unable to convert [" + data + "] to BigInteger");
}
}
}
return null;
}
private BigDecimal getBigDecimalValue(SimpleData data) {
String strVal = data.getString();
if(strVal == null) {
Number nval = data.getNumber();
if(nval != null) {
strVal = nval.toString();
}
}
if(strVal != null) {
try {
return new BigDecimal(strVal);
}
catch(Exception exep) {
if(L.isLoggable(Level.WARNING)) {
L.warning(() -> "Unable to convert [" + data + "] to BigDecimal");
}
}
}
return null;
}
private Byte getByteValue(SimpleData data) {
Byte paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.byteValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Byte.parseByte(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to byte");
}
}
}
return paramVal;
}
private Short getShortValue(SimpleData data) {
Short paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.shortValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Short.parseShort(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to short");
}
}
}
return paramVal;
}
private Integer getIntegerValue(SimpleData data) {
Integer paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.intValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Integer.parseInt(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to integer");
}
}
}
return paramVal;
}
private Long getLongValue(SimpleData data) {
Long paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.longValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Long.parseLong(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to long");
}
}
}
return paramVal;
}
private Float getFloatValue(SimpleData data) {
Float paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.floatValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Float.parseFloat(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to float");
}
}
}
return paramVal;
}
private Double getDoubleValue(SimpleData data) {
Double paramVal = null;
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.doubleValue();
}
else {
String sval = data.getString();
if(sval != null) {
try {
paramVal = Double.parseDouble(sval);
}
catch(NumberFormatException exep) {
L.warning(() -> "Unable to convert string [" + sval + "] to double");
}
}
}
return paramVal;
}
private Boolean getBooleanValue(SimpleData data) {
Boolean paramVal = data.getBoolean();
if(paramVal != null) {
return paramVal;
}
Number nval = data.getNumber();
if(nval != null) {
paramVal = nval.intValue() != 0;
}
else {
String sval = data.getString();
if(sval != null) {
paramVal = Boolean.parseBoolean(sval.toLowerCase(Locale.getDefault()));
}
}
return paramVal;
}
private Status doSetter(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
Setter setter = entity.getSetter(dataKey);
if(setter == null) {
return Status.NOT_VALID;
}
Object paramVal = create(data, setter.getInputType());
if(paramVal == null) {
return Status.NOT_VALID;
}
Method method = setter.getMethod();
try {
method.setAccessible(true);
method.invoke(targetObj, paramVal);
method.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), method.getName(),
"Error invoking setter - " + exep.getMessage(), exep);
}
return Status.SUCCESS;
}
private Status doBlankMap(AnyData data, String dataKey,
TargetEntity entity, Object targetObj) throws ConvertException {
BlankMapped bmapped = entity.getBlankMapped();
if(bmapped == null) {
return Status.NOT_VALID;
}
Object paramVal = create(data, bmapped.getInputType());
if(paramVal == null) {
return Status.NOT_VALID;
}
Method method = bmapped.getMethod();
try {
method.setAccessible(true);
method.invoke(targetObj, dataKey, paramVal);
method.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), method.getName(),
"Error invoking blank mapped method - " + exep.getMessage(), exep);
}
return Status.SUCCESS;
}
}
@@ -12,17 +12,25 @@
* limitations under the License.
*/
package daxi.moe.lib.transform;
package daxi.moe.lib.mod2obj;
/**
* Defines the possible statuses for a transformation. The transformation can be from the model data
* to Java objects or vice versa.
* Reports whether a converter could handle the supplied data and whether conversion succeeded.
*
* @author indroneel
*/
public enum M2JStatus {
public enum Status {
/**
* The converter did not handle the supplied data.
*/
NOT_VALID,
SUCCESS,
ERROR
/**
* The conversion completed successfully.
*/
SUCCESS
}
@@ -0,0 +1,137 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.mod2obj;
import daxi.moe.app.ConvertException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
/**
* A TargetEntity is a representation of a target class that can be populated with data from a
* model. It contains information about the setters and blank methods available in the target class.
*
* @author indroneel
*/
public class TargetEntity {
private static final Logger L = Logger.getLogger(TargetEntity.class.getName());
private final Class<?> targetType;
private final Map<String, Setter> setters;
private BlankLinear blankLinear;
private BlankMapped blankMapped;
public TargetEntity(Class<?> targetType) throws ConvertException {
this.targetType = targetType;
setters = new HashMap<>();
collateAllMethods(targetType);
}
//TODO: remove dead code
/*
public TargetEntity(Object targetObj) throws ConvertException {
this(targetObj.getClass());
}
*/
public boolean isInvalid() {
return setters.isEmpty() && blankLinear == null && blankMapped == null;
}
public boolean hasSetters() {
return !setters.isEmpty();
}
public Setter getSetter(String dataKey) {
return setters.get(dataKey);
}
public BlankLinear getBlankLinear() {
return blankLinear;
}
public BlankMapped getBlankMapped() {
return blankMapped;
}
public String dumpInfo() {
StringBuilder sb = new StringBuilder();
sb.append(String.format("TargetEntity: %s\n", targetType.getName()));
sb.append("=== START DUMP ===\n");
sb.append("Setters:\n");
for (Map.Entry<String, Setter> entry : setters.entrySet()) {
sb.append(" ").append(entry.getKey()).append(" -> ").append(entry.getValue()).append("\n");
}
sb.append("BlankLinear: ").append(blankLinear).append("\n");
sb.append("BlankMapped: ").append(blankMapped).append("\n");
sb.append("=== END DUMP ===\n");
return sb.toString();
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private void collateAllMethods(Class<?> type) throws ConvertException {
if(type.getClassLoader() == null) {
// Skip system classes
return;
}
for (Method method : type.getDeclaredMethods()) {
Setter sm = Setter.of(method);
if(sm != null) {
if(setters.containsKey(sm.getDataKey())) {
throw new ConvertException(type.getName(), sm.getMethod().getName(),
"Duplicate setter for data key: " + sm.getDataKey(), null);
}
setters.put(sm.getDataKey(), sm);
continue;
}
//else
BlankLinear bkl = BlankLinear.of(method);
if(bkl != null) {
if(blankLinear == null) {
blankLinear = bkl;
}
else {
throw new ConvertException(type.getName(), bkl.getMethod().getName(),
"Duplicate blank linear method: " + bkl.getMethod().getName(), null);
}
}
//else
BlankMapped bkm = BlankMapped.of(method);
if(bkm != null) {
if(blankMapped == null) {
blankMapped = bkm;
}
else {
throw new ConvertException(type.getName(), bkm.getMethod().getName(),
"Duplicate blank mapped method: " + bkm.getMethod().getName(), null);
}
}
}
if (type.getSuperclass() != null) {
collateAllMethods(type.getSuperclass());
}
}
}
@@ -10,24 +10,22 @@
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package daxi.moe.lib;
package daxi.moe.lib.obj2mod;
import daxi.moe.app.Internal;
import daxi.moe.app.Moe;
import daxi.moe.app.MoeException;
import daxi.moe.codec.MoeCodec;
import daxi.moe.codec.MoeEncoder;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;
/**
*
* @author indroneel
*/
@@ -38,21 +36,26 @@ public class InternalImpl implements Internal {
private final MoeEncoder encoder;
private final List<Moe.Options> options;
//private final M2JGlobals globals;
private final Retrievers retrievers;
private AnyData model;
InternalImpl(MoeCodec provider, List<Moe.Options> options) {
encoder = provider.encoder();
public InternalImpl(MoeCodec codec, List<Moe.Options> options) {
encoder = codec.encoder();
this.options = options;
//globals = new M2JGlobals(options);
retrievers = new Retrievers(options);
model = new AnyData(new MappedData());
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Internal
@Override
public Internal from(Object obj) {
public Internal from(Object obj) throws MoeException {
Retriever retriever = retrievers.getRetriever(obj);
if(retriever != null) {
model = retriever.transform(obj);
}
return this;
}
@@ -62,12 +65,12 @@ public class InternalImpl implements Internal {
}
@Override
public byte[] convert() throws IOException {
return new byte[0];
public byte[] convert() throws MoeException {
return encoder.convert(model, false);
}
@Override
public byte[] convert(boolean pretty) throws IOException {
return new byte[0];
public byte[] convert(boolean pretty) throws MoeException {
return encoder.convert(model, pretty);
}
}
@@ -0,0 +1,88 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.obj2mod;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.LinearData;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.Iterator;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class LinearRetriever implements Retriever {
private static final Logger L = Logger.getLogger(LinearRetriever.class.getName());
private final Retrievers retrievers;
public LinearRetriever(Retrievers retrievers) {
this.retrievers = retrievers;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Retriever
@Override
public boolean supports(Object targetObj) {
Class<?> tcls = targetObj.getClass();
return Collection.class.isAssignableFrom(tcls) || tcls.isArray();
}
@Override
public AnyData transform(Object targetObj) throws ConvertException {
Class<?> tcls = targetObj.getClass();
LinearData ldata = new LinearData();
if(Collection.class.isAssignableFrom(tcls)) {
for (Object item : (Collection<?>) targetObj) {
AnyData idata = transformItem(item);
if (idata != null) {
ldata.add(idata);
}
}
}
else if(tcls.isArray()) {
Class<?> compType = tcls.getComponentType();
int length = Array.getLength(targetObj);
for(int i = 0; i < length; i++) {
AnyData idata = transformItem(Array.get(targetObj, i));
if(idata != null) {
ldata.add(idata);
}
}
}
return new AnyData(ldata);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private AnyData transformItem(Object item) throws ConvertException {
Retriever retriever = retrievers.getRetriever(item);
if(retriever != null) {
return retriever.transform(item);
}
else {
L.warning(() -> "Unsupported item - " + item.getClass().getName());
return null;
}
}
}
@@ -0,0 +1,112 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.obj2mod;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class MappedRetriever implements Retriever {
private static final Logger L = Logger.getLogger(MappedRetriever.class.getName());
private final Retrievers retrievers;
public MappedRetriever(Retrievers retrievers) {
this.retrievers = retrievers;
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Retriever
@Override
public boolean supports(Object targetObj) {
Class<?> tcls = targetObj.getClass();
if(tcls.getClassLoader() == null) {
// This is a system class, we don't support it.
return false;
}
/*
if(targetObj instanceof String
|| targetObj instanceof Number || targetObj instanceof Boolean) {
// This is a String, Number, or Boolean, we don't support it.
return false;
}
if(Collection.class.isAssignableFrom(tcls)) {
// This is a Collection, we don't support it.
return false;
}
*/
if(tcls.isArray()) {
// This is an array, we don't support it.
return false;
}
return true;
}
@Override
public AnyData transform(Object targetObj) throws ConvertException {
SourceEntity sent = new SourceEntity(targetObj);
Set<String> dataKeys = sent.getDataKeys();
if(dataKeys == null || dataKeys.isEmpty()) {
return null;
}
MappedData mdata = new MappedData();
for(String dataKey : dataKeys) {
ToMethod tm = sent.getToMethod(dataKey);
Method mthd = tm.getMethod();
Object retVal = null;
final Class<?> rtnType = tm.getReturnType();
try {
mthd.setAccessible(true);
retVal = mthd.invoke(targetObj);
mthd.setAccessible(false);
}
catch (ReflectiveOperationException exep) {
if (L.isLoggable(Level.WARNING)) {
L.log(Level.WARNING, exep.getMessage(), exep);
}
throw new ConvertException(targetObj.getClass().getName(), mthd.getName(),
"Error invoking getter - " + exep.getMessage(), exep);
}
Retriever retriever = retrievers.getRetriever(retVal);
if(retriever != null) {
AnyData adata = retriever.transform(retVal);
if(adata != null) {
mdata.put(dataKey, adata);
}
}
else {
L.warning(() -> "Unsupported return type - " + rtnType.getName());
}
}
return new AnyData(mdata);
}
}
@@ -12,19 +12,18 @@
* limitations under the License.
*/
package daxi.moe.app;
package daxi.moe.lib.obj2mod;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import java.util.Optional;
/**
* @author indroneel
*/
public interface Converter {
public interface Retriever {
<T> T decode(AnyData ad, Class<T> type);
boolean supports(Object targetObj);
Optional<AnyData> encode(Object obj);
AnyData transform(Object targetObj) throws ConvertException;
}
@@ -0,0 +1,49 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.obj2mod;
import daxi.moe.app.Moe;
import java.util.List;
/**
* @author indroneel
*/
public class Retrievers {
private final Retriever simple;
private final Retriever linear;
private final Retriever mapped;
public Retrievers(List<Moe.Options> options) {
simple = new SimpleRetriever();
linear = new LinearRetriever(this);
mapped = new MappedRetriever(this);
}
public Retriever getRetriever(Object targetObj) {
if(simple.supports(targetObj)) {
return simple;
}
else if(linear.supports(targetObj)) {
return linear;
}
else if(mapped.supports(targetObj)) {
return mapped;
}
return null;
}
}
@@ -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 daxi.moe.lib.obj2mod;
import daxi.moe.app.ConvertException;
import daxi.moe.model.AnyData;
import daxi.moe.model.SimpleData;
/**
* @author indroneel
*/
public class SimpleRetriever implements Retriever {
////////////////////////////////////////////////////////////////////////////////////////////////
// Methods of interface Retriever
@Override
public boolean supports(Object targetObj) {
return targetObj instanceof String || targetObj instanceof StringBuilder
|| targetObj instanceof StringBuffer || targetObj instanceof Number
|| targetObj instanceof Boolean;
}
@Override
public AnyData transform(Object targetObj) throws ConvertException {
SimpleData sdata = null;
if(targetObj instanceof CharSequence) {
sdata = new SimpleData(targetObj.toString());
}
else if(targetObj instanceof Number) {
sdata = new SimpleData((Number) targetObj);
}
else if(targetObj instanceof Boolean) {
sdata = new SimpleData((Boolean) targetObj);
}
return new AnyData(sdata);
}
}
@@ -0,0 +1,84 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.obj2mod;
import daxi.moe.app.ConvertException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.logging.Logger;
/**
* @author indroneel
*/
public class SourceEntity {
private static final Logger L = Logger.getLogger(SourceEntity.class.getName());
private final Class<?> sourceType;
private final Map<String, ToMethod> toMethods;
public SourceEntity(Class<?> sourceType) throws ConvertException {
this.sourceType = sourceType;
toMethods = new HashMap<>();
collateAllMethods(sourceType);
}
public SourceEntity(Object srcObj) throws ConvertException {
this(srcObj.getClass());
}
public Class<?> getSourceType() {
return sourceType;
}
public Set<String> getDataKeys() {
return toMethods.keySet();
}
public ToMethod getToMethod(String dataKey) {
return toMethods.get(dataKey);
}
////////////////////////////////////////////////////////////////////////////////////////////////
// Helper methods
private void collateAllMethods(Class<?> type) throws ConvertException {
if(type.getClassLoader() == null) {
// Skip system classes
return;
}
for (Method method : type.getDeclaredMethods()) {
ToMethod tm = ToMethod.of(method);
if(tm != null) {
if(toMethods.containsKey(tm.getDataKey())) {
throw new ConvertException(type.getName(), tm.getMethod().getName(),
"Duplicate getters for data key: " + tm.getDataKey(), null);
}
toMethods.put(tm.getDataKey(), tm);
continue;
}
}
if (type.getSuperclass() != null) {
collateAllMethods(type.getSuperclass());
}
}
}
@@ -0,0 +1,86 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.obj2mod;
import daxi.moe.app.MapTo;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Parameter;
/**
* @author indroneel
*/
public class ToMethod {
private final Method method;
private final String dataKey;
private final Class<?> returnType;
public ToMethod(Method method) {
this.method = method;
MapTo mapping = method.getAnnotation(MapTo.class);
if(mapping == null) {
// If the method does not have the @MapTo annotation, it is not valid for retrieval
throw new IllegalArgumentException();
}
// populate the dataKey field with the value of the @MapTo annotation
dataKey = mapping.value().trim();
if(dataKey.isBlank()) {
// If the data key is blank, it is not a getter method
throw new IllegalArgumentException();
}
int mod = method.getModifiers();
// If the method is abstract, static, or not private, it is not valid for retrieval
if(Modifier.isAbstract(mod) || Modifier.isStatic(mod) || !Modifier.isPrivate(mod)) {
throw new IllegalArgumentException();
}
Parameter[] params = method.getParameters();
if(params.length > 0) {
// If the method takes one or more parameters, it is not valid for retrieval
throw new IllegalArgumentException();
}
returnType = method.getReturnType();
if(returnType == Void.TYPE) {
// If the method returns void, it is not valid for retrieval
throw new IllegalArgumentException();
}
}
public final String getDataKey() {
return dataKey;
}
public final Method getMethod() {
return method;
}
public final Class<?> getReturnType() {
return returnType;
}
public static ToMethod of(Method method) {
try {
return new ToMethod(method);
}
catch (IllegalArgumentException exep) {
return null;
}
}
}
@@ -1,76 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.transform;
import daxi.moe.app.Moe;
import java.util.List;
/**
* A registry for model-to-Java transformers as singletons. It also stores options that were set
* during instatiation of MOE.
*
* @author indroneel
*/
public class M2JGlobals {
private final List<Moe.Options> options;
private M2JSimple simM2j;
private M2JLinear linM2j;
private M2JMapped mapM2j;
private M2JObject objM2j;
public M2JGlobals(List<Moe.Options> options) {
this.options = options;
}
public void setM2J(M2JSimple m2j) {
simM2j = m2j;
}
public void setM2J(M2JLinear m2j) {
linM2j = m2j;
}
public void setM2J(M2JMapped m2j) {
mapM2j = m2j;
}
public void setM2J(M2JObject m2j) {
objM2j = m2j;
}
public boolean hasOption(Moe.Options opt) {
return options.contains(opt);
}
public M2JSimple getM2JSimple() {
return simM2j;
}
public M2JLinear getM2JLinear() {
return linM2j;
}
public M2JMapped getM2JMapped() {
return mapM2j;
}
public M2JObject getM2JObject() {
return objM2j;
}
}
@@ -1,41 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.transform;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* Defines a marker interface for classes that can be used to populate portions of a Java object
* with {@link daxi.moe.model.LinearData}.
*
* @author indroneel
*/
public interface M2JLinear {
/**
* Converts a linear data from the given mapped data into the target object using the specified
* method.
*
* @param data The mapped data that contains the linear data to convert.
* @param targetObj The target object to populate with the converted data.
* @param targetMthd The method to use for populating the target object.
* @return The status of the conversion.
*/
M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
}
@@ -1,41 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.transform;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* Defines a marker interface for classes that can be used to populate portions of a Java object
* with {@link daxi.moe.model.MappedData}.
*
* @author indroneel
*/
public interface M2JMapped {
/**
* Converts a nested mapped data contained within a given mapped data into the target object using
* the specified method.
*
* @param data The mapped data that contains the nested mapped data to convert.
* @param targetObj The target object to populate with the converted data.
* @param targetMthd The method to use for populating the target object.
* @return The status of the conversion.
*/
M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
}
@@ -1,49 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.transform;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* Defines a marker interface for classes that can be used to convert from
* {@link daxi.moe.model.MappedData} to a Java object.
*
* @author indroneel
*/
public interface M2JObject {
/**
* Populates a Java object with data from a {@link MappedData} instance using the specified method.
* @param data the {@link MappedData} instance containing the data to populate the Java object
* @param targetObj the Java object to populate
* @param targetMthd the method to use for populating the Java object
* @return the status of the operation
*/
M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
/**
* Constructs a Java object of the specified type from the given {@link MappedData} instance.
* @param data the {@link MappedData} instance containing the data to populate the Java object
* @param targetType the class of the Java object to construct
* @param <T> the type of the Java object to construct
* @return the constructed Java object of the specified type
*/
<T> T convert(MappedData data, Class<T> targetType);
}
@@ -1,41 +0,0 @@
/*
* Copyright (c) DuxTechnica
*
* Licensed under the DuxTechnica Limited Use Source Code License Agreement (DT-LUSCL); you may not
* use this file except in compliance with the License. You may obtain a copy of the License by
* contacting:
*
* Dux Technica, [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 daxi.moe.lib.transform;
import daxi.moe.model.MappedData;
import java.lang.reflect.Method;
/**
* Defines a marker interface for classes that can be used to populate portions of a Java object
* with {@link daxi.moe.model.SimpleData}.
*
* @author indroneel
*/
public interface M2JSimple {
/**
* Converts a linear data from the given mapped data into the target object using the specified
* method.
*
* @param data the mapped data that contains the simple data to convert
* @param targetObj the object to populate
* @param targetMthd the method to invoke on the target object to set the value
* @return The status of the conversion.
*/
M2JStatus convert(MappedData data, Object targetObj, Method targetMthd);
}
+1
View File
@@ -21,6 +21,7 @@
</properties>
<modules>
<module>moe-api</module>
<module>moe-main</module>
<module>moe-json</module>
<module>moe-yaml</module>