Compare commits

...

20 Commits
main ... dev

Author SHA1 Message Date
Edouard DUPIN
caeff094ef [FIX] arbo 2025-05-24 00:24:25 +02:00
3f99296328 [FEAT] continue maven integration 2024-06-09 09:57:21 +02:00
ec6a03835d [FEAT] use Maven a build system root tool 2024-06-07 09:26:18 +02:00
c6cb79c8d7 [DEV] rework to Maven 2023-07-27 07:34:47 +02:00
044c125b6f [DEV] first ready to use introspection of json elements 2022-11-01 23:44:38 +01:00
b2a4488117 [DEV] remove dependency with scenarium 2022-10-03 23:44:48 +02:00
e13d2dcd7f ---No commit message--- 2022-10-03 00:08:28 +02:00
4a615a3e92 ---No commit message--- 2022-10-03 00:08:20 +02:00
cdf655ad2a ---No commit message--- 2022-10-01 15:45:33 +02:00
a1f571173b [DEV] update aknot 2022-09-03 21:05:34 +02:00
137c707eb5 [DEV] integrate new jsion 2022-09-02 18:24:30 +02:00
9e57384a7c [DEV] remove dependency 2022-05-03 15:07:51 +02:00
f2fcd75fb9 [DEV] udate some log model 2022-04-11 00:50:51 +02:00
5e0fdf1bc8 [DEV] update log interface 2022-04-01 00:57:38 +02:00
7e7bf02598 [DEV] commit all with new insland 2022-03-20 23:39:28 +01:00
82cf27b69c [DEV] update classpath 2021-08-23 11:12:07 +02:00
a916232bf1 [DEV] add test of lutin builder 2021-06-14 13:41:18 +02:00
d98f2b7769 [DEV] some clean 2021-05-03 16:47:02 +02:00
6aa5a0e966 [DEV] continue update 2021-03-25 18:54:53 +01:00
862decc203 [DEV] continue rework 2021-03-16 00:29:53 +01:00
64 changed files with 3420 additions and 2163 deletions

View File

@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<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"/>
</fileset>
</fileset-config>

View File

@ -1,35 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src">
<attributes>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry including="**/*.java" kind="src" output="out/eclipse/classes-test" path="test/src">
<attributes>
<attribute name="test" value="true"/>
<attribute name="optional" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-14">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.junit.JUNIT_CONTAINER/5">
<attributes>
<attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/scenarium-logger">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry combineaccessrules="false" kind="src" path="/atriasoft-etk">
<attributes>
<attribute name="module" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="out/eclipse/classes"/>
</classpath>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<launchConfiguration type="org.eclipse.ant.AntBuilderLaunchConfigurationType">
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_BUILDER_ENABLED" value="false"/>
<stringAttribute key="org.eclipse.ui.externaltools.ATTR_DISABLED_BUILDER" value="net.sf.eclipsecs.core.CheckstyleBuilder"/>
<mapAttribute key="org.eclipse.ui.externaltools.ATTR_TOOL_ARGUMENTS"/>
<booleanAttribute key="org.eclipse.ui.externaltools.ATTR_TRIGGERS_CONFIGURED" value="true"/>
</launchConfiguration>

2
.gitignore vendored
View File

@ -1,3 +1,5 @@
/__pycache__/
/bin/
/Operator/
/DrawerProperties/

View File

@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>atriasoft-ejson</name>
<comment></comment>
<projects>
<project>atriasoft-ejson</project>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>net.sf.eclipsecs.core.CheckstyleBuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>net.sf.eclipsecs.core.CheckstyleNature</nature>
</natures>
</projectDescription>

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

@ -0,0 +1,82 @@
#!/usr/bin/python
import realog.debug as debug
import lutin.tools as tools
import realog.debug as debug
import lutin.image as image
import os
import lutin.multiprocess as lutinMultiprocess
def get_type():
return "LIBRARY_DYNAMIC"
def get_desc():
return "Ewol Tool Kit"
def get_licence():
return "MPL-2"
def get_compagny_type():
return "org"
def get_compagny_name():
return "atria-soft"
#def get_maintainer():
# return "authors.txt"
#def get_version():
# return "version.txt"
def configure(target, my_module):
my_module.add_src_file([
'src/module-info.java',
'src/org/atriasoft/ejson/model/JsonNumber.java',
'src/org/atriasoft/ejson/model/JsonNode.java',
'src/org/atriasoft/ejson/model/JsonNull.java',
'src/org/atriasoft/ejson/model/JsonArray.java',
'src/org/atriasoft/ejson/model/JsonNodeType.java',
'src/org/atriasoft/ejson/model/JsonBoolean.java',
'src/org/atriasoft/ejson/model/JsonString.java',
'src/org/atriasoft/ejson/model/JsonObject.java',
'src/org/atriasoft/ejson/internal/LOGGER.java',
'src/org/atriasoft/ejson/annotation/JsonManaged.java',
'src/org/atriasoft/ejson/annotation/EjsonAnnotation.java',
'src/org/atriasoft/ejson/annotation/JsonDefaultManaged.java',
'src/org/atriasoft/ejson/annotation/JsonOptional.java',
'src/org/atriasoft/ejson/annotation/JsonDefaultOptional.java',
'src/org/atriasoft/ejson/annotation/JsonName.java',
'src/org/atriasoft/ejson/serializer/SerializerJson.java',
'src/org/atriasoft/ejson/builder/BuilderGeneric.java',
'src/org/atriasoft/ejson/builder/Builder.java',
'src/org/atriasoft/ejson/exception/EjsonParserError.java',
'src/org/atriasoft/ejson/exception/EjsonParserErrorMulti.java',
'src/org/atriasoft/ejson/exception/EjsonException.java',
'src/org/atriasoft/ejson/exception/EjsonBuilderException.java',
'src/org/atriasoft/ejson/exception/EjsonNodeDoesNotExist.java',
'src/org/atriasoft/ejson/parser/StoreMode.java',
'src/org/atriasoft/ejson/parser/ParsingProperty.java',
'src/org/atriasoft/ejson/parser/Tools.java',
'src/org/atriasoft/ejson/parser/PositionParsing.java',
'src/org/atriasoft/ejson/parser/FilePos.java',
'src/org/atriasoft/ejson/parser/ParseJson.java',
'src/org/atriasoft/ejson/Ejson.java',
])
my_module.add_path('src/', type='java')
my_module.add_depend([
'io-scenarium-logger',
'org-atriasoft-etk'
])
#my_module.add_path([
# 'lib/spotbugs-annotations-4.2.2.jar'
# ],
# type='java',
# export=True
#);
my_module.add_flag('java', "RELEASE_15_PREVIEW");
return True

139
pom.xml Normal file
View File

@ -0,0 +1,139 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.atriasoft</groupId>
<artifactId>ejson</artifactId>
<version>0.1.0</version>
<licenses>
<license>
<name>Mozilla Public License 2.0</name>
<url>https://opensource.org/licenses/MPL-2.0</url>
<distribution>repo</distribution>
</license>
</licenses>
<developers>
<developer>
<id>dev1</id>
<name>Edouard DUPIN</name>
<email>edouard.dupin@proton.me</email>
<roles>
<role>Lead Developer</role>
</roles>
</developer>
</developers>
<repositories>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
</repositories>
<distributionManagement>
<repository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</repository>
<snapshotRepository>
<id>gitea</id>
<url>https://gitea.atria-soft.org/api/packages/org.atriasoft/maven</url>
</snapshotRepository>
</distributionManagement>
<dependencies>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>etk</artifactId>
<version>0.1.0</version>
</dependency>
<dependency>
<groupId>org.atriasoft</groupId>
<artifactId>aknot</artifactId>
<version>0.1.0</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.11.0-M2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>2.1.0-alpha1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main</sourceDirectory>
<testSourceDirectory>src/test</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.0</version>
<configuration>
<source>21</source>
<target>21</target>
</configuration>
</plugin>
<!-- Create the source bundle -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
<version>3.3.1</version>
<executions>
<execution>
<id>attach-sources</id>
<goals>
<goal>jar</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- junit results -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M5</version>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<configuration>
<archive>
<manifest>
<mainClass>fully.qualified.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<!-- Java-doc generation for stand-alone site -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>private</show>
<nohelp>true</nohelp>
</configuration>
</plugin>
</plugins>
</build>
<!-- Generate Java-docs As Part Of Project Reports -->
<reporting>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<show>public</show>
</configuration>
</plugin>
</plugins>
</reporting>
</project>

View File

@ -10,28 +10,32 @@ import org.atriasoft.ejson.builder.Builder;
import org.atriasoft.ejson.builder.BuilderGeneric;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonParserErrorMulti;
import org.atriasoft.ejson.internal.Log;
import org.atriasoft.ejson.generator.GeneratorGeneric;
import org.atriasoft.ejson.model.JsonNode;
import org.atriasoft.ejson.parser.ParseJson;
import org.atriasoft.ejson.parser.ParsingProperty;
import org.atriasoft.ejson.serializer.SerializerJson;
import org.atriasoft.etk.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Ejson {
final static Logger LOGGER = LoggerFactory.getLogger(Ejson.class);
/**
* Display the Document on console
* Display the Document on console
*/
public static void display(final JsonNode root) {
final StringBuilder tmpp = new StringBuilder();
SerializerJson.serialize(root, tmpp, 0);
Log.info("Generated JSON : \n" + tmpp.toString());
GeneratorGeneric.serialize(root, tmpp, 0);
LOGGER.info("Generated JSON : \n{}", tmpp.toString());
}
/**
* Generate a string that contain the created XML
*
* @param data Data where the json is stored
*/
public static void generate(final JsonNode root, final StringBuilder data) {
SerializerJson.serialize(root, data, 1);
GeneratorGeneric.serialize(root, data, 1);
}
public static JsonNode parse(final String data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti {
@ -42,5 +46,19 @@ public class Ejson {
return (JsonNode) parser.parse(data, property);
}
public static JsonNode parse(final Uri data) throws Exception, EjsonBuilderException, EjsonParserErrorMulti {
final Builder builder = new BuilderGeneric();
final ParseJson parser = new ParseJson(builder);
final ParsingProperty property = new ParsingProperty();
property.setDisplayError(true);
final byte[] elemData = Uri.getAllData(data);
if (elemData == null) {
LOGGER.error("Can not read the Stream : {}", data);
return null;
}
final String dataToParse = new String(elemData);
return (JsonNode) parser.parse(dataToParse, property);
}
private Ejson() {}
}

View File

@ -0,0 +1,121 @@
package org.atriasoft.ejson;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.aknot.model.ModelType;
import org.atriasoft.ejson.builder.Builder;
import org.atriasoft.ejson.builder.BuilderIntrospection;
import org.atriasoft.ejson.builder.IntrospectionObject;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.atriasoft.ejson.parser.ParseJson;
import org.atriasoft.ejson.parser.ParsingProperty;
import org.atriasoft.etk.Uri;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class JsonMapper {
final static Logger LOGGER = LoggerFactory.getLogger(JsonMapper.class);
private static String readFile(final Path path, final Charset encoding) throws IOException {
final byte[] encoded = Files.readAllBytes(path);
return new String(encoded, encoding);
}
public JsonMapper() {
}
/*
public void generate(final Object root, final StringBuilder data) throws EjsonException, AknotException {
GeneratorIntrospection generator;
try {
generator = new GeneratorIntrospection(ModelType.NORMAL, root.getClass());
generator.generate(root, data);
} catch (final EjsonBuilderException ex) {
throw ex;
} catch (final Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
*/
/**
* Parse a single root node that have the name of the Class Parsed:
* <pre>
* &gt;ClassName a="kk" ... &lt;
* ...
* &gt;/ClassName&lt;
* </pre>
* @param <T> Object type to parse
* @param data Data String to Parse
* @param classType Object Class to introspect data (POJO)
* @return The Object parsed or null
*/
@SuppressWarnings("unchecked")
public <T> T parse(final String data, final Class<T> classType) throws EjsonException, EjsonNodeDoesNotExist, AknotException {
Builder builder;
try {
builder = new BuilderIntrospection(ModelType.NORMAL, classType);
final ParseJson parser = new ParseJson(builder);
final ParsingProperty property = new org.atriasoft.ejson.parser.ParsingProperty();
property.setDisplayError(true);
final IntrospectionObject introspectionObject = (IntrospectionObject) parser.parse(data, property);
introspectionObject.generateTheObject(true);
final Object listRet = introspectionObject.getData();
LOGGER.error("elements: {} , {}", listRet.getClass(), classType);
if (listRet != null && !listRet.getClass().isArray() && listRet.getClass() == classType) {
return (T) listRet;
} else if (listRet != null && listRet.getClass().isArray() && listRet.getClass().componentType() == classType) {
final T[] tmp = (T[]) listRet;
if (tmp.length >= 1) {
return tmp[0];
}
}
return null;
} catch (final EjsonException ex) {
ex.printStackTrace();
throw ex;
}
}
public <T> T read(final Class<T> classType, final Path path) throws EjsonException, AknotException, IOException {
String content = null;
try {
content = readFile(path, StandardCharsets.UTF_8);
} catch (final IOException e) {
e.printStackTrace();
}
return parse(content, classType);
}
public <T> T read(final Class<T> classType, final Uri uri) throws EjsonException, AknotException, IOException {
final byte[] elemData = Uri.getAllData(uri);
if (elemData == null) {
LOGGER.error("Can not read the Stream : " + uri);
return null;
}
final String content = new String(elemData);
return parse(content, classType);
}
/*
public void store(final Object root, final Path path) throws EjsonException, AknotException, IOException {
final StringBuilder builder = new StringBuilder();
generate(root, builder);
Files.writeString(path, builder.toString());
}
public void store(final Object root, final Uri uri) throws EjsonException, AknotException, IOException {
final StringBuilder builder = new StringBuilder();
generate(root, builder);
Uri.writeAll(uri, builder.toString());
}
*/
}

View File

@ -5,10 +5,21 @@
*/
package org.atriasoft.ejson.builder;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
public interface Builder {
/**
* End of parsing element
* @param parent Element representing the end of declaration
* @throws EjsonBuilderException Error with this node or element.
* @throws AknotException
*/
void endParsing(Object parent) throws EjsonBuilderException, AknotException;
/**
* New comment added on this Element (For an Array)
* @param parent Element representing the node of the Declaration is added
@ -23,8 +34,12 @@ public interface Builder {
* @param nodeName name of the element where the node is added
* @return Declaration object value
* @throws EjsonBuilderException Error with this node or element.
* @throws AknotException
* @throws EjsonNodeDoesNotExist
*/
Object newArray(Object parent, String nodeName) throws EjsonBuilderException;
Object newArray(Object parent, String nodeName) throws EjsonBuilderException, AknotException, EjsonNodeDoesNotExist;
void newArrayFinished(Object parent, String string, Object obj) throws EjsonException, AknotException;
/**
* Add a property on the Element. (For an Array)
@ -33,7 +48,7 @@ public interface Builder {
* @param propertyValue Value of the property
* @throws EjsonBuilderException Error with this node or element.
*/
void newBoolean(Object parent, boolean value) throws EjsonBuilderException, Exception;
void newBoolean(Object parent, boolean value) throws EjsonException, AknotException;
/**
* Add a property on the Element. (For an Object)
@ -41,14 +56,14 @@ public interface Builder {
* @param nodeName name of the element where the node is added
* @throws EjsonBuilderException Error with this node or element.
*/
void newBoolean(Object parent, String nodeName, boolean value) throws EjsonBuilderException, Exception;
void newBoolean(Object parent, String nodeName, boolean value) throws EjsonException, AknotException;
/**
* New null element detected on the current node (For an Array)
* @param parent Parent representing the node of the null is set
* @throws EjsonBuilderException Error with this node or element.
*/
void newNull(Object parent) throws EjsonBuilderException, Exception;
void newNull(Object parent) throws EjsonException, AknotException;
/**
* New null element detected on the current node (For an Object)
@ -56,7 +71,7 @@ public interface Builder {
* @param nodeName name of the element where the node is added
* @throws EjsonBuilderException Error with this node or element.
*/
void newNull(Object parent, String nodeName) throws EjsonBuilderException, Exception;
void newNull(Object parent, String nodeName) throws EjsonException, AknotException;
/**
* New number xxx.yyy element detected on the current node (For an Array)
@ -64,7 +79,7 @@ public interface Builder {
* @param value Double value of the number
* @throws EjsonBuilderException Error with this node or element.
*/
void newNumber(Object parent, double value) throws EjsonBuilderException, Exception;
void newNumber(Object parent, double value) throws EjsonException, AknotException;
/**
* New number xxx element detected on the current node (For an Array)
@ -72,7 +87,7 @@ public interface Builder {
* @param value Long value of the number
* @throws EjsonBuilderException Error with this node or element.
*/
void newNumber(Object parent, long value) throws EjsonBuilderException, Exception;
void newNumber(Object parent, long value) throws EjsonException, AknotException;
/**
* New number xxx.yyy element detected on the current node (For an Object)
@ -81,7 +96,7 @@ public interface Builder {
* @param value Double value of the number
* @throws EjsonBuilderException Error with this node or element.
*/
void newNumber(Object parent, String nodeName, double value) throws EjsonBuilderException, Exception;
void newNumber(Object parent, String nodeName, double value) throws EjsonException, AknotException;
/**
* New number xxx element detected on the current node (For an Object)
@ -90,7 +105,7 @@ public interface Builder {
* @param value Long value of the number
* @throws EjsonBuilderException Error with this node or element.
*/
void newNumber(Object parent, String nodeName, long value) throws EjsonBuilderException, Exception;
void newNumber(Object parent, String nodeName, long value) throws EjsonException, AknotException;
/**
* Add a new sub-element on the current parent element (For an Array)
@ -98,7 +113,7 @@ public interface Builder {
* @return the object representing the Element.
* @throws EjsonBuilderException Error with this node or element.
*/
Object newObject(Object parent) throws EjsonBuilderException, Exception;
Object newObject(Object parent) throws EjsonException, AknotException;
/**
* Add a new sub-element on the current parent element (For an Object)
@ -107,14 +122,14 @@ public interface Builder {
* @return the object representing the Element.
* @throws EjsonBuilderException Error with this node or element.
*/
Object newObject(Object parent, String nodeName) throws EjsonBuilderException, Exception;
Object newObject(Object parent, String nodeName) throws EjsonException, AknotException;
/**
* Create or get the root element of the document
* @return An object that id a root element.
* @throws EjsonBuilderException Error with this node or element.
*/
Object newRoot() throws EjsonBuilderException;
Object newRoot() throws EjsonBuilderException, AknotException;
/**
* Add a new sub-element on the current parent element (For an Array)
@ -123,7 +138,7 @@ public interface Builder {
* @return the object representing the Element.
* @throws EjsonBuilderException Error with this node or element.
*/
void newString(Object parent, String value) throws EjsonBuilderException, Exception;
void newString(Object parent, String value) throws EjsonException, AknotException;
/**
* Add a new sub-element on the current parent element (For an Object)
@ -133,5 +148,5 @@ public interface Builder {
* @return the object representing the Element.
* @throws EjsonBuilderException Error with this node or element.
*/
void newString(Object parent, String nodeName, String value) throws EjsonBuilderException, Exception;
void newString(Object parent, String nodeName, String value) throws EjsonException, AknotException;
}

View File

@ -5,7 +5,9 @@
*/
package org.atriasoft.ejson.builder;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.model.JsonArray;
import org.atriasoft.ejson.model.JsonBoolean;
import org.atriasoft.ejson.model.JsonNull;
@ -15,10 +17,14 @@ import org.atriasoft.ejson.model.JsonString;
public class BuilderGeneric implements Builder {
@Override
public void endParsing(final Object parent) throws EjsonBuilderException {
// nothing to do ... this is for revert build.
}
@Override
public Object newArray(final Object parent) throws EjsonBuilderException {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
if (parent instanceof final JsonArray elem) {
final JsonArray out = new JsonArray();
elem.add(out);
return out;
@ -28,8 +34,7 @@ public class BuilderGeneric implements Builder {
@Override
public Object newArray(final Object parent, final String nodeName) throws EjsonBuilderException {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
if (parent instanceof final JsonObject elem) {
final JsonArray out = new JsonArray();
elem.put(nodeName, out);
return out;
@ -38,9 +43,14 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newBoolean(final Object parent, final boolean value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public void newArrayFinished(final Object parent, final String string, final Object obj) throws EjsonException, AknotException {
// TODO Auto-generated method stub
}
@Override
public void newBoolean(final Object parent, final boolean value) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonBoolean out = new JsonBoolean(value);
elem.add(out);
return;
@ -50,9 +60,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newBoolean(final Object parent, final String nodeName, final boolean value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public void newBoolean(final Object parent, final String nodeName, final boolean value) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonBoolean out = new JsonBoolean(value);
elem.put(nodeName, out);
return;
@ -61,9 +70,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNull(final Object parent) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public void newNull(final Object parent) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonNull out = new JsonNull();
elem.add(out);
return;
@ -73,9 +81,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNull(final Object parent, final String nodeName) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public void newNull(final Object parent, final String nodeName) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonNull out = new JsonNull();
elem.put(nodeName, out);
return;
@ -84,9 +91,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNumber(final Object parent, final double value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public void newNumber(final Object parent, final double value) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonNumber out = new JsonNumber(value);
elem.add(out);
return;
@ -96,9 +102,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNumber(final Object parent, final long value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public void newNumber(final Object parent, final long value) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonNumber out = new JsonNumber(value);
elem.add(out);
return;
@ -108,9 +113,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNumber(final Object parent, final String nodeName, final double value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public void newNumber(final Object parent, final String nodeName, final double value) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonNumber out = new JsonNumber(value);
elem.put(nodeName, out);
return;
@ -119,9 +123,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newNumber(final Object parent, final String nodeName, final long value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public void newNumber(final Object parent, final String nodeName, final long value) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonNumber out = new JsonNumber(value);
elem.put(nodeName, out);
return;
@ -130,9 +133,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public Object newObject(final Object parent) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public Object newObject(final Object parent) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonObject out = new JsonObject();
elem.add(out);
return out;
@ -141,9 +143,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public Object newObject(final Object parent, final String nodeName) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public Object newObject(final Object parent, final String nodeName) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonObject out = new JsonObject();
elem.put(nodeName, out);
return out;
@ -157,9 +158,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newString(final Object parent, final String value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonArray) {
final JsonArray elem = (JsonArray) parent;
public void newString(final Object parent, final String value) throws EjsonException, AknotException {
if (parent instanceof final JsonArray elem) {
final JsonString out = new JsonString(value);
elem.add(out);
return;
@ -169,9 +169,8 @@ public class BuilderGeneric implements Builder {
}
@Override
public void newString(final Object parent, final String nodeName, final String value) throws EjsonBuilderException, Exception {
if (parent instanceof JsonObject) {
final JsonObject elem = (JsonObject) parent;
public void newString(final Object parent, final String nodeName, final String value) throws EjsonException, AknotException {
if (parent instanceof final JsonObject elem) {
final JsonString out = new JsonString(value);
elem.put(nodeName, out);
return;

View File

@ -0,0 +1,511 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package org.atriasoft.ejson.builder;
import java.util.ArrayList;
import java.util.List;
import org.atriasoft.aknot.StringSerializer;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.aknot.model.IntrospectionModel;
import org.atriasoft.aknot.model.ModelType;
import org.atriasoft.aknot.pojo.CacheIntrospectionModel;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class BuilderIntrospection implements Builder {
final static Logger LOGGER = LoggerFactory.getLogger(BuilderIntrospection.class);
// Keep in cach all the object alredy parsed ==> optimize CPU
CacheIntrospectionModel cacheModel = new CacheIntrospectionModel();
// The root class (need to keep it if we use 2 time the builder, the root class is no more accessible).
final Class<?> rootClassType;
final String rootNodeName;
public BuilderIntrospection(final ModelType model, final Class<?> classType) throws EjsonException, AknotException {
this.rootClassType = classType;
final IntrospectionModel typeModel = this.cacheModel.findOrCreate(model, null, classType);
this.rootNodeName = typeModel.getNames()[0];
}
@Override
public void endParsing(final Object element) throws EjsonBuilderException, AknotException {
LOGGER.trace("End of Element: {}", element);
if (element == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) element;
if (introspectionObject.getModelIntrospection() == null) {
// property on nothing ???
return;
}
introspectionObject.generateTheObject(true);
}
@Override
public Object newArray(final Object parent) throws EjsonBuilderException {
throw new EjsonBuilderException("Must be implemented ...");
/*
if (parent instanceof final JsonArray elem) {
final JsonArray out = new JsonArray();
elem.add(out);
return out;
}
throw new EjsonBuilderException("can not add Comment on something else than array");
*/
}
@Override
public Object newArray(final Object parent, final String nodeName) throws EjsonBuilderException, AknotException, EjsonNodeDoesNotExist {
if (parent == null) {
return null;
}
LOGGER.trace("new element on NodeName=" + nodeName);
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
Class<?> typeClass = null;
String listTreeName = null;
if (!introspectionObject.isSubNodeOrPropertyExist(nodeName) && model.isIgnoreUnknown()) {
LOGGER.debug("Ignore array: '" + nodeName + "', it does not exist.");
return null;
}
try {
typeClass = introspectionObject.getTypeOfSubNode(nodeName, true);
} catch (final AknotException e) {
throw new EjsonNodeDoesNotExist("Fait to get type of node " + nodeName + " does not exist: " + e.getMessage());
}
try {
listTreeName = introspectionObject.getTreeNameOfSubNode(nodeName, true);
} catch (final AknotException e) {
throw new EjsonNodeDoesNotExist("Node does not exist: " + e.getMessage());
}
if (typeClass != null) {
// specific case for List ==> need to get the subType in introspection ...
if (typeClass.isArray()) {
final Class<?> subTypeClass = typeClass.getComponentType();
LOGGER.trace("Create array new 'SUB' class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
IntrospectionModel inferData = null;
inferData = this.cacheModel.findOrCreate(ModelType.LIST, listTreeName, subTypeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
if (List.class.isAssignableFrom(typeClass)) {
Class<?> subTypeClass = null;
try {
subTypeClass = introspectionObject.getTypeOfSubNodeSubType(nodeName);
} catch (final AknotException e) {
throw new EjsonBuilderException("Node does not exist: " + e.getMessage());
}
LOGGER.trace("Create List new 'SUB' class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
IntrospectionModel inferData = null;
inferData = this.cacheModel.findOrCreate(ModelType.LIST, listTreeName, subTypeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
LOGGER.trace("Create new class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, typeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
return null;
}
@Override
public void newArrayFinished(final Object parent, String tmpName, final Object element) throws EjsonException, AknotException {
LOGGER.error("New element fionished : ==> " + tmpName);
if (parent == null || element == null) {
return;
}
final IntrospectionObject introspectionElementObject = (IntrospectionObject) element;
if (introspectionElementObject.getModelIntrospection() == null) {
// property on nothing ???
return;
}
final IntrospectionObject introspectionParentObject = (IntrospectionObject) parent;
if (introspectionParentObject.getModelIntrospection() == null) {
if (tmpName.equals(this.rootNodeName)) {
// this is the root node ...
final Object tmpp = introspectionParentObject.getData();
if (tmpp instanceof List) {
@SuppressWarnings("unchecked")
final List<Object> elementsOut = (List<Object>) tmpp;
elementsOut.add(introspectionElementObject.getData());
}
}
return;
}
if (tmpName == null) {
tmpName = introspectionElementObject.getModelIntrospection().getTokenBasicList();
}
introspectionParentObject.addObject(tmpName, introspectionElementObject.getData());
}
@Override
public void newBoolean(final Object parent, final boolean value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (!model.isArray() && !model.isList()) {
throw new EjsonBuilderException("Add element on other than an array: ");
}
introspectionObject.addData(value);
}
@Override
public void newBoolean(final Object parent, final String nodeName, final boolean value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Try inject number(long) in an ARRAY/List data= '" + value + "'");
}
/*
Class<?> typeClass = model.getClassType();
if (! typeClass.isPrimitive()) {
throw new EjsonBuilderException("Try inject number(long) in an " + typeClass.getCanonicalName() + " data= '" + value + "'");
}
*/
introspectionObject.addObject(nodeName, value);
}
@Override
public void newNull(final Object parent) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (!model.isArray() && !model.isList()) {
throw new EjsonBuilderException("Add element on other than an array: ");
}
introspectionObject.addData(null);
}
@Override
public void newNull(final Object parent, final String nodeName) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Try inject number(long) in an ARRAY/List data");
}
/*
Class<?> typeClass = model.getClassType();
if (! typeClass.isPrimitive()) {
throw new EjsonBuilderException("Try inject number(long) in an " + typeClass.getCanonicalName() + " data= '" + value + "'");
}
*/
introspectionObject.putProperty(nodeName, null);
}
@Override
public void newNumber(final Object parent, final double value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (!model.isArray() && !model.isList()) {
throw new EjsonBuilderException("Add element on other than an array: ");
}
introspectionObject.addData(value);
}
@Override
public void newNumber(final Object parent, final long value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (!model.isArray() && !model.isList()) {
throw new EjsonBuilderException("Add element on other than an array: ");
}
introspectionObject.addData(value);
}
@Override
public void newNumber(final Object parent, final String nodeName, final double value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Try inject number(long) in an ARRAY/List data= '" + value + "'");
}
/*
Class<?> typeClass = model.getClassType();
if (! typeClass.isPrimitive()) {
throw new EjsonBuilderException("Try inject number(long) in an " + typeClass.getCanonicalName() + " data= '" + value + "'");
}
*/
introspectionObject.putProperty(nodeName, value);
}
@Override
public void newNumber(final Object parent, final String nodeName, final long value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Try inject number(long) in an ARRAY/List data= '" + value + "'");
}
/*
Class<?> typeClass = model.getClassType();
if (! typeClass.isPrimitive()) {
throw new EjsonBuilderException("Try inject number(long) in an " + typeClass.getCanonicalName() + " data= '" + value + "'");
}
*/
introspectionObject.addObject(nodeName, value);
}
@Override
public Object newObject(final Object parent) throws EjsonException, AknotException {
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (!model.isArray() && !model.isList()) {
throw new EjsonBuilderException("Object created inside a non list ... ==> impssible case");
}
final Class<?> typeClass = model.getClassType();
LOGGER.trace("Create new class: '" + typeClass.getCanonicalName() + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, typeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
//throw new EjsonBuilderException("Must be implemented ...");
}
@Override
public Object newObject(final Object parent, final String nodeName) throws EjsonException, AknotException {
LOGGER.trace("new element on NodeName=" + nodeName);
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
Class<?> typeClass = null;
String listTreeName = null;
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Object is not compatible with an requested array: " + nodeName);
} else {
if (!introspectionObject.isSubNodeOrPropertyExist(nodeName) && model.isIgnoreUnknown()) {
LOGGER.debug("Ignore node: '" + nodeName + "' Does not exist...");
return null;
}
try {
typeClass = introspectionObject.getTypeOfSubNode(nodeName, true);
listTreeName = introspectionObject.getTreeNameOfSubNode(nodeName, true);
} catch (final AknotException e) {
throw new EjsonBuilderException("Node does not exist: " + e.getMessage());
}
}
if (typeClass != null) {
// specific case for List ==> need to get the subType in introspection ...
if (typeClass.isArray()) {
final Class<?> subTypeClass = typeClass.getComponentType();
LOGGER.trace("Create array new 'SUB' class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
IntrospectionModel inferData = null;
// when we request a list elements, we need to add the element in a list, then we need the return is LIST and not ARRAY
inferData = this.cacheModel.findOrCreate(ModelType.LIST, listTreeName, subTypeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
if (List.class.isAssignableFrom(typeClass)) {
Class<?> subTypeClass = null;
try {
subTypeClass = introspectionObject.getTypeOfSubNodeSubType(nodeName);
} catch (final AknotException e) {
throw new EjsonBuilderException("Node does not exist: " + e.getMessage());
}
LOGGER.trace("Create List new 'SUB' class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
IntrospectionModel inferData = null;
inferData = this.cacheModel.findOrCreate(ModelType.LIST, listTreeName, subTypeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
LOGGER.trace("Create new class: '" + typeClass.getCanonicalName() + "' for node '" + nodeName + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, listTreeName, typeClass);
// Create the data when object is ended created...
return new IntrospectionObject(inferData);
}
return null;
}
@Override
public Object newRoot() throws EjsonBuilderException, AknotException {
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, this.rootNodeName, this.rootClassType);
return new IntrospectionObject(inferData);
}
@Override
public void newString(final Object parent, final String value) throws EjsonException, AknotException {
if (parent == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) parent;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
/*if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Try inject string in an ARRAY/List data= '" + value + "' ==> " + model.getClassType());
}*/
if (model.hasTextModel()) {
final String beanName = model.getTextBeanName();
if (beanName == null) {
if (model.isIgnoreUnknown()) {
LOGGER.debug("Ignore node : **TEXT**");
return;
}
throw new EjsonBuilderException("The node **TEXT** Does not exist...");
}
final Class<?> typeClass = model.getTypeOfText();
if (typeClass != null) {
// specific case for List ==> need to get the subType in introspection ...
if (typeClass.isPrimitive()) {
final Object out = StringSerializer.valueOf(typeClass, value);
introspectionObject.putProperty(beanName, out);
} else if (typeClass.isArray()) {
LOGGER.error("Not managed !!! ");
/*
final String[] elems = propertyValue.split(";");
final Class<?> subTypeClass = typeClass.getComponentType();
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.putProperty(propertyName, out);
*/
} else if (List.class.isAssignableFrom(typeClass)) {
LOGGER.error("Not managed !!! ");
/*
final String[] elems = propertyValue.split(";");
final Class<?> subTypeClass = introspectionObject.getTypeOfSubProperty(propertyName);
LOGGER.trace("Create List new 'SUB' class: '" + typeClass.getCanonicalName() + "' for property '" + propertyName + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.putProperty(propertyName, out);
*/
} else {
//LOGGER.error("Not managed !!! ");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, typeClass);
final Object out = inferData.getValueFromText(value);
introspectionObject.putProperty(IntrospectionObject.PUBLIC_TEXT_NAME, out);
}
}
} else {
final Class<?> typeClass = model.getClassType();
if (typeClass != null) {
// specific case for List ==> need to get the subType in introspection ...
if (typeClass.isPrimitive()) {
final Object out = StringSerializer.valueOf(typeClass, value);
introspectionObject.addObject(model.getTokenBasicList(), out);
} else if (typeClass.isArray()) {
final String[] elems = value.split(";");
final Class<?> subTypeClass = typeClass.getComponentType();
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.addObject(model.getTokenBasicList(), out);
} else if (List.class.isAssignableFrom(typeClass)) {
final String[] elems = value.split(";");
final Class<?> subTypeClass = introspectionObject.getTypeOfSubNode(value, true);
LOGGER.trace("Create List new 'SUB' class: '" + typeClass.getCanonicalName() + "' for property '" + value + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.addObject(model.getTokenBasicList(), out);
} else {
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, typeClass);
final Object out = inferData.getValueFromText(value);
introspectionObject.addObject(model.getTokenBasicList(), out);
}
} else {
introspectionObject.setText(value);
}
}
}
@Override
public void newString(final Object element, final String nodeName, final String value) throws EjsonException, AknotException {
if (element == null) {
return;
}
final IntrospectionObject introspectionObject = (IntrospectionObject) element;
final IntrospectionModel model = introspectionObject.getModelIntrospection();
if (model.isArray() || model.isList()) {
throw new EjsonBuilderException("Model (List/Array) can not have property with name '" + nodeName + "'");
}
final String beanName = model.getBeanName(nodeName);
if (beanName == null) {
if (model.isIgnoreUnknown()) {
LOGGER.debug("Ignore node : '" + nodeName + "'");
return;
}
throw new EjsonBuilderException("The node '" + nodeName + "' Does not exist...");
}
// T O D O: check why we do not use the been name to get the type ..... !!!!!!!!!!!
final Class<?> typeClass = model.getTypeOfSubNode(nodeName, true);
if (typeClass != null) {
// specific case for List ==> need to get the subType in introspection ...
if (typeClass.isPrimitive()) {
final Object out = StringSerializer.valueOf(typeClass, value);
introspectionObject.addObject(nodeName, out);
} else if (typeClass.isArray()) {
final String[] elems = value.split(";");
final Class<?> subTypeClass = typeClass.getComponentType();
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.addObject(nodeName, out);
} else if (List.class.isAssignableFrom(typeClass)) {
final String[] elems = value.split(";");
final Class<?> subTypeClass = introspectionObject.getTypeOfSubNode(value, true);
LOGGER.trace("Create List new 'SUB' class: '" + typeClass.getCanonicalName() + "' for property '" + value + "'");
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, subTypeClass);
final List<Object> out = new ArrayList<>();
for (int iii = 0; iii < elems.length; iii++) {
final Object tmp = inferData.getValueFromText(elems[iii]);
out.add(tmp);
}
introspectionObject.addObject(nodeName, out);
} else {
final IntrospectionModel inferData = this.cacheModel.findOrCreate(ModelType.NORMAL, null, typeClass);
final Object out = inferData.getValueFromText(value);
introspectionObject.addObject(nodeName, out);
}
}
/*
} else {
introspectionObject.addObject(nodeName, value);
}
*/
}
}

View File

@ -0,0 +1,176 @@
package org.atriasoft.ejson.builder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.aknot.model.IntrospectionModel;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class IntrospectionObject {
final static Logger LOGGER = LoggerFactory.getLogger(IntrospectionObject.class);
public static final String PUBLIC_TEXT_NAME = "##<< ** TEXT-ZONE ** >>##";
private final IntrospectionModel modelInterface;
private Object data = null;
private final Map<String, Object> properties = new HashMap<>();
private final Map<String, List<Object>> nodes = new HashMap<>();
public IntrospectionObject(final IntrospectionModel dataInterface) {
this.modelInterface = dataInterface;
}
public void addData(final Object value) throws AknotException, EjsonException {
LOGGER.warn("Add Object in list {}", value);
final Object value2 = this.modelInterface.getValueConverted(value, this.modelInterface.getClassType());
final String uniqueName = this.modelInterface.getTokenBasicList();
if (!this.nodes.containsKey(uniqueName)) {
final List<Object> tmp = new ArrayList<>();
tmp.add(value2);
LOGGER.warn(" ==> new list");
this.nodes.put(uniqueName, tmp);
} else {
LOGGER.warn(" ==> previous list");
this.nodes.get(uniqueName).add(value2);
LOGGER.warn(" >> {}", this.nodes.get(uniqueName));
}
}
@SuppressWarnings("unchecked")
public void addObject(final String nodeName, Object value) throws EjsonException, AknotException {
if (value == null) {
// specific case when a List is empty <links></links> but define for a specific list ==> need no action
return;
}
final String beanName = this.modelInterface.getBeanName(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
List<Object> node = this.nodes.get(beanName);
// Convert in the correct internal type if needed.
final Class<?> type = this.modelInterface.getTypeOfSubNode(nodeName, true);
if (type == byte.class || type == Byte.class || type == float.class || type == Float.class || type == double.class || type == Double.class || type == long.class || type == Long.class
|| type == int.class || type == Integer.class || type == boolean.class || type == Boolean.class || type == short.class || type == Short.class) {
value = this.modelInterface.getValueConverted(value, type);
}
if (node == null) {
if (List.class.isAssignableFrom(value.getClass())) {
node = (List<Object>) value;
} else if (value.getClass().isArray()) {
LOGGER.error("this is a big problem ...");
} else {
node = new ArrayList<>();
node.add(value);
}
this.nodes.put(beanName, node);
} else if (value.getClass().isArray()) {
LOGGER.error("this is a big problem ...");
} else if (List.class.isAssignableFrom(value.getClass())) {
final List<Object> nodeIn = (List<Object>) value;
node.addAll(nodeIn);
} else {
node.add(value);
}
}
public void generateTheObject(final boolean attributeIndependent) throws AknotException {
if (this.data != null) {
// nothing to do ... ==> element already created
return;
}
LOGGER.warn("Create the element for the Specific node ... type = " + this.modelInterface.getClassType().getCanonicalName() + (this.modelInterface.isArray() ? "[array]" : "")
+ (this.modelInterface.isList() ? "[List]" : ""));
LOGGER.warn(" Properties : " + this.properties.keySet());
LOGGER.warn(" Nodes : " + this.nodes.keySet());
this.data = this.modelInterface.createObject(this.properties, this.nodes, attributeIndependent);
}
public Object getData() {
return this.data;
}
public IntrospectionModel getModelIntrospection() {
return this.modelInterface;
}
public String getTreeNameOfSubNode(final String nodeName, final boolean attributeIndependent) throws AknotException, EjsonNodeDoesNotExist {
final String beanName = this.modelInterface.getBeanName(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
return this.modelInterface.getTreeNameOfSubNode(beanName, attributeIndependent);
}
public Class<?> getTypeOfProperty(final String nodeName) throws AknotException, EjsonNodeDoesNotExist {
final String beanName = this.modelInterface.getBeanName(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
return this.modelInterface.getTypeOfProperty(beanName);
}
/**
* Detect a subNode, and ask the type of the node at the parent Class
* @param nodeName Name of the node
* @return Class of the node to create
*/
public Class<?> getTypeOfSubNode(final String nodeName, final boolean attributeIndependent) throws AknotException, EjsonNodeDoesNotExist {
final String beanName = this.modelInterface.getBeanNameModel(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
return this.modelInterface.getTypeOfSubNode(beanName, attributeIndependent);
}
public Class<?> getTypeOfSubNodeSubType(final String nodeName) throws AknotException, EjsonNodeDoesNotExist {
final String beanName = this.modelInterface.getBeanNameModel(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
return this.modelInterface.getTypeOfSubNodeList(beanName, true);
}
public Class<?> getTypeOfSubProperty(final String nodeName) throws AknotException, EjsonNodeDoesNotExist {
final String beanName = this.modelInterface.getBeanName(nodeName);
if (beanName == null) {
throw new EjsonNodeDoesNotExist("The node '" + nodeName + "' Does not exist...");
}
return this.modelInterface.getTypeOfSubProperty(beanName);
}
public boolean isSubNodeOrPropertyExist(final String nodeName) {
final String beanName = this.modelInterface.getBeanName(nodeName);
if (beanName == null) {
return false;
}
return true;
}
public void putProperty(final String propertyName, final Object propertyValue) throws AknotException, EjsonException {
String beanName = null;
if (propertyName == PUBLIC_TEXT_NAME) {
beanName = this.modelInterface.getTextBeanName();
} else {
beanName = this.modelInterface.getBeanName(propertyName);
}
if (this.properties.containsKey(beanName)) {
throw new EjsonException("Property have multiple values ==> impossible case; A Node must contain only 1 attibutes");
}
this.properties.put(beanName, propertyValue);
}
public void setText(final String text) throws AknotException, EjsonException {
if (this.data != null) {
throw new EjsonException("Can not set multiple text value in a single NODE ...");
}
this.data = this.modelInterface.getValueFromText(text);
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,4 @@
/** @file
/* @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
@ -9,50 +9,47 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.atriasoft.ejson.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** @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;
*/
public class JsonArray extends JsonNode {
final static Logger LOGGER = LoggerFactory.getLogger(JsonArray.class);
protected List<JsonNode> listSub = new ArrayList<>(); //!< List of subNodes;
/**
* Constructor
*/
public JsonArray() {
super();
};
}
/**
* 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) {
if (_node == null) {
Log.error("Try to set an empty node");
public void add(final JsonNode node) {
if (node == null) {
LOGGER.error("Try to set an empty node");
return;
}
for (int iii = 0; iii < this.listSub.size(); iii++) {
if (this.listSub.get(iii) == _node) {
Log.error("Try to add a node that is already added before !!!");
for (final JsonNode jsonNode : this.listSub) {
if (jsonNode == node) {
LOGGER.error("Try to add a node that is already added before !!!");
return;
}
}
this.listSub.add(_node);
this.listSub.add(node);
}
@Override
public void clear() {
super.clear();
this.listSub.clear();
};
}
@Override
public JsonArray clone() throws CloneNotSupportedException {
@ -65,11 +62,11 @@ public class JsonArray extends JsonNode {
/**
* 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.
*/
public boolean exist(final int _id) {
if (_id < 0 || _id >= this.listSub.size()) {
public boolean exist(final int id) {
if (id < 0 || id >= this.listSub.size()) {
return false;
}
return true;
@ -77,15 +74,15 @@ public class JsonArray extends JsonNode {
/**
* 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.
* @throws EjsonNodeDoesNotExist The Node does not exist
*/
public JsonNode get(final int _id) throws EjsonNodeDoesNotExist {
if (_id < 0 || _id >= this.listSub.size()) {
throw new EjsonNodeDoesNotExist("Node does not exist: " + _id + "/" + this.listSub.size());
public JsonNode get(final int id) throws EjsonNodeDoesNotExist {
if (id < 0 || 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 +100,7 @@ public class JsonArray extends JsonNode {
/**
* 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) {
this.listSub.remove(index);
@ -117,4 +114,4 @@ public class JsonArray extends JsonNode {
return this.listSub.size();
}
};
}

View File

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

View File

@ -0,0 +1,145 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package org.atriasoft.ejson.model;
/**
* Text node interface (internal data between two Marker: &lt;XXX&gt; ALL here &lt;/XXX&gt;
*/
public class JsonNumber extends JsonNode {
private Object value;
/**
* Constructor
*/
public JsonNumber() {
this.value = 0L;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final byte data) {
this.value = (long) data;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final double data) {
this.value = (double) data;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final float data) {
this.value = (double) data;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final int data) {
this.value = (long) data;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final long data) {
final Long tmp = data;
this.value = data;
}
/**
* Constructor
* @param data Value of the Number
*/
public JsonNumber(final short data) {
this.value = (long) data;
}
@Override
public JsonNodeType getType() {
return JsonNodeType.Number;
}
public double getValue() {
if (this.value instanceof Double tmp) {
return tmp;
}
return (Long) this.value;
}
public long getValueLong() {
if (this.value instanceof Double tmp) {
return (long) ((double) tmp);
}
return (Long) this.value;
}
public boolean isDouble() {
return this.value instanceof Double;
}
public boolean isLong() {
return this.value instanceof Long;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final byte data) {
this.value = (long) data;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final double data) {
this.value = (double) data;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final float data) {
this.value = (double) data;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final int data) {
this.value = (long) data;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final long data) {
this.value = data;
}
/**
* Set the value of the Number element
* @param data Value of the Number
*/
public void setValue(final short data) {
this.value = (long) data;
}
}

View File

@ -9,8 +9,10 @@ import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.exception.EjsonNodeDoesNotExist;
import org.atriasoft.ejson.internal.Log;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** @file
* @author Edouard DUPIN
@ -18,17 +20,17 @@ import org.atriasoft.ejson.internal.Log;
* @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 {
protected Map<String, JsonNode> listSub = new LinkedHashMap<>(); //!< List of subNodes;
final static Logger LOGGER = LoggerFactory.getLogger(JsonObject.class);
protected Map<String, JsonNode> listSub = new LinkedHashMap<>(); // !< List of subNodes;
/**
* Constructor
* Constructor
*/
public JsonObject() {
super();
};
}
@Override
public void clear() {
@ -49,29 +51,32 @@ public class JsonObject extends JsonNode {
}
});
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)
* @param[in] _name Name of the element that is requested
* get an element with his name (work only with Element)
*
* @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.
* @throws EjsonNodeDoesNotExist The Node does not exist
*/
public JsonNode get(final String _name) throws EjsonNodeDoesNotExist {
return this.listSub.get(_name);
public JsonNode get(final String name) throws EjsonNodeDoesNotExist {
return this.listSub.get(name);
}
/**
* Get the list of the sub-nodes.
* Get the list of the sub-nodes.
*
* @return List of current nodes.
*/
public Map<String, JsonNode> getNodes() {
@ -84,32 +89,36 @@ public class JsonObject extends JsonNode {
}
/**
* 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.
* add a node at the element (not Attribute (move in the attribute automaticly).
*
* @param nodeName Name of the node.
* @param node Node to add.
*/
public void put(final String nodeName, final JsonNode _node) {
if (_node == null) {
Log.error("Try to set an empty node");
public void put(final String nodeName, final JsonNode node) {
if (node == null) {
LOGGER.error("Try to set an empty node");
return;
}
this.listSub.put(nodeName, _node);
this.listSub.put(nodeName, node);
}
/**
* Remove all element with this name
* @param[in] _nodeName Name of nodes to remove.
* Remove all element with this name
*
* @param nodeName Name of nodes to remove.
*/
public void remove(final String 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.
*/
public int size() {
return this.listSub.size();
}
};
}

View File

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

View File

@ -0,0 +1,455 @@
package org.atriasoft.ejson.parser;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.builder.Builder;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonParserError;
import org.atriasoft.ejson.exception.EjsonParserErrorMulti;
import org.atriasoft.etk.Tools;
import org.atriasoft.etk.util.FilePos;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParseJson {
final static Logger LOGGER = LoggerFactory.getLogger(ParseJson.class);
// global builder that is generate the final Tree
private final Builder builder;
public ParseJson(final Builder builder) {
this.builder = builder;
}
boolean iParseArray(final Object parent, final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonException, AknotException {
for (int iii = pos.value; iii < data.length(); iii++) {
//LOGGER.trace("parse Array: '{}'", data.charAt(iii));
filePos.check(data.charAt(iii));
if (data.charAt(iii) == ' ' || data.charAt(iii) == '\t' || data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
// white space == > nothing to do ...
} else if (data.charAt(iii) == '#') {
// comment Line ...
for (iii++; iii < data.length(); iii++) {
if (data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
break;
}
}
} else if (data.charAt(iii) == ']') {
// find end of value:
pos.value = iii; // == > return the end element type ==> useful to check end and check if adding element is needed
if (parent != null) {
// continue parsing without registering object ...
this.builder.endParsing(parent);
}
return true;
} else if (data.charAt(iii) == '{') {
pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (!subParseObject(null, data, pos, filePos, parsingProperty)) {
return false;
}
} else {
final Object obj = this.builder.newObject(parent);
if (!subParseObject(obj, data, pos, filePos, parsingProperty)) {
return false;
}
this.builder.newArrayFinished(parent, null, obj);
}
iii = pos.value;
} else if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) {
return false;
}
} else {
final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) {
return false;
}
this.builder.newString(parent, dataString);
}
iii = pos.value;
} else if (data.charAt(iii) == '[') {
pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (!iParseArray(null, data, pos, filePos, parsingProperty)) {
return false;
}
} else {
final Object obj = this.builder.newArray(parent);
if (!iParseArray(obj, data, pos, filePos, parsingProperty)) {
return false;
}
}
iii = pos.value;
} else if (data.charAt(iii) == 'f' || data.charAt(iii) == 't') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
} else {
final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
this.builder.newBoolean(parent, dataBoolean);
}
iii = pos.value;
} else if (data.charAt(iii) == 'n') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false;
}
} else {
if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false;
}
this.builder.newNull(parent);
}
iii = pos.value;
} else if (Tools.checkNumber(data.charAt(iii))) {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
} else {
final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
if (dataNumber instanceof final Double vall) {
this.builder.newNumber(parent, vall);
} else if (dataNumber instanceof final Long vall) {
this.builder.newNumber(parent, vall);
}
}
iii = pos.value;
} else if (data.charAt(iii) == ',') {
// find Separator : Restart cycle ...
// TODO : check if element are separated with ','
} else if (data.charAt(iii) == '}') {
// 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)"));
// move the current index
pos.value = iii + 1;
return false;
} else {
// find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii + 1), filePos, "Find '" + data.charAt(iii) + "' with no element in the array..."));
// move the current index
pos.value = iii + 1;
return false;
}
}
pos.value = data.length();
return false;
}
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') {
pos.value += 3;
filePos.add(3);
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'
&& data.charAt(pos.value + 4) == 'e') {
pos.value += 4;
filePos.add(4);
return false;
}
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "boolean parsing error ..."));
return null;
}
boolean iParseNull(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
if (pos.value + 3 >= data.length()) {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "can not parse null !!! "));
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') {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "Not a corect 'null' element"));
return false;
}
pos.value += 3;
filePos.add(3);
return true;
}
Object iParseNumber(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
String tmpVal = "";
boolean isDouble = false;
for (int iii = pos.value; iii < data.length(); iii++) {
filePos.check(data.charAt(iii));
if (!Tools.checkNumber(data.charAt(iii))) {
pos.value = iii - 1;
// Specific for raw Parsing when using introspection model.
if (isDouble) {
return Double.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();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "get end of string whithout fincding end of quote"));
return null;
}
String iParseString(final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
final Character end = data.charAt(pos.value);
boolean backslashPrevious = false;
final StringBuilder out = new StringBuilder();
for (int iii = pos.value + 1; iii < data.length(); iii++) {
//LOGGER.trace("parse String: '{}'", data.charAt(iii));
filePos.check(data.charAt(iii));
if (data.charAt(iii) == '\\') {
if (backslashPrevious) {
out.append('\\');
backslashPrevious = false;
} else {
backslashPrevious = true;
}
} else if (data.charAt(iii) != end) {
if (backslashPrevious) {
out.append('\\');
backslashPrevious = false;
}
out.append(data.charAt(iii));
} else if (backslashPrevious) {
out.append('"');
backslashPrevious = false;
} else {
pos.value = iii;
return out.toString();
}
}
pos.value = data.length();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, pos.value), filePos, "get end of string whithout fincding end of quote"));
return null;
}
public Object parse(final String data, final ParsingProperty property) throws EjsonException, AknotException {
//LOGGER.trace("Start parsing document (type: string) size={}", data.length());
// came from char == > force in utf8 ...
final FilePos pos = new FilePos(1, 0);
final PositionParsing parsePos = new PositionParsing();
//parsePos.value = -1;
final Object rootNode = this.builder.newRoot();
subParseObject(rootNode, data, parsePos, pos, property);
if (property.isErrorDetected()) {
if (property.isThrowOnError()) {
throw new EjsonParserErrorMulti("Parsing error multiple error detected", property.getErrors());
}
return null;
}
this.builder.endParsing(rootNode);
return rootNode;
}
boolean subParseObject(final Object parent, final String data, final PositionParsing pos, final FilePos filePos, final ParsingProperty parsingProperty) throws EjsonException, AknotException {
StatusParsing mode = StatusParsing.parseName;
StringBuilder currentName = new StringBuilder();
boolean standalone = true;
int startPos = pos.value + 1;
if (data.charAt(pos.value) != '{') { // when the main node call it, it can be start with != '{'
standalone = false;
startPos = pos.value;
}
for (int iii = startPos; iii < data.length(); iii++) {
//LOGGER.trace("parse Object: '{}'", data.charAt(iii));
filePos.check(data.charAt(iii));
if (data.charAt(iii) == ' ' || data.charAt(iii) == '\t' || data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
// white space == > nothing to do ...
} else if (data.charAt(iii) == '#') {
// comment Line ...
for (iii++; iii < data.length(); iii++) {
if (data.charAt(iii) == '\n' || data.charAt(iii) == '\r') {
break;
}
}
} else if (data.charAt(iii) == '}') {
// find end of value:
pos.value = iii; // == > return the end element type ==> useful to check end and check if adding element is needed
if (parent != null) {
this.builder.endParsing(parent);
}
return true;
} else if (mode == StatusParsing.parseName) {
if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
final char startValue = data.charAt(iii);
currentName = new StringBuilder();
for (iii++; iii < data.length(); iii++) {
filePos.check(data.charAt(iii));
if (data.charAt(iii) == startValue) {
mode = StatusParsing.parseMiddle;
break;
}
currentName.append(data.charAt(iii));
}
} else if (Tools.checkString(data.charAt(iii))) {
currentName.append(data.charAt(iii));
for (iii++; iii < data.length(); iii++) {
filePos.check(data.charAt(iii));
if (!Tools.checkString(data.charAt(iii))) {
mode = StatusParsing.parseMiddle;
iii--;
break;
}
currentName.append(data.charAt(iii));
}
} else {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "element unknow ..."));
pos.value = iii;
return false;
}
} else if (mode == StatusParsing.parseMiddle) {
if (data.charAt(iii) != ':') {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "separator is not ':'"));
return false;
}
mode = StatusParsing.parseValue;
} else if (mode == StatusParsing.parseValue) {
if (data.charAt(iii) == '{') {
pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (!subParseObject(null, data, pos, filePos, parsingProperty)) {
return false;
}
} else {
final Object obj = this.builder.newObject(parent, currentName.toString());
if (!subParseObject(obj, data, pos, filePos, parsingProperty)) {
return false;
}
this.builder.newArrayFinished(parent, currentName.toString(), obj);
}
iii = pos.value;
currentName = new StringBuilder();
} else if (data.charAt(iii) == '"' || data.charAt(iii) == '\'') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) {
return false;
}
} else {
final String dataString = iParseString(data, pos, filePos, parsingProperty);
if (dataString == null) {
return false;
}
this.builder.newString(parent, currentName.toString(), dataString);
}
iii = pos.value;
currentName = new StringBuilder();
} else if (data.charAt(iii) == '[') {
pos.value = iii + 1;
if (parent == null) {
// continue parsing without registering object ...
if (!iParseArray(null, data, pos, filePos, parsingProperty)) {
return false;
}
} else {
final Object obj = this.builder.newArray(parent, currentName.toString());
if (!iParseArray(obj, data, pos, filePos, parsingProperty)) {
return false;
}
this.builder.newArrayFinished(parent, currentName.toString(), obj);
}
iii = pos.value;
currentName = new StringBuilder();
} else if (data.charAt(iii) == 'f' || data.charAt(iii) == 't') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
} else {
final Boolean dataBoolean = iParseBoolean(data, pos, filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
this.builder.newBoolean(parent, currentName.toString(), dataBoolean);
}
iii = pos.value;
currentName = new StringBuilder();
} else if (data.charAt(iii) == 'n') {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false;
}
} else {
if (!iParseNull(data, pos, filePos, parsingProperty)) {
return false;
}
this.builder.newNull(parent, currentName.toString());
}
iii = pos.value;
currentName = new StringBuilder();
} else if (Tools.checkNumber(data.charAt(iii))) {
pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
} else {
final Object dataNumber = iParseNumber(data, pos, filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
if (dataNumber instanceof final Double valll) {
this.builder.newNumber(parent, currentName.toString(), valll);
} else if (dataNumber instanceof final Long valll) {
this.builder.newNumber(parent, currentName.toString(), valll);
}
}
iii = pos.value;
currentName = new StringBuilder();
} else if (data.charAt(iii) == ',') {
// find Separator : Restart cycle ...
mode = StatusParsing.parseName;
currentName = new StringBuilder();
} else {
// find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(data, iii), filePos, "Find '" + data.charAt(iii) + "' with no element in the element..."));
// move the curent index
pos.value = iii + 1;
return false;
}
}
}
pos.value = data.length();
return !standalone;
}
}
enum StatusParsing {
parseMiddle, parseName, parseValue,
}

View File

@ -4,22 +4,24 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.atriasoft.aknot.pojo.IntrospectionProperty;
import org.atriasoft.ejson.exception.EjsonParserError;
import org.atriasoft.ejson.internal.Log;
import org.atriasoft.etk.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ParsingProperty {
final static Logger LOGGER = LoggerFactory.getLogger(ParsingProperty.class);
/// check the case sensitive of the nodes (end marker) and attribute (duplicates)
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
private final List<EjsonParserError> errors = new ArrayList<>();
/// Permissive XML parsing (allows some errors must not be critical).
private boolean permisiveXML = false;
/// 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
@ -48,23 +50,23 @@ public class ParsingProperty {
*/
public boolean createError(final EjsonParserError error) throws EjsonParserError {
// need display the error
if (this.writeError == true) {
if (this.writeError) {
displayError(error);
}
// need throw the error
if (this.throwOnError == true && this.permisiveXML == false) {
if (this.throwOnError && !this.permisiveXML) {
throw error;
}
// Keep it in case
this.errors.add(error);
return this.permisiveXML == false;
return !this.permisiveXML;
}
/**
* Request Display in log all the errors.
*/
public void displayError() {
this.errors.forEach(o -> displayError(o));
this.errors.forEach(this::displayError);
}
/**
@ -72,7 +74,7 @@ public class ParsingProperty {
* @param error The error to display.
*/
public void displayError(final EjsonParserError error) {
Log.error(error.getFilePos() + " " + error.getMessage() + "\n" + error.getDataLine() + "\n" + Tools.createPosPointer(error.getDataLine(), error.getFilePos().getCol()));
LOGGER.error("{} {}\n{}\n", error.getFilePos(), error.getMessage(), error.getDataLine(), Tools.createPosPointer(error.getDataLine(), error.getFilePos().getCol()));
}
/**
@ -100,20 +102,12 @@ public class ParsingProperty {
return Collections.unmodifiableList(this.errors);
}
/**
* Get the current storing mode
* @return store element and attribute values
*/
public StoreMode getStoreMode() {
return this.storeMode;
}
/**
* Check is error has been detected
* @return true if some error are stored.
*/
public boolean isErrorDetected() {
return this.errors.isEmpty() == false;
return !this.errors.isEmpty();
}
/**
@ -134,18 +128,18 @@ public class ParsingProperty {
/**
* 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) {
this.caseSensitive = _val;
public void setCaseSensitive(final boolean val) {
this.caseSensitive = val;
}
/**
* 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) {
this.writeError = _value;
public void setDisplayError(final boolean value) {
this.writeError = value;
}
/**
@ -156,14 +150,6 @@ public class ParsingProperty {
this.permisiveXML = permisiveXML;
}
/**
* Set the new storing mode for Element and Attributes
* @param storeMode new Storing mode
*/
public void setStoreMode(final StoreMode storeMode) {
this.storeMode = storeMode;
}
/**
* Set throwing on error (if permissive, it throw at the end of parsing)
* @param throwOnError true if it throw on error.

View File

@ -1,19 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
open module org.atriasoft.ejson {
exports org.atriasoft.ejson;
exports org.atriasoft.ejson.model;
exports org.atriasoft.ejson.exception;
exports org.atriasoft.ejson.builder;
exports org.atriasoft.ejson.parser;
exports org.atriasoft.ejson.annotation;
requires transitive org.atriasoft.etk;
requires transitive io.scenarium.logger;
requires java.base;
}

View File

@ -1,19 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Meta-annotation (annotations used on other annotations)
* used for marking all annotations that are
* part of Ejson package. Can be used for recognizing all
* Ejson annotations generically, and in future also for
* passing other generic annotation configuration.
*/
@Target({ ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface EjsonAnnotation {
// for now, a pure tag annotation, no parameters
}

View File

@ -1,21 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that set the element are not managed by default. Need to add @JsonManaged to be enable.
*
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation
public @interface JsonDefaultManaged {
/**
* Set this at false to remove all the field and the function from Json introspection
* @return true if the element are by default managed.
*/
boolean value() default true;
}

View File

@ -1,21 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that set the element not found are ignored.
*
*/
@Target({ ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation
public @interface JsonDefaultOptional {
/**
* Set this at true to set all the element optional.
* @return true if the element are by default optional.
*/
boolean value() default false;
}

View File

@ -1,21 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that force the json Parser to manage this element (used when the class is mark as @JsondefaultNotManaged).
*
*/
@Target({ ElementType.FIELD, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation
public @interface JsonManaged {
/**
* Set this at false to remove this function or this field form the XML parsing system
* @return true if the element is managed.
*/
boolean value() default true;
}

View File

@ -1,23 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that can be used to define an other name of the attribute or the Element name.
*
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation
public @interface JsonName {
/**
* Names of the property of the Element name
* @note The first name if the default generated in serialization.
* @return The list the the possible names
*/
String[] value();
}

View File

@ -1,21 +0,0 @@
package org.atriasoft.ejson.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Marker annotation that to ignore the element if not present in the XML, the default case the parser throw a missing error.
*
*/
@Target({ ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER })
@Retention(RetentionPolicy.RUNTIME)
@EjsonAnnotation
public @interface JsonOptional {
/**
* Set if the element is optional or not. If optional, the parser does not throw error if the element is not declared.
* @return thru if optional
*/
boolean value() default true;
}

View File

@ -1,73 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package org.atriasoft.ejson.internal;
import io.scenarium.logger.LogLevel;
import io.scenarium.logger.Logger;
public class Log {
private static final String LIB_NAME = "ejson";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
public static void critical(final String data) {
if (PRINT_CRITICAL) {
Logger.critical(LIB_NAME_DRAW, data);
}
}
public static void debug(final String data) {
if (PRINT_DEBUG) {
Logger.debug(LIB_NAME_DRAW, data);
}
}
public static void error(final String data) {
if (PRINT_ERROR) {
Logger.error(LIB_NAME_DRAW, data);
}
}
public static void info(final String data) {
if (PRINT_INFO) {
Logger.info(LIB_NAME_DRAW, data);
}
}
public static void print(final String data) {
if (PRINT_PRINT) {
Logger.print(LIB_NAME_DRAW, data);
}
}
public static void todo(final String data) {
if (PRINT_TODO) {
Logger.todo(LIB_NAME_DRAW, data);
}
}
public static void verbose(final String data) {
if (PRINT_VERBOSE) {
Logger.verbose(LIB_NAME_DRAW, data);
}
}
public static void warning(final String data) {
if (PRINT_WARNING) {
Logger.warning(LIB_NAME_DRAW, data);
}
}
private Log() {}
}

View File

@ -1,164 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package org.atriasoft.ejson.model;
/**
* Text node interface (internal data between two Marker: &lt;XXX&gt; ALL here &lt;/XXX&gt;
*/
public class JsonNumber extends JsonNode {
private Object value;
/**
* Constructor
*/
public JsonNumber() {
final Long tmp = 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
* @param[in] _data Value of the Number
*/
public JsonNumber(final double _data) {
super();
final Double tmp = (double) _data;
this.value = tmp;
}
/**
* Constructor
* @param[in] _data Value of the Number
*/
public JsonNumber(final float _data) {
super();
final Double tmp = (double) _data;
this.value = tmp;
}
/**
* Constructor
* @param[in] _data Value of the Number
*/
public JsonNumber(final int _data) {
super();
final Long tmp = (long) _data;
this.value = tmp;
}
/**
* Constructor
* @param[in] _data Value of the Number
*/
public JsonNumber(final long _data) {
super();
final Long tmp = _data;
this.value = tmp;
}
/**
* Constructor
* @param[in] _data Value of the Number
*/
public JsonNumber(final short _data) {
super();
final Long tmp = (long) _data;
this.value = tmp;
}
@Override
public JsonNodeType getType() {
return JsonNodeType.Number;
}
public double getValue() {
if (this.value instanceof Double) {
return (Double) this.value;
}
return (Long) this.value;
}
public long getValueLong() {
if (this.value instanceof Double) {
final double val = (Double) this.value;
return (long) val;
}
return (Long) this.value;
}
public boolean isDouble() {
return this.value instanceof Double;
}
public boolean isLong() {
return this.value instanceof Long;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final byte _data) {
final Long tmp = (long) _data;
this.value = tmp;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final double _data) {
final Double tmp = (double) _data;
this.value = tmp;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final float _data) {
final Double tmp = (double) _data;
this.value = tmp;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final int _data) {
final Long tmp = (long) _data;
this.value = tmp;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final long _data) {
final Long tmp = _data;
this.value = tmp;
}
/**
* Set the value of the Number element
* @param[in] _data Value of the Number
*/
public void setValue(final short _data) {
final Long tmp = (long) _data;
this.value = tmp;
}
};

View File

@ -1,185 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package org.atriasoft.ejson.parser;
/** @file
* @author Edouard DUPIN
* @copyright 2011, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
/**
* Position in the file of the original data.
*/
public class FilePos {
private int col; //!< source text colomn
private int line; //!< source Line colomn
/**
* default contructor (set line and col at 0)
*/
public FilePos() {
this.col = 0;
this.line = 0;
}
/**
* initialize constructor
* @param[in] _line Line in the file
* @param[in] _col Colomn in the file
*/
public FilePos(final int _line, final int _col) {
this.col = _col;
this.line = _line;
}
/**
* Addition operator
* @param[in] _obj Addition object..
* @return Reference on this
*/
public FilePos add(final FilePos _obj) {
if (_obj.line == 0) {
this.col += _obj.col;
} else {
this.col = _obj.col;
this.line += _obj.line;
}
return this;
}
/**
* Colomn addition operator
* @param[in] _col Number of colomn to add
* @return Reference on this
*/
public FilePos add(final int _col) {
this.col += _col;
return this;
}
/**
* Check if the value is a new line and update internal property
* @param[in] _val Char value to check
* @return true We find a new line
* @return false We NOT find a new line
*/
public boolean check(final Character _val) {
this.col++;
if (_val == '\n') {
newLine();
return true;
}
return false;
}
/**
* Reset position at 0,0
*/
public void clear() {
this.col = 0;
this.line = 0;
}
@Override
public FilePos clone() {
final FilePos out = new FilePos();
out.col = this.col;
out.line = this.line;
return out;
}
/**
* Decrement the colomn position
* @return Reference on this
*/
public FilePos decrement() {
this.col--;
return this;
}
@Override
public boolean equals(final Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof FilePos)) {
return false;
}
final FilePos other = (FilePos) obj;
return this.col == other.col && this.line == other.line;
}
/**
* Get the colomn position
* @return Colomn in number of utf8-char
*/
public int getCol() {
return this.col;
}
/**
* Get the line number position
* @return line ID (start at 0)
*/
public int getLine() {
return this.line;
}
@Override
public int hashCode() {
return super.hashCode() + this.line + this.col;
}
/**
* Increment the colomn position
* @return Reference on this
*/
public FilePos increment() {
this.col++;
return this;
}
/**
* Find a new line & reset colomn at 0
*/
public void newLine() {
this.col = 0;
this.line++;
}
/**
* Asignment operator
* @param[in] _obj Object to copy
* @return Reference on this
*/
public FilePos set(final FilePos _obj) {
this.col = _obj.col;
this.line = _obj.line;
return this;
}
/**
* Setter of specific data
* @param[in] _line Line in the file
* @param[in] _col Colomn in the file
*/
public void set(final int _line, final int _col) {
this.col = _col;
this.line = _line;
}
@Override
public String toString() {
String out = "(l=";
out += this.line;
out += ",c=";
out += this.col;
out += ")";
return out;
}
};

View File

@ -1,447 +0,0 @@
package org.atriasoft.ejson.parser;
import org.atriasoft.ejson.builder.Builder;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonParserError;
import org.atriasoft.ejson.exception.EjsonParserErrorMulti;
import org.atriasoft.ejson.internal.Log;
public class ParseJson {
// global builder that is generate the final Tree
private final Builder builder;
public ParseJson(final Builder builder) {
this.builder = builder;
}
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++) {
//Log.verbose("parse Array: '" + _data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii));
if (_data.charAt(iii) == ' ' || _data.charAt(iii) == '\t' || _data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') {
// white space == > nothing to do ...
} else if (_data.charAt(iii) == '#') {
// comment Line ...
for (iii++; iii < _data.length(); iii++) {
if (_data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') {
break;
}
}
} else if (_data.charAt(iii) == ']') {
// find end of value:
_pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed
return true;
} else if (_data.charAt(iii) == '{') {
_pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (iParseObject(null, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
final Object obj = this.builder.newObject(parent);
if (iParseObject(obj, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
}
iii = _pos.value;
} else if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty);
if (dataString == null) {
return false;
}
} else {
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty);
if (dataString == null) {
return false;
}
this.builder.newString(parent, dataString);
}
iii = _pos.value;
} else if (_data.charAt(iii) == '[') {
_pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (iParseArray(null, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
final Object obj = this.builder.newArray(parent);
if (iParseArray(obj, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
}
iii = _pos.value;
} else if (_data.charAt(iii) == 'f' || _data.charAt(iii) == 't') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
} else {
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
this.builder.newBoolean(parent, dataBoolean);
}
iii = _pos.value;
} else if (_data.charAt(iii) == 'n') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) {
return false;
}
this.builder.newNull(parent);
}
iii = _pos.value;
} else if (true == Tools.checkNumber(_data.charAt(iii))) {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
} else {
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
if (dataNumber instanceof Double) {
this.builder.newNumber(parent, (Double) dataNumber);
} else if (dataNumber instanceof Long) {
this.builder.newNumber(parent, (Long) dataNumber);
}
}
iii = _pos.value;
} else if (_data.charAt(iii) == ',') {
// find Separator : Restart cycle ...
// TODO : check if element are separated with ','
} else if (_data.charAt(iii) == '}') {
// 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)"));
// move the curent index
_pos.value = iii + 1;
return false;
} else {
// find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii + 1), _filePos, "Find '" + _data.charAt(iii) + "' with no element in the array..."));
// move the curent index
_pos.value = iii + 1;
return false;
}
}
_pos.value = _data.length();
return false;
}
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') {
_pos.value += 3;
_filePos.add(3);
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'
&& _data.charAt(_pos.value + 4) == 'e') {
_pos.value += 4;
_filePos.add(4);
return false;
}
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "boolean parsing error ..."));
return null;
}
boolean iParseNull(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
if (_pos.value + 3 >= _data.length()) {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "can not parse null !!! "));
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') {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "Not a corect 'null' element"));
return false;
}
_pos.value += 3;
_filePos.add(3);
return true;
}
Object iParseNumber(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
String tmpVal = "";
boolean isDouble = false;
for (int iii = _pos.value; iii < _data.length(); iii++) {
_filePos.check(_data.charAt(iii));
if (Tools.checkNumber(_data.charAt(iii)) == true) {
if (_data.charAt(iii) == '.' || _data.charAt(iii) == 'e' || _data.charAt(iii) == '^') {
isDouble = true;
}
tmpVal += _data.charAt(iii);
} else {
_pos.value = iii - 1;
if (isDouble == true) {
return Double.valueOf(tmpVal);
} else {
return Long.valueOf(tmpVal);
}
}
}
_pos.value = _data.length();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "get end of string whithout fincding end of quote"));
return null;
}
boolean iParseObject(final Object parent, final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws Exception {
statusParsing mode = statusParsing.parseName;
String currentName = "";
boolean standalone = true;
int startPos = _pos.value + 1;
if (_data.charAt(_pos.value) != '{') { // when the main node call it, it can be start with != '{'
standalone = false;
startPos = _pos.value;
}
for (int iii = startPos; iii < _data.length(); iii++) {
//Log.verbose("parse Object: '" + _data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii));
final FilePos tmpPos;
if (_data.charAt(iii) == ' ' || _data.charAt(iii) == '\t' || _data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') {
// white space == > nothing to do ...
} else if (_data.charAt(iii) == '#') {
// comment Line ...
for (iii++; iii < _data.length(); iii++) {
if (_data.charAt(iii) == '\n' || _data.charAt(iii) == '\r') {
break;
}
}
} else if (_data.charAt(iii) == '}') {
// find end of value:
_pos.value = iii; // == > return the end element type ==> usefull to check end and check if adding element is needed
return true;
} else if (mode == statusParsing.parseName) {
if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') {
final char startValue = _data.charAt(iii);
currentName = "";
for (iii++; iii < _data.length(); iii++) {
_filePos.check(_data.charAt(iii));
if (_data.charAt(iii) == startValue) {
mode = statusParsing.parseMiddle;
break;
} else {
currentName += _data.charAt(iii);
}
}
} else if (Tools.checkString(_data.charAt(iii))) {
currentName += _data.charAt(iii);
for (iii++; iii < _data.length(); iii++) {
_filePos.check(_data.charAt(iii));
if (false == Tools.checkString(_data.charAt(iii))) {
mode = statusParsing.parseMiddle;
iii--;
break;
} else {
currentName += _data.charAt(iii);
}
}
} else {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "element unknow ..."));
_pos.value = iii;
return false;
}
} else if (mode == statusParsing.parseMiddle) {
if (_data.charAt(iii) == ':') {
mode = statusParsing.parseValue;
} else {
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "separator is not ':'"));
return false;
}
} else if (mode == statusParsing.parseValue) {
if (_data.charAt(iii) == '{') {
_pos.value = iii + 1;
// find an object:
if (parent == null) {
// continue parsing without registering object ...
if (iParseObject(null, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
final Object obj = this.builder.newObject(parent, currentName);
if (iParseObject(obj, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
}
iii = _pos.value;
currentName = "";
} else if (_data.charAt(iii) == '"' || _data.charAt(iii) == '\'') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty);
if (dataString == null) {
return false;
}
} else {
final String dataString = iParseString(_data, _pos, _filePos, parsingProperty);
if (dataString == null) {
return false;
}
this.builder.newString(parent, currentName, dataString);
}
iii = _pos.value;
currentName = "";
} else if (_data.charAt(iii) == '[') {
_pos.value = iii + 1;
if (parent == null) {
// continue parsing without registering object ...
if (iParseArray(null, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
final Object obj = this.builder.newArray(parent, currentName);
if (iParseArray(obj, _data, _pos, _filePos, parsingProperty) == false) {
return false;
}
}
iii = _pos.value;
currentName = "";
} else if (_data.charAt(iii) == 'f' || _data.charAt(iii) == 't') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
} else {
final Boolean dataBoolean = iParseBoolean(_data, _pos, _filePos, parsingProperty);
if (dataBoolean == null) {
return false;
}
this.builder.newBoolean(parent, currentName, dataBoolean);
}
iii = _pos.value;
currentName = "";
} else if (_data.charAt(iii) == 'n') {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) {
return false;
}
} else {
if (iParseNull(_data, _pos, _filePos, parsingProperty) == false) {
return false;
}
this.builder.newNull(parent, currentName);
}
iii = _pos.value;
currentName = "";
} else if (true == Tools.checkNumber(_data.charAt(iii))) {
_pos.value = iii;
if (parent == null) {
// continue parsing without registering object ...
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
} else {
final Object dataNumber = iParseNumber(_data, _pos, _filePos, parsingProperty);
if (dataNumber == null) {
return false;
}
if (dataNumber instanceof Double) {
this.builder.newNumber(parent, currentName, (Double) dataNumber);
} else if (dataNumber instanceof Long) {
this.builder.newNumber(parent, currentName, (Long) dataNumber);
}
}
iii = _pos.value;
currentName = "";
} else if (_data.charAt(iii) == ',') {
// find Separator : Restart cycle ...
mode = statusParsing.parseName;
currentName = "";
} else {
// find an error ....
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, iii), _filePos, "Find '" + _data.charAt(iii) + "' with no element in the element..."));
// move the curent index
_pos.value = iii + 1;
return false;
}
}
}
_pos.value = _data.length();
if (standalone == false) {
return true;
}
return false;
}
String iParseString(final String _data, final PositionParsing _pos, final FilePos _filePos, final ParsingProperty parsingProperty) throws EjsonBuilderException {
final Character end = _data.charAt(_pos.value);
boolean backslashPrevious = false;
String out = "";
for (int iii = _pos.value + 1; iii < _data.length(); iii++) {
//Log.verbose("parse String: '" + _data.charAt(iii) + "'");
_filePos.check(_data.charAt(iii));
if (_data.charAt(iii) == '\\') {
if (backslashPrevious == true) {
out += '\\';
backslashPrevious = false;
} else {
backslashPrevious = true;
}
} else if (_data.charAt(iii) != end) {
if (backslashPrevious == true) {
out += '\\';
backslashPrevious = false;
}
out += _data.charAt(iii);
} else if (backslashPrevious == true) {
out += '"';
backslashPrevious = false;
} else {
_pos.value = iii;
return out;
}
}
_pos.value = _data.length();
parsingProperty.createError(new EjsonParserError(Tools.extractLine(_data, _pos.value), _filePos, "get end of string whithout fincding end of quote"));
return null;
}
public Object parse(final String data, final ParsingProperty property) throws Exception, EjsonBuilderException, EjsonParserErrorMulti {
Log.verbose("Start parsing document (type: string) size=" + data.length());
// came from char == > force in utf8 ...
final FilePos pos = new FilePos(1, 0);
final PositionParsing parsePos = new PositionParsing();
//parsePos.value = -1;
final Object rootNode = this.builder.newRoot();
iParseObject(rootNode, data, parsePos, pos, property);
if (property.isErrorDetected() == true) {
if (property.isThrowOnError() == true) {
throw new EjsonParserErrorMulti("Parsing error multiple error detected", property.getErrors());
}
return null;
}
return rootNode;
}
};
enum statusParsing {
parseName,
parseMiddle,
parseValue,
}

View File

@ -1,7 +0,0 @@
package org.atriasoft.ejson.parser;
public enum StoreMode {
NORMAL,
UPPERCASE,
LOWERCASE,
}

View File

@ -1,299 +0,0 @@
package org.atriasoft.ejson.parser;
public class Tools {
/**
* add indentation of the string input.
* @param[in,out] _data String where the indentation is done.
* @param[in] _indent Number of tab to add at the string.
*/
public static void addIndent(final StringBuilder _data, final int _indent) {
for (int iii = 0; iii < _indent; iii++) {
_data.append("\t");
}
}
/**
* 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[in] _firstChar True if the element check is the first char.
* @return true The value can 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) {
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 == '\n' || _val == '\t'
|| _val == '\r') {
return false;
}
if (_firstChar == true) {
if (_val == '-' || _val == '.' || (_val >= '0' && _val <= '9')) {
return false;
}
}
return true;
}
public static boolean checkNumber(final Character _val) {
if (_val == '-' || _val == '+' || _val == 'e' || _val == '.' || (_val >= '0' && _val <= '9')) {
return true;
}
return false;
}
public static boolean checkString(final Character _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 == '\n'
|| _val == '\t' || _val == '\r') {
return false;
}
return true;
}
public static String cleanNumberList(final String data) {
return data.replaceAll("[ \t\n\r]", "").replaceAll(",", ";");
}
/**
* 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[in] _pos Start position in the string.
* @param[out] _filePos new poistion of te file to add.
* @return number of white element.
*/
public static int countWhiteChar(final String _data, final int _pos, final FilePos _filePos) {
_filePos.clear();
int white = 0;
for (int iii = _pos; iii < _data.length(); iii++) {
_filePos.check(_data.charAt(iii));
if (Tools.isWhiteChar(_data.charAt(iii)) == true) {
white++;
} else {
break;
}
}
_filePos.decrement();
return white;
}
public static String createPosPointer(final String _line, final int _pos) {
String out = "";
int iii;
for (iii = 0; iii < _pos && iii < _line.length(); iii++) {
if (_line.charAt(iii) == '\t') {
out += "\t";
} else {
out += " ";
}
}
for (; iii < _pos; iii++) {
out += " ";
}
out += "^";
return out;
}
// based on this: https://stackoverflow.com/questions/4052840/most-efficient-way-to-make-the-first-character-of-a-string-lower-case
public static String decapitalizeFirst(final String string) {
if (string == null || string.length() == 0) {
return string;
}
final char c[] = string.toCharArray();
c[0] = Character.toLowerCase(c[0]);
return new String(c);
}
/**
* Display the cuurent element that is curently parse.
* @param[in] _val Char that is parsed.
* @param[in] _filePos Position of the char in the file.
*/
public static void drawElementParsed(final Character _val, final FilePos _filePos) {
// if (_val == '\n') {
// Log.debug(_filePos + " parse '\\n'");
// } else if (_val == '\t') {
// Log.debug(_filePos + " parse '\\t'");
// } else {
// Log.debug(_filePos + " parse '" + _val + "'");
// }
}
public static String extractLine(final String data, final int _pos) {
// search back : '\n'
int startPos = data.lastIndexOf('\n', _pos);
if (startPos == _pos) {
startPos = 0;
} else {
startPos++;
}
// search forward : '\n'
int stopPos = _pos;
if (data.length() == _pos) {
stopPos = _pos;
} else if (data.charAt(_pos) != '\n') {
stopPos = data.indexOf('\n', _pos);
if (stopPos == _pos) {
stopPos = data.length();
}
}
if (startPos == -1) {
startPos = 0;
} else if (startPos >= data.length()) {
return "";
}
if (stopPos == -1) {
return "";
} else if (stopPos >= data.length()) {
stopPos = data.length();
}
return data.substring(startPos, stopPos);
}
public static boolean isWhiteChar(final Character _val) {
if (_val == ' ' || _val == '\t' || _val == '\n' || _val == '\r') {
return true;
}
return false;
}
public static Boolean[] parseBooleanClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final Boolean[] out = new Boolean[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Boolean.valueOf(str);
}
return out;
}
public static boolean[] parseBooleanStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final boolean[] out = new boolean[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Boolean.valueOf(str);
}
return out;
}
public static Byte[] parseByteClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final Byte[] out = new Byte[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Byte.parseByte(str);
}
return out;
}
public static byte[] parseByteStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final byte[] out = new byte[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Byte.parseByte(str);
}
return out;
}
public static Integer[] parseIntegerClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final Integer[] out = new Integer[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Integer.parseInt(str);
}
return out;
}
public static int[] parseIntegerStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final int[] out = new int[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Integer.parseInt(str);
}
return out;
}
public static Long[] parseLongClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final Long[] out = new Long[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Long.parseLong(str);
}
return out;
}
public static long[] parseLongStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final long[] out = new long[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Long.parseLong(str);
}
return out;
}
public static Short[] parseShortClassStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final Short[] out = new Short[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Short.parseShort(str);
}
return out;
}
public static short[] parseShortStringList(String data) { // throws NumberFormatException
data = cleanNumberList(data);
final String dataArray[] = data.split(";");
final short[] out = new short[dataArray.length];
int count = 0;
for (final String str : dataArray) {
out[count++] = Short.parseShort(str);
}
return out;
}
// transform the Text with :
// "&lt;" == "<"
// "&gt;" == ">"
// "&amp;" == "&"
// "&apos;" == "'"
// "&quot;" == """
public static String replaceSpecialChar(final String _inval) {
final String out = _inval;
out.replace("&lt;", "<");
out.replace("&gt;", ">");
out.replace("&apos;", "'");
out.replace("&quot;", "\"");
out.replace("&amp;", "&");
//EXML_ERROR("INNN '"<< _inval << "' => '" << out << "'");
return out;
}
public static String replaceSpecialCharOut(final String _inval) {
final String out = _inval;
out.replace("<", "&lt;");
out.replace(">", "&gt;");
out.replace("'", "&apos;");
out.replace("\"", "&quot;");
out.replace("&", "&amp;");
//EXML_ERROR("OUTTT '"<< _inval << "' => '" << out << "'");
return out;
}
private Tools() {}
}

View File

@ -0,0 +1,47 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson.generic;
import org.atriasoft.ejson.Ejson;
import org.atriasoft.ejson.model.JsonNode;
import org.atriasoft.ejson.parser.ParsingProperty;
import org.junit.jupiter.api.Assertions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
class EjsonLocal {
final static Logger LOGGER = LoggerFactory.getLogger(ParsingProperty.class);
// 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) {
//doc.setCaseSensitive(!caseInSensitive);
LOGGER.trace("parse : \n{}", input);
JsonNode root = null;
try {
root = Ejson.parse(input);
if (errorPos == 1) {
Assertions.fail("Must have detected an error");
return;
}
} catch (final Exception e) {
if (errorPos == 1) {
return;
}
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
}
final StringBuilder out = new StringBuilder();
// TODO 2 is for failing in generate ...
Ejson.generate(root, out);
final String data = out.toString();
if (errorPos == 3) {
Assertions.assertNotEquals(ref, data);
}
Assertions.assertEquals(ref, data);
}
private EjsonLocal() {}
}

View File

@ -0,0 +1,349 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson.generic;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EjsonTestAll {
final static Logger LOGGER = LoggerFactory.getLogger(EjsonTestAll.class);
//@formatter:off
private static String refOutputAll = """
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{ "value": "Close", "onclick": "CloseDoc()" },
{ "value": "New", "onclick": "CreateNewDoc()" },
{ "value": "Open", "onclick": "OpenDoc()" },
{ "value": "Close", "onclick": "CloseDoc()" }
]
}
}
}""";
//@formatter:on
@BeforeAll
public static void beforeClass() {
LOGGER.trace("----------------------------------------------------------------");
}
@Test
public void testBaseObject() {
//@formatter:off
final String base = """
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": { "value": "Close", "onclick": "CloseDoc()" }
}
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric1() {
//@formatter:off
final String base = """
{
"glossary": {
"title": "example glossary",
"GlossDiv": {
"title": "S",
"GlossList": {
"GlossEntry": {
"ID": "SGML",
"SortAs": "SGML",
"GlossTerm": "Standard Generalized Markup Language",
"Acronym": "SGML",
"Abbrev": "ISO 8879:1986",
"GlossDef": {
"para": "A meta-markup language, used to create markup languages such as DocBook.",
"GlossSeeAlso": [ "GML", "XML" ]
},
"GlossSee": "markup"
}
}
}
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric2() {
//@formatter:off
final String base = """
{
"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{ "value": "New", "onclick": "CreateNewDoc()" },
{ "value": "Open", "onclick": "OpenDoc()" },
{ "value": "Close", "onclick": "CloseDoc()" }
]
}
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric3() {
//@formatter:off
final String base = """
{
"widget": {
"debug": "on",
"window": {
"title": "Sample Konfabulator Widget",
"name": "main_window",
"width": 500,
"height": 500
},
"image": {
"src": "Images/Sun.png",
"name": "sun1",
"hOffset": 250,
"vOffset": 250,
"alignment": "center"
},
"text": {
"data": "Click Here",
"size": 36,
"style": "bold",
"name": "text1",
"hOffset": 250,
"vOffset": 100,
"alignment": "center",
"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
}
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric4() {
//@formatter:off
final String base = """
{
"web-app": {
"servlet": [
{
"servlet-name": "cofaxCDS",
"servlet-class": "org.cofax.cds.CDSServlet",
"init-param": {
"configGlossary:installationAt": "Philadelphia, PA",
"configGlossary:adminEmail": "ksm@pobox.com",
"configGlossary:poweredBy": "Cofax",
"configGlossary:poweredByIcon": "/images/cofax.gif",
"configGlossary:staticPath": "/content/static",
"templateProcessorClass": "org.cofax.WysiwygTemplate",
"templateLoaderClass": "org.cofax.FilesTemplateLoader",
"templatePath": "templates",
"templateOverridePath": "",
"defaultListTemplate": "listTemplate.htm",
"defaultFileTemplate": "articleTemplate.htm",
"useJSP": false,
"jspListTemplate": "listTemplate.jsp",
"jspFileTemplate": "articleTemplate.jsp",
"cachePackageTagsTrack": 200,
"cachePackageTagsStore": 200,
"cachePackageTagsRefresh": 60,
"cacheTemplatesTrack": 100,
"cacheTemplatesStore": 50,
"cacheTemplatesRefresh": 15,
"cachePagesTrack": 200,
"cachePagesStore": 100,
"cachePagesRefresh": 10,
"cachePagesDirtyRead": 10,
"searchEngineListTemplate": "forSearchEnginesList.htm",
"searchEngineFileTemplate": "forSearchEngines.htm",
"searchEngineRobotsDb": "WEB-INF/robots.db",
"useDataStore": true,
"dataStoreClass": "org.cofax.SqlDataStore",
"redirectionClass": "org.cofax.SqlRedirection",
"dataStoreName": "cofax",
"dataStoreDriver": "com.microsoft.jdbc.sqlserver.SQLServerDriver",
"dataStoreUrl": "jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon",
"dataStoreUser": "sa",
"dataStorePassword": "dataStoreTestQuery",
"dataStoreTestQuery": "SET NOCOUNT ON;select test='test';",
"dataStoreLogFile": "/usr/local/tomcat/logs/datastore.log",
"dataStoreInitConns": 10,
"dataStoreMaxConns": 100,
"dataStoreConnUsageLimit": 100,
"dataStoreLogLevel": "debug",
"maxUrlLength": 500
}
},
{
"servlet-name": "cofaxEmail",
"servlet-class": "org.cofax.cds.EmailServlet",
"init-param": { "mailHost": "mail1", "mailHostOverride": "mail2" }
},
{
"servlet-name": "cofaxAdmin",
"servlet-class": "org.cofax.cds.AdminServlet"
},
{ "servlet-name": "fileServlet", "servlet-class": "org.cofax.cds.FileServlet" },
{
"servlet-name": "cofaxTools",
"servlet-class": "org.cofax.cms.CofaxToolsServlet",
"init-param": {
"templatePath": "toolstemplates/",
"log": 1,
"logLocation": "/usr/local/tomcat/logs/CofaxTools.log",
"logMaxSize": "",
"dataLog": 1,
"dataLogLocation": "/usr/local/tomcat/logs/dataLOGGER.log",
"dataLogMaxSize": "",
"removePageCache": "/content/admin/remove?cache=pages&id=",
"removeTemplateCache": "/content/admin/remove?cache=templates&id=",
"fileTransferFolder": "/usr/local/tomcat/webapps/content/fileTransferFolder",
"lookInContext": 1,
"adminGroupID": 4,
"betaServer": true
}
}
],
"servlet-mapping": {
"cofaxCDS": "/",
"cofaxEmail": "/cofaxutil/aemail/*",
"cofaxAdmin": "/admin/*",
"fileServlet": "/static/*",
"cofaxTools": "/tools/*"
},
"taglib": { "taglib-uri": "cofax.tld", "taglib-location": "/WEB-INF/tlds/cofax.tld" }
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric5() {
//@formatter:off
final String base = """
{
"menu": {
"header": "SVG Viewer",
"items": [
{ "id": "Open" },
{ "id": "OpenNew", "label": "Open New" },
null,
{ "id": "ZoomIn", "label": "Zoom In" },
{ "id": "ZoomOut", "label": "Zoom Out" },
{ "id": "OriginalView", "label": "Original View" },
null,
{ "id": "Quality" },
{ "id": "Pause" },
{ "id": "Mute" },
null,
{ "id": "Find", "label": "Find..." },
{ "id": "FindAgain", "label": "Find Again" },
{ "id": "Copy" },
{ "id": "CopyAgain", "label": "Copy Again" },
{ "id": "CopySVG", "label": "Copy SVG" },
{ "id": "ViewSVG", "label": "View SVG" },
{ "id": "ViewSource", "label": "View Source" },
{ "id": "SaveAs", "label": "Save As" },
null,
{ "id": "Help" },
{ "id": "About", "label": "About Adobe CVG Viewer..." }
]
}
}""";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testIndentedList() {
//@formatter:off
EjsonLocal.test(refOutputAll,
"""
{
menu: {
id: "file",
value: "File",
popup: {
menuitem: [
{
value: "Close",
onclick: "CloseDoc()"
},
{
value: "New",
onclick: "CreateNewDoc()"
},
{
value: "Open",
onclick: "OpenDoc()"
},
{
value: "Close",
onclick: "CloseDoc()"
}
]
}
}
}
""",
-1);
//@formatter:on
}
@Test
public void testIndentedListWithNoBasicObject() {
//@formatter:off
EjsonLocal.test(refOutputAll,
"""
menu: {
id: "file",
value: "File",
popup: {
menuitem: [
{
value: "Close",
onclick: "CloseDoc()"
},
{
value: "New",
onclick: "CreateNewDoc()"
},
{
value: "Open",
onclick: "OpenDoc()"
},
{
value: "Close",
onclick: "CloseDoc()"
}
]
}
}
""",
-1);
//@formatter:on
}
}

View File

@ -0,0 +1,91 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson.generic;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EjsonTestBoolean {
final static Logger LOGGER = LoggerFactory.getLogger(EjsonTestBoolean.class);
private static String refOutputBoolean1 = "{\n\t\"tmpElement\": true\n}";
private static String refOutputBoolean2 = "{\n\t\"tmpElement\": false\n}";
@BeforeAll
public static void beforeClass() {
LOGGER.trace("----------------------------------------------------------------");
}
@Test
@Order(1)
public void multipleValue() {
EjsonLocal.test("{\n\t\"tmpElement\": false,\n\t\"tmpElement2\": true\n}", "{ tmpElement:false, tmpElement2:true }\n", -1);
}
@Test
@Order(2)
public void test010BaseTrue() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:true }\n", -1);
}
@Test
@Order(3)
public void test020TabbedTrue() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ \t\ntmpElement:true \t\n }\n", -1);
}
@Test
@Order(4)
public void test030NoneTrue() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "tmpElement:true\n", -1);
}
@Test
@Order(5)
public void test040BaseTrue1() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:TRUE }\n", 1);
}
@Test
@Order(6)
public void test050BaseTrue2() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean1, "{ tmpElement:True }\n", 1);
}
@Test
@Order(7)
public void test110BaseFalse() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:false }\n", -1);
}
@Test
@Order(8)
public void test120TabbedFalse() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ \t\ntmpElement:false \t\n }\n", -1);
}
@Test
@Order(9)
public void test130NoneFalse() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "tmpElement:false\n", -1);
}
@Test
@Order(10)
public void test140BaseFalse1() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:FALSE }\n", 1);
}
@Test
@Order(11)
public void test150BaseFalse2() {
EjsonLocal.test(EjsonTestBoolean.refOutputBoolean2, "{ tmpElement:False }\n", 1);
}
}

View File

@ -3,36 +3,40 @@
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
package test.atriasoft.ejson.generic;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EjsonTestNull {
static private String refOutputNull = "{\n\t\"tmpElement\": null\n}";
final static Logger LOGGER = LoggerFactory.getLogger(EjsonTestNull.class);
private static final String REF_OUTPUT_NULL = "{\n\t\"tmpElement\": null\n}";
@BeforeAll
public static void beforeClass() {
Log.verbose("----------------------------------------------------------------");
LOGGER.trace("----------------------------------------------------------------");
}
@Test
@Order(1)
public void test10BasicNullElement() {
EjsonLocal.test(refOutputNull, "{ tmpElement:null }\n", -1);
EjsonLocal.test(EjsonTestNull.REF_OUTPUT_NULL, "{ tmpElement:null }\n", -1);
}
@Test
@Order(2)
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
@Order(3)
public void test30TabbedNullElementNoPThese() {
EjsonLocal.test(refOutputNull, "tmpElement:null\n", -1);
EjsonLocal.test(EjsonTestNull.REF_OUTPUT_NULL, "tmpElement:null\n", -1);
}
@Test

View File

@ -3,30 +3,34 @@
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
package test.atriasoft.ejson.generic;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class EjsonTestNumber {
static private String refOutputNumber = "{\n\t\"tmpElement\": 956256\n}";
final static Logger LOGGER = LoggerFactory.getLogger(EjsonTestNumber.class);
private static final String REF_OUTPUT_NUMBER = "{\n\t\"tmpElement\": 956256\n}";
@BeforeAll
public static void beforeClass() {
Log.verbose("----------------------------------------------------------------");
LOGGER.trace("----------------------------------------------------------------");
}
@Test
@Order(1)
public void test10Base() {
EjsonLocal.test(refOutputNumber, "{ tmpElement:956256 }\n", -1);
EjsonLocal.test(EjsonTestNumber.REF_OUTPUT_NUMBER, "{ tmpElement:956256 }\n", -1);
}
@Test
@Order(2)
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
@ -44,6 +48,6 @@ public class EjsonTestNumber {
@Test
@Order(5)
public void test50None() {
EjsonLocal.test(refOutputNumber, "tmpElement:956256\n", -1);
EjsonLocal.test(EjsonTestNumber.REF_OUTPUT_NUMBER, "tmpElement:956256\n", -1);
}
}

View File

@ -0,0 +1,420 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson.introspection;
import java.util.Arrays;
import org.atriasoft.aknot.exception.AknotException;
import org.atriasoft.ejson.JsonMapper;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonException;
import org.atriasoft.ejson.exception.EjsonParserErrorMulti;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import test.atriasoft.ejson.introspection.model.ClassMethodEnum;
import test.atriasoft.ejson.introspection.model.ClassPublicChild;
import test.atriasoft.ejson.introspection.model.ClassPublicMemberOnly;
import test.atriasoft.ejson.introspection.model.ClassPublicMethodOnly;
import test.atriasoft.ejson.introspection.model.ClassPublicMethodeNode;
import test.atriasoft.ejson.introspection.model.ClassPublicMethodeStructured;
import test.atriasoft.ejson.introspection.model.SimpleEnum;
public class EjsonTestIntrospection {
final static Logger LOGGER = LoggerFactory.getLogger(EjsonTestIntrospection.class);
@BeforeAll
public static void beforeClass() {
LOGGER.trace("----------------------------------------------------------------");
}
@Test
public void test1() throws EjsonParserErrorMulti, EjsonBuilderException {
//@formatter:off
final String dataToParse = """
{
"memberByte":12,
"memberShort":1223,
"memberInteger":4541542,
"memberLong": 4564654654,
"memberBoolean": true\s,
"memberByteClass": 55\s,
"memberShortClass": 1523\s,
"memberIntegerClass": 4654654\s,
"memberLongClass": 545645645454,
"memberBooleanClass": true\s,
"memberStringClass": "sdfgsdkjfglksqjéé",
"memberArrayByte": [12, 15,123, 100, 2],
"memberArrayByteClass":[
\n 12,1, 100,122],
"memberArrayShort":[1245,1894, -100,-12542],
"memberArrayShortClass":[-1245,-1894, 0,2542,15615],
"memberArrayInteger":[123456,-654987],
"memberArrayIntegerClass":[1567845,45621354,-5646544],
"memberArrayLong":[1651324654,65421351685,-5],
"memberArrayLongClass":[6746541351,546546546,564654654,654654654654,-45546],
"memberArrayBoolean":[true, true, false],
"memberArrayBooleanClass":[false, false, true, true],
}
""";
//@formatter:on
final ClassPublicMemberOnly elem = Assertions.assertDoesNotThrow(() -> {
final JsonMapper mapper = new JsonMapper();
return mapper.parse(dataToParse, ClassPublicMemberOnly.class);
});
Assertions.assertNotNull(elem);
Assertions.assertEquals((byte) 12, elem.memberByte);
Assertions.assertEquals((short) 1223, elem.memberShort);
Assertions.assertEquals(4541542, elem.memberInteger);
Assertions.assertEquals(4564654654L, elem.memberLong);
Assertions.assertEquals(true, elem.memberBoolean);
Assertions.assertEquals((byte) 55, elem.memberByteClass);
Assertions.assertEquals((short) 1523, elem.memberShortClass);
Assertions.assertEquals(4654654, elem.memberIntegerClass);
Assertions.assertEquals(545645645454L, elem.memberLongClass);
Assertions.assertEquals(true, elem.memberBooleanClass);
Assertions.assertEquals("sdfgsdkjfglksqjéé", elem.memberStringClass);
Assertions.assertEquals(5, elem.memberArrayByte.length);
Assertions.assertEquals((byte) 12, elem.memberArrayByte[0]);
Assertions.assertEquals((byte) 15, elem.memberArrayByte[1]);
Assertions.assertEquals((byte) 123, elem.memberArrayByte[2]);
Assertions.assertEquals((byte) 100, elem.memberArrayByte[3]);
Assertions.assertEquals(2, elem.memberArrayByte[4]);
Assertions.assertEquals(4, elem.memberArrayByteClass.length);
Assertions.assertEquals((byte) 12, elem.memberArrayByteClass[0]);
Assertions.assertEquals((byte) 1, elem.memberArrayByteClass[1]);
Assertions.assertEquals((byte) 100, elem.memberArrayByteClass[2]);
Assertions.assertEquals((byte) 122, elem.memberArrayByteClass[3]);
Assertions.assertEquals(4, elem.memberArrayShort.length);
Assertions.assertEquals((short) 1245, elem.memberArrayShort[0]);
Assertions.assertEquals((short) 1894, elem.memberArrayShort[1]);
Assertions.assertEquals((short) -100, elem.memberArrayShort[2]);
Assertions.assertEquals((short) -12542, elem.memberArrayShort[3]);
Assertions.assertEquals(5, elem.memberArrayShortClass.length);
Assertions.assertEquals((short) -1245, elem.memberArrayShortClass[0]);
Assertions.assertEquals((short) -1894, elem.memberArrayShortClass[1]);
Assertions.assertEquals((short) 0, elem.memberArrayShortClass[2]);
Assertions.assertEquals((short) 2542, elem.memberArrayShortClass[3]);
Assertions.assertEquals((short) 15615, elem.memberArrayShortClass[4]);
Assertions.assertEquals(2, elem.memberArrayInteger.length);
//Assertions.assertArrayEquals(Arrays.asList(123456, -654987).toArray(), elem.memberArrayInteger);
Assertions.assertEquals(3, elem.memberArrayIntegerClass.length);
Assertions.assertArrayEquals(Arrays.asList(1567845, 45621354, -5646544).toArray(), elem.memberArrayIntegerClass);
Assertions.assertEquals(3, elem.memberArrayLong.length);
//Assertions.assertArrayEquals(Arrays.asList(1651324654L, 65421351685L, -5L).toArray(), elem.memberArrayLong);
Assertions.assertEquals(5, elem.memberArrayLongClass.length);
Assertions.assertArrayEquals(Arrays.asList(6746541351L, 546546546L, 564654654L, 654654654654L, -45546L).toArray(), elem.memberArrayLongClass);
Assertions.assertEquals(3, elem.memberArrayBoolean.length);
//Assertions.assertArrayEquals(Arrays.asList(true, true, false).toArray(), elem.memberArrayBoolean);
Assertions.assertEquals(4, elem.memberArrayBooleanClass.length);
Assertions.assertArrayEquals(Arrays.asList(false, false, true, true).toArray(), elem.memberArrayBooleanClass);
}
@Test
public void test2() {
//@formatter:off
final String dataToParse = """
{
"memberByte": 12,
"memberShort": 1223,
"memberInteger": 4541542,
"memberLong": 4564654654,
"memberBoolean": true,
"memberByteClass": 55,
"memberShortClass": 1523,
"memberIntegerClass": 4654654,
"memberLongClass": 545645645454,
"memberBooleanClass": true,
"memberStringClass": "sdfgsdkjfglksqjéé",
"memberArrayByte": [12, 15,123, 100, 2],
"memberArrayByteClass":[
\n 12,1, 100,122],
"memberArrayShort":[1245,1894, -100,-12542],
"memberArrayShortClass":[-1245,-1894, 0,2542,15615],
"memberArrayInteger":[123456,-654987],
"memberArrayIntegerClass":[1567845,45621354,-5646544],
"memberArrayLong":[1651324654,65421351685,-5],
"memberArrayLongClass":[6746541351,546546546,564654654,654654654654,-45546],
"memberArrayBoolean":[true, true, false],
"memberArrayBooleanClass":[false, false, true, true],
}
""";
//@formatter:on
final ClassPublicMethodOnly elem = Assertions.assertDoesNotThrow(() -> {
final JsonMapper mapper = new JsonMapper();
return mapper.parse(dataToParse, ClassPublicMethodOnly.class);
});
Assertions.assertNotNull(elem);
Assertions.assertEquals((byte) 12, elem.getMemberByte());
Assertions.assertEquals((short) 1223, elem.getMemberShort());
Assertions.assertEquals(4541542, elem.getMemberInteger());
Assertions.assertEquals(4564654654L, elem.getMemberLong());
Assertions.assertEquals(true, elem.isMemberBoolean());
Assertions.assertEquals((byte) 55, elem.getMemberByteClass());
Assertions.assertEquals((short) 1523, elem.getMemberShortClass());
Assertions.assertEquals(4654654, elem.getMemberIntegerClass());
Assertions.assertEquals(545645645454L, elem.getMemberLongClass());
Assertions.assertEquals(true, elem.isMemberBooleanClass());
Assertions.assertEquals("sdfgsdkjfglksqjéé", elem.getMemberStringClass());
Assertions.assertEquals(5, elem.getMemberArrayByte().length);
Assertions.assertEquals((byte) 12, elem.getMemberArrayByte()[0]);
Assertions.assertEquals((byte) 15, elem.getMemberArrayByte()[1]);
Assertions.assertEquals((byte) 123, elem.getMemberArrayByte()[2]);
Assertions.assertEquals((byte) 100, elem.getMemberArrayByte()[3]);
Assertions.assertEquals(2, elem.getMemberArrayByte()[4]);
Assertions.assertEquals(4, elem.getMemberArrayByteClass().length);
Assertions.assertEquals((byte) 12, elem.getMemberArrayByteClass()[0]);
Assertions.assertEquals((byte) 1, elem.getMemberArrayByteClass()[1]);
Assertions.assertEquals((byte) 100, elem.getMemberArrayByteClass()[2]);
Assertions.assertEquals((byte) 122, elem.getMemberArrayByteClass()[3]);
Assertions.assertEquals(4, elem.getMemberArrayShort().length);
Assertions.assertEquals((short) 1245, elem.getMemberArrayShort()[0]);
Assertions.assertEquals((short) 1894, elem.getMemberArrayShort()[1]);
Assertions.assertEquals((short) -100, elem.getMemberArrayShort()[2]);
Assertions.assertEquals((short) -12542, elem.getMemberArrayShort()[3]);
Assertions.assertEquals(5, elem.getMemberArrayShortClass().length);
Assertions.assertEquals((short) -1245, elem.getMemberArrayShortClass()[0]);
Assertions.assertEquals((short) -1894, elem.getMemberArrayShortClass()[1]);
Assertions.assertEquals((short) 0, elem.getMemberArrayShortClass()[2]);
Assertions.assertEquals((short) 2542, elem.getMemberArrayShortClass()[3]);
Assertions.assertEquals((short) 15615, elem.getMemberArrayShortClass()[4]);
Assertions.assertEquals(2, elem.getMemberArrayInteger().length);
//Assertions.assertArrayEquals(Arrays.asList(123456, -654987).toArray(), elem.getMemberArrayInteger());
Assertions.assertEquals(3, elem.getMemberArrayIntegerClass().length);
Assertions.assertArrayEquals(Arrays.asList(1567845, 45621354, -5646544).toArray(), elem.getMemberArrayIntegerClass());
Assertions.assertEquals(3, elem.getMemberArrayLong().length);
//Assertions.assertArrayEquals(Arrays.asList(1651324654L, 65421351685L, -5L).toArray(), elem.getMemberArrayLong());
Assertions.assertEquals(5, elem.getMemberArrayLongClass().length);
Assertions.assertArrayEquals(Arrays.asList(6746541351L, 546546546L, 564654654L, 654654654654L, -45546L).toArray(), elem.getMemberArrayLongClass());
Assertions.assertEquals(3, elem.getMemberArrayBoolean().length);
//Assertions.assertArrayEquals(Arrays.asList(true, true, false).toArray(), elem.getMemberArrayBoolean());
Assertions.assertEquals(4, elem.getMemberArrayBooleanClass().length);
Assertions.assertArrayEquals(Arrays.asList(false, false, true, true).toArray(), elem.getMemberArrayBooleanClass());
}
@Test
public void test3() {
//@formatter:off
final String dataToParse = """
{
"memberByte": 12,
"memberShort": 1223,
"memberInteger": 4541542,
"memberLong": 4564654654,
"memberBoolean": true,
"memberByteClass": 55,
"memberShortClass": 1523,
"memberIntegerClass": 4654654,
"memberLongClass": 545645645454,
"memberBooleanClass": true,
"memberStringClass": "sdfgsdkjfglksqjéé",
"memberArrayByte": [ 12 ] ,
"memberArrayByte": [15],
"memberArrayByte": [123],
"memberArrayByte": [100],
"memberArrayByte": [2],
"memberArrayByteClass": [
\n 12],
"memberArrayByteClass": [1],
"memberArrayByteClass": [ 100],
"memberArrayByteClass": [122],
"memberArrayShort": [1245],
"memberArrayShort": [1894],
"memberArrayShort": [ -100],
"memberArrayShort": [-12542],
"memberArrayShortClass": [-1245],
"memberArrayShortClass": [-1894],
"memberArrayShortClass": [ 0],
"memberArrayShortClass": [2542],
"memberArrayShortClass": [15615],
"memberArrayInteger": [123456],
"memberArrayInteger": [-654987],
"memberArrayIntegerClass": [1567845],
"memberArrayIntegerClass": [45621354],
"memberArrayIntegerClass": [-5646544],
"memberArrayLong": [1651324654],
"memberArrayLong": [65421351685],
"memberArrayLong": [-5],
"memberArrayLongClass": [6746541351],
"memberArrayLongClass": [546546546],
"memberArrayLongClass": [564654654],
"memberArrayLongClass": [654654654654],
"memberArrayLongClass": [-45546],
"memberArrayBoolean": [true],
"memberArrayBoolean": [ true],
"memberArrayBoolean": [false],
"memberArrayBooleanClass": [false],
"memberArrayBooleanClass": [ false],
"memberArrayBooleanClass":[ true],
"memberArrayBooleanClass": [ true],
"memberListByteClass": [55 ],
"memberListByteClass": [ -53 ],
"memberListShortClass": [ 31632],
"memberListShortClass": [-32100 ],
"memberListIntegerClass": [15612 ],
"memberListIntegerClass": [ 542 ],
"memberListLongClass": [16521 ],
"memberListLongClass": [ 4654 ],
"memberListLongClass": [9875546 ],
"memberListBooleanClass": [ true],
"memberListBooleanClass": [false ],
,
""";
//@formatter:on
final JsonMapper mapper2 = new JsonMapper();
try {
final ClassPublicMethodeNode elem2 = mapper2.parse(dataToParse, ClassPublicMethodeNode.class);
} catch (final EjsonException | AknotException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void test4() {
//@formatter:off
final String dataToParse = """
{
"memberArrayByte": [
12,
15,
123, -100,
2,
],
"memberListByte": [-112,
-115,
-13, -10,
12,
]
}
""";
//@formatter:on
final ClassPublicMethodeStructured elem = Assertions.assertDoesNotThrow(() -> {
final JsonMapper mapper = new JsonMapper();
return mapper.parse(dataToParse, ClassPublicMethodeStructured.class);
});
Assertions.assertNotNull(elem);
Assertions.assertEquals(5, elem.getMemberArrayByte().length);
Assertions.assertEquals((byte) 12, elem.getMemberArrayByte()[0]);
Assertions.assertEquals((byte) 15, elem.getMemberArrayByte()[1]);
Assertions.assertEquals((byte) 123, elem.getMemberArrayByte()[2]);
Assertions.assertEquals((byte) -100, elem.getMemberArrayByte()[3]);
Assertions.assertEquals((byte) 2, elem.getMemberArrayByte()[4]);
Assertions.assertEquals(5, elem.getMemberListByte().size());
Assertions.assertEquals((byte) -112, elem.getMemberListByte().get(0));
Assertions.assertEquals((byte) -115, elem.getMemberListByte().get(1));
Assertions.assertEquals((byte) -13, elem.getMemberListByte().get(2));
Assertions.assertEquals((byte) -10, elem.getMemberListByte().get(3));
Assertions.assertEquals((byte) 12, elem.getMemberListByte().get(4));
}
@Test
public void test5() {
//@formatter:off
final String dataToParse = """
{
"data": "PLIF",
"dataArray": [ "PLIF", "PROUT"]
}""";
//@formatter:on
final ClassMethodEnum elem = Assertions.assertDoesNotThrow(() -> {
final JsonMapper mapper = new JsonMapper();
return mapper.parse(dataToParse, ClassMethodEnum.class);
});
Assertions.assertNotNull(elem);
Assertions.assertEquals(SimpleEnum.PLIF, elem.getDataArray()[0]);
Assertions.assertEquals(SimpleEnum.PROUT, elem.getDataArray()[1]);
Assertions.assertEquals(SimpleEnum.PLIF, elem.getData());
}
@Test
public void test6() {
//@formatter:off
final String dataToParse222 = """
{
memberData: {
"memberArrayByte": [11, 12],
"memberListByte": [13, 14],
},
}
""";
final String dataToParse = """
{
memberData: {
"memberArrayByte": [11, 12],
"memberListByte": [13, 14],
},
memberDataArray: [
{
"memberListByte": [21, 22],
},
{
"memberArrayByte": [23, 24],
},
],
memberDataList: [
{
"memberListByte": [31, 32]
},
{
"memberArrayByte": [33, 34],
},
],
value: {
"data": "PLIF",
"dataArray": [ "PLIF", "PROUT"]
}
}""";
//@formatter:on
final ClassPublicChild elem = Assertions.assertDoesNotThrow(() -> {
final JsonMapper mapper = new JsonMapper();
return mapper.parse(dataToParse, ClassPublicChild.class);
});
Assertions.assertNotNull(elem);
Assertions.assertNotNull(elem.memberData);
Assertions.assertNotNull(elem.memberDataArray);
Assertions.assertNotNull(elem.memberDataList);
Assertions.assertNotNull(elem.value);
Assertions.assertEquals(2, elem.memberDataArray.length);
Assertions.assertEquals(2, elem.memberDataList.size());
Assertions.assertEquals((byte) 11, elem.memberData.getMemberArrayByte()[0]);
Assertions.assertEquals((byte) 12, elem.memberData.getMemberArrayByte()[1]);
Assertions.assertEquals((byte) 13, elem.memberData.getMemberListByte().get(0));
Assertions.assertEquals((byte) 14, elem.memberData.getMemberListByte().get(1));
Assertions.assertEquals((byte) 21, elem.memberDataArray[0].getMemberListByte().get(0));
Assertions.assertEquals((byte) 22, elem.memberDataArray[0].getMemberListByte().get(1));
Assertions.assertEquals((byte) 23, elem.memberDataArray[1].getMemberArrayByte()[0]);
Assertions.assertEquals((byte) 24, elem.memberDataArray[1].getMemberArrayByte()[1]);
Assertions.assertEquals((byte) 31, elem.memberDataList.get(0).getMemberListByte().get(0));
Assertions.assertEquals((byte) 32, elem.memberDataList.get(0).getMemberListByte().get(1));
Assertions.assertEquals((byte) 33, elem.memberDataList.get(1).getMemberArrayByte()[0]);
Assertions.assertEquals((byte) 34, elem.memberDataList.get(1).getMemberArrayByte()[1]);
Assertions.assertEquals(SimpleEnum.PLIF, elem.value.getDataArray()[0]);
Assertions.assertEquals(SimpleEnum.PROUT, elem.value.getDataArray()[1]);
Assertions.assertEquals(SimpleEnum.PLIF, elem.value.getData());
}
}

View File

@ -0,0 +1,8 @@
package test.atriasoft.ejson.introspection.model;
import org.atriasoft.aknot.annotation.AknotDefaultManaged;
@AknotDefaultManaged(value = false)
public class ClassInversion {
}

View File

@ -0,0 +1,26 @@
package test.atriasoft.ejson.introspection.model;
import org.atriasoft.aknot.annotation.AknotName;
@AknotName("elem")
public class ClassMethodEnum {
private SimpleEnum data;
private SimpleEnum[] dataArray;
public SimpleEnum getData() {
return this.data;
}
public SimpleEnum[] getDataArray() {
return this.dataArray;
}
public void setData(final SimpleEnum data) {
this.data = data;
}
public void setDataArray(final SimpleEnum[] dataArray) {
this.dataArray = dataArray;
}
}

View File

@ -0,0 +1,11 @@
package test.atriasoft.ejson.introspection.model;
import java.util.List;
public class ClassPublicChild {
// note: when private the decorator must be set on getter or setter, liker this you can use the internal name you want...
public ClassPublicMethodeStructured memberData;
public ClassPublicMethodeStructured[] memberDataArray;
public List<ClassPublicMethodeStructured> memberDataList;
public ClassMethodEnum value;
}

View File

@ -0,0 +1,31 @@
package test.atriasoft.ejson.introspection.model;
import org.atriasoft.aknot.annotation.AknotDefaultAttribute;
import org.atriasoft.aknot.annotation.AknotName;
@AknotDefaultAttribute
@AknotName("elem")
public class ClassPublicMemberOnly {
public boolean[] memberArrayBoolean;
public Boolean[] memberArrayBooleanClass;
public byte[] memberArrayByte;
public Byte[] memberArrayByteClass;
public int[] memberArrayInteger;
public Integer[] memberArrayIntegerClass;
public long[] memberArrayLong;
public Long[] memberArrayLongClass;
public short[] memberArrayShort;
public Short[] memberArrayShortClass;
public boolean memberBoolean;
public Boolean memberBooleanClass;
//this work !!! @AKName(value = "jhkjhhkj")
public byte memberByte;
public Byte memberByteClass;
public int memberInteger;
public Integer memberIntegerClass;
public long memberLong;
public Long memberLongClass;
public short memberShort;
public Short memberShortClass;
public String memberStringClass;
}

View File

@ -0,0 +1,198 @@
package test.atriasoft.ejson.introspection.model;
import org.atriasoft.aknot.annotation.AknotDefaultAttribute;
import org.atriasoft.aknot.annotation.AknotName;
@AknotDefaultAttribute
@AknotName("elem")
public class ClassPublicMethodOnly {
private boolean[] memberArrayBoolean;
private Boolean[] memberArrayBooleanClass;
private byte[] memberArrayByte;
private Byte[] memberArrayByteClass;
private int[] memberArrayInteger;
private Integer[] memberArrayIntegerClass;
private long[] memberArrayLong;
private Long[] memberArrayLongClass;
private short[] memberArrayShort;
private Short[] memberArrayShortClass;
private boolean memberBoolean;
private Boolean memberBooleanClass;
private byte memberByte;
private Byte memberByteClass;
private int memberInteger;
private Integer memberIntegerClass;
private long memberLong;
private Long memberLongClass;
private short memberShort;
private Short memberShortClass;
private String memberStringClass;
public boolean[] getMemberArrayBoolean() {
return this.memberArrayBoolean;
}
public Boolean[] getMemberArrayBooleanClass() {
return this.memberArrayBooleanClass;
}
public byte[] getMemberArrayByte() {
return this.memberArrayByte;
}
public Byte[] getMemberArrayByteClass() {
return this.memberArrayByteClass;
}
public int[] getMemberArrayInteger() {
return this.memberArrayInteger;
}
public Integer[] getMemberArrayIntegerClass() {
return this.memberArrayIntegerClass;
}
public long[] getMemberArrayLong() {
return this.memberArrayLong;
}
public Long[] getMemberArrayLongClass() {
return this.memberArrayLongClass;
}
public short[] getMemberArrayShort() {
return this.memberArrayShort;
}
public Short[] getMemberArrayShortClass() {
return this.memberArrayShortClass;
}
public byte getMemberByte() {
return this.memberByte;
}
public Byte getMemberByteClass() {
return this.memberByteClass;
}
public int getMemberInteger() {
return this.memberInteger;
}
public Integer getMemberIntegerClass() {
return this.memberIntegerClass;
}
public long getMemberLong() {
return this.memberLong;
}
public Long getMemberLongClass() {
return this.memberLongClass;
}
public short getMemberShort() {
return this.memberShort;
}
public Short getMemberShortClass() {
return this.memberShortClass;
}
public String getMemberStringClass() {
return this.memberStringClass;
}
public boolean isMemberBoolean() {
return this.memberBoolean;
}
public Boolean isMemberBooleanClass() {
return this.memberBooleanClass;
}
public void setMemberArrayBoolean(final boolean[] memberArrayBoolean) {
this.memberArrayBoolean = memberArrayBoolean;
}
public void setMemberArrayBooleanClass(final Boolean[] memberArrayBooleanClass) {
this.memberArrayBooleanClass = memberArrayBooleanClass;
}
public void setMemberArrayByte(final byte[] memberArrayByte) {
this.memberArrayByte = memberArrayByte;
}
public void setMemberArrayByteClass(final Byte[] memberArrayByteClass) {
this.memberArrayByteClass = memberArrayByteClass;
}
public void setMemberArrayInteger(final int[] memberArrayInteger) {
this.memberArrayInteger = memberArrayInteger;
}
public void setMemberArrayIntegerClass(final Integer[] memberArrayIntegerClass) {
this.memberArrayIntegerClass = memberArrayIntegerClass;
}
public void setMemberArrayLong(final long[] memberArrayLong) {
this.memberArrayLong = memberArrayLong;
}
public void setMemberArrayLongClass(final Long[] memberArrayLongClass) {
this.memberArrayLongClass = memberArrayLongClass;
}
public void setMemberArrayShort(final short[] memberArrayShort) {
this.memberArrayShort = memberArrayShort;
}
public void setMemberArrayShortClass(final Short[] memberArrayShortClass) {
this.memberArrayShortClass = memberArrayShortClass;
}
public void setMemberBoolean(final boolean memberBoolean) {
this.memberBoolean = memberBoolean;
}
public void setMemberBooleanClass(final Boolean memberBooleanClass) {
this.memberBooleanClass = memberBooleanClass;
}
public void setMemberByte(final byte memberByte) {
this.memberByte = memberByte;
}
public void setMemberByteClass(final Byte memberByteClass) {
this.memberByteClass = memberByteClass;
}
public void setMemberInteger(final int memberInteger) {
this.memberInteger = memberInteger;
}
public void setMemberIntegerClass(final Integer memberIntegerClass) {
this.memberIntegerClass = memberIntegerClass;
}
public void setMemberLong(final long memberLong) {
this.memberLong = memberLong;
}
public void setMemberLongClass(final Long memberLongClass) {
this.memberLongClass = memberLongClass;
}
public void setMemberShort(final short memberShort) {
this.memberShort = memberShort;
}
public void setMemberShortClass(final Short memberShortClass) {
this.memberShortClass = memberShortClass;
}
public void setMemberStringClass(final String memberStringClass) {
this.memberStringClass = memberStringClass;
}
}

View File

@ -0,0 +1,248 @@
package test.atriasoft.ejson.introspection.model;
import java.util.List;
import org.atriasoft.aknot.annotation.AknotName;
@AknotName("elem")
public class ClassPublicMethodeNode {
private boolean[] memberArrayBoolean;
private Boolean[] memberArrayBooleanClass;
private byte[] memberArrayByte;
private Byte[] memberArrayByteClass;
private int[] memberArrayInteger;
private Integer[] memberArrayIntegerClass;
private long[] memberArrayLong;
private Long[] memberArrayLongClass;
private short[] memberArrayShort;
private Short[] memberArrayShortClass;
private List<Boolean> memberListBooleanClass;
private List<Byte> memberListByteClass;
private List<Integer> memberListIntegerClass;
private List<Long> memberListLongClass;
private List<Short> memberListShortClass;
private boolean memberBoolean;
private Boolean memberBooleanClass;
private byte memberByte;
private Byte memberByteClass;
private int memberInteger;
private Integer memberIntegerClass;
private long memberLong;
private Long memberLongClass;
private short memberShort;
private Short memberShortClass;
private String memberStringClass;
public boolean[] getMemberArrayBoolean() {
return this.memberArrayBoolean;
}
public Boolean[] getMemberArrayBooleanClass() {
return this.memberArrayBooleanClass;
}
public byte[] getMemberArrayByte() {
return this.memberArrayByte;
}
public Byte[] getMemberArrayByteClass() {
return this.memberArrayByteClass;
}
public int[] getMemberArrayInteger() {
return this.memberArrayInteger;
}
public Integer[] getMemberArrayIntegerClass() {
return this.memberArrayIntegerClass;
}
public long[] getMemberArrayLong() {
return this.memberArrayLong;
}
public Long[] getMemberArrayLongClass() {
return this.memberArrayLongClass;
}
public short[] getMemberArrayShort() {
return this.memberArrayShort;
}
public Short[] getMemberArrayShortClass() {
return this.memberArrayShortClass;
}
public Boolean getMemberBooleanClass() {
return this.memberBooleanClass;
}
public byte getMemberByte() {
return this.memberByte;
}
public Byte getMemberByteClass() {
return this.memberByteClass;
}
public int getMemberInteger() {
return this.memberInteger;
}
public Integer getMemberIntegerClass() {
return this.memberIntegerClass;
}
public List<Boolean> getMemberListBooleanClass() {
return this.memberListBooleanClass;
}
public List<Byte> getMemberListByteClass() {
return this.memberListByteClass;
}
public List<Integer> getMemberListIntegerClass() {
return this.memberListIntegerClass;
}
public List<Long> getMemberListLongClass() {
return this.memberListLongClass;
}
public List<Short> getMemberListShortClass() {
return this.memberListShortClass;
}
public long getMemberLong() {
return this.memberLong;
}
public Long getMemberLongClass() {
return this.memberLongClass;
}
public short getMemberShort() {
return this.memberShort;
}
public Short getMemberShortClass() {
return this.memberShortClass;
}
public String getMemberStringClass() {
return this.memberStringClass;
}
public boolean isMemberBoolean() {
return this.memberBoolean;
}
public Boolean isMemberBooleanClass() {
return this.memberBooleanClass;
}
public void setMemberArrayBoolean(final boolean[] memberArrayBoolean) {
this.memberArrayBoolean = memberArrayBoolean;
}
public void setMemberArrayBooleanClass(final Boolean[] memberArrayBooleanClass) {
this.memberArrayBooleanClass = memberArrayBooleanClass;
}
public void setMemberArrayByte(final byte[] memberArrayByte) {
this.memberArrayByte = memberArrayByte;
}
public void setMemberArrayByteClass(final Byte[] memberArrayByteClass) {
this.memberArrayByteClass = memberArrayByteClass;
}
public void setMemberArrayInteger(final int[] memberArrayInteger) {
this.memberArrayInteger = memberArrayInteger;
}
public void setMemberArrayIntegerClass(final Integer[] memberArrayIntegerClass) {
this.memberArrayIntegerClass = memberArrayIntegerClass;
}
public void setMemberArrayLong(final long[] memberArrayLong) {
this.memberArrayLong = memberArrayLong;
}
public void setMemberArrayLongClass(final Long[] memberArrayLongClass) {
this.memberArrayLongClass = memberArrayLongClass;
}
public void setMemberArrayShort(final short[] memberArrayShort) {
this.memberArrayShort = memberArrayShort;
}
public void setMemberArrayShortClass(final Short[] memberArrayShortClass) {
this.memberArrayShortClass = memberArrayShortClass;
}
public void setMemberBoolean(final boolean memberBoolean) {
this.memberBoolean = memberBoolean;
}
public void setMemberBooleanClass(final Boolean memberBooleanClass) {
this.memberBooleanClass = memberBooleanClass;
}
public void setMemberByte(final byte memberByte) {
this.memberByte = memberByte;
}
public void setMemberByteClass(final Byte memberByteClass) {
this.memberByteClass = memberByteClass;
}
public void setMemberInteger(final int memberInteger) {
this.memberInteger = memberInteger;
}
public void setMemberIntegerClass(final Integer memberIntegerClass) {
this.memberIntegerClass = memberIntegerClass;
}
public void setMemberListBooleanClass(final List<Boolean> memberListBooleanClass) {
this.memberListBooleanClass = memberListBooleanClass;
}
public void setMemberListByteClass(final List<Byte> memberListByteClass) {
this.memberListByteClass = memberListByteClass;
}
public void setMemberListIntegerClass(final List<Integer> memberListIntegerClass) {
this.memberListIntegerClass = memberListIntegerClass;
}
public void setMemberListLongClass(final List<Long> memberListLongClass) {
this.memberListLongClass = memberListLongClass;
}
public void setMemberListShortClass(final List<Short> memberListShortClass) {
this.memberListShortClass = memberListShortClass;
}
public void setMemberLong(final long memberLong) {
this.memberLong = memberLong;
}
public void setMemberLongClass(final Long memberLongClass) {
this.memberLongClass = memberLongClass;
}
public void setMemberShort(final short memberShort) {
this.memberShort = memberShort;
}
public void setMemberShortClass(final Short memberShortClass) {
this.memberShortClass = memberShortClass;
}
public void setMemberStringClass(final String memberStringClass) {
this.memberStringClass = memberStringClass;
}
}

View File

@ -0,0 +1,32 @@
package test.atriasoft.ejson.introspection.model;
import java.util.List;
import org.atriasoft.aknot.annotation.AknotList;
import org.atriasoft.aknot.annotation.AknotName;
@AknotName("elem")
public class ClassPublicMethodeStructured {
// note: when private the decorator must be set on getter or setter, liker this you can use the internal name you want...
private byte[] memberArrayByte;
private List<Byte> memberListByte;
@AknotList(value = "value")
public byte[] getMemberArrayByte() {
return this.memberArrayByte;
}
@AknotList(value = "elem")
public List<Byte> getMemberListByte() {
return this.memberListByte;
}
public void setMemberArrayByte(final byte[] memberArrayByte) {
this.memberArrayByte = memberArrayByte;
}
public void setMemberListByte(final List<Byte> memberListByte) {
this.memberListByte = memberListByte;
}
}

View File

@ -0,0 +1,7 @@
package test.atriasoft.ejson.introspection.model;
public enum SimpleEnum {
PLIF,
PLAF,
PROUT;
}

2
test/.gitignore vendored
View File

@ -1 +1,3 @@
/__pycache__/
/bin/

View File

@ -0,0 +1,35 @@
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
org.slf4j.simpleLogger.defaultLogLevel=trace
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false

View File

@ -1,59 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
import org.atriasoft.ejson.Ejson;
import org.atriasoft.ejson.exception.EjsonBuilderException;
import org.atriasoft.ejson.exception.EjsonParserErrorMulti;
import org.atriasoft.ejson.model.JsonNode;
import org.junit.jupiter.api.Assertions;
class EjsonLocal {
// _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) {
//doc.setCaseSensitive(!_caseInSensitive);
Log.verbose("parse : \n" + _input);
JsonNode root = null;
try {
root = Ejson.parse(_input);
if (_errorPos == 1) {
Assertions.fail("Must have detected an error");
return;
}
} catch (final EjsonParserErrorMulti e) {
if (_errorPos == 1) {
return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
}
} catch (final EjsonBuilderException e) {
if (_errorPos == 1) {
return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
}
} catch (final Exception e) {
if (_errorPos == 1) {
return;
} else {
e.printStackTrace();
Assertions.fail("Must have NOT detected an error " + e.getMessage());
}
}
final StringBuilder out = new StringBuilder();
// TODO: 2 is for failing in generate ...
Ejson.generate(root, out);
final String data = out.toString();
if (_errorPos == 3) {
Assertions.assertNotEquals(_ref, data);
return;
} else {
Assertions.assertEquals(_ref, data);
}
}
}

View File

@ -1,334 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
public class EjsonTestAll {
//@formatter:off
private static String refOutputAll = "{\n"
+ " \"menu\": {\n"
+ " \"id\": \"file\",\n"
+ " \"value\": \"File\",\n"
+ " \"popup\": {\n"
+ " \"menuitem\": [\n"
+ " { \"value\": \"Close\", \"onclick\": \"CloseDoc()\" },\n"
+ " { \"value\": \"New\", \"onclick\": \"CreateNewDoc()\" },\n"
+ " { \"value\": \"Open\", \"onclick\": \"OpenDoc()\" },\n"
+ " { \"value\": \"Close\", \"onclick\": \"CloseDoc()\" }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
@BeforeAll
public static void beforeClass() {
Log.verbose("----------------------------------------------------------------");
}
@Test
public void testBaseObject() {
//@formatter:off
final String base = "{\n"
+ " \"menu\": {\n"
+ " \"id\": \"file\",\n"
+ " \"value\": \"File\",\n"
+ " \"popup\": {\n"
+ " \"menuitem\": { \"value\": \"Close\", \"onclick\": \"CloseDoc()\" }\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric1() {
//@formatter:off
final String base = "{\n"
+ " \"glossary\": {\n"
+ " \"title\": \"example glossary\",\n"
+ " \"GlossDiv\": {\n"
+ " \"title\": \"S\",\n"
+ " \"GlossList\": {\n"
+ " \"GlossEntry\": {\n"
+ " \"ID\": \"SGML\",\n"
+ " \"SortAs\": \"SGML\",\n"
+ " \"GlossTerm\": \"Standard Generalized Markup Language\",\n"
+ " \"Acronym\": \"SGML\",\n"
+ " \"Abbrev\": \"ISO 8879:1986\",\n"
+ " \"GlossDef\": {\n"
+ " \"para\": \"A meta-markup language, used to create markup languages such as DocBook.\",\n"
+ " \"GlossSeeAlso\": [ \"GML\", \"XML\" ]\n"
+ " },\n"
+ " \"GlossSee\": \"markup\"\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric2() {
//@formatter:off
final String base = "{\n"
+ " \"menu\": {\n"
+ " \"id\": \"file\",\n"
+ " \"value\": \"File\",\n"
+ " \"popup\": {\n"
+ " \"menuitem\": [\n"
+ " { \"value\": \"New\", \"onclick\": \"CreateNewDoc()\" },\n"
+ " { \"value\": \"Open\", \"onclick\": \"OpenDoc()\" },\n"
+ " { \"value\": \"Close\", \"onclick\": \"CloseDoc()\" }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric3() {
//@formatter:off
final String base = "{\n"
+ " \"widget\": {\n"
+ " \"debug\": \"on\",\n"
+ " \"window\": {\n"
+ " \"title\": \"Sample Konfabulator Widget\",\n"
+ " \"name\": \"main_window\",\n"
+ " \"width\": 500,\n"
+ " \"height\": 500\n"
+ " },\n"
+ " \"image\": {\n"
+ " \"src\": \"Images/Sun.png\",\n"
+ " \"name\": \"sun1\",\n"
+ " \"hOffset\": 250,\n"
+ " \"vOffset\": 250,\n"
+ " \"alignment\": \"center\"\n"
+ " },\n"
+ " \"text\": {\n"
+ " \"data\": \"Click Here\",\n"
+ " \"size\": 36,\n"
+ " \"style\": \"bold\",\n"
+ " \"name\": \"text1\",\n"
+ " \"hOffset\": 250,\n"
+ " \"vOffset\": 100,\n"
+ " \"alignment\": \"center\",\n"
+ " \"onMouseUp\": \"sun1.opacity = (sun1.opacity / 100) * 90;\"\n"
+ " }\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric4() {
//@formatter:off
final String base = "{\n"
+ " \"web-app\": {\n"
+ " \"servlet\": [\n"
+ " {\n"
+ " \"servlet-name\": \"cofaxCDS\",\n"
+ " \"servlet-class\": \"org.cofax.cds.CDSServlet\",\n"
+ " \"init-param\": {\n"
+ " \"configGlossary:installationAt\": \"Philadelphia, PA\",\n"
+ " \"configGlossary:adminEmail\": \"ksm@pobox.com\",\n"
+ " \"configGlossary:poweredBy\": \"Cofax\",\n"
+ " \"configGlossary:poweredByIcon\": \"/images/cofax.gif\",\n"
+ " \"configGlossary:staticPath\": \"/content/static\",\n"
+ " \"templateProcessorClass\": \"org.cofax.WysiwygTemplate\",\n"
+ " \"templateLoaderClass\": \"org.cofax.FilesTemplateLoader\",\n"
+ " \"templatePath\": \"templates\",\n"
+ " \"templateOverridePath\": \"\",\n"
+ " \"defaultListTemplate\": \"listTemplate.htm\",\n"
+ " \"defaultFileTemplate\": \"articleTemplate.htm\",\n"
+ " \"useJSP\": false,\n"
+ " \"jspListTemplate\": \"listTemplate.jsp\",\n"
+ " \"jspFileTemplate\": \"articleTemplate.jsp\",\n"
+ " \"cachePackageTagsTrack\": 200,\n"
+ " \"cachePackageTagsStore\": 200,\n"
+ " \"cachePackageTagsRefresh\": 60,\n"
+ " \"cacheTemplatesTrack\": 100,\n"
+ " \"cacheTemplatesStore\": 50,\n"
+ " \"cacheTemplatesRefresh\": 15,\n"
+ " \"cachePagesTrack\": 200,\n"
+ " \"cachePagesStore\": 100,\n"
+ " \"cachePagesRefresh\": 10,\n"
+ " \"cachePagesDirtyRead\": 10,\n"
+ " \"searchEngineListTemplate\": \"forSearchEnginesList.htm\",\n"
+ " \"searchEngineFileTemplate\": \"forSearchEngines.htm\",\n"
+ " \"searchEngineRobotsDb\": \"WEB-INF/robots.db\",\n"
+ " \"useDataStore\": true,\n"
+ " \"dataStoreClass\": \"org.cofax.SqlDataStore\",\n"
+ " \"redirectionClass\": \"org.cofax.SqlRedirection\",\n"
+ " \"dataStoreName\": \"cofax\",\n"
+ " \"dataStoreDriver\": \"com.microsoft.jdbc.sqlserver.SQLServerDriver\",\n"
+ " \"dataStoreUrl\": \"jdbc:microsoft:sqlserver://LOCALHOST:1433;DatabaseName=goon\",\n"
+ " \"dataStoreUser\": \"sa\",\n"
+ " \"dataStorePassword\": \"dataStoreTestQuery\",\n"
+ " \"dataStoreTestQuery\": \"SET NOCOUNT ON;select test='test';\",\n"
+ " \"dataStoreLogFile\": \"/usr/local/tomcat/logs/datastore.log\",\n"
+ " \"dataStoreInitConns\": 10,\n"
+ " \"dataStoreMaxConns\": 100,\n"
+ " \"dataStoreConnUsageLimit\": 100,\n"
+ " \"dataStoreLogLevel\": \"debug\",\n"
+ " \"maxUrlLength\": 500\n"
+ " }\n"
+ " },\n"
+ " {\n"
+ " \"servlet-name\": \"cofaxEmail\",\n"
+ " \"servlet-class\": \"org.cofax.cds.EmailServlet\",\n"
+ " \"init-param\": { \"mailHost\": \"mail1\", \"mailHostOverride\": \"mail2\" }\n"
+ " },\n"
+ " {\n"
+ " \"servlet-name\": \"cofaxAdmin\",\n"
+ " \"servlet-class\": \"org.cofax.cds.AdminServlet\"\n"
+ " },\n"
+ " { \"servlet-name\": \"fileServlet\", \"servlet-class\": \"org.cofax.cds.FileServlet\" },\n"
+ " {\n"
+ " \"servlet-name\": \"cofaxTools\",\n"
+ " \"servlet-class\": \"org.cofax.cms.CofaxToolsServlet\",\n"
+ " \"init-param\": {\n"
+ " \"templatePath\": \"toolstemplates/\",\n"
+ " \"log\": 1,\n"
+ " \"logLocation\": \"/usr/local/tomcat/logs/CofaxTools.log\",\n"
+ " \"logMaxSize\": \"\",\n"
+ " \"dataLog\": 1,\n"
+ " \"dataLogLocation\": \"/usr/local/tomcat/logs/dataLog.log\",\n"
+ " \"dataLogMaxSize\": \"\",\n"
+ " \"removePageCache\": \"/content/admin/remove?cache=pages&id=\",\n"
+ " \"removeTemplateCache\": \"/content/admin/remove?cache=templates&id=\",\n"
+ " \"fileTransferFolder\": \"/usr/local/tomcat/webapps/content/fileTransferFolder\",\n"
+ " \"lookInContext\": 1,\n"
+ " \"adminGroupID\": 4,\n"
+ " \"betaServer\": true\n"
+ " }\n"
+ " }\n"
+ " ],\n"
+ " \"servlet-mapping\": {\n"
+ " \"cofaxCDS\": \"/\",\n"
+ " \"cofaxEmail\": \"/cofaxutil/aemail/*\",\n"
+ " \"cofaxAdmin\": \"/admin/*\",\n"
+ " \"fileServlet\": \"/static/*\",\n"
+ " \"cofaxTools\": \"/tools/*\"\n"
+ " },\n"
+ " \"taglib\": { \"taglib-uri\": \"cofax.tld\", \"taglib-location\": \"/WEB-INF/tlds/cofax.tld\" }\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testGeneric5() {
//@formatter:off
final String base = "{\n"
+ " \"menu\": {\n"
+ " \"header\": \"SVG Viewer\",\n"
+ " \"items\": [\n"
+ " { \"id\": \"Open\" },\n"
+ " { \"id\": \"OpenNew\", \"label\": \"Open New\" },\n"
+ " null,\n"
+ " { \"id\": \"ZoomIn\", \"label\": \"Zoom In\" },\n"
+ " { \"id\": \"ZoomOut\", \"label\": \"Zoom Out\" },\n"
+ " { \"id\": \"OriginalView\", \"label\": \"Original View\" },\n"
+ " null,\n"
+ " { \"id\": \"Quality\" },\n"
+ " { \"id\": \"Pause\" },\n"
+ " { \"id\": \"Mute\" },\n"
+ " null,\n"
+ " { \"id\": \"Find\", \"label\": \"Find...\" },\n"
+ " { \"id\": \"FindAgain\", \"label\": \"Find Again\" },\n"
+ " { \"id\": \"Copy\" },\n"
+ " { \"id\": \"CopyAgain\", \"label\": \"Copy Again\" },\n"
+ " { \"id\": \"CopySVG\", \"label\": \"Copy SVG\" },\n"
+ " { \"id\": \"ViewSVG\", \"label\": \"View SVG\" },\n"
+ " { \"id\": \"ViewSource\", \"label\": \"View Source\" },\n"
+ " { \"id\": \"SaveAs\", \"label\": \"Save As\" },\n"
+ " null,\n"
+ " { \"id\": \"Help\" },\n"
+ " { \"id\": \"About\", \"label\": \"About Adobe CVG Viewer...\" }\n"
+ " ]\n"
+ " }\n"
+ "}";
//@formatter:on
EjsonLocal.test(base, base, -1);
}
@Test
public void testIndentedList() {
//@formatter:off
EjsonLocal.test(refOutputAll,
"{\n"
+ " menu: {\n"
+ " id: \"file\",\n"
+ " value: \"File\",\n"
+ " popup: {\n"
+ " menuitem: [\n"
+ " {\n"
+ " value: \"Close\",\n"
+ " onclick: \"CloseDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"New\",\n"
+ " onclick: \"CreateNewDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"Open\",\n"
+ " onclick: \"OpenDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"Close\",\n"
+ " onclick: \"CloseDoc()\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ " }\n"
+ "}\n",
-1);
//@formatter:on
}
@Test
public void testIndentedListWithNoBasicObject() {
//@formatter:off
EjsonLocal.test(refOutputAll,
"menu: {\n"
+ " id: \"file\",\n"
+ " value: \"File\",\n"
+ " popup: {\n"
+ " menuitem: [\n"
+ " {\n"
+ " value: \"Close\",\n"
+ " onclick: \"CloseDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"New\",\n"
+ " onclick: \"CreateNewDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"Open\",\n"
+ " onclick: \"OpenDoc()\"\n"
+ " },\n"
+ " {\n"
+ " value: \"Close\",\n"
+ " onclick: \"CloseDoc()\"\n"
+ " }\n"
+ " ]\n"
+ " }\n"
+ "}\n",
-1);
//@formatter:on
}
}

View File

@ -1,87 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Order;
import org.junit.jupiter.api.Test;
public class EjsonTestBoolean {
static private String refOutputBoolean1 = "{\n\t\"tmpElement\": true\n}";
static private String refOutputBoolean2 = "{\n\t\"tmpElement\": false\n}";
@BeforeAll
public static void beforeClass() {
Log.verbose("----------------------------------------------------------------");
}
@Test
@Order(1)
public void multipleValue() {
EjsonLocal.test("{\n\t\"tmpElement\": false,\n\t\"tmpElement2\": true\n}", "{ tmpElement:false, tmpElement2:true }\n", -1);
}
@Test
@Order(2)
public void test010BaseTrue() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:true }\n", -1);
}
@Test
@Order(3)
public void test020TabbedTrue() {
EjsonLocal.test(refOutputBoolean1, "{ \t\ntmpElement:true \t\n }\n", -1);
}
@Test
@Order(4)
public void test030NoneTrue() {
EjsonLocal.test(refOutputBoolean1, "tmpElement:true\n", -1);
}
@Test
@Order(5)
public void test040BaseTrue1() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:TRUE }\n", 1);
}
@Test
@Order(6)
public void test050BaseTrue2() {
EjsonLocal.test(refOutputBoolean1, "{ tmpElement:True }\n", 1);
}
@Test
@Order(7)
public void test110BaseFalse() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:false }\n", -1);
}
@Test
@Order(8)
public void test120TabbedFalse() {
EjsonLocal.test(refOutputBoolean2, "{ \t\ntmpElement:false \t\n }\n", -1);
}
@Test
@Order(9)
public void test130NoneFalse() {
EjsonLocal.test(refOutputBoolean2, "tmpElement:false\n", -1);
}
@Test
@Order(10)
public void test140BaseFalse1() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:FALSE }\n", 1);
}
@Test
@Order(11)
public void test150BaseFalse2() {
EjsonLocal.test(refOutputBoolean2, "{ tmpElement:False }\n", 1);
}
}

View File

@ -1,73 +0,0 @@
/** @file
* @author Edouard DUPIN
* @copyright 2021, Edouard DUPIN, all right reserved
* @license MPL v2.0 (see license file)
*/
package test.atriasoft.ejson;
import io.scenarium.logger.LogLevel;
import io.scenarium.logger.Logger;
public class Log {
private static final String LIB_NAME = "ejson-test";
private static final String LIB_NAME_DRAW = Logger.getDrawableName(LIB_NAME);
private static final boolean PRINT_CRITICAL = Logger.getNeedPrint(LIB_NAME, LogLevel.CRITICAL);
private static final boolean PRINT_ERROR = Logger.getNeedPrint(LIB_NAME, LogLevel.ERROR);
private static final boolean PRINT_WARNING = Logger.getNeedPrint(LIB_NAME, LogLevel.WARNING);
private static final boolean PRINT_INFO = Logger.getNeedPrint(LIB_NAME, LogLevel.INFO);
private static final boolean PRINT_DEBUG = Logger.getNeedPrint(LIB_NAME, LogLevel.DEBUG);
private static final boolean PRINT_VERBOSE = Logger.getNeedPrint(LIB_NAME, LogLevel.VERBOSE);
private static final boolean PRINT_TODO = Logger.getNeedPrint(LIB_NAME, LogLevel.TODO);
private static final boolean PRINT_PRINT = Logger.getNeedPrint(LIB_NAME, LogLevel.PRINT);
public static void critical(final String data) {
if (PRINT_CRITICAL) {
Logger.critical(LIB_NAME_DRAW, data);
}
}
public static void debug(final String data) {
if (PRINT_DEBUG) {
Logger.debug(LIB_NAME_DRAW, data);
}
}
public static void error(final String data) {
if (PRINT_ERROR) {
Logger.error(LIB_NAME_DRAW, data);
}
}
public static void info(final String data) {
if (PRINT_INFO) {
Logger.info(LIB_NAME_DRAW, data);
}
}
public static void print(final String data) {
if (PRINT_PRINT) {
Logger.print(LIB_NAME_DRAW, data);
}
}
public static void todo(final String data) {
if (PRINT_TODO) {
Logger.todo(LIB_NAME_DRAW, data);
}
}
public static void verbose(final String data) {
if (PRINT_VERBOSE) {
Logger.verbose(LIB_NAME_DRAW, data);
}
}
public static void warning(final String data) {
if (PRINT_WARNING) {
Logger.warning(LIB_NAME_DRAW, data);
}
}
private Log() {}
}