[DEV] continue update

This commit is contained in:
Edouard DUPIN 2021-03-25 18:54:53 +01:00
parent 862decc203
commit 6aa5a0e966
26 changed files with 571 additions and 604 deletions

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?> <?xml version="1.0" encoding="UTF-8"?>
<fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false"> <fileset-config file-format-version="1.2.0" simple-config="true" sync-formatter="false">
<fileset name="all" enabled="true" check-config-name="ewol" local="false"> <fileset name="all" enabled="true" check-config-name="Ewol" local="false">
<file-match-pattern match-pattern="." include-pattern="true"/> <file-match-pattern match-pattern="." include-pattern="true"/>
</fileset> </fileset>
</fileset-config> </fileset-config>

14
ejson.iml Normal file
View File

@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
<sourceFolder url="file://$MODULE_DIR$/test/src" isTestSource="true" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="module" module-name="etk" exported="" />
<orderEntry type="library" scope="TEST" name="org.junit.jupiter:junit-jupiter-api:5.7.1" level="project" />
</component>
</module>

View File

@ -19,22 +19,23 @@ import org.atriasoft.etk.Uri;
public class Ejson { public class Ejson {
/** /**
* Display the Document on console * Display the Document on console
*/ */
public static void display(final JsonNode root) { public static void display(final JsonNode root) {
final StringBuilder tmpp = new StringBuilder(); final StringBuilder tmpp = new StringBuilder();
SerializerJson.serialize(root, tmpp, 0); SerializerJson.serialize(root, tmpp, 0);
Log.info("Generated JSON : \n" + tmpp.toString()); Log.info("Generated JSON : \n" + tmpp.toString());
} }
/** /**
* Generate a string that contain the created XML * Generate a string that contain the created XML
*
* @param data Data where the json is stored * @param data Data where the json is stored
*/ */
public static void generate(final JsonNode root, final StringBuilder data) { public static void generate(final JsonNode root, final StringBuilder data) {
SerializerJson.serialize(root, data, 1); SerializerJson.serialize(root, data, 1);
} }
public static JsonNode parse(final String data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti { public static JsonNode parse(final String data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti {
final Builder builder = new BuilderGeneric(); final Builder builder = new BuilderGeneric();
final ParseJson parser = new ParseJson(builder); final ParseJson parser = new ParseJson(builder);
@ -42,14 +43,16 @@ public class Ejson {
property.setDisplayError(true); property.setDisplayError(true);
return (JsonNode) parser.parse(data, property); return (JsonNode) parser.parse(data, property);
} }
public static JsonNode parse(final Uri data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti { public static JsonNode parse(final Uri data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti {
final Builder builder = new BuilderGeneric(); final Builder builder = new BuilderGeneric();
final ParseJson parser = new ParseJson(builder); final ParseJson parser = new ParseJson(builder);
final ParsingProperty property = new ParsingProperty(); final ParsingProperty property = new ParsingProperty();
property.setDisplayError(true); property.setDisplayError(true);
Log.critical("not implemented...");
return (JsonNode) parser.parse("", property); return (JsonNode) parser.parse("", property);
} }
private Ejson() {} private Ejson() {
}
} }

View File

@ -12,7 +12,7 @@ import java.lang.annotation.Target;
* Ejson annotations generically, and in future also for * Ejson annotations generically, and in future also for
* passing other generic annotation configuration. * passing other generic annotation configuration.
*/ */
@Target({ ElementType.ANNOTATION_TYPE }) @Target(ElementType.ANNOTATION_TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
public @interface EjsonAnnotation { public @interface EjsonAnnotation {
// for now, a pure tag annotation, no parameters // for now, a pure tag annotation, no parameters

View File

@ -9,7 +9,7 @@ import java.lang.annotation.Target;
* Marker annotation that set the element are not managed by default. Need to add @JsonManaged to be enable. * Marker annotation that set the element are not managed by default. Need to add @JsonManaged to be enable.
* *
*/ */
@Target({ ElementType.TYPE }) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation @EjsonAnnotation
public @interface JsonDefaultManaged { public @interface JsonDefaultManaged {

View File

@ -9,7 +9,7 @@ import java.lang.annotation.Target;
* Marker annotation that set the element not found are ignored. * Marker annotation that set the element not found are ignored.
* *
*/ */
@Target({ ElementType.TYPE }) @Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation @EjsonAnnotation
public @interface JsonDefaultOptional { public @interface JsonDefaultOptional {

View File

@ -17,8 +17,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public Object newArray(final Object parent) throws EjsonBuilderException { public Object newArray(final Object parent) throws EjsonBuilderException {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonArray out = new JsonArray(); final JsonArray out = new JsonArray();
elem.add(out); elem.add(out);
return out; return out;
@ -28,8 +27,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public Object newArray(final Object parent, final String nodeName) throws EjsonBuilderException { public Object newArray(final Object parent, final String nodeName) throws EjsonBuilderException {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonArray out = new JsonArray(); final JsonArray out = new JsonArray();
elem.put(nodeName, out); elem.put(nodeName, out);
return out; return out;
@ -39,8 +37,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newBoolean(final Object parent, final boolean value) throws EjsonBuilderException, Exception { public void newBoolean(final Object parent, final boolean value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonBoolean out = new JsonBoolean(value); final JsonBoolean out = new JsonBoolean(value);
elem.add(out); elem.add(out);
return; return;
@ -51,8 +48,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newBoolean(final Object parent, final String nodeName, final boolean value) throws EjsonBuilderException, Exception { public void newBoolean(final Object parent, final String nodeName, final boolean value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonBoolean out = new JsonBoolean(value); final JsonBoolean out = new JsonBoolean(value);
elem.put(nodeName, out); elem.put(nodeName, out);
return; return;
@ -62,8 +58,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNull(final Object parent) throws EjsonBuilderException, Exception { public void newNull(final Object parent) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonNull out = new JsonNull(); final JsonNull out = new JsonNull();
elem.add(out); elem.add(out);
return; return;
@ -74,8 +69,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNull(final Object parent, final String nodeName) throws EjsonBuilderException, Exception { public void newNull(final Object parent, final String nodeName) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonNull out = new JsonNull(); final JsonNull out = new JsonNull();
elem.put(nodeName, out); elem.put(nodeName, out);
return; return;
@ -85,8 +79,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNumber(final Object parent, final double value) throws EjsonBuilderException, Exception { public void newNumber(final Object parent, final double value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonNumber out = new JsonNumber(value); final JsonNumber out = new JsonNumber(value);
elem.add(out); elem.add(out);
return; return;
@ -97,8 +90,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNumber(final Object parent, final long value) throws EjsonBuilderException, Exception { public void newNumber(final Object parent, final long value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonNumber out = new JsonNumber(value); final JsonNumber out = new JsonNumber(value);
elem.add(out); elem.add(out);
return; return;
@ -109,8 +101,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNumber(final Object parent, final String nodeName, final double value) throws EjsonBuilderException, Exception { public void newNumber(final Object parent, final String nodeName, final double value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonNumber out = new JsonNumber(value); final JsonNumber out = new JsonNumber(value);
elem.put(nodeName, out); elem.put(nodeName, out);
return; return;
@ -120,8 +111,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newNumber(final Object parent, final String nodeName, final long value) throws EjsonBuilderException, Exception { public void newNumber(final Object parent, final String nodeName, final long value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonNumber out = new JsonNumber(value); final JsonNumber out = new JsonNumber(value);
elem.put(nodeName, out); elem.put(nodeName, out);
return; return;
@ -131,8 +121,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public Object newObject(final Object parent) throws EjsonBuilderException, Exception { public Object newObject(final Object parent) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonObject out = new JsonObject(); final JsonObject out = new JsonObject();
elem.add(out); elem.add(out);
return out; return out;
@ -142,8 +131,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public Object newObject(final Object parent, final String nodeName) throws EjsonBuilderException, Exception { public Object newObject(final Object parent, final String nodeName) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonObject out = new JsonObject(); final JsonObject out = new JsonObject();
elem.put(nodeName, out); elem.put(nodeName, out);
return out; return out;
@ -158,8 +146,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newString(final Object parent, final String value) throws EjsonBuilderException, Exception { public void newString(final Object parent, final String value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) { if (parent instanceof JsonArray elem) {
final JsonArray elem = (JsonArray) parent;
final JsonString out = new JsonString(value); final JsonString out = new JsonString(value);
elem.add(out); elem.add(out);
return; return;
@ -170,8 +157,7 @@ public class BuilderGeneric implements Builder {
@Override @Override
public void newString(final Object parent, final String nodeName, final String value) throws EjsonBuilderException, Exception { public void newString(final Object parent, final String nodeName, final String value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) { if (parent instanceof JsonObject elem) {
final JsonObject elem = (JsonObject) parent;
final JsonString out = new JsonString(value); final JsonString out = new JsonString(value);
elem.put(nodeName, out); elem.put(nodeName, out);
return; return;

View File

@ -5,10 +5,13 @@
*/ */
package org.atriasoft.ejson.exception; package org.atriasoft.ejson.exception;
import java.io.Serial;
public class EjsonBuilderException extends EjsonException { public class EjsonBuilderException extends EjsonException {
/** /**
* Generate Unique ID for serialization * Generate Unique ID for serialization
*/ */
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public EjsonBuilderException(final String data) { public EjsonBuilderException(final String data) {

View File

@ -5,10 +5,13 @@
*/ */
package org.atriasoft.ejson.exception; package org.atriasoft.ejson.exception;
import java.io.Serial;
public class EjsonException extends Exception { public class EjsonException extends Exception {
/** /**
* Generate Unique ID for serialization * Generate Unique ID for serialization
*/ */
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public EjsonException(final String data) { public EjsonException(final String data) {

View File

@ -5,10 +5,13 @@
*/ */
package org.atriasoft.ejson.exception; package org.atriasoft.ejson.exception;
import java.io.Serial;
public class EjsonNodeDoesNotExist extends EjsonException { public class EjsonNodeDoesNotExist extends EjsonException {
/** /**
* Generate Unique ID for serialization * Generate Unique ID for serialization
*/ */
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
public EjsonNodeDoesNotExist(final String data) { public EjsonNodeDoesNotExist(final String data) {

View File

@ -2,7 +2,10 @@ package org.atriasoft.ejson.exception;
import org.atriasoft.ejson.parser.FilePos; import org.atriasoft.ejson.parser.FilePos;
import java.io.Serial;
public class EjsonParserError extends EjsonBuilderException { public class EjsonParserError extends EjsonBuilderException {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final String dataLine; //!< Parse line error (copy); private final String dataLine; //!< Parse line error (copy);

View File

@ -1,8 +1,10 @@
package org.atriasoft.ejson.exception; package org.atriasoft.ejson.exception;
import java.io.Serial;
import java.util.List; import java.util.List;
public class EjsonParserErrorMulti extends EjsonBuilderException { public class EjsonParserErrorMulti extends EjsonBuilderException {
@Serial
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
private final List<EjsonParserError> errors; // list of errors private final List<EjsonParserError> errors; // list of errors

View File

@ -1,4 +1,4 @@
/** @file /* @file
* @author Edouard DUPIN * @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved * @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file) * @license MPL v2.0 (see license file)
@ -12,11 +12,6 @@ import java.util.List;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist; import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.atriasoft.ejson.internal.Log; import org.atriasoft.ejson.internal.Log;
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
/** /**
* Basic element Node of an XML document lt;YYYYYgt; * Basic element Node of an XML document lt;YYYYYgt;
*/ */
@ -27,32 +22,31 @@ public class JsonArray extends JsonNode {
* Constructor * Constructor
*/ */
public JsonArray() { public JsonArray() {
super(); }
};
/** /**
* add a node at the element (not Attribute (move in the attribute automaticly). * add a node at the element (not Attribute (move in the attribute automaticly).
* @param[in] _node Pointer of the node to add. * @param node Pointer of the node to add.
*/ */
public void add(final JsonNode _node) { public void add(final JsonNode node) {
if (_node == null) { if (node == null) {
Log.error("Try to set an empty node"); Log.error("Try to set an empty node");
return; return;
} }
for (int iii = 0; iii < this.listSub.size(); iii++) { for (final JsonNode jsonNode : this.listSub) {
if (this.listSub.get(iii) == _node) { if (jsonNode == node) {
Log.error("Try to add a node that is already added before !!!"); Log.error("Try to add a node that is already added before !!!");
return; return;
} }
} }
this.listSub.add(_node); this.listSub.add(node);
} }
@Override @Override
public void clear() { public void clear() {
super.clear(); super.clear();
this.listSub.clear(); this.listSub.clear();
}; }
@Override @Override
public JsonArray clone() throws CloneNotSupportedException { public JsonArray clone() throws CloneNotSupportedException {
@ -65,11 +59,11 @@ public class JsonArray extends JsonNode {
/** /**
* get the Node pointer of the element id. * get the Node pointer of the element id.
* @param[in] _id Id of the element. * @param id Id of the element.
* @return true if the Node exist. * @return true if the Node exist.
*/ */
public boolean exist(final int _id) { public boolean exist(final int id) {
if (_id < 0 || _id >= this.listSub.size()) { if (id < 0 || id >= this.listSub.size()) {
return false; return false;
} }
return true; return true;
@ -77,15 +71,15 @@ public class JsonArray extends JsonNode {
/** /**
* get the Node pointer of the element id. * get the Node pointer of the element id.
* @param[in] _id Id of the element. * @param id Id of the element.
* @return Pointer on node. * @return Pointer on node.
* @throws EjsonNodeDoesNotExist The Node does not exist * @throws EjsonNodeDoesNotExist The Node does not exist
*/ */
public JsonNode get(final int _id) throws EjsonNodeDoesNotExist { public JsonNode get(final int id) throws EjsonNodeDoesNotExist {
if (_id < 0 || _id >= this.listSub.size()) { if (id < 0 || id >= this.listSub.size()) {
throw new EjsonNodeDoesNotExist("Node does not exist: " + _id + "/" + this.listSub.size()); throw new EjsonNodeDoesNotExist("Node does not exist: " + id + "/" + this.listSub.size());
} }
return this.listSub.get(_id); return this.listSub.get(id);
} }
/** /**
@ -103,7 +97,7 @@ public class JsonArray extends JsonNode {
/** /**
* Remove all element with this name * Remove all element with this name
* @param[in] index index of nodes to remove. * @param index index of nodes to remove.
*/ */
public void remove(final int index) { public void remove(final int index) {
this.listSub.remove(index); this.listSub.remove(index);
@ -117,4 +111,4 @@ public class JsonArray extends JsonNode {
return this.listSub.size(); return this.listSub.size();
} }
}; }

View File

@ -15,17 +15,15 @@ public class JsonBoolean extends JsonNode {
* Constructor * Constructor
*/ */
public JsonBoolean() { public JsonBoolean() {
super();
this.value = false; this.value = false;
}; }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the boolean * @param data Value of the boolean
*/ */
public JsonBoolean(final boolean _data) { public JsonBoolean(final boolean data) {
super(); setValue(data);
setValue(_data);
} }
@Override @Override
@ -41,4 +39,4 @@ public class JsonBoolean extends JsonNode {
this.value = value; this.value = value;
} }
}; }

View File

@ -15,68 +15,56 @@ public class JsonNumber extends JsonNode {
* Constructor * Constructor
*/ */
public JsonNumber() { public JsonNumber() {
final Long tmp = 0L; this.value = 0L;
this.value = tmp;
};
/**
* Constructor
* @param[in] _data Value of the Number
*/
public JsonNumber(final byte _data) {
super();
final Long tmp = (long) _data;
this.value = tmp;
} }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public JsonNumber(final double _data) { public JsonNumber(final byte data) {
super(); this.value = (long) data;
final Double tmp = (double) _data;
this.value = tmp;
} }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public JsonNumber(final float _data) { public JsonNumber(final double data) {
super(); this.value = (double) data;
final Double tmp = (double) _data;
this.value = tmp;
} }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public JsonNumber(final int _data) { public JsonNumber(final float data) {
super(); this.value = (double) data;
final Long tmp = (long) _data;
this.value = tmp;
} }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public JsonNumber(final long _data) { public JsonNumber(final int data) {
super(); this.value = (long) data;
final Long tmp = _data;
this.value = tmp;
} }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public JsonNumber(final short _data) { public JsonNumber(final long data) {
super(); final Long tmp = data;
final Long tmp = (long) _data; this.value = data;
this.value = tmp; }
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final short data) {
this.value = (long) data;
} }
@Override @Override
@ -85,16 +73,15 @@ public class JsonNumber extends JsonNode {
} }
public double getValue() { public double getValue() {
if (this.value instanceof Double) { if (this.value instanceof Double tmp) {
return (Double) this.value; return tmp;
} }
return (Long) this.value; return (Long) this.value;
} }
public long getValueLong() { public long getValueLong() {
if (this.value instanceof Double) { if (this.value instanceof Double tmp) {
final double val = (Double) this.value; return (long) ((double) tmp);
return (long) val;
} }
return (Long) this.value; return (Long) this.value;
} }
@ -109,56 +96,50 @@ public class JsonNumber extends JsonNode {
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final byte _data) { public void setValue(final byte data) {
final Long tmp = (long) _data; this.value = (long) data;
this.value = tmp;
} }
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final double _data) { public void setValue(final double data) {
final Double tmp = (double) _data; this.value = (double) data;
this.value = tmp;
} }
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final float _data) { public void setValue(final float data) {
final Double tmp = (double) _data; this.value = (double) data;
this.value = tmp;
} }
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final int _data) { public void setValue(final int data) {
final Long tmp = (long) _data; this.value = (long) data;
this.value = tmp;
} }
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final long _data) { public void setValue(final long data) {
final Long tmp = _data; this.value = data;
this.value = tmp;
} }
/** /**
* Set the value of the Number element * Set the value of the Number element
* @param[in] _data Value of the Number * @param data Value of the Number
*/ */
public void setValue(final short _data) { public void setValue(final short data) {
final Long tmp = (long) _data; this.value = (long) data;
this.value = tmp;
} }
}; }

View File

@ -18,17 +18,16 @@ import org.atriasoft.ejson.internal.Log;
* @license MPL v2.0 (see license file) * @license MPL v2.0 (see license file)
*/ */
/** /**
* Basic element Node of an XML document lt;YYYYYgt; * Basic element Node of an JSON document &lt;&gt;
*/ */
public class JsonObject extends JsonNode { public class JsonObject extends JsonNode {
protected Map<String, JsonNode> listSub = new LinkedHashMap<>(); //!< List of subNodes; protected Map<String, JsonNode> listSub = new LinkedHashMap<>(); // !< List of subNodes;
/** /**
* Constructor * Constructor
*/ */
public JsonObject() { public JsonObject() {
super(); }
};
@Override @Override
public void clear() { public void clear() {
@ -49,29 +48,32 @@ public class JsonObject extends JsonNode {
} }
}); });
return out; return out;
};
/**
* get an element with his name (work only with Element)
* @param[in] _name Name of the element that is requested
* @return true if the Node exist.
*/
public boolean exist(final String _name) {
return this.listSub.get(_name) != null;
} }
/** /**
* get an element with his name (work only with Element) * get an element with his name (work only with Element)
* @param[in] _name Name of the element that is requested *
* @param name Name of the element that is requested
* @return true if the Node exist.
*/
public boolean exist(final String name) {
return this.listSub.get(name) != null;
}
/**
* get an element with his name (work only with Element)
*
* @param name Name of the element that is requested
* @return Pointer on the node. * @return Pointer on the node.
* @throws EjsonNodeDoesNotExist The Node does not exist * @throws EjsonNodeDoesNotExist The Node does not exist
*/ */
public JsonNode get(final String _name) throws EjsonNodeDoesNotExist { public JsonNode get(final String name) throws EjsonNodeDoesNotExist {
return this.listSub.get(_name); return this.listSub.get(name);
} }
/** /**
* Get the list of the sub-nodes. * Get the list of the sub-nodes.
*
* @return List of current nodes. * @return List of current nodes.
*/ */
public Map<String, JsonNode> getNodes() { public Map<String, JsonNode> getNodes() {
@ -84,32 +86,36 @@ public class JsonObject extends JsonNode {
} }
/** /**
* add a node at the element (not Attribute (move in the attribute automaticly). * add a node at the element (not Attribute (move in the attribute automaticly).
* @param[in] nodeName Name of the node. *
* @param[in] _node Node to add. * @param nodeName Name of the node.
* @param node Node to add.
*/ */
public void put(final String nodeName, final JsonNode _node) { public void put(final String nodeName, final JsonNode node) {
if (_node == null) { if (node == null) {
Log.error("Try to set an empty node"); Log.error("Try to set an empty node");
return; return;
} }
this.listSub.put(nodeName, _node); this.listSub.put(nodeName, node);
} }
/** /**
* Remove all element with this name * Remove all element with this name
* @param[in] _nodeName Name of nodes to remove. *
* @param nodeName Name of nodes to remove.
*/ */
public void remove(final String nodeName) { public void remove(final String nodeName) {
this.listSub.remove(nodeName); this.listSub.remove(nodeName);
} }
/** /**
* get the number of sub element in the node (can be Comment ; Element ; Text :Declaration). * get the number of sub element in the node (can be Comment ; Element ; Text
* :Declaration).
*
* @return a number >=0. * @return a number >=0.
*/ */
public int size() { public int size() {
return this.listSub.size(); return this.listSub.size();
} }
}; }

View File

@ -15,17 +15,15 @@ public class JsonString extends JsonNode {
* Constructor * Constructor
*/ */
public JsonString() { public JsonString() {
super();
setValue(""); setValue("");
}; }
/** /**
* Constructor * Constructor
* @param[in] _data Value of the string * @param data Value of the string
*/ */
public JsonString(final String _data) { public JsonString(final String data) {
super(); setValue(data);
setValue(_data);
} }
@Override @Override
@ -41,4 +39,4 @@ public class JsonString extends JsonNode {
this.value = value; this.value = value;
} }
}; }

View File

@ -28,48 +28,48 @@ public class FilePos {
/** /**
* initialize constructor * initialize constructor
* @param[in] _line Line in the file * @param line Line in the file
* @param[in] _col Colomn in the file * @param col Colomn in the file
*/ */
public FilePos(final int _line, final int _col) { public FilePos(final int line, final int col) {
this.col = _col; this.col = col;
this.line = _line; this.line = line;
} }
/** /**
* Addition operator * Addition operator
* @param[in] _obj Addition object.. * @param obj Addition object..
* @return Reference on this * @return Reference on this
*/ */
public FilePos add(final FilePos _obj) { public FilePos add(final FilePos obj) {
if (_obj.line == 0) { if (obj.line == 0) {
this.col += _obj.col; this.col += obj.col;
} else { } else {
this.col = _obj.col; this.col = obj.col;
this.line += _obj.line; this.line += obj.line;
} }
return this; return this;
} }
/** /**
* Colomn addition operator * Colomn addition operator
* @param[in] _col Number of colomn to add * @param col Number of colomn to add
* @return Reference on this * @return Reference on this
*/ */
public FilePos add(final int _col) { public FilePos add(final int col) {
this.col += _col; this.col += col;
return this; return this;
} }
/** /**
* Check if the value is a new line and update internal property * Check if the value is a new line and update internal property
* @param[in] _val Char value to check * @param val Char value to check
* @return true We find a new line * @return true We find a new line
* @return false We NOT find a new line * @return false We NOT find a new line
*/ */
public boolean check(final Character _val) { public boolean check(final Character val) {
this.col++; this.col++;
if (_val == '\n') { if (val == '\n') {
newLine(); newLine();
return true; return true;
} }
@ -153,23 +153,23 @@ public class FilePos {
/** /**
* Asignment operator * Asignment operator
* @param[in] _obj Object to copy * @param obj Object to copy
* @return Reference on this * @return Reference on this
*/ */
public FilePos set(final FilePos _obj) { public FilePos set(final FilePos obj) {
this.col = _obj.col; this.col = obj.col;
this.line = _obj.line; this.line = obj.line;
return this; return this;
} }
/** /**
* Setter of specific data * Setter of specific data
* @param[in] _line Line in the file * @param line Line in the file
* @param[in] _col Colomn in the file * @param col Colomn in the file
*/ */
public void set(final int _line, final int _col) { public void set(final int line, final int col) {
this.col = _col; this.col = col;
this.line = _line; this.line = line;
} }
@Override @Override
@ -182,4 +182,4 @@ public class FilePos {
return out; return out;
} }
}; }

View File

@ -14,109 +14,109 @@ public class ParseJson {
this.builder = builder; this.builder = builder;
} }
boolean iParseArray(final Object parent, final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws Exception { boolean iParseArray(final Object parent, final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws Exception {
for (int iii = _pos.value + 1; iii < _data.length(); iii++) { for (int iii = pos.value + 1; iii < data.length(); iii++) {
//Log.verbose("parse Array: '" + _data.charAt(iii) + "'"); //Log.verbose("parse Array: '" + data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (_data.charAt(iii) == ' ' || _data.charAt(iii) == '\t' || _data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') { if (data.charAt(iii) == ' ' || data.charAt(iii) == '\t' || data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
// white space == > nothing to do ... // white space == > nothing to do ...
} else if (_data.charAt(iii) == '#') { } else if (data.charAt(iii) == '#') {
// comment Line ... // comment Line ...
for (iii++; iii < _data.length(); iii++) { for (iii++; iii < data.length(); iii++) {
if (_data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') { if (data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
break; break;
} }
} }
} else if (_data.charAt(iii) == ']') { } else if (data.charAt(iii) == ']') {
// find end of value: // find end of value:
_pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed
return true; return true;
} else if (_data.charAt(iii) == '{') { } else if (data.charAt(iii) == '{') {
_pos.value = iii + 1; pos.value = iii + 1;
// find an object: // find an object:
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseObject(null, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseObject(null, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
final Object obj = this.builder.newObject(parent); final Object obj = this.builder.newObject(parent);
if (iParseObject(obj, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseObject(obj, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} }
iii = _pos.value; iii = pos.value;
} else if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') { } else if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty); final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) { if (dataString == null) {
return false; return false;
} }
} else { } else {
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty); final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) { if (dataString == null) {
return false; return false;
} }
this.builder.newString(parent, dataString); this.builder.newString(parent, dataString);
} }
iii = _pos.value; iii = pos.value;
} else if (_data.charAt(iii) == '[') { } else if (data.charAt(iii) == '[') {
_pos.value = iii + 1; pos.value = iii + 1;
// find an object: // find an object:
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseArray(null, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseArray(null, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
final Object obj = this.builder.newArray(parent); final Object obj = this.builder.newArray(parent);
if (iParseArray(obj, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseArray(obj, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} }
iii = _pos.value; iii = pos.value;
} else if (_data.charAt(iii) == 'f' || _data.charAt(iii) == 't') { } else if (data.charAt(iii) == 'f' || data.charAt(iii) == 't') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty); final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) { if (dataBoolean == null) {
return false; return false;
} }
} else { } else {
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty); final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) { if (dataBoolean == null) {
return false; return false;
} }
this.builder.newBoolean(parent, dataBoolean); this.builder.newBoolean(parent, dataBoolean);
} }
iii = _pos.value; iii = pos.value;
} else if (_data.charAt(iii) == 'n') { } else if (data.charAt(iii) == 'n') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) { if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) { if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false; return false;
} }
this.builder.newNull(parent); this.builder.newNull(parent);
} }
iii = _pos.value; iii = pos.value;
} else if (true == Tools.checkNumber(_data.charAt(iii))) { } else if (Tools.checkNumber(data.charAt(iii))) {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty); final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) { if (dataNumber == null) {
return false; return false;
} }
} else { } else {
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty); final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) { if (dataNumber == null) {
return false; return false;
} }
@ -126,297 +126,290 @@ public class ParseJson {
this.builder.newNumber(parent, (Long) dataNumber); this.builder.newNumber(parent, (Long) dataNumber);
} }
} }
iii = _pos.value; iii = pos.value;
} else if (_data.charAt(iii) == ',') { } else if (data.charAt(iii) == ',') {
// find Separator : Restart cycle ... // find Separator : Restart cycle ...
// TODO : check if element are separated with ',' // TODO : check if element are separated with ','
} else if (_data.charAt(iii) == '}') { } else if (data.charAt(iii) == '}') {
// find an error .... // find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "Find '}' with no element in the element... Check if is not a ']' element (to stop array)")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "Find '}' with no element in the element... Check if is not a ']' element (to stop array)"));
// move the curent index // move the curent index
_pos.value = iii + 1; pos.value = iii + 1;
return false; return false;
} else { } else {
// find an error .... // find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii + 1), _filePos, "Find '" + _data.charAt(iii) + "' with no element in the array...")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii + 1), filePos, "Find '" + data.charAt(iii) + "' with no element in the array..."));
// move the curent index // move the curent index
_pos.value = iii + 1; pos.value = iii + 1;
return false; return false;
} }
} }
_pos.value = _data.length(); pos.value = data.length();
return false; return false;
} }
Boolean iParseBoolean(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException { Boolean iParseBoolean(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
if (_data.charAt(_pos.value) == 't' && _pos.value + 3 < _data.length() && _data.charAt(_pos.value + 1) == 'r' && _data.charAt(_pos.value + 2) == 'u' && _data.charAt(_pos.value + 3) == 'e') { if (data.charAt(pos.value) == 't' && pos.value + 3 < data.length() && data.charAt(pos.value + 1) == 'r' && data.charAt(pos.value + 2) == 'u' && data.charAt(pos.value + 3) == 'e') {
_pos.value += 3; pos.value += 3;
_filePos.add(3); filePos.add(3);
return true; return true;
} }
if (_data.charAt(_pos.value) == 'f' && _pos.value + 4 < _data.length() && _data.charAt(_pos.value + 1) == 'a' && _data.charAt(_pos.value + 2) == 'l' && _data.charAt(_pos.value + 3) == 's' if (data.charAt(pos.value) == 'f' && pos.value + 4 < data.length() && data.charAt(pos.value + 1) == 'a' && data.charAt(pos.value + 2) == 'l' && data.charAt(pos.value + 3) == 's'
&& _data.charAt(_pos.value + 4) == 'e') { && data.charAt(pos.value + 4) == 'e') {
_pos.value += 4; pos.value += 4;
_filePos.add(4); filePos.add(4);
return false; return false;
} }
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "boolean parsing error ...")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "boolean parsing error ..."));
return null; return null;
} }
boolean iParseNull(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException { boolean iParseNull(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
if (_pos.value + 3 >= _data.length()) { if (pos.value + 3 >= data.length()) {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "can not parse null !!! ")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "can not parse null !!! "));
return false; return false;
} }
if (_data.charAt(_pos.value) != 'n' || _data.charAt(_pos.value + 1) != 'u' || _data.charAt(_pos.value + 2) != 'l' || _data.charAt(_pos.value + 3) != 'l') { if (data.charAt(pos.value) != 'n' || data.charAt(pos.value + 1) != 'u' || data.charAt(pos.value + 2) != 'l' || data.charAt(pos.value + 3) != 'l') {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "Not a corect 'null' element")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "Not a corect 'null' element"));
return false; return false;
} }
_pos.value += 3; pos.value += 3;
_filePos.add(3); filePos.add(3);
return true; return true;
} }
Object iParseNumber(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException { Object iParseNumber(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
String tmpVal = ""; String tmpVal = "";
boolean isDouble = false; boolean isDouble = false;
for (int iii = _pos.value; iii < _data.length(); iii++) { for (int iii = pos.value; iii < data.length(); iii++) {
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (Tools.checkNumber(_data.charAt(iii)) == true) { if (!Tools.checkNumber(data.charAt(iii))) {
if (_data.charAt(iii) == '.' || _data.charAt(iii) == 'e' || _data.charAt(iii) == '^') { pos.value = iii - 1;
isDouble = true; if (isDouble) {
}
tmpVal += _data.charAt(iii);
} else {
_pos.value = iii - 1;
if (isDouble == true) {
return Double.valueOf(tmpVal); return Double.valueOf(tmpVal);
} else { } else {
return Long.valueOf(tmpVal); return Long.valueOf(tmpVal);
} }
} }
if (data.charAt(iii) == '.' || data.charAt(iii) == 'e' || data.charAt(iii) == '^') {
isDouble = true;
}
tmpVal += data.charAt(iii);
} }
_pos.value = _data.length(); pos.value = data.length();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "get end of string whithout fincding end of quote")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "get end of string whithout fincding end of quote"));
return null; return null;
} }
boolean iParseObject(final Object parent, final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws Exception { boolean iParseObject(final Object parent, final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws Exception {
statusParsing mode = statusParsing.parseName; StatusParsing mode = StatusParsing.parseName;
String currentName = ""; StringBuilder currentName = new StringBuilder();
boolean standalone = true; boolean standalone = true;
int startPos = _pos.value + 1; int startPos = pos.value + 1;
if (_data.charAt(_pos.value) != '{') { // when the main node call it, it can be start with != '{' if (data.charAt(pos.value) != '{') { // when the main node call it, it can be start with != '{'
standalone = false; standalone = false;
startPos = _pos.value; startPos = pos.value;
} }
for (int iii = startPos; iii < _data.length(); iii++) { for (int iii = startPos; iii < data.length(); iii++) {
//Log.verbose("parse Object: '" + _data.charAt(iii) + "'"); //Log.verbose("parse Object: '" + data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
final FilePos tmpPos; final FilePos tmpPos;
if (_data.charAt(iii) == ' ' || _data.charAt(iii) == '\t' || _data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') { if (data.charAt(iii) == ' ' || data.charAt(iii) == '\t' || data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
// white space == > nothing to do ... // white space == > nothing to do ...
} else if (_data.charAt(iii) == '#') { } else if (data.charAt(iii) == '#') {
// comment Line ... // comment Line ...
for (iii++; iii < _data.length(); iii++) { for (iii++; iii < data.length(); iii++) {
if (_data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') { if (data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
break; break;
} }
} }
} else if (_data.charAt(iii) == '}') { } else if (data.charAt(iii) == '}') {
// find end of value: // find end of value:
_pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed
return true; return true;
} else if (mode == statusParsing.parseName) { } else if (mode == StatusParsing.parseName) {
if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') { if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
final char startValue = _data.charAt(iii); final char startValue = data.charAt(iii);
currentName = ""; currentName = new StringBuilder();
for (iii++; iii < _data.length(); iii++) { for (iii++; iii < data.length(); iii++) {
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (_data.charAt(iii) == startValue) { if (data.charAt(iii) == startValue) {
mode = statusParsing.parseMiddle; mode = StatusParsing.parseMiddle;
break; break;
} else {
currentName += _data.charAt(iii);
} }
currentName.append(data.charAt(iii));
} }
} else if (Tools.checkString(_data.charAt(iii))) { } else if (Tools.checkString(data.charAt(iii))) {
currentName += _data.charAt(iii); currentName.append(data.charAt(iii));
for (iii++; iii < _data.length(); iii++) { for (iii++; iii < data.length(); iii++) {
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (false == Tools.checkString(_data.charAt(iii))) { if (!Tools.checkString(data.charAt(iii))) {
mode = statusParsing.parseMiddle; mode = StatusParsing.parseMiddle;
iii--; iii--;
break; break;
} else {
currentName += _data.charAt(iii);
} }
currentName.append(data.charAt(iii));
} }
} else { } else {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "element unknow ...")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "element unknow ..."));
_pos.value = iii; pos.value = iii;
return false; return false;
} }
} else if (mode == statusParsing.parseMiddle) { } else if (mode == StatusParsing.parseMiddle) {
if (_data.charAt(iii) == ':') { if (data.charAt(iii) != ':') {
mode = statusParsing.parseValue; parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "separator is not ':'"));
} else {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "separator is not ':'"));
return false; return false;
} }
} else if (mode == statusParsing.parseValue) { mode = StatusParsing.parseValue;
if (_data.charAt(iii) == '{') { } else if (mode == StatusParsing.parseValue) {
_pos.value = iii + 1; if (data.charAt(iii) == '{') {
pos.value = iii + 1;
// find an object: // find an object:
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseObject(null, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseObject(null, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
final Object obj = this.builder.newObject(parent, currentName); final Object obj = this.builder.newObject(parent, currentName.toString());
if (iParseObject(obj, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseObject(obj, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') { } else if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty); final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) { if (dataString == null) {
return false; return false;
} }
} else { } else {
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty); final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) { if (dataString == null) {
return false; return false;
} }
this.builder.newString(parent, currentName, dataString); this.builder.newString(parent, currentName.toString(), dataString);
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (_data.charAt(iii) == '[') { } else if (data.charAt(iii) == '[') {
_pos.value = iii + 1; pos.value = iii + 1;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseArray(null, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseArray(null, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
final Object obj = this.builder.newArray(parent, currentName); final Object obj = this.builder.newArray(parent, currentName.toString());
if (iParseArray(obj, _data, _pos, _filePos, parsingProperty) == false) { if (!iParseArray(obj, data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (_data.charAt(iii) == 'f' || _data.charAt(iii) == 't') { } else if (data.charAt(iii) == 'f' || data.charAt(iii) == 't') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty); final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) { if (dataBoolean == null) {
return false; return false;
} }
} else { } else {
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty); final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) { if (dataBoolean == null) {
return false; return false;
} }
this.builder.newBoolean(parent, currentName, dataBoolean); this.builder.newBoolean(parent, currentName.toString(), dataBoolean);
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (_data.charAt(iii) == 'n') { } else if (data.charAt(iii) == 'n') {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) { if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false; return false;
} }
} else { } else {
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) { if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false; return false;
} }
this.builder.newNull(parent, currentName); this.builder.newNull(parent, currentName.toString());
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (true == Tools.checkNumber(_data.charAt(iii))) { } else if (Tools.checkNumber(data.charAt(iii))) {
_pos.value = iii; pos.value = iii;
if (parent == null) { if (parent == null) {
// continue parsing without registering object ... // continue parsing without registering object ...
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty); final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) { if (dataNumber == null) {
return false; return false;
} }
} else { } else {
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty); final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) { if (dataNumber == null) {
return false; return false;
} }
if (dataNumber instanceof Double) { if (dataNumber instanceof Double) {
this.builder.newNumber(parent, currentName, (Double) dataNumber); this.builder.newNumber(parent, currentName.toString(), (Double) dataNumber);
} else if (dataNumber instanceof Long) { } else if (dataNumber instanceof Long) {
this.builder.newNumber(parent, currentName, (Long) dataNumber); this.builder.newNumber(parent, currentName.toString(), (Long) dataNumber);
} }
} }
iii = _pos.value; iii = pos.value;
currentName = ""; currentName = new StringBuilder();
} else if (_data.charAt(iii) == ',') { } else if (data.charAt(iii) == ',') {
// find Separator : Restart cycle ... // find Separator : Restart cycle ...
mode = statusParsing.parseName; mode = StatusParsing.parseName;
currentName = ""; currentName = new StringBuilder();
} else { } else {
// find an error .... // find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "Find '" + _data.charAt(iii) + "' with no element in the element...")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "Find '" + data.charAt(iii) + "' with no element in the element..."));
// move the curent index // move the curent index
_pos.value = iii + 1; pos.value = iii + 1;
return false; return false;
} }
} }
} }
_pos.value = _data.length(); pos.value = data.length();
if (standalone == false) { return !standalone;
return true;
}
return false;
} }
String iParseString(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException { String iParseString(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
final Character end = _data.charAt(_pos.value); final Character end = data.charAt(pos.value);
boolean backslashPrevious = false; boolean backslashPrevious = false;
String out = ""; StringBuilder out = new StringBuilder();
for (int iii = _pos.value + 1; iii < _data.length(); iii++) { for (int iii = pos.value + 1; iii < data.length(); iii++) {
//Log.verbose("parse String: '" + _data.charAt(iii) + "'"); //Log.verbose("parse String: '" + data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (_data.charAt(iii) == '\\') { if (data.charAt(iii) == '\\') {
if (backslashPrevious == true) { if (backslashPrevious) {
out += '\\'; out.append('\\');
backslashPrevious = false; backslashPrevious = false;
} else { } else {
backslashPrevious = true; backslashPrevious = true;
} }
} else if (_data.charAt(iii) != end) { } else if (data.charAt(iii) != end) {
if (backslashPrevious == true) { if (backslashPrevious) {
out += '\\'; out.append('\\');
backslashPrevious = false; backslashPrevious = false;
} }
out += _data.charAt(iii); out.append(data.charAt(iii));
} else if (backslashPrevious == true) { } else if (backslashPrevious) {
out += '"'; out.append('"');
backslashPrevious = false; backslashPrevious = false;
} else { } else {
_pos.value = iii; pos.value = iii;
return out; return out.toString();
} }
} }
_pos.value = _data.length(); pos.value = data.length();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "get end of string whithout fincding end of quote")); parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "get end of string whithout fincding end of quote"));
return null; return null;
} }
@ -429,8 +422,8 @@ public class ParseJson {
final Object rootNode = this.builder.newRoot(); final Object rootNode = this.builder.newRoot();
iParseObject(rootNode, data, parsePos, pos, property); iParseObject(rootNode, data, parsePos, pos, property);
if (property.isErrorDetected() == true) { if (property.isErrorDetected()) {
if (property.isThrowOnError() == true) { if (property.isThrowOnError()) {
throw new EjsonParserErrorMulti("Parsing error multiple error detected", property.getErrors()); throw new EjsonParserErrorMulti("Parsing error multiple error detected", property.getErrors());
} }
return null; return null;
@ -438,10 +431,8 @@ public class ParseJson {
return rootNode; return rootNode;
} }
}; }
enum statusParsing { enum StatusParsing {
parseName, parseMiddle, parseName, parseValue,
parseMiddle,
parseValue,
} }

View File

@ -10,16 +10,16 @@ import org.atriasoft.ejson.internal.Log;
public class ParsingProperty { public class ParsingProperty {
/// check the case sensitive of the nodes (end marker) and attribute (duplicates) /// check the case sensitive of the nodes (end marker) and attribute (duplicates)
private boolean caseSensitive = true; private boolean caseSensitive = true;
// Mode to store the Element name or the Attibute name
private StoreMode storeMode = StoreMode.NORMAL;
/// write error when not throw on error.
private boolean writeError = false;
/// throw when an error when it is detected (if permissive XML it throw only at the end of parsing).
private boolean throwOnError = true;
/// Permissive XML parsing (allows some errors must not be critical).
private boolean permisiveXML = false;
// List of all error detected // List of all error detected
private final List<EjsonParserError> errors = new ArrayList<>(); private final List<EjsonParserError> errors = new ArrayList<>();
/// Permissive XML parsing (allows some errors must not be critical).
private boolean permisiveXML = false;
// Mode to store the Element name or the Attibute name
private StoreMode storeMode = StoreMode.NORMAL;
/// throw when an error when it is detected (if permissive XML it throw only at the end of parsing).
private boolean throwOnError = true;
/// write error when not throw on error.
private boolean writeError = false;
/** /**
* Constructor * Constructor
@ -48,23 +48,23 @@ public class ParsingProperty {
*/ */
public boolean createError(final EjsonParserError error) throws EjsonParserError { public boolean createError(final EjsonParserError error) throws EjsonParserError {
// need display the error // need display the error
if (this.writeError == true) { if (this.writeError) {
displayError(error); displayError(error);
} }
// need throw the error // need throw the error
if (this.throwOnError == true && this.permisiveXML == false) { if (this.throwOnError && !this.permisiveXML) {
throw error; throw error;
} }
// Keep it in case // Keep it in case
this.errors.add(error); this.errors.add(error);
return this.permisiveXML == false; return !this.permisiveXML;
} }
/** /**
* Request Display in log all the errors. * Request Display in log all the errors.
*/ */
public void displayError() { public void displayError() {
this.errors.forEach(o -> displayError(o)); this.errors.forEach(this::displayError);
} }
/** /**
@ -113,7 +113,7 @@ public class ParsingProperty {
* @return true if some error are stored. * @return true if some error are stored.
*/ */
public boolean isErrorDetected() { public boolean isErrorDetected() {
return this.errors.isEmpty() == false; return !this.errors.isEmpty();
} }
/** /**
@ -134,18 +134,18 @@ public class ParsingProperty {
/** /**
* Enable or diasable the case sensitive (must be done before the call of parsing) * Enable or diasable the case sensitive (must be done before the call of parsing)
* @param[in] _val true if enable; false else. * @param val true if enable; false else.
*/ */
public void setCaseSensitive(final boolean _val) { public void setCaseSensitive(final boolean val) {
this.caseSensitive = _val; this.caseSensitive = val;
} }
/** /**
* Set the display of the error when detected. * Set the display of the error when detected.
* @param[in] _value true: display error, false not display error (get it at end) * @param value true: display error, false not display error (get it at end)
*/ */
public void setDisplayError(final boolean _value) { public void setDisplayError(final boolean value) {
this.writeError = _value; this.writeError = value;
} }
/** /**

View File

@ -3,49 +3,45 @@ package org.atriasoft.ejson.parser;
public class Tools { public class Tools {
/** /**
* add indentation of the string input. * add indentation of the string input.
* @param[in,out] _data String where the indentation is done. * @param data String where the indentation is done.
* @param[in] _indent Number of tab to add at the string. * @param indent Number of tab to add at the string.
*/ */
public static void addIndent(final StringBuilder _data, final int _indent) { public static void addIndent(final StringBuilder data, final int indent) {
for (int iii = 0; iii < _indent; iii++) { data.append("\t".repeat(Math.max(0, indent)));
_data.append("\t");
}
} }
/** /**
* check if an element or attribute is availlable (not : !"#$%&'()*+,/;<=>?@[\]^`{|}~ \\n\\t\\r and for first char : not -.0123456789). * check if an element or attribute is availlable (not : !"#$%&'()*+,/;<=>?@[\]^`{|}~ \\n\\t\\r and for first char : not -.0123456789).
* @param[in] _val Value to check the conformity. * @param val Value to check the conformity.
* @param[in] _firstChar True if the element check is the first char. * @param firstChar True if the element check is the first char.
* @return true The value can be a part of attribute name * @return true The value can be a part of attribute name / false The value can NOT be a part of attribute name
* @return false The value can NOT be a part of attribute name
*/ */
public static boolean checkAvaillable(final Character _val, final boolean _firstChar) { public static boolean checkAvaillable(final Character val, final boolean firstChar) {
if (_val == '!' || _val == '"' || _val == '#' || _val == '$' || _val == '%' || _val == '&' || _val == '\'' // ' if (val == '!' || val == '"' || val == '#' || val == '$' || val == '%' || val == '&' || val == '\'' // '
|| _val == '(' || _val == ')' || _val == '*' || _val == '+' || _val == ',' || _val == '/' || _val == ';' || _val == '<' || _val == '=' || _val == '>' || _val == '?' || _val == '@' || val == '(' || val == ')' || val == '*' || val == '+' || val == ',' || val == '/' || val == ';' || val == '<' || val == '=' || val == '>' || val == '?' || val == '@' || val == '['
|| _val == '[' || _val == '\\' || _val == ']' || _val == '^' || _val == '`' || _val == '{' || _val == '|' || _val == '}' || _val == '~' || _val == ' ' || _val == '\n' || _val == '\t' || val == '\\' || val == ']' || val == '^' || val == '`' || val == '{' || val == '|' || val == '}' || val == '~' || val == ' ' || val == '\n' || val == '\t' || val == '\r') {
|| _val == '\r') {
return false; return false;
} }
if (_firstChar == true) { if (firstChar) {
if (_val == '-' || _val == '.' || (_val >= '0' && _val <= '9')) { if (val == '-' || val == '.' || (val >= '0' && val <= '9')) {
return false; return false;
} }
} }
return true; return true;
} }
public static boolean checkNumber(final Character _val) { public static boolean checkNumber(final Character val) {
if (_val == '-' || _val == '+' || _val == 'e' || _val == '.' || (_val >= '0' && _val <= '9')) { if (val == '-' || val == '+' || val == 'e' || val == '.' || (val >= '0' && val <= '9')) {
return true; return true;
} }
return false; return false;
} }
public static boolean checkString(final Character _val) { public static boolean checkString(final Character val) {
if (_val == '!' || _val == '"' || _val == '#' || _val == '$' || _val == '%' || _val == '&' || _val == '\'' // ' if (val == '!' || val == '"' || val == '#' || val == '$' || val == '%' || val == '&' || val == '\'' // '
|| _val == '(' || _val == ')' || _val == '*' || _val == '+' || _val == ',' || _val == '/' || _val == ':' || _val == ';' || _val == '<' || _val == '=' || _val == '>' || _val == '?' || val == '(' || val == ')' || val == '*' || val == '+' || val == ',' || val == '/' || val == ':' || val == ';' || val == '<' || val == '=' || val == '>' || val == '?' || val == '@'
|| _val == '@' || _val == '[' || _val == '\\' || _val == ']' || _val == '^' || _val == '`' || _val == '{' || _val == '|' || _val == '}' || _val == '~' || _val == ' ' || _val == '\n' || val == '[' || val == '\\' || val == ']' || val == '^' || val == '`' || val == '{' || val == '|' || val == '}' || val == '~' || val == ' ' || val == '\n' || val == '\t'
|| _val == '\t' || _val == '\r') { || val == '\r') {
return false; return false;
} }
return true; return true;
@ -57,41 +53,40 @@ public class Tools {
/** /**
* count the number of white char in the string from the specify position (stop at the first element that is not a white char) * count the number of white char in the string from the specify position (stop at the first element that is not a white char)
* @param[in] _data Data to parse. * @param data Data to parse.
* @param[in] _pos Start position in the string. * @param pos Start position in the string.
* @param[out] _filePos new poistion of te file to add. * @param filePos new poistion of te file to add.
* @return number of white element. * @return number of white element.
*/ */
public static int countWhiteChar(final String _data, final int _pos, final FilePos _filePos) { public static int countWhiteChar(final String data, final int pos, final FilePos filePos) {
_filePos.clear(); filePos.clear();
int white = 0; int white = 0;
for (int iii = _pos; iii < _data.length(); iii++) { for (int iii = pos; iii < data.length(); iii++) {
_filePos.check(_data.charAt(iii)); filePos.check(data.charAt(iii));
if (Tools.isWhiteChar(_data.charAt(iii)) == true) { if (!Tools.isWhiteChar(data.charAt(iii))) {
white++;
} else {
break; break;
} }
white++;
} }
_filePos.decrement(); filePos.decrement();
return white; return white;
} }
public static String createPosPointer(final String _line, final int _pos) { public static String createPosPointer(final String line, final int pos) {
String out = ""; final StringBuilder out = new StringBuilder();
int iii; int iii;
for (iii = 0; iii < _pos && iii < _line.length(); iii++) { for (iii = 0; iii < pos && iii < line.length(); iii++) {
if (_line.charAt(iii) == '\t') { if (line.charAt(iii) == '\t') {
out += "\t"; out.append("\t");
} else { } else {
out += " "; out.append(" ");
} }
} }
for (; iii < _pos; iii++) { for (; iii < pos; iii++) {
out += " "; out.append(" ");
} }
out += "^"; out.append("^");
return out; return out.toString();
} }
// based on this: https://stackoverflow.com/questions/4052840/most-efficient-way-to-make-the-first-character-of-a-string-lower-case // based on this: https://stackoverflow.com/questions/4052840/most-efficient-way-to-make-the-first-character-of-a-string-lower-case
@ -99,67 +94,61 @@ public class Tools {
if (string == null || string.length() == 0) { if (string == null || string.length() == 0) {
return string; return string;
} }
final char c[] = string.toCharArray(); final char[] c = string.toCharArray();
c[0] = Character.toLowerCase(c[0]); c[0] = Character.toLowerCase(c[0]);
return new String(c); return new String(c);
} }
/** /**
* Display the cuurent element that is curently parse. * Display the current element that is currently parse.
* @param[in] _val Char that is parsed. * @param val Char that is parsed.
* @param[in] _filePos Position of the char in the file. * @param filePos Position of the char in the file.
*/ */
public static void drawElementParsed(final Character _val, final FilePos _filePos) { public static void drawElementParsed(final Character val, final FilePos filePos) {
// if (_val == '\n') { // if (val == '\n') {
// Log.debug(_filePos + " parse '\\n'"); // Log.debug(filePos + " parse '\\n'");
// } else if (_val == '\t') { // } else if (val == '\t') {
// Log.debug(_filePos + " parse '\\t'"); // Log.debug(filePos + " parse '\\t'");
// } else { // } else {
// Log.debug(_filePos + " parse '" + _val + "'"); // Log.debug(filePos + " parse '" + val + "'");
// } // }
} }
public static String extractLine(final String data, final int _pos) { public static String extractLine(final String data, final int pos) {
// search back : '\n' // search back : '\n'
int startPos = data.lastIndexOf('\n', _pos); int startPos = data.lastIndexOf('\n', pos);
if (startPos == _pos) { if (startPos == pos) {
startPos = 0; startPos = 0;
} else { } else {
startPos++; startPos++;
} }
// search forward : '\n' // search forward : '\n'
int stopPos = _pos; int stopPos = pos;
if (data.length() == _pos) { if (data.length() != pos && data.charAt(pos) != '\n') {
stopPos = _pos; stopPos = data.indexOf('\n', pos);
} else if (data.charAt(_pos) != '\n') { if (stopPos == pos) {
stopPos = data.indexOf('\n', _pos);
if (stopPos == _pos) {
stopPos = data.length(); stopPos = data.length();
} }
} }
if (startPos == -1) { if (startPos >= data.length()) {
startPos = 0;
} else if (startPos >= data.length()) {
return ""; return "";
} }
if (stopPos == -1) { if (stopPos == -1) {
return ""; return "";
} else if (stopPos >= data.length()) { }
if (stopPos >= data.length()) {
stopPos = data.length(); stopPos = data.length();
} }
return data.substring(startPos, stopPos); return data.substring(startPos, stopPos);
} }
public static boolean isWhiteChar(final Character _val) { public static boolean isWhiteChar(final Character val) {
if (_val == ' ' || _val == '\t' || _val == '\n' || _val == '\r') { return val == ' ' || val == '\t' || val == '\n' || val == '\r';
return true;
}
return false;
} }
public static Boolean[] parseBooleanClassStringList(String data) { // throws NumberFormatException public static Boolean[] parseBooleanClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final Boolean[] out = new Boolean[dataArray.length]; final Boolean[] out = new Boolean[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -169,19 +158,19 @@ public class Tools {
} }
public static boolean[] parseBooleanStringList(String data) { // throws NumberFormatException public static boolean[] parseBooleanStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final boolean[] out = new boolean[dataArray.length]; final boolean[] out = new boolean[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
out[count++] = Boolean.valueOf(str); out[count++] = Boolean.parseBoolean(str);
} }
return out; return out;
} }
public static Byte[] parseByteClassStringList(String data) { // throws NumberFormatException public static Byte[] parseByteClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final Byte[] out = new Byte[dataArray.length]; final Byte[] out = new Byte[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -191,8 +180,8 @@ public class Tools {
} }
public static byte[] parseByteStringList(String data) { // throws NumberFormatException public static byte[] parseByteStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final byte[] out = new byte[dataArray.length]; final byte[] out = new byte[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -202,8 +191,8 @@ public class Tools {
} }
public static Integer[] parseIntegerClassStringList(String data) { // throws NumberFormatException public static Integer[] parseIntegerClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final Integer[] out = new Integer[dataArray.length]; final Integer[] out = new Integer[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -213,8 +202,8 @@ public class Tools {
} }
public static int[] parseIntegerStringList(String data) { // throws NumberFormatException public static int[] parseIntegerStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final int[] out = new int[dataArray.length]; final int[] out = new int[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -224,8 +213,8 @@ public class Tools {
} }
public static Long[] parseLongClassStringList(String data) { // throws NumberFormatException public static Long[] parseLongClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final Long[] out = new Long[dataArray.length]; final Long[] out = new Long[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -235,8 +224,8 @@ public class Tools {
} }
public static long[] parseLongStringList(String data) { // throws NumberFormatException public static long[] parseLongStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final long[] out = new long[dataArray.length]; final long[] out = new long[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -246,8 +235,8 @@ public class Tools {
} }
public static Short[] parseShortClassStringList(String data) { // throws NumberFormatException public static Short[] parseShortClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final Short[] out = new Short[dataArray.length]; final Short[] out = new Short[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -257,8 +246,8 @@ public class Tools {
} }
public static short[] parseShortStringList(String data) { // throws NumberFormatException public static short[] parseShortStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data); data = Tools.cleanNumberList(data);
final String dataArray[] = data.split(";"); final String[] dataArray = data.split(";");
final short[] out = new short[dataArray.length]; final short[] out = new short[dataArray.length];
int count = 0; int count = 0;
for (final String str : dataArray) { for (final String str : dataArray) {
@ -273,25 +262,25 @@ public class Tools {
// "&amp;" == "&" // "&amp;" == "&"
// "&apos;" == "'" // "&apos;" == "'"
// "&quot;" == """ // "&quot;" == """
public static String replaceSpecialChar(final String _inval) { public static String replaceSpecialChar(final String inval) {
final String out = _inval; String out = inval;
out.replace("&lt;", "<"); out = out.replace("&lt;", "<");
out.replace("&gt;", ">"); out = out.replace("&gt;", ">");
out.replace("&apos;", "'"); out = out.replace("&apos;", "'");
out.replace("&quot;", "\""); out = out.replace("&quot;", "\"");
out.replace("&amp;", "&"); out = out.replace("&amp;", "&");
//EXML_ERROR("INNN '"<< _inval << "' => '" << out << "'"); //EXMLERROR("INNN '"<< inval << "' => '" << out << "'");
return out; return out;
} }
public static String replaceSpecialCharOut(final String _inval) { public static String replaceSpecialCharOut(final String inval) {
final String out = _inval; String out = inval;
out.replace("<", "&lt;"); out = out.replace("<", "&lt;");
out.replace(">", "&gt;"); out = out.replace(">", "&gt;");
out.replace("'", "&apos;"); out = out.replace("'", "&apos;");
out.replace("\"", "&quot;"); out = out.replace("\"", "&quot;");
out.replace("&", "&amp;"); out = out.replace("&", "&amp;");
//EXML_ERROR("OUTTT '"<< _inval << "' => '" << out << "'"); //EXMLERROR("OUTTT '"<< inval << "' => '" << out << "'");
return out; return out;
} }

View File

@ -14,20 +14,19 @@ import org.atriasoft.ejson.model.JsonString;
import org.atriasoft.ejson.parser.Tools; import org.atriasoft.ejson.parser.Tools;
public class SerializerJson { public class SerializerJson {
public static void serialize(final JsonNode node, final StringBuilder data, final int indent) { public static void serialize(final JsonNode node, final StringBuilder data, final int indent) {
if (node instanceof JsonObject) { if (node instanceof JsonObject) {
serializeObject((JsonObject) node, data, indent); SerializerJson.serializeObject((JsonObject) node, data, indent);
} else if (node instanceof JsonArray) { } else if (node instanceof JsonArray) {
serializeArray((JsonArray) node, data, indent); SerializerJson.serializeArray((JsonArray) node, data, indent);
} else if (node instanceof JsonNumber) { } else if (node instanceof JsonNumber) {
serializeNumber((JsonNumber) node, data, indent); SerializerJson.serializeNumber((JsonNumber) node, data, indent);
} else if (node instanceof JsonNull) { } else if (node instanceof JsonNull) {
serializeNull((JsonNull) node, data, indent); SerializerJson.serializeNull((JsonNull) node, data, indent);
} else if (node instanceof JsonString) { } else if (node instanceof JsonString) {
serializeString((JsonString) node, data, indent); SerializerJson.serializeString((JsonString) node, data, indent);
} else if (node instanceof JsonBoolean) { } else if (node instanceof JsonBoolean) {
serializeBoolean((JsonBoolean) node, data, indent); SerializerJson.serializeBoolean((JsonBoolean) node, data, indent);
} else { } else {
// TODO throw an error ... // TODO throw an error ...
} }
@ -38,14 +37,14 @@ public class SerializerJson {
if (indent == -1) { if (indent == -1) {
data.append("["); data.append("[");
boolean needComa = false; boolean needComa = false;
for (int iii = 0; iii < tmp.size(); iii++) { for (final JsonNode jsonNode : tmp) {
if (tmp.get(iii) == null) { if (jsonNode == null) {
continue; continue;
} }
if (needComa == true) { if (needComa) {
data.append(","); data.append(",");
} }
serialize(tmp.get(iii), data, -1); SerializerJson.serialize(jsonNode, data, -1);
needComa = true; needComa = true;
} }
data.append("]"); data.append("]");
@ -54,8 +53,7 @@ public class SerializerJson {
if (tmp.size() > 3) { if (tmp.size() > 3) {
oneLine = false; oneLine = false;
} else { } else {
for (int iii = 0; iii < tmp.size(); iii++) { for (final JsonNode tmpInspect : tmp) {
final JsonNode tmpInspect = tmp.get(iii);
if (tmpInspect == null) { if (tmpInspect == null) {
continue; continue;
} }
@ -75,28 +73,28 @@ public class SerializerJson {
} }
} }
} }
if (true == oneLine) { if (oneLine) {
data.append("[ "); data.append("[ ");
} else { } else {
data.append("[\n"); data.append("[\n");
} }
for (int iii = 0; iii < tmp.size(); iii++) { for (int iii = 0; iii < tmp.size(); iii++) {
if (false == oneLine) { if (!oneLine) {
Tools.addIndent(data, indent); Tools.addIndent(data, indent);
} }
if (tmp.get(iii) != null) { if (tmp.get(iii) != null) {
serialize(tmp.get(iii), data, indent + 1); SerializerJson.serialize(tmp.get(iii), data, indent + 1);
if (iii < tmp.size() - 1) { if (iii < tmp.size() - 1) {
data.append(","); data.append(",");
} }
} }
if (oneLine == true) { if (oneLine) {
data.append(" "); data.append(" ");
} else { } else {
data.append("\n"); data.append("\n");
} }
} }
if (false == oneLine) { if (!oneLine) {
Tools.addIndent(data, indent - 1); Tools.addIndent(data, indent - 1);
} }
data.append("]"); data.append("]");
@ -105,7 +103,7 @@ public class SerializerJson {
} }
private static void serializeBoolean(final JsonBoolean node, final StringBuilder data, final int indent) { private static void serializeBoolean(final JsonBoolean node, final StringBuilder data, final int indent) {
if (node.getValue() == true) { if (node.getValue()) {
data.append("true"); data.append("true");
} else { } else {
data.append("false"); data.append("false");
@ -117,7 +115,7 @@ public class SerializerJson {
} }
private static void serializeNumber(final JsonNumber node, final StringBuilder data, final int indent) { private static void serializeNumber(final JsonNumber node, final StringBuilder data, final int indent) {
if (node.isDouble() == true) { if (node.isDouble()) {
data.append(node.getValue()); data.append(node.getValue());
} else { } else {
data.append(node.getValueLong()); data.append(node.getValueLong());
@ -129,17 +127,15 @@ public class SerializerJson {
if (indent == -1) { if (indent == -1) {
data.append("{"); data.append("{");
boolean needComa = false; boolean needComa = false;
final Iterator<Map.Entry<String, JsonNode>> iterator = tmp.entrySet().iterator(); for (final Map.Entry<String, JsonNode> entry : tmp.entrySet()) {
while (iterator.hasNext()) { if (needComa) {
final Map.Entry<String, JsonNode> entry = iterator.next();
if (needComa == true) {
data.append(","); data.append(",");
} }
needComa = true; needComa = true;
data.append("\""); data.append("\"");
data.append(entry.getKey()); data.append(entry.getKey());
data.append("\":"); data.append("\":");
serialize(entry.getValue(), data, -1); SerializerJson.serialize(entry.getValue(), data, -1);
} }
data.append("}"); data.append("}");
} else { } else {
@ -149,9 +145,7 @@ public class SerializerJson {
} else if (indent <= 1) { } else if (indent <= 1) {
oneLine = false; oneLine = false;
} else { } else {
final Iterator<Map.Entry<String, JsonNode>> iterator = tmp.entrySet().iterator(); for (final Map.Entry<String, JsonNode> entry : tmp.entrySet()) {
while (iterator.hasNext()) {
final Map.Entry<String, JsonNode> entry = iterator.next();
final JsonNode tmpInstect = entry.getValue(); final JsonNode tmpInstect = entry.getValue();
if (tmpInstect == null) { if (tmpInstect == null) {
continue; continue;
@ -172,7 +166,7 @@ public class SerializerJson {
} }
} }
} }
if (oneLine == true) { if (oneLine) {
data.append("{ "); data.append("{ ");
} else { } else {
data.append("{\n"); data.append("{\n");
@ -180,23 +174,23 @@ public class SerializerJson {
final Iterator<Map.Entry<String, JsonNode>> iterator = tmp.entrySet().iterator(); final Iterator<Map.Entry<String, JsonNode>> iterator = tmp.entrySet().iterator();
while (iterator.hasNext()) { while (iterator.hasNext()) {
final Map.Entry<String, JsonNode> entry = iterator.next(); final Map.Entry<String, JsonNode> entry = iterator.next();
if (oneLine == false) { if (!oneLine) {
Tools.addIndent(data, indent); Tools.addIndent(data, indent);
} }
data.append("\""); data.append("\"");
data.append(entry.getKey()); data.append(entry.getKey());
data.append("\": "); data.append("\": ");
serialize(entry.getValue(), data, indent + 1); SerializerJson.serialize(entry.getValue(), data, indent + 1);
if (iterator.hasNext() == true) { if (iterator.hasNext()) {
data.append(","); data.append(",");
} }
if (oneLine == true) { if (oneLine) {
data.append(" "); data.append(" ");
} else { } else {
data.append("\n"); data.append("\n");
} }
} }
if (oneLine == false) { if (!oneLine) {
Tools.addIndent(data, indent - 1); Tools.addIndent(data, indent - 1);
} }
data.append("}"); data.append("}");
@ -214,4 +208,6 @@ public class SerializerJson {
data.append("\""); data.append("\"");
} }
private SerializerJson() {}
} }

View File

@ -12,48 +12,45 @@ import org.atriasoft.ejson.model.JsonNode;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
class EjsonLocal { class EjsonLocal {
// _errorPos : -1 : no error , 1 : parsing error, 2 generation error, 3 comparaison error ???? // errorPos : -1 : no error , 1 : parsing error, 2 generation error, 3 comparaison error ????
public static void test(final String _ref, final String _input, final int _errorPos) { public static void test(final String ref, final String input, final int errorPos) {
//doc.setCaseSensitive(!_caseInSensitive); //doc.setCaseSensitive(!caseInSensitive);
Log.verbose("parse : \n" + _input); Log.verbose("parse : \n" + input);
JsonNode root = null; JsonNode root = null;
try { try {
root = Ejson.parse(_input); root = Ejson.parse(input);
if (_errorPos == 1) { if (errorPos == 1) {
Assertions.fail("Must have detected an error"); Assertions.fail("Must have detected an error");
return; return;
} }
} catch (final EjsonParserErrorMulti e) { } catch (final EjsonParserErrorMulti e) {
if (_errorPos == 1) { if (errorPos == 1) {
return; return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} }
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} catch (final EjsonBuilderException e) { } catch (final EjsonBuilderException e) {
if (_errorPos == 1) { if (errorPos == 1) {
return; return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} }
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} catch (final Exception e) { } catch (final Exception e) {
if (_errorPos == 1) { if (errorPos == 1) {
return; return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} }
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
} }
final StringBuilder out = new StringBuilder(); final StringBuilder out = new StringBuilder();
// TODO: 2 is for failing in generate ... // TODO 2 is for failing in generate ...
Ejson.generate(root, out); Ejson.generate(root, out);
final String data = out.toString(); final String data = out.toString();
if (_errorPos == 3) { if (errorPos == 3) {
Assertions.assertNotEquals(_ref, data); Assertions.assertNotEquals(ref, data);
return;
} else {
Assertions.assertEquals(_ref, data);
} }
Assertions.assertEquals(ref, data);
} }
private EjsonLocal() {}
} }

View File

@ -10,9 +10,9 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class EjsonTestBoolean { public class EjsonTestBoolean {
static private String refOutputBoolean1 = "{\n\t\"tmpElement\": true\n}"; private static String refOutputBoolean1 = "{\n\t\"tmpElement\": true\n}";
static private String refOutputBoolean2 = "{\n\t\"tmpElement\": false\n}"; private static String refOutputBoolean2 = "{\n\t\"tmpElement\": false\n}";
@BeforeAll @BeforeAll
public static void beforeClass() { public static void beforeClass() {
@ -28,60 +28,60 @@ public class EjsonTestBoolean {
@Test @Test
@Order(2) @Order(2)
public void test010BaseTrue() { public void test010BaseTrue() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:true }\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:true }\n", -1);
} }
@Test @Test
@Order(3) @Order(3)
public void test020TabbedTrue() { public void test020TabbedTrue() {
EjsonLocal.test(refOutputBoolean1, "{ \t\ntmpElement:true \t\n }\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ \t\ntmpElement:true \t\n }\n", -1);
} }
@Test @Test
@Order(4) @Order(4)
public void test030NoneTrue() { public void test030NoneTrue() {
EjsonLocal.test(refOutputBoolean1, "tmpElement:true\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "tmpElement:true\n", -1);
} }
@Test @Test
@Order(5) @Order(5)
public void test040BaseTrue1() { public void test040BaseTrue1() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:TRUE }\n", 1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:TRUE }\n", 1);
} }
@Test @Test
@Order(6) @Order(6)
public void test050BaseTrue2() { public void test050BaseTrue2() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:True }\n", 1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:True }\n", 1);
} }
@Test @Test
@Order(7) @Order(7)
public void test110BaseFalse() { public void test110BaseFalse() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:false }\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:false }\n", -1);
} }
@Test @Test
@Order(8) @Order(8)
public void test120TabbedFalse() { public void test120TabbedFalse() {
EjsonLocal.test(refOutputBoolean2, "{ \t\ntmpElement:false \t\n }\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ \t\ntmpElement:false \t\n }\n", -1);
} }
@Test @Test
@Order(9) @Order(9)
public void test130NoneFalse() { public void test130NoneFalse() {
EjsonLocal.test(refOutputBoolean2, "tmpElement:false\n", -1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "tmpElement:false\n", -1);
} }
@Test @Test
@Order(10) @Order(10)
public void test140BaseFalse1() { public void test140BaseFalse1() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:FALSE }\n", 1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:FALSE }\n", 1);
} }
@Test @Test
@Order(11) @Order(11)
public void test150BaseFalse2() { public void test150BaseFalse2() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:False }\n", 1); EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:False }\n", 1);
} }
} }

View File

@ -10,7 +10,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class EjsonTestNull { public class EjsonTestNull {
static private String refOutputNull = "{\n\t\"tmpElement\": null\n}"; private static final String REF_OUTPUT_NULL = "{\n\t\"tmpElement\": null\n}";
@BeforeAll @BeforeAll
public static void beforeClass() { public static void beforeClass() {
@ -20,19 +20,19 @@ public class EjsonTestNull {
@Test @Test
@Order(1) @Order(1)
public void test10BasicNullElement() { public void test10BasicNullElement() {
EjsonLocal.test(refOutputNull, "{ tmpElement:null }\n", -1); EjsonLocal.test(EjsonTestNull.REF_OUTPUT_NULL, "{ tmpElement:null }\n", -1);
} }
@Test @Test
@Order(2) @Order(2)
public void test20TabbedNullElement() { public void test20TabbedNullElement() {
EjsonLocal.test(refOutputNull, "{ \t\ntmpElement:null \t\n }\n", -1); EjsonLocal.test(EjsonTestNull.REF_OUTPUT_NULL, "{ \t\ntmpElement:null \t\n }\n", -1);
} }
@Test @Test
@Order(3) @Order(3)
public void test30TabbedNullElementNoPThese() { public void test30TabbedNullElementNoPThese() {
EjsonLocal.test(refOutputNull, "tmpElement:null\n", -1); EjsonLocal.test(EjsonTestNull.REF_OUTPUT_NULL, "tmpElement:null\n", -1);
} }
@Test @Test

View File

@ -10,7 +10,7 @@ import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
public class EjsonTestNumber { public class EjsonTestNumber {
static private String refOutputNumber = "{\n\t\"tmpElement\": 956256\n}"; private static final String REF_OUTPUT_NUMBER = "{\n\t\"tmpElement\": 956256\n}";
@BeforeAll @BeforeAll
public static void beforeClass() { public static void beforeClass() {
@ -20,13 +20,13 @@ public class EjsonTestNumber {
@Test @Test
@Order(1) @Order(1)
public void test10Base() { public void test10Base() {
EjsonLocal.test(refOutputNumber, "{ tmpElement:956256 }\n", -1); EjsonLocal.test(EjsonTestNumber.REF_OUTPUT_NUMBER, "{ tmpElement:956256 }\n", -1);
} }
@Test @Test
@Order(2) @Order(2)
public void test20Tabbed() { public void test20Tabbed() {
EjsonLocal.test(refOutputNumber, "{ \t\ntmpElement:956256 \t\n }\n", -1); EjsonLocal.test(EjsonTestNumber.REF_OUTPUT_NUMBER, "{ \t\ntmpElement:956256 \t\n }\n", -1);
} }
@Test @Test
@ -44,6 +44,6 @@ public class EjsonTestNumber {
@Test @Test
@Order(5) @Order(5)
public void test50None() { public void test50None() {
EjsonLocal.test(refOutputNumber, "tmpElement:956256\n", -1); EjsonLocal.test(EjsonTestNumber.REF_OUTPUT_NUMBER, "tmpElement:956256\n", -1);
} }
} }