You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@uima.apache.org by re...@apache.org on 2021/07/09 16:27:59 UTC
[uima-uimaj] 01/01: [UIMA-6373] Format UIMA Core Java SDK codebase
This is an automated email from the ASF dual-hosted git repository.
rec pushed a commit to branch refactoring/UIMA-6373-Format-UIMA-Core-Java-SDK-codebase
in repository https://gitbox.apache.org/repos/asf/uima-uimaj.git
commit d2400ffdd6f4074d31397626376d308d73f384a3
Author: Richard Eckart de Castilho <re...@apache.org>
AuthorDate: Fri Jul 9 18:27:47 2021 +0200
[UIMA-6373] Format UIMA Core Java SDK codebase
- Format the JSON module
---
.../org/apache/uima/json/JsonCasSerializer.java | 1192 +++++++++++---------
.../apache/uima/json/JsonMetaDataSerializer.java | 97 +-
.../impl/JsonContentHandlerJacksonWrapper.java | 289 +++--
.../json/impl/MetaDataObjectSerializer_json.java | 163 +--
.../apache/uima/json/JsonCasSerializerTest.java | 390 +++----
.../apache/uima/json/JsonMetaDataObjectTest.java | 118 +-
.../apache/uima/json/JsonXmiCasSerializerTest.java | 8 +-
.../resource/metadata/impl/TestFruitBagObject.java | 31 +-
.../resource/metadata/impl/TestFruitObject.java | 54 +-
9 files changed, 1293 insertions(+), 1049 deletions(-)
diff --git a/uimaj-json/src/main/java/org/apache/uima/json/JsonCasSerializer.java b/uimaj-json/src/main/java/org/apache/uima/json/JsonCasSerializer.java
index a71dc9e..ff49517 100644
--- a/uimaj-json/src/main/java/org/apache/uima/json/JsonCasSerializer.java
+++ b/uimaj-json/src/main/java/org/apache/uima/json/JsonCasSerializer.java
@@ -78,101 +78,139 @@ import com.fasterxml.jackson.core.io.SerializedString;
/**
* <h2>CAS serializer for JSON formats.</h2>
- * <p>Writes a CAS in a JSON format.</p>
- *
- * <p>To use,</p>
+ * <p>
+ * Writes a CAS in a JSON format.
+ * </p>
+ *
+ * <p>
+ * To use,
+ * </p>
* <ul>
- * <li>create an instance of this class,</li>
- * <li>(optionally) configure the instance, and then</li>
- * <li>call serialize on the instance, optionally passing in additional parameters.</li></ul>
- *
- * <p>After the 1st 2 steps, the serializer instance may be used for multiple calls (on multiple threads) to
- * the 3rd serialize step, if all calls use the same configuration.</p>
+ * <li>create an instance of this class,</li>
+ * <li>(optionally) configure the instance, and then</li>
+ * <li>call serialize on the instance, optionally passing in additional parameters.</li>
+ * </ul>
*
- * <p>There are "convenience" static serialize methods that do these three steps for common configurations.</p>
+ * <p>
+ * After the 1st 2 steps, the serializer instance may be used for multiple calls (on multiple
+ * threads) to the 3rd serialize step, if all calls use the same configuration.
+ * </p>
*
- * <p>Parameters can be configured in this instance (I), and/or as part of the serialize(S) call.</p>
+ * <p>
+ * There are "convenience" static serialize methods that do these three steps for common
+ * configurations.
+ * </p>
*
- * <p>The parameters that can be configured are:</p>
+ * <p>
+ * Parameters can be configured in this instance (I), and/or as part of the serialize(S) call.
+ * </p>
+ *
+ * <p>
+ * The parameters that can be configured are:
+ * </p>
* <ul>
- * <li>(S) The CAS to serialize
- * <li>(S) where to put the output - an OutputStream, Writer, or File</li>
- * <li>(I,S) a type system - (default null) if supplied, it is used to "filter" types and features that are serialized. If provided, only
- * those that exist in the passed in type system are included in the serialization</li>
- * <li>(I,S) a flag for prettyprinting - default false (no prettyprinting)</li>
+ * <li>(S) The CAS to serialize
+ * <li>(S) where to put the output - an OutputStream, Writer, or File</li>
+ * <li>(I,S) a type system - (default null) if supplied, it is used to "filter" types and features
+ * that are serialized. If provided, only those that exist in the passed in type system are included
+ * in the serialization</li>
+ * <li>(I,S) a flag for prettyprinting - default false (no prettyprinting)</li>
* </ul>
*
- * <p>For Json serialization, additional configuration from the Jackson implementation can be configured</p>
- * on 2 associated Jackson instances:
- * <ul><li>JsonFactory</li>
- * <li>JsonGenerator</li></ul>
- * using the standard Jackson methods on the associated JsonFactory instance;
- * see the Jackson JsonFactory and JsonGenerator javadocs for details.
+ * <p>
+ * For Json serialization, additional configuration from the Jackson implementation can be
+ * configured
+ * </p>
+ * on 2 associated Jackson instances:
+ * <ul>
+ * <li>JsonFactory</li>
+ * <li>JsonGenerator</li>
+ * </ul>
+ * using the standard Jackson methods on the associated JsonFactory instance; see the Jackson
+ * JsonFactory and JsonGenerator javadocs for details.
*
- * <p>These 2 Jackson objects are settable/gettable from an instance of this class.
- * They are created if not supplied by the caller.</p>
+ * <p>
+ * These 2 Jackson objects are settable/gettable from an instance of this class. They are created if
+ * not supplied by the caller.
+ * </p>
*
- * <p>Once this instance is configured, the serialize method is called
- * to serialized a CAS to an output.</p>
+ * <p>
+ * Once this instance is configured, the serialize method is called to serialized a CAS to an
+ * output.
+ * </p>
*
- * <p>Instances of this class must be used on only one thread while configuration is being done;
- * afterwards, multiple threads may use the configured instance, to call serialize.</p>
+ * <p>
+ * Instances of this class must be used on only one thread while configuration is being done;
+ * afterwards, multiple threads may use the configured instance, to call serialize.
+ * </p>
*/
public class JsonCasSerializer {
private static final SerializedString CONTEXT_NAME = new SerializedString("_context");
-
+
private static final SerializedString TYPE_SYSTEM_NAME = new SerializedString("_type_system");
-
+
private static final SerializedString TYPES_NAME = new SerializedString("_types");
private static final SerializedString ID_NAME = new SerializedString("_id");
private static final SerializedString SUB_TYPES_NAME = new SerializedString("_subtypes");
-
+
private static final SerializedString FEATURE_TYPES_NAME = new SerializedString("_feature_types");
private static final SerializedString FEATURE_REFS_NAME = new SerializedString("_ref");
private static final SerializedString FEATURE_ARRAY_NAME = new SerializedString("_array");
- private static final SerializedString FEATURE_BYTE_ARRAY_NAME = new SerializedString("_byte_array");
-
+ private static final SerializedString FEATURE_BYTE_ARRAY_NAME = new SerializedString(
+ "_byte_array");
+
+ private static final SerializedString REFERENCED_FSS_NAME = new SerializedString(
+ "_referenced_fss");
+ private static final SerializedString VIEWS_NAME = new SerializedString("_views");
- private static final SerializedString REFERENCED_FSS_NAME = new SerializedString("_referenced_fss");
- private static final SerializedString VIEWS_NAME = new SerializedString("_views");
-
private static final SerializedString TYPE_NAME = new SerializedString("_type");
-
+
private static final SerializedString COLLECTION_NAME = new SerializedString("_collection");
-
private static final SerializedString DELTA_CAS_NAME = new SerializedString("_delta_cas");
private static final SerializedString ADDED_MEMBERS_NAME = new SerializedString("added_members");
- private static final SerializedString DELETED_MEMBERS_NAME = new SerializedString("deleted_members");
- private static final SerializedString REINDEXED_MEMBERS_NAME = new SerializedString("reindexed_members");
-
+ private static final SerializedString DELETED_MEMBERS_NAME = new SerializedString(
+ "deleted_members");
+ private static final SerializedString REINDEXED_MEMBERS_NAME = new SerializedString(
+ "reindexed_members");
+
/**
- * <p>The serialization can optionally include context information in addition to the feature structures.</p>
+ * <p>
+ * The serialization can optionally include context information in addition to the feature
+ * structures.
+ * </p>
+ *
+ * <p>
+ * This context information is specified, per used-type.
+ * </p>
*
- * <p>This context information is specified, per used-type.</p>
+ * <p>
+ * It can be further subdivided into 3 parts:
+ * </p>
+ * <ol>
+ * <li>What their (used) subtypes are. This enables iterating over a type and all of its subtypes,
+ * e.g. an iterator over all "Annotations".</li>
+ * <li>whether or not to include the map from short type names to their fully qualified
+ * equivalents.</li>
+ * <li>Information to enable deserialization of some ambiguous values, depending on the range type
+ * of a feature
+ * </ol>
*
- * <p>It can be further subdivided into 3 parts:</p>
- * <ol>
- * <li>What their (used) subtypes are. This enables iterating over a type
- * and all of its subtypes, e.g. an iterator over all "Annotations".</li>
- * <li> whether or not to include the map from short type names to their fully qualified equivalents.</li>
- * <li>Information to enable deserialization of some ambiguous values, depending on the range type of a feature
- * </ol>
- *
- * <p>Some of these may be omitted, if not wanted. This enum allows specifying what to omit.</p>
+ * <p>
+ * Some of these may be omitted, if not wanted. This enum allows specifying what to omit.
+ * </p>
*
*/
public enum JsonContextFormat {
- omitContext, // omit the entire context
- omitSubtypes,
- omitExpandedTypeNames,
+ omitContext, // omit the entire context
+ omitSubtypes, omitExpandedTypeNames,
}
-
+
private final CasSerializerSupport css = new CasSerializerSupport();
-
+
// for testing
CasSerializerSupport getCss() {
return css;
@@ -180,7 +218,7 @@ public class JsonCasSerializer {
private JsonFactory jsonFactory = null;
- private boolean isDynamicEmbedding = true;
+ private boolean isDynamicEmbedding = true;
private boolean isWithContext = true;
private boolean isWithSubtypes = true;
private boolean isWithExpandedTypeNames = true;
@@ -188,21 +226,23 @@ public class JsonCasSerializer {
private String typeSystemReference;
-
+ // @formatter:off
/***********************************************
- * C O N S T R U C T O R S *
+ * C O N S T R U C T O R S *
***********************************************/
+ // @formatter:on
/**
* Creates a new JsonCasSerializer
*/
public JsonCasSerializer() {
- }
-
+ }
+
+ // @formatter:off
/**************************************************
- * J S O N *
+ * J S O N *
**************************************************/
-
+
/****************************************************
* Static JSON Serializer methods for convenience *
* *
@@ -210,7 +250,8 @@ public class JsonCasSerializer {
* The non-static methods *
* are named serializeJson *
****************************************************/
-
+ // @formatter:on
+
/**
* Serializes a CAS using JSON
*
@@ -219,26 +260,28 @@ public class JsonCasSerializer {
* @param output
* a File, OutputStream or Writer to which to write the XMI document
*
- * @throws IOException if there was an IOException
+ * @throws IOException
+ * if there was an IOException
*/
- public static void jsonSerialize(CAS aCAS, Object output) throws IOException {
+ public static void jsonSerialize(CAS aCAS, Object output) throws IOException {
jsonSerialize(aCAS, null, output, false, null, null);
}
/**
- * Serializes a CAS to an output (File, OutputStream, XMI stream, or Writer).
- * The supplied typesystem filters the output
+ * Serializes a CAS to an output (File, OutputStream, XMI stream, or Writer). The supplied
+ * typesystem filters the output
*
* @param aCAS
* CAS to serialize.
* @param aTargetTypeSystem
* type system used for filtering what gets serialized. Any types or features not in the
- * target type system will not be serialized. A null value indicates no filtering, that is,
- * that all types and features will be serialized.
- * @param output
+ * target type system will not be serialized. A null value indicates no filtering, that
+ * is, that all types and features will be serialized.
+ * @param output
* output (File, OutputStream, or Writer) to which to write the JSON document
*
- * @throws IOException if there was an IOException
+ * @throws IOException
+ * if there was an IOException
*/
public static void jsonSerialize(CAS aCAS, TypeSystem aTargetTypeSystem, Object output)
throws IOException {
@@ -246,37 +289,41 @@ public class JsonCasSerializer {
}
/**
- * Serializes a Delta CAS to an output (File, Writer, or OutputStream).
- * This version of this method allows many options to be configured.
- *
- *
+ * Serializes a Delta CAS to an output (File, Writer, or OutputStream). This version of this
+ * method allows many options to be configured.
+ *
+ *
* @param aCAS
* CAS to serialize.
* @param aTargetTypeSystem
* type system to which the produced XMI will conform. Any types or features not in the
- * target type system will not be serialized. A null value indicates that all types and features
- * will be serialized.
+ * target type system will not be serialized. A null value indicates that all types and
+ * features will be serialized.
* @param output
* File, Writer, or OutputStream to which to write the JSON document
* @param aPrettyPrint
- * if true the JSON output will be formatted with newlines and indenting. If false it will be unformatted.
+ * if true the JSON output will be formatted with newlines and indenting. If false it
+ * will be unformatted.
* @param aMarker
- * an optional object used to determine which FeatureStructures and modifications were created after
- * the mark was set. Used to serialize a Delta CAS consisting of only new FSs and views and
- * preexisting FSs and Views that have been modified. If null, full serialization is done.
- * See the JavaDocs for {@link Marker} for details.
- * @param sharedData optional, used for delta serialization (not yet supported)
- * @throws IOException if there was an IOException
+ * an optional object used to determine which FeatureStructures and modifications were
+ * created after the mark was set. Used to serialize a Delta CAS consisting of only new
+ * FSs and views and preexisting FSs and Views that have been modified. If null, full
+ * serialization is done. See the JavaDocs for {@link Marker} for details.
+ * @param sharedData
+ * optional, used for delta serialization (not yet supported)
+ * @throws IOException
+ * if there was an IOException
*/
- public static void jsonSerialize(CAS aCAS, TypeSystem aTargetTypeSystem, Object output, boolean aPrettyPrint,
- Marker aMarker, XmiSerializationSharedData sharedData)
+ public static void jsonSerialize(CAS aCAS, TypeSystem aTargetTypeSystem, Object output,
+ boolean aPrettyPrint, Marker aMarker, XmiSerializationSharedData sharedData)
throws IOException {
JsonCasSerializer ser = new JsonCasSerializer();
- ser.setFilterTypes((TypeSystemImpl)aTargetTypeSystem);
+ ser.setFilterTypes((TypeSystemImpl) aTargetTypeSystem);
ser.setPrettyPrint(aPrettyPrint);
ser.serialize(aCAS, output, sharedData, aMarker);
- }
-
+ }
+
+ // @formatter:off
/*************************************************************************************
* Multi-step api
*
@@ -296,19 +343,25 @@ public class JsonCasSerializer {
* 2) call its serializeJson method, passing in the CAS, and an output (Writer/Outputstream/File)
*
*************************************************************************************/
-
+ // @formatter:on
+
/**
- * Serialize a Cas to an Output, using configurations set on this instance.
- * Constructs a JsonContentHandlerJacksonWrapper, using configured JsonFactory and prettyprint settings if any
- * @param cas - the CAS to serialize
- * @param output - where the output goes, an OutputStream, Writer, or File
- * @throws IOException if there was an IOException
+ * Serialize a Cas to an Output, using configurations set on this instance. Constructs a
+ * JsonContentHandlerJacksonWrapper, using configured JsonFactory and prettyprint settings if any
+ *
+ * @param cas
+ * - the CAS to serialize
+ * @param output
+ * - where the output goes, an OutputStream, Writer, or File
+ * @throws IOException
+ * if there was an IOException
*/
public void serialize(CAS cas, Object output) throws IOException {
serialize(cas, output, null, null);
}
-
- public void serialize(CAS cas, Object output, XmiSerializationSharedData sharedData, Marker marker) throws IOException {
+
+ public void serialize(CAS cas, Object output, XmiSerializationSharedData sharedData,
+ Marker marker) throws IOException {
JsonContentHandlerJacksonWrapper jch;
try {
jch = new JsonContentHandlerJacksonWrapper(jsonFactory, output, css.isFormattedOutput);
@@ -317,137 +370,161 @@ public class JsonCasSerializer {
}
serialize(cas, jch, sharedData, marker);
}
-
+
/**
* Serialize a Cas to an Output configured in the passed in JsonContentHandlerJacksonWrapper
- * Constructs a new CasDocSerializer instance to do the serialization,
- * configured using this class's Delta marker setting (if any)
- * @param cas The CAS to serialize
- * @param jch the configured content handler
- * @throws IOException if there was an IOException
+ * Constructs a new CasDocSerializer instance to do the serialization, configured using this
+ * class's Delta marker setting (if any)
+ *
+ * @param cas
+ * The CAS to serialize
+ * @param jch
+ * the configured content handler
+ * @throws IOException
+ * if there was an IOException
*/
public void serialize(CAS cas, JsonContentHandlerJacksonWrapper jch) throws IOException {
serialize(cas, jch, null, null);
- }
-
- public void serialize(CAS cas, JsonContentHandlerJacksonWrapper jch, XmiSerializationSharedData sharedData, Marker marker) throws IOException {
- JsonDocSerializer ser = new JsonDocSerializer(jch, ((CASImpl) cas).getBaseCAS(), sharedData, (MarkerImpl) marker);
- try {
- ser.cds.needNameSpaces = false;
- ser.cds.serialize();
- } catch (Exception e) {
- if (e instanceof IOException) {
- throw (IOException) e;
- }
- throw new RuntimeException(e);
+ }
+
+ public void serialize(CAS cas, JsonContentHandlerJacksonWrapper jch,
+ XmiSerializationSharedData sharedData, Marker marker) throws IOException {
+ JsonDocSerializer ser = new JsonDocSerializer(jch, ((CASImpl) cas).getBaseCAS(), sharedData,
+ (MarkerImpl) marker);
+ try {
+ ser.cds.needNameSpaces = false;
+ ser.cds.serialize();
+ } catch (Exception e) {
+ if (e instanceof IOException) {
+ throw (IOException) e;
}
+ throw new RuntimeException(e);
+ }
}
-
+
+ // @formatter:off
/********************************************************
* Routines to set/reset configuration *
********************************************************/
+ // @formatter:on
/**
* set or reset the pretty print flag (default is false)
- * @param pp true to do pretty printing of output
+ *
+ * @param pp
+ * true to do pretty printing of output
* @return the original instance, possibly updated
*/
public JsonCasSerializer setPrettyPrint(boolean pp) {
css.setPrettyPrint(pp);
return this;
}
-
+
/**
- * set which JsonFactory instance to use; if null, a new instance is used
- * this can be used to preconfigure the JsonFactory instance
- * @param jsonFactory -
+ * set which JsonFactory instance to use; if null, a new instance is used this can be used to
+ * preconfigure the JsonFactory instance
+ *
+ * @param jsonFactory
+ * -
* @return the original instance, possibly updated
*/
public JsonCasSerializer setJsonFactory(JsonFactory jsonFactory) {
this.jsonFactory = jsonFactory;
return this;
}
-
+
/**
- * pass in a type system to use for filtering what gets serialized;
- * only those types and features which are defined this type system are included.
- * @param ts the filter
+ * pass in a type system to use for filtering what gets serialized; only those types and features
+ * which are defined this type system are included.
+ *
+ * @param ts
+ * the filter
* @return the original instance, possibly updated
*/
public JsonCasSerializer setFilterTypes(TypeSystemImpl ts) {
css.setFilterTypes(ts);
return this;
}
-
+
public JsonCasSerializer setTypeSystemReference(String reference) {
typeSystemReference = reference;
return this;
}
// not done here, done on serialize call, because typically changes for each call
-// /**
-// * set the Marker to specify delta cas serialization
-// * forces static embedding mode
-// * @param m - the marker
-// * @return the original instance, possibly updated
-// */
-// public JsonCasSerializer setDeltaCas(Marker m, XmiSerializationSharedData sharedData) {
-// css.setDeltaCas(m);
-// setStaticEmbedding(); // delta requires static embedding mode
-// return this;
-// }
-
+ // /**
+ // * set the Marker to specify delta cas serialization
+ // * forces static embedding mode
+ // * @param m - the marker
+ // * @return the original instance, possibly updated
+ // */
+ // public JsonCasSerializer setDeltaCas(Marker m, XmiSerializationSharedData sharedData) {
+ // css.setDeltaCas(m);
+ // setStaticEmbedding(); // delta requires static embedding mode
+ // return this;
+ // }
+
/**
* set an error handler to receive information about errors
- * @param eh the error handler
+ *
+ * @param eh
+ * the error handler
* @return the original instance, possibly updated
*/
public JsonCasSerializer setErrorHandler(ErrorHandler eh) {
css.setErrorHandler(eh);
return this;
}
-
+
/**
* Sets static embedding mode
+ *
* @return the original instance, possibly updated
*/
public JsonCasSerializer setStaticEmbedding() {
isDynamicEmbedding = false;
return this;
}
-
+
/**
* sets which Json context format to use when serializing
- * @param format the format to use for the serialization
- * Specifying the context flag also specifies all 3 subflags
- * Specifying one of the subflags as true sets the context flag to true if it isn't already
+ *
+ * @param format
+ * the format to use for the serialization Specifying the context flag also specifies all
+ * 3 subflags Specifying one of the subflags as true sets the context flag to true if it
+ * isn't already
* @return the original instance, possibly updated
*/
public JsonCasSerializer setJsonContext(JsonContextFormat format) {
switch (format) {
- case omitContext:
- isWithContext = false;
- isWithSubtypes = false;
- isWithExpandedTypeNames = false; break;
-
- case omitSubtypes:
- isWithSubtypes = false; break;
-
- case omitExpandedTypeNames:
- isWithExpandedTypeNames = false; break;
+ case omitContext:
+ isWithContext = false;
+ isWithSubtypes = false;
+ isWithExpandedTypeNames = false;
+ break;
+
+ case omitSubtypes:
+ isWithSubtypes = false;
+ break;
+
+ case omitExpandedTypeNames:
+ isWithExpandedTypeNames = false;
+ break;
}
return this;
}
-
+
public JsonCasSerializer setOmit0Values(boolean omitDefaultValues) {
isOmit0Values = omitDefaultValues;
return this;
}
-
+
private static class MapType2Subtypes extends RedBlackTree<IntVector> {
/**
*
- * @param type main type
- * @param subtype subtype of main type
+ * @param type
+ * main type
+ * @param subtype
+ * subtype of main type
* @return true if added, false if already was there
*/
boolean addSubtype(int type, int subtype) {
@@ -457,7 +534,7 @@ public class JsonCasSerializer {
iv.add(subtype);
put(type, iv);
return true;
- }
+ }
if (iv.contains(subtype)) {
return false;
}
@@ -465,60 +542,63 @@ public class JsonCasSerializer {
return true;
}
}
-
+
class JsonDocSerializer extends CasSerializerSupportSerialize {
-
+
private final CasDocSerializer cds;
-
+
private final JsonContentHandlerJacksonWrapper jch;
private final JsonGenerator jg;
-
+
private final Map<String, SerializedString> serializedStrings = new HashMap<>();
-
+
private final Map<String, XmlElementName> usedTypeName2XmlElementName;
-
+
private final MapType2Subtypes mapType2Subtypes = new MapType2Subtypes();
-
+
private final List<TypeImpl> parentTypesWithNoInstances = new ArrayList<>();
-
+
private int lastEncodedTypeCode;
-
+
private boolean startedReferencedFSs;
-
+
private final boolean isOmitDefaultValues;
-
+
private final boolean isWithContext;
private final boolean isWithSubtypes;
-
- private boolean indexId; // true causes fs to be listed as "id" : { ...}, false as "type" : [ {...}
-
+
+ private boolean indexId; // true causes fs to be listed as "id" : { ...}, false as "type" : [
+ // {...}
+
private boolean isEmbedded = false; // true for embedded FSs, causes _type to be included
-
- private boolean isEmbeddedFromFsFeature; // used for NL formatting, false if embedded due to Array or List
+
+ private boolean isEmbeddedFromFsFeature; // used for NL formatting, false if embedded due to
+ // Array or List
private boolean startedFeatureTypes;
-
-
- private JsonDocSerializer(ContentHandler ch, CASImpl cas, XmiSerializationSharedData sharedData, MarkerImpl marker) {
- cds = css.new CasDocSerializer(ch, cas, sharedData, marker, this, JsonCasSerializer.this.isDynamicEmbedding);
- this.isOmitDefaultValues = JsonCasSerializer.this.isOmit0Values;
- isWithSubtypes = JsonCasSerializer.this.isWithSubtypes;
+
+ private JsonDocSerializer(ContentHandler ch, CASImpl cas, XmiSerializationSharedData sharedData,
+ MarkerImpl marker) {
+ cds = css.new CasDocSerializer(ch, cas, sharedData, marker, this,
+ JsonCasSerializer.this.isDynamicEmbedding);
+ this.isOmitDefaultValues = JsonCasSerializer.this.isOmit0Values;
+ isWithSubtypes = JsonCasSerializer.this.isWithSubtypes;
jch = (JsonContentHandlerJacksonWrapper) ch;
jg = jch.getJsonGenerator();
- isWithContext = JsonCasSerializer.this.isWithContext || isWithSubtypes || isWithExpandedTypeNames;
+ isWithContext = JsonCasSerializer.this.isWithContext || isWithSubtypes
+ || isWithExpandedTypeNames;
usedTypeName2XmlElementName = new HashMap<>(cds.tsi.getNumberOfTypes());
}
-
+
@Override
protected void initializeNamespaces() {
- if (cds.sharedData != null &&
- (null != cds.sharedData.getOutOfTypeSystemElements() ||
- cds.sharedData.hasOutOfTypeSystemArrayElements())) {
- throw new UnsupportedOperationException("Can't do JSON serialization "
- + "if there are out-of-type-system elements,"
- + " because there's no type information available (needed for _context)");
+ if (cds.sharedData != null && (null != cds.sharedData.getOutOfTypeSystemElements()
+ || cds.sharedData.hasOutOfTypeSystemArrayElements())) {
+ throw new UnsupportedOperationException(
+ "Can't do JSON serialization " + "if there are out-of-type-system elements,"
+ + " because there's no type information available (needed for _context)");
}
}
@@ -529,44 +609,44 @@ public class JsonCasSerializer {
}
jch.writeNlJustBeforeNext();
jg.writeFieldName(DELTA_CAS_NAME);
- jg.writeStartObject();
-
+ jg.writeStartObject();
+
cds.writeViewsCommons(); // encodes cas.sofaCount + 1 elements
- jg.writeEndObject(); // and end of views property
+ jg.writeEndObject(); // and end of views property
}
-
+
@Override
- protected void writeFeatureStructures(int elementCount /* not used */ ) throws Exception{
- jch.withoutNl(); // set up prettyprint mode so this class controls it
-
- jg.writeStartObject(); // container for (maybe) context, fss (2 parts), and (maybe) delta view info
-
+ protected void writeFeatureStructures(int elementCount /* not used */ ) throws Exception {
+ jch.withoutNl(); // set up prettyprint mode so this class controls it
+
+ jg.writeStartObject(); // container for (maybe) context, fss (2 parts), and (maybe) delta view
+ // info
+
if (isWithContext) {
serializeJsonLdContext();
}
-
+
jch.writeNlJustBeforeNext();
-
+
// write the reachable from indexes FS
indexId = false;
-
jg.writeFieldName(VIEWS_NAME);
jg.writeStartObject();
-
- final List<TOP>[] byViewByTypeFSs = sortByViewType();
-
+
+ final List<TOP>[] byViewByTypeFSs = sortByViewType();
+
for (int viewNbr = 1; viewNbr <= byViewByTypeFSs.length; viewNbr++) {
// viewNbr starts at 1
lastEncodedTypeCode = -1;
final List<TOP> fssInView = byViewByTypeFSs[viewNbr - 1];
final Sofa sofa = cds.getSofa(viewNbr);
if (sofa == null && fssInView.size() == 0) {
- continue; // skip non-existent initial view with no sofa and no elements
+ continue; // skip non-existent initial view with no sofa and no elements
}
jch.writeNlJustBeforeNext();
String viewName = (null == sofa) ? CAS.NAME_DEFAULT_SOFA : sofa.getSofaID();
- jg.writeFieldName(viewName); // view namne
+ jg.writeFieldName(viewName); // view namne
jg.writeStartObject();
for (TOP fs : fssInView) {
cds.encodeFS(fs);
@@ -576,51 +656,51 @@ public class JsonCasSerializer {
}
jg.writeEndObject();
}
-
- jg.writeEndObject(); // end of value for _views
-
+
+ jg.writeEndObject(); // end of value for _views
+
// write the non-embeddable referenced FSs
-
+
indexId = true;
startedReferencedFSs = false;
cds.encodeQueued();
if (startedReferencedFSs) {
jg.writeEndObject(); // of all referenced FSs
}
-
+
}
-
+
@Override
protected void writeEndOfSerialization() throws IOException {
jg.writeEndObject(); // wrapper of _context and cas
jg.flush();
}
-
+
// sort the by-view by-type set
- // previously Serialized
+ // previously Serialized
/**
* @return the List<TOP>[] returned by cds.indexedFSs, but with each view sorted by type
*/
private List<TOP>[] sortByViewType() {
-
+
@SuppressWarnings("unchecked")
- final List<TOP>[] r = new List[cds.indexedFSs.length];
-
+ final List<TOP>[] r = new List[cds.indexedFSs.length];
+
int i = 0;
for (final List<TOP> fss : cds.indexedFSs) {
- r[i] = (fss == null) ? Collections.EMPTY_LIST : (List<TOP>) ((ArrayList<TOP>)fss).clone();
+ r[i] = (fss == null) ? Collections.EMPTY_LIST : (List<TOP>) ((ArrayList<TOP>) fss).clone();
r[i++].sort(cds.sortFssByType);
}
return r;
}
-
+
@Override
protected void writeView(Sofa sofa, Collection<TOP> members) throws IOException {
jch.writeNlJustBeforeNext();
String sofaXmiId = (null == sofa) ? "0" : cds.getXmiId(sofa);
jg.writeArrayFieldStart(sofaXmiId);
writeViewMembers(members);
- //check for out-of-typesystem members
+ // check for out-of-typesystem members
if (cds.sharedData != null) {
List<String> ootsMembers = cds.sharedData.getOutOfTypeSystemViewMembers(sofaXmiId);
jch.writeNlJustBeforeNext();
@@ -629,25 +709,27 @@ public class JsonCasSerializer {
jg.writeEndArray();
}
-
- private void writeViewForDeltas(SerializedString kind, Collection<TOP> deltaMembers) throws IOException {
+
+ private void writeViewForDeltas(SerializedString kind, Collection<TOP> deltaMembers)
+ throws IOException {
jg.writeFieldName(kind);
jg.writeStartArray();
- writeViewMembers(deltaMembers);
+ writeViewMembers(deltaMembers);
jg.writeEndArray();
}
-
+
@Override
- protected void writeView(Sofa sofa, Collection<TOP> added, Collection<TOP> deleted, Collection<TOP> reindexed) throws IOException {
+ protected void writeView(Sofa sofa, Collection<TOP> added, Collection<TOP> deleted,
+ Collection<TOP> reindexed) throws IOException {
jch.writeNlJustBeforeNext();
jg.writeFieldName(cds.getXmiId(sofa));
jg.writeStartObject();
writeViewForDeltas(ADDED_MEMBERS_NAME, added);
writeViewForDeltas(DELETED_MEMBERS_NAME, deleted);
- writeViewForDeltas(REINDEXED_MEMBERS_NAME, reindexed);
+ writeViewForDeltas(REINDEXED_MEMBERS_NAME, reindexed);
jg.writeEndObject();
}
-
+
private void writeViewMembers(Collection<TOP> members) throws IOException {
int nextBreak = CasSerializerSupport.PP_ELEMENTS;
int i = 0;
@@ -667,7 +749,7 @@ public class JsonCasSerializer {
/*
* version for oots data
*/
-
+
private void writeViewMembers(List<String> members) throws IOException {
int nextBreak = CasSerializerSupport.PP_ELEMENTS;
int i = 0;
@@ -682,122 +764,129 @@ public class JsonCasSerializer {
jg.writeNumber(Integer.parseInt(xmiId));
}
}
+
/**
* <h2>JSON: serialize context info</h2>
*
- * <p>The context has several parts.
- * <p>The typeSystemReference is an optional URI to a type system that is written out.
- * <p>The types part is organized by the type hierarchy, starting with the uima.cas.TOP type. There is an entry
- * for each type which has 1 or more serailized instances, and also for all supertypes of those types.
- * The entry is a JSON key-value pair "short-type-name" : {...}. </p>
+ * <p>
+ * The context has several parts.
+ * <p>
+ * The typeSystemReference is an optional URI to a type system that is written out.
+ * <p>
+ * The types part is organized by the type hierarchy, starting with the uima.cas.TOP type. There
+ * is an entry for each type which has 1 or more serailized instances, and also for all
+ * supertypes of those types. The entry is a JSON key-value pair "short-type-name" : {...}.
+ * </p>
*
- * <p>The information for each type has 3 sections:</p>
+ * <p>
+ * The information for each type has 3 sections:
+ * </p>
* <ol>
- * <li>_subtypes - a JSON map of key-value pairs, keyed by the short type-name of
- * used subtypes of this type. If this type has
- * no used subtypes, this element is omitted.
- * The value is an instance of this structure, for that type.</li>
- *
- * <li>_id - the fully qualified UIMA type name</li>
- *
- * <li>@featureTypes - a map with keys being specific features of the type
- * that need extra information about their contents,
- * and the value being that extra information.</li>
+ * <li>_subtypes - a JSON map of key-value pairs, keyed by the short type-name of used subtypes
+ * of this type. If this type has no used subtypes, this element is omitted. The value is an
+ * instance of this structure, for that type.</li>
+ *
+ * <li>_id - the fully qualified UIMA type name</li>
+ *
+ * <li>@featureTypes - a map with keys being specific features of the type that need extra
+ * information about their contents, and the value being that extra information.</li>
* </ol>
- *
- * RANGE_IDs specify the type of the value of a feature. There are currently 2 kinds:
- *
- * <ul>
- * <li>"@featureByteArray" - indicates the string value should be decoded as a base64 binary encoded byte array</li>
- * <li>"{ "@featureRef" : "short_type_name" } - indicates the number or array of numbers
- * should be interpreted as a reference to a FS having this number (or array of numbers)
- * as its id(s).
- * 0 is interpreted as a null reference.
- * The type of the FS being referred to is of type "short_type_name" or a subtype.</li>
- * </ul>
- * @throws IOException
+ *
+ * RANGE_IDs specify the type of the value of a feature. There are currently 2 kinds:
+ *
+ * <ul>
+ * <li>"@featureByteArray" - indicates the string value should be decoded as a base64 binary
+ * encoded byte array</li>
+ * <li>"{ "@featureRef" : "short_type_name" } - indicates the number or array of numbers should
+ * be interpreted as a reference to a FS having this number (or array of numbers) as its id(s).
+ * 0 is interpreted as a null reference. The type of the FS being referred to is of type
+ * "short_type_name" or a subtype.</li>
+ * </ul>
+ *
+ * @throws IOException
*/
-
- private void serializeJsonLdContext() throws IOException {
+
+ private void serializeJsonLdContext() throws IOException {
jg.writeFieldName(CONTEXT_NAME);
jg.writeStartObject();
-
+
if (typeSystemReference != null) {
jch.writeNlJustBeforeNext();
jg.writeFieldName(TYPE_SYSTEM_NAME);
jg.writeString(typeSystemReference);
}
-
+
collectUsedSubtypes();
-
+
jch.writeNlJustBeforeNext();
jg.writeFieldName(TYPES_NAME);
jg.writeStartObject();
-
+
for (TypeImpl ti : cds.getSortedUsedTypes()) {
- jch.writeNlJustBeforeNext();
+ jch.writeNlJustBeforeNext();
jg.writeFieldName(getSerializedTypeName(ti));
jg.writeStartObject();
if (isWithExpandedTypeNames) {
- jg.writeFieldName(ID_NAME); // form for using SerializedString
+ jg.writeFieldName(ID_NAME); // form for using SerializedString
jg.writeString(ti.getName());
}
addJsonFeatContext(ti);
if (isWithSubtypes) {
addJsonSubtypes(ti);
}
- jg.writeEndObject(); // end of one type
+ jg.writeEndObject(); // end of one type
}
-
+
// write out contexts for types in the supertype chain which have no instances
for (final TypeImpl ti : parentTypesWithNoInstances) {
- jch.writeNlJustBeforeNext();
+ jch.writeNlJustBeforeNext();
jg.writeFieldName(getSerializedTypeName(ti));
jg.writeStartObject();
XmlElementName xe = cds.typeCode2namespaceNames[ti.getCode()];
if (isWithExpandedTypeNames) {
- jg.writeFieldName(ID_NAME); // form for using SerializedString
+ jg.writeFieldName(ID_NAME); // form for using SerializedString
jg.writeString(xe.nsUri);
}
-
+
addJsonFeatContext(ti);
if (isWithSubtypes) {
addJsonSubtypes(ti);
}
- jg.writeEndObject(); // end of one type
-
+ jg.writeEndObject(); // end of one type
+
}
-
- jg.writeEndObject(); // end of _types
-
- jg.writeEndObject(); // end of _context
+
+ jg.writeEndObject(); // end of _types
+
+ jg.writeEndObject(); // end of _context
}
-
+
/**
* _feature_types : { "featName" : "_ref" or "_byte_array, ... }
*
- * @param type the type for which to generate the feature context info
- * @throws IOException
+ * @param type
+ * the type for which to generate the feature context info
+ * @throws IOException
*/
private void addJsonFeatContext(TypeImpl type) throws IOException {
final FeatureImpl[] feats = type.getFeatureImpls();
startedFeatureTypes = false;
-
+
for (FeatureImpl feat : feats) {
final int fsClass = CasSerializerSupport.classifyType(feat.getRangeImpl());
SerializedString featKind = featureTypeLabel(fsClass);
if (null != featKind) {
maybeDoStartFeatureTypes();
- jg.writeFieldName(getSerializedString(feat.getShortName()));
+ jg.writeFieldName(getSerializedString(feat.getShortName()));
jg.writeString(featKind);
- }
+ }
}
if (startedFeatureTypes) {
jg.writeEndObject();
- }
+ }
}
-
+
private void maybeDoStartFeatureTypes() throws IOException {
if (!startedFeatureTypes) {
jch.writeNlJustBeforeNext();
@@ -806,14 +895,15 @@ public class JsonCasSerializer {
startedFeatureTypes = true;
}
}
-
+
private SerializedString getShortFeatureName(FeatureImpl feat) {
return getSerializedString(feat.getShortName());
}
-
+
/**
* Add subtype information for used types limited to used subtypes
- * @throws IOException
+ *
+ * @throws IOException
*/
private void addJsonSubtypes(TypeImpl ti) throws IOException {
IntVector iv = mapType2Subtypes.get(ti.getCode());
@@ -821,7 +911,7 @@ public class JsonCasSerializer {
jch.writeNlJustBeforeNext();
jg.writeFieldName(SUB_TYPES_NAME);
jg.writeStartArray();
-
+
TypeSystemImpl tsi = ti.getTypeSystem();
for (int typeCode : iv.toArray()) {
jg.writeString(getSerializedTypeName(tsi.getTypeForCode(typeCode)));
@@ -829,24 +919,24 @@ public class JsonCasSerializer {
jg.writeEndArray();
}
}
-
+
private void collectUsedSubtypes() {
final TypeImpl[] tiArray = cds.getSortedUsedTypes();
-
- for (TypeImpl ti : tiArray) { // all used types
+
+ for (TypeImpl ti : tiArray) { // all used types
int subtypeCode = ti.getCode();
-
- // loop up the super chain for this type,
+
+ // loop up the super chain for this type,
// add parent -> subtype entries (until try to add one that's already there)
-
- for (TypeImpl parent = (TypeImpl) ti.getSuperType();
- parent != null;
- parent = (TypeImpl) parent.getSuperType()) {
+
+ for (TypeImpl parent = (TypeImpl) ti
+ .getSuperType(); parent != null; parent = (TypeImpl) parent.getSuperType()) {
final int parentCode = parent.getCode();
// next comparator must match the one used for sorting the tiArray
// https://issues.apache.org/jira/browse/UIMA-5171
- // if parent not contained in tiArray
- if (Arrays.binarySearch(tiArray, parent, CasSerializerSupport.COMPARATOR_SHORT_TYPENAME) < 0 ) {
+ // if parent not contained in tiArray
+ if (Arrays.binarySearch(tiArray, parent,
+ CasSerializerSupport.COMPARATOR_SHORT_TYPENAME) < 0) {
if (!parentTypesWithNoInstances.contains(parent)) {
parentTypesWithNoInstances.add(parent);
}
@@ -859,7 +949,7 @@ public class JsonCasSerializer {
}
}
}
-
+
private SerializedString getSerializedTypeName(TypeImpl ti) {
XmlElementName xe = cds.typeCode2namespaceNames[ti.getCode()];
if (null == xe) {
@@ -871,7 +961,7 @@ public class JsonCasSerializer {
}
return getSerializedString(xe.qName);
}
-
+
private SerializedString getSerializedString(String s) {
SerializedString ss = serializedStrings.get(s);
if (ss == null) {
@@ -881,35 +971,33 @@ public class JsonCasSerializer {
return ss;
}
-
/*
- * keep map from short type name to XmlElementName (full name, namespace, etc)
- * This map starts out empty
- * first use of type puts entry in
- * first use of type with different full name adds namespace to both
+ * keep map from short type name to XmlElementName (full name, namespace, etc) This map starts
+ * out empty first use of type puts entry in first use of type with different full name adds
+ * namespace to both
*/
@Override
protected void checkForNameCollision(XmlElementName xmlElementName) {
- XmlElementName xel = usedTypeName2XmlElementName.get(xmlElementName.localName);
+ XmlElementName xel = usedTypeName2XmlElementName.get(xmlElementName.localName);
if (xel != null) {
- if (xel.nsUri.equals(xmlElementName.nsUri)) { // nsUri is the fully qualified name
- return; // don't need name spaces yet, or have already added them for this item
+ if (xel.nsUri.equals(xmlElementName.nsUri)) { // nsUri is the fully qualified name
+ return; // don't need name spaces yet, or have already added them for this item
} else {
addNameSpace(xel);
addNameSpace(xmlElementName);
-// usedTypeName2XmlElementName.clear(); // not needed anymore
+ // usedTypeName2XmlElementName.clear(); // not needed anymore
return;
}
}
usedTypeName2XmlElementName.put(xmlElementName.localName, xmlElementName);
return;
}
-
+
@Override
protected boolean writeFsStart(TOP fs, int typeCode) throws IOException {
if (isEmbedded) {
if (!isEmbeddedFromFsFeature) {
- jch.writeNlJustBeforeNext(); // if from feature, already did nl
+ jch.writeNlJustBeforeNext(); // if from feature, already did nl
}
jg.writeStartObject();
} else if (indexId) {
@@ -921,7 +1009,7 @@ public class JsonCasSerializer {
}
jch.writeNlJustBeforeNext();
jg.writeFieldName(cds.getXmiId(fs));
- jg.writeStartObject(); // start of feat : value
+ jg.writeStartObject(); // start of feat : value
} else { // fs's as arrays under typeName
if (typeCode != lastEncodedTypeCode) {
if (lastEncodedTypeCode != -1) {
@@ -933,29 +1021,29 @@ public class JsonCasSerializer {
jg.writeFieldName(getSerializedTypeName(fs._getTypeImpl()));
jg.writeStartArray();
}
- // if we're not going to write the actual FS here,
- // and are just going to write the ref,
- // skip the start object
- if (!cds.isDynamicMultiRef || !cds.multiRefFSs.contains(fs)) {
+ // if we're not going to write the actual FS here,
+ // and are just going to write the ref,
+ // skip the start object
+ if (!cds.isDynamicMultiRef || !cds.multiRefFSs.contains(fs)) {
jch.writeNlJustBeforeNext();
- jg.writeStartObject(); // start of feat : value
+ jg.writeStartObject(); // start of feat : value
}
}
return indexId;
}
-
+
@Override
protected void writeFsRef(TOP fs) throws Exception {
- jg.writeNumber(cds.getXmiIdAsInt(fs));
- }
-
-// private void maybeWriteIdFeat(int addr) throws IOException {
-// if (!omitId) {
-// jg.writeFieldName(ID_NAME);
-// jg.writeNumber(cds.getXmiIdAsInt(addr));
-// }
-// }
-
+ jg.writeNumber(cds.getXmiIdAsInt(fs));
+ }
+
+ // private void maybeWriteIdFeat(int addr) throws IOException {
+ // if (!omitId) {
+ // jg.writeFieldName(ID_NAME);
+ // jg.writeNumber(cds.getXmiIdAsInt(addr));
+ // }
+ // }
+
private void maybeWriteTypeFeat(TypeImpl ti) throws IOException {
if (indexId || isEmbedded) {
jg.writeFieldName(TYPE_NAME);
@@ -967,18 +1055,18 @@ public class JsonCasSerializer {
protected void writeFs(TOP fs, int typeCode) throws IOException {
writeFsOrLists(fs, fs._getTypeImpl(), false);
}
-
+
@Override
protected void writeListsAsIndividualFSs(TOP fs, int typeCode) throws IOException {
writeFsOrLists(fs, fs._getTypeImpl(), true);
}
-
+
private void writeFsOrLists(TOP fs, TypeImpl ti, boolean isListAsFSs) throws IOException {
final FeatureImpl[] feats = ti.getFeatureImpls();
-
-// maybeWriteIdFeat(addr);
+
+ // maybeWriteIdFeat(addr);
maybeWriteTypeFeat(ti);
-
+
for (final FeatureImpl feat : feats) {
if (cds.isFiltering) {
@@ -988,87 +1076,108 @@ public class JsonCasSerializer {
continue;
}
}
-
-// final int featAddr = addr + cds.cas.getAdjustedFeatureOffset(featCode);
-// final int featValRaw = cds.cas.getHeapValue(featAddr);
+
+ // final int featAddr = addr + cds.cas.getAdjustedFeatureOffset(featCode);
+ // final int featValRaw = cds.cas.getHeapValue(featAddr);
final int featureClass = CasSerializerSupport.classifyType(feat.getRangeImpl());
final SerializedString shortName = getSerializedString(feat.getShortName());
-
+
switch (featureClass) {
-
- case LowLevelCAS.TYPE_CLASS_BYTE: writeNumeric(feat, fs._getByteValueNc (feat)); break;
- case LowLevelCAS.TYPE_CLASS_SHORT: writeNumeric(feat, fs._getShortValueNc(feat)); break;
- case LowLevelCAS.TYPE_CLASS_INT: writeNumeric(feat, fs._getIntValueNc (feat)); break;
- case LowLevelCAS.TYPE_CLASS_LONG: writeNumeric(feat, fs._getLongValueNc (feat)); break;
-
- case LowLevelCAS.TYPE_CLASS_FS: {
- TOP ref = fs._getFeatureValueNc(feat);
- if (ref == null /* && isOmitDefaultValues*/) continue;
- writeFsOrRef(ref, feat); // writes nl before embedded fs
- break;
- }
-
- case LowLevelCAS.TYPE_CLASS_FLOAT:
- final float floatVal = fs._getFloatValueNc(feat);
- if (floatVal == 0.F && isOmitDefaultValues) continue;
- jg.writeFieldName(shortName);
- jg.writeNumber(floatVal);
- break;
-
- case LowLevelCAS.TYPE_CLASS_DOUBLE:
- final double doubleVal = fs._getDoubleValueNc(feat);
- if (doubleVal == 0L && isOmitDefaultValues) continue;
- jg.writeFieldName(shortName);
- jg.writeNumber(doubleVal);
- break;
-
- case LowLevelCAS.TYPE_CLASS_BOOLEAN:
- jg.writeFieldName(shortName);
- jg.writeBoolean(fs._getBooleanValueNc(feat));
- break;
-
- case LowLevelCAS.TYPE_CLASS_STRING: {
- String s = fs._getStringValueNc(feat);
- if (s == null /*&& isOmitDefaultValues*/) continue;
- jg.writeFieldName(shortName);
- jg.writeString(s);
- break;
- }
-
- case LowLevelCAS.TYPE_CLASS_INTARRAY:
- case LowLevelCAS.TYPE_CLASS_FLOATARRAY:
- case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY:
- case LowLevelCAS.TYPE_CLASS_BYTEARRAY:
- case LowLevelCAS.TYPE_CLASS_SHORTARRAY:
- case LowLevelCAS.TYPE_CLASS_LONGARRAY:
- case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY:
- case LowLevelCAS.TYPE_CLASS_STRINGARRAY:
- case LowLevelCAS.TYPE_CLASS_FSARRAY:
- writeArray(fs, feat, featureClass);
- break;
-
- case CasSerializerSupport.TYPE_CLASS_INTLIST:
- case CasSerializerSupport.TYPE_CLASS_FLOATLIST:
- case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
- case CasSerializerSupport.TYPE_CLASS_FSLIST:
- writeList(fs, feat, featureClass, isListAsFSs);
- break;
- default: Misc.internalError();
- } // end of switch
+
+ case LowLevelCAS.TYPE_CLASS_BYTE:
+ writeNumeric(feat, fs._getByteValueNc(feat));
+ break;
+ case LowLevelCAS.TYPE_CLASS_SHORT:
+ writeNumeric(feat, fs._getShortValueNc(feat));
+ break;
+ case LowLevelCAS.TYPE_CLASS_INT:
+ writeNumeric(feat, fs._getIntValueNc(feat));
+ break;
+ case LowLevelCAS.TYPE_CLASS_LONG:
+ writeNumeric(feat, fs._getLongValueNc(feat));
+ break;
+
+ case LowLevelCAS.TYPE_CLASS_FS: {
+ TOP ref = fs._getFeatureValueNc(feat);
+ if (ref == null /* && isOmitDefaultValues */) {
+ continue;
+ }
+ writeFsOrRef(ref, feat); // writes nl before embedded fs
+ break;
+ }
+
+ case LowLevelCAS.TYPE_CLASS_FLOAT:
+ final float floatVal = fs._getFloatValueNc(feat);
+ if (floatVal == 0.F && isOmitDefaultValues) {
+ continue;
+ }
+ jg.writeFieldName(shortName);
+ jg.writeNumber(floatVal);
+ break;
+
+ case LowLevelCAS.TYPE_CLASS_DOUBLE:
+ final double doubleVal = fs._getDoubleValueNc(feat);
+ if (doubleVal == 0L && isOmitDefaultValues) {
+ continue;
+ }
+ jg.writeFieldName(shortName);
+ jg.writeNumber(doubleVal);
+ break;
+
+ case LowLevelCAS.TYPE_CLASS_BOOLEAN:
+ jg.writeFieldName(shortName);
+ jg.writeBoolean(fs._getBooleanValueNc(feat));
+ break;
+
+ case LowLevelCAS.TYPE_CLASS_STRING: {
+ String s = fs._getStringValueNc(feat);
+ if (s == null /* && isOmitDefaultValues */) {
+ continue;
+ }
+ jg.writeFieldName(shortName);
+ jg.writeString(s);
+ break;
+ }
+
+ case LowLevelCAS.TYPE_CLASS_INTARRAY:
+ case LowLevelCAS.TYPE_CLASS_FLOATARRAY:
+ case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY:
+ case LowLevelCAS.TYPE_CLASS_BYTEARRAY:
+ case LowLevelCAS.TYPE_CLASS_SHORTARRAY:
+ case LowLevelCAS.TYPE_CLASS_LONGARRAY:
+ case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY:
+ case LowLevelCAS.TYPE_CLASS_STRINGARRAY:
+ case LowLevelCAS.TYPE_CLASS_FSARRAY:
+ writeArray(fs, feat, featureClass);
+ break;
+
+ case CasSerializerSupport.TYPE_CLASS_INTLIST:
+ case CasSerializerSupport.TYPE_CLASS_FLOATLIST:
+ case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
+ case CasSerializerSupport.TYPE_CLASS_FSLIST:
+ writeList(fs, feat, featureClass, isListAsFSs);
+ break;
+ default:
+ Misc.internalError();
+ } // end of switch
} // end of loop over all features
}
-
+
private void writeNumeric(FeatureImpl fi, long v) throws IOException {
- if (v == 0 && isOmitDefaultValues) return;
+ if (v == 0 && isOmitDefaultValues) {
+ return;
+ }
jg.writeFieldName(getShortFeatureName(fi));
jg.writeNumber(v);
}
-
+
private void writeArray(TOP fs, FeatureImpl fi, int featureClass) throws IOException {
- assert(fs != null);
+ assert (fs != null);
TOP array = fs._getFeatureValueNc(fi);
- if (array == null) return;
-
+ if (array == null) {
+ return;
+ }
+
jg.writeFieldName(getShortFeatureName(fi));
if (isDynamicOrStaticMultiRef(fi, array)) {
jg.writeNumber(cds.getXmiIdAsInt(array));
@@ -1076,12 +1185,15 @@ public class JsonCasSerializer {
writeJsonArrayValues(array, featureClass);
}
}
-
- private void writeList(TOP fs, FeatureImpl fi, int featureClass, boolean isListAsFSs) throws IOException {
- assert(fs != null);
+
+ private void writeList(TOP fs, FeatureImpl fi, int featureClass, boolean isListAsFSs)
+ throws IOException {
+ assert (fs != null);
TOP list = fs._getFeatureValueNc(fi);
- if (list == null) return;
-
+ if (list == null) {
+ return;
+ }
+
jg.writeFieldName(getShortFeatureName(fi));
if (isDynamicOrStaticMultiRef(fi, list, isListAsFSs)) {
jg.writeNumber(cds.getXmiIdAsInt(list));
@@ -1089,7 +1201,8 @@ public class JsonCasSerializer {
writeJsonListValues(list);
}
}
-
+
+ // @formatter:off
/**
* for arrays and lists,
* recursively write one FS,
@@ -1100,6 +1213,7 @@ public class JsonCasSerializer {
* @param addr
* @throws IOException
*/
+ // @formatter:on
private void writeFsOrRef(TOP fs) throws IOException {
if (fs == null || !cds.isDynamicMultiRef || cds.multiRefFSs.contains(fs)) {
jg.writeNumber(cds.getXmiIdAsInt(fs));
@@ -1108,7 +1222,7 @@ public class JsonCasSerializer {
writeEmbeddedFs(fs);
}
}
-
+
private void writeEmbeddedFs(TOP fs) throws IOException {
boolean savedEmbedded = isEmbedded;
try {
@@ -1121,9 +1235,9 @@ public class JsonCasSerializer {
throw new RuntimeException(e);
} finally {
isEmbedded = savedEmbedded;
- } // embed
+ } // embed
}
-
+
private void writeFsOrRef(TOP fs, FeatureImpl fi) throws IOException {
if (fs == null || !cds.isDynamicMultiRef || cds.multiRefFSs.contains(fs)) {
jg.writeFieldName(getShortFeatureName(fi));
@@ -1132,27 +1246,27 @@ public class JsonCasSerializer {
jch.writeNlJustBeforeNext();
jg.writeFieldName(getShortFeatureName(fi));
isEmbeddedFromFsFeature = true;
- // Use cases: can write embed, which has embed, which has non-embed
- // once hit non-embed, this flag would be turned off,
- // But it's only tested at the beginning of writeEmbeddedFs, so subsequent fields reset this
- // This flag only used to control new lines for embedded case
+ // Use cases: can write embed, which has embed, which has non-embed
+ // once hit non-embed, this flag would be turned off,
+ // But it's only tested at the beginning of writeEmbeddedFs, so subsequent fields reset this
+ // This flag only used to control new lines for embedded case
writeEmbeddedFs(fs);
isEmbeddedFromFsFeature = false; // restore default
}
}
-
+
/**
* Write FSArrays
*/
@Override
protected void writeArrays(TOP fs, int typeCode, int typeClass) throws IOException {
-// maybeWriteIdFeat(addr);
+ // maybeWriteIdFeat(addr);
maybeWriteTypeFeat(fs._getTypeImpl());
- jg.writeFieldName(COLLECTION_NAME);
+ jg.writeFieldName(COLLECTION_NAME);
writeJsonArrayValues(fs, typeClass);
}
-
+
@Override
protected void writeEndOfIndividualFs() throws IOException {
jg.writeEndObject();
@@ -1161,116 +1275,119 @@ public class JsonCasSerializer {
// writes a set of values in a JSON array
// or null if the reference to the UIMA array is actually null
// 0 length arrays are written as []
- // Note: FSs can be embedded for FS Arrays
+ // Note: FSs can be embedded for FS Arrays
private void writeJsonArrayValues(TOP array, int arrayType) throws IOException {
if (array == null) {
jg.writeNull();
return;
}
-
+
cds.visited_not_yet_written.remove(array);
CommonArrayFS ca = (CommonArrayFS) array;
final int array_size = ca.size();
if (arrayType == LowLevelCAS.TYPE_CLASS_BYTEARRAY) {
- // special case for byte arrays:
+ // special case for byte arrays:
// serialize using standard JACKSON/JSON binary serialization
// (doing extra copy to avoid figuring out the impl details)
- ByteArray ba = (ByteArray) array;
+ ByteArray ba = (ByteArray) array;
jg.writeBinary(ba._getTheArray());
-
+
} else {
jg.writeStartArray();
-// int pos = cds.cas.getArrayStartAddress(addr);
-
- switch(arrayType) {
- case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY: {
- boolean[] a = ((BooleanArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeBoolean(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_BYTEARRAY: {
- ByteArray ba = (ByteArray) array;
- jg.writeBinary(ba._getTheArray());
- break;
- }
- case LowLevelCAS.TYPE_CLASS_SHORTARRAY: {
- short[] a = ((ShortArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_INTARRAY: {
- int[] a = ((IntegerArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_LONGARRAY: {
- long[] a = ((LongArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_FLOATARRAY: {
- float[] a = ((FloatArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY: {
- double[] a = ((DoubleArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_STRINGARRAY: {
- String[] a = ((StringArray)array)._getTheArray();
- writeArrayElements(array_size, i -> jg.writeString(a[i]));
- break;
- }
- case LowLevelCAS.TYPE_CLASS_FSARRAY: writeFSArray(array, array_size); break;
- default: Misc.internalError();
+ // int pos = cds.cas.getArrayStartAddress(addr);
+
+ switch (arrayType) {
+ case LowLevelCAS.TYPE_CLASS_BOOLEANARRAY: {
+ boolean[] a = ((BooleanArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeBoolean(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_BYTEARRAY: {
+ ByteArray ba = (ByteArray) array;
+ jg.writeBinary(ba._getTheArray());
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_SHORTARRAY: {
+ short[] a = ((ShortArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_INTARRAY: {
+ int[] a = ((IntegerArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_LONGARRAY: {
+ long[] a = ((LongArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_FLOATARRAY: {
+ float[] a = ((FloatArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY: {
+ double[] a = ((DoubleArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeNumber(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_STRINGARRAY: {
+ String[] a = ((StringArray) array)._getTheArray();
+ writeArrayElements(array_size, i -> jg.writeString(a[i]));
+ break;
+ }
+ case LowLevelCAS.TYPE_CLASS_FSARRAY:
+ writeFSArray(array, array_size);
+ break;
+ default:
+ Misc.internalError();
} // end of switch
-
+
jg.writeEndArray();
}
}
-
- private void writeArrayElements(final int size, IntConsumer_withIOException ic) throws IOException {
+
+ private void writeArrayElements(final int size, IntConsumer_withIOException ic)
+ throws IOException {
for (int i = 0; i < size; i++) {
ic.accept(i);
}
}
-
+
private void writeFSArray(TOP array, int array_size) throws NumberFormatException, IOException {
FSArray fsArray = (FSArray) array;
-
- List<XmiArrayElement> ootsArrayElementsList = cds.sharedData == null
- ? null
- : cds.sharedData.getOutOfTypeSystemArrayElements(fsArray);
+
+ List<XmiArrayElement> ootsArrayElementsList = cds.sharedData == null ? null
+ : cds.sharedData.getOutOfTypeSystemArrayElements(fsArray);
int ootsIndex = 0;
TOP[] fsItems = fsArray._getTheArray();
-
- for (int j = 0; j < array_size; j++) { // j used to id the oots things
- TOP fsItem = fsItems[j]; // int heapValue = cds.cas.getHeapValue(pos++);
+
+ for (int j = 0; j < array_size; j++) { // j used to id the oots things
+ TOP fsItem = fsItems[j]; // int heapValue = cds.cas.getHeapValue(pos++);
if (fsItem == null) {
- // this null array element might have been a reference to an
+ // this null array element might have been a reference to an
// out-of-typesystem FS, which, when deserialized, was replaced with NULL,
// so check the ootsArrayElementsList
boolean found = false;
if (ootsArrayElementsList != null) {
-
+
while (ootsIndex < ootsArrayElementsList.size()) {
XmiArrayElement arel = ootsArrayElementsList.get(ootsIndex++);
if (arel.index == j) {
jg.writeNumber(Integer.parseInt(arel.xmiId));
found = true;
break;
- }
+ }
}
}
if (!found) {
jg.writeNumber(0);
}
-
- // else, not null FS ref
+
+ // else, not null FS ref
} else {
if (cds.isFiltering) { // return as null any references to types not in target TS
String typeName = fsItem._getTypeImpl().getName();
@@ -1278,18 +1395,19 @@ public class JsonCasSerializer {
fsItem = null;
}
}
- writeFsOrRef(fsItem); // allow embedding in array
+ writeFsOrRef(fsItem); // allow embedding in array
}
} // end of loop over all refs in FS array
}
-
+
// a null ref is written as null
// an empty list is written as []
/**
- * Only called if no sharing of list nodes exists (except for non-dynamic case)
- * Only called for list nodes referred to by Feature value slots in some FS.
-
- * @param curNode the address of the start of the list
+ * Only called if no sharing of list nodes exists (except for non-dynamic case) Only called for
+ * list nodes referred to by Feature value slots in some FS.
+ *
+ * @param curNode
+ * the address of the start of the list
* @throws IOException
*/
private void writeJsonListValues(TOP curNode) throws IOException {
@@ -1298,36 +1416,38 @@ public class JsonCasSerializer {
}
final PositiveIntSet visited = new PositiveIntSet_impl();
-
+
jg.writeStartArray();
FeatureStructure nextNode = null;
- while (curNode != null) {
+ while (curNode != null) {
cds.visited_not_yet_written.remove(curNode);
- if (curNode instanceof EmptyList) {
- break; // would be the end element. a 0 is also treated as an end element
+ if (curNode instanceof EmptyList) {
+ break; // would be the end element. a 0 is also treated as an end element
}
-
+
if (!visited.add(curNode._id())) {
- break; // loop detected, stop. no error report here, would be reported earlier during enqueue
+ break; // loop detected, stop. no error report here, would be reported earlier during
+ // enqueue
}
-
-// final int val = cds.cas.getHeapValue(curNode + cds.cas.getAdjustedFeatureOffset(headFeat));
+
+ // final int val = cds.cas.getHeapValue(curNode +
+ // cds.cas.getAdjustedFeatureOffset(headFeat));
if (curNode instanceof NonEmptyStringList) {
- NonEmptyStringList l = (NonEmptyStringList)curNode;
+ NonEmptyStringList l = (NonEmptyStringList) curNode;
jg.writeString(l.getHead());
nextNode = l.getCommonTail();
} else if (curNode instanceof NonEmptyFloatList) {
- NonEmptyFloatList l = (NonEmptyFloatList)curNode;
+ NonEmptyFloatList l = (NonEmptyFloatList) curNode;
jg.writeNumber(l.getHead());
nextNode = l.getCommonTail();
} else if (curNode instanceof NonEmptyFSList) {
- NonEmptyFSList l = (NonEmptyFSList)curNode;
- writeFsOrRef(l); // maybe embed
+ NonEmptyFSList l = (NonEmptyFSList) curNode;
+ writeFsOrRef(l); // maybe embed
nextNode = l.getCommonTail();
- } else { // for ints
- NonEmptyIntegerList l = (NonEmptyIntegerList)curNode;
+ } else { // for ints
+ NonEmptyIntegerList l = (NonEmptyIntegerList) curNode;
jg.writeNumber(l.getHead());
nextNode = l.getCommonTail();
}
@@ -1335,23 +1455,25 @@ public class JsonCasSerializer {
}
jg.writeEndArray();
}
-
+
/**
* Return null or a string representing the type of the feature
- *
- *
- * @param fsClass the class of the feature
- * @param featCode the feature code
+ *
+ *
+ * @param fsClass
+ * the class of the feature
+ * @param featCode
+ * the feature code
* @return _ref, _array, _byte_array, or null
*/
-
+
private SerializedString featureTypeLabel(int fsClass) {
switch (fsClass) {
- case LowLevelCAS.TYPE_CLASS_FS:
- case LowLevelCAS.TYPE_CLASS_FSARRAY:
+ case LowLevelCAS.TYPE_CLASS_FS:
+ case LowLevelCAS.TYPE_CLASS_FSARRAY:
case CasSerializerSupport.TYPE_CLASS_FSLIST:
return FEATURE_REFS_NAME;
-
+
case LowLevelCAS.TYPE_CLASS_INTARRAY:
case LowLevelCAS.TYPE_CLASS_FLOATARRAY:
case LowLevelCAS.TYPE_CLASS_STRINGARRAY:
@@ -1361,20 +1483,18 @@ public class JsonCasSerializer {
case LowLevelCAS.TYPE_CLASS_DOUBLEARRAY:
case CasSerializerSupport.TYPE_CLASS_INTLIST:
case CasSerializerSupport.TYPE_CLASS_FLOATLIST:
- case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
+ case CasSerializerSupport.TYPE_CLASS_STRINGLIST:
// we have refs only if the feature has
// multipleReferencesAllowed = true
- return FEATURE_ARRAY_NAME;
+ return FEATURE_ARRAY_NAME;
case LowLevelCAS.TYPE_CLASS_BYTEARRAY:
return FEATURE_BYTE_ARRAY_NAME;
-
- default: // for primitives
+
+ default: // for primitives
return null;
}
}
-
-
/**
* Converts a UIMA-style dotted type name to the element name that should be used in the
@@ -1398,37 +1518,37 @@ public class JsonCasSerializer {
// convert short name to shared string, without interning, reduce GCs
shortName = cds.getUniqueString(shortName);
- return new XmlElementName(uimaTypeName, shortName, shortName); // use short name for qname until namespaces needed
+ return new XmlElementName(uimaTypeName, shortName, shortName); // use short name for qname
+ // until namespaces needed
}
-
+
/**
* Called to generate a new namespace prefix and add it to this element - due to a collision
+ *
* @param xmlElementName
*/
@Override
protected void addNameSpace(XmlElementName xmlElementName) {
- if (xmlElementName.qName.equals(xmlElementName.localName)) { // may have already had namespace added
+ if (xmlElementName.qName.equals(xmlElementName.localName)) { // may have already had namespace
+ // added
// split uima type name into namespace and short name
String uimaTypeName = xmlElementName.nsUri;
String shortName = xmlElementName.localName;
final int lastDotIndex = uimaTypeName.lastIndexOf('.');
-
+
// determine what namespace prefix to use
String prefix = cds.getNameSpacePrefix(uimaTypeName, uimaTypeName, lastDotIndex);
xmlElementName.qName = cds.getUniqueString(prefix + ':' + shortName);
}
}
-
+
private boolean isDynamicOrStaticMultiRef(FeatureImpl fi, TOP fs) {
- return (!cds.isDynamicMultiRef) ?
- cds.isStaticMultiRef(fi) :
- cds.multiRefFSs.contains(fs);
+ return (!cds.isDynamicMultiRef) ? cds.isStaticMultiRef(fi) : cds.multiRefFSs.contains(fs);
}
-
+
private boolean isDynamicOrStaticMultiRef(FeatureImpl fi, TOP fs, boolean isListAsFSs) {
- return (!cds.isDynamicMultiRef) ?
- (isListAsFSs || cds.isStaticMultiRef(fi)) :
- cds.multiRefFSs.contains(fs);
+ return (!cds.isDynamicMultiRef) ? (isListAsFSs || cds.isStaticMultiRef(fi))
+ : cds.multiRefFSs.contains(fs);
}
}
diff --git a/uimaj-json/src/main/java/org/apache/uima/json/JsonMetaDataSerializer.java b/uimaj-json/src/main/java/org/apache/uima/json/JsonMetaDataSerializer.java
index c210067..d1cc6ad 100644
--- a/uimaj-json/src/main/java/org/apache/uima/json/JsonMetaDataSerializer.java
+++ b/uimaj-json/src/main/java/org/apache/uima/json/JsonMetaDataSerializer.java
@@ -39,9 +39,13 @@ public class JsonMetaDataSerializer {
/**
* Serialize to a writer
- * @param object - the instance of an XMLizable to serialize
- * @param aWriter - where the output goes
- * @throws SAXException - wrapping an IOException, probably
+ *
+ * @param object
+ * - the instance of an XMLizable to serialize
+ * @param aWriter
+ * - where the output goes
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
public static void toJSON(XMLizable object, Writer aWriter) throws SAXException {
toJSON(object, aWriter, false);
@@ -49,33 +53,45 @@ public class JsonMetaDataSerializer {
/**
* Serialize to a writer
- * @param object - the instance of an XMLizable to serialize
- * @param aWriter - where the output goes
- * @param isFormattedOutput true for pretty printing
- * @throws SAXException - wrapping an IOException, probably
+ *
+ * @param object
+ * - the instance of an XMLizable to serialize
+ * @param aWriter
+ * - where the output goes
+ * @param isFormattedOutput
+ * true for pretty printing
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
- public static void toJSON(XMLizable object, Writer aWriter, boolean isFormattedOutput) throws SAXException {
+ public static void toJSON(XMLizable object, Writer aWriter, boolean isFormattedOutput)
+ throws SAXException {
JsonGenerator jg;
try {
jg = new JsonFactory().createGenerator(aWriter);
} catch (IOException e) {
throw new SAXException(e);
}
-
+
toJSON(object, jg, isFormattedOutput);
}
-
+
/**
* Serialize use a specific instance of a JsonGenerator which encapsulates where the output goes
- * @param object - the instance of an XMLizable to serialize
- * @param jg the generator to use
- * @param isFormattedOutput true for pretty printing
- * @throws SAXException - wrapping an IOException, probably
+ *
+ * @param object
+ * - the instance of an XMLizable to serialize
+ * @param jg
+ * the generator to use
+ * @param isFormattedOutput
+ * true for pretty printing
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
- public static void toJSON(XMLizable object, JsonGenerator jg, boolean isFormattedOutput) throws SAXException {
+ public static void toJSON(XMLizable object, JsonGenerator jg, boolean isFormattedOutput)
+ throws SAXException {
JsonContentHandlerJacksonWrapper jch;
SerialContext sc = MetaDataObject_impl.serialContext.get();
-
+
boolean setContext = false;
if (null == sc) {
jch = new JsonContentHandlerJacksonWrapper(jg, isFormattedOutput);
@@ -85,12 +101,12 @@ public class JsonMetaDataSerializer {
} else {
jch = (JsonContentHandlerJacksonWrapper) sc.ch;
}
-
+
try {
jch.withoutNl();
-
+
object.toXML(jch);
-
+
jg.flush();
} catch (IOException e) {
throw new SAXException(e);
@@ -103,10 +119,13 @@ public class JsonMetaDataSerializer {
/**
* Writes out this object's JSON representation.
- * @param object - the instance of an XMLizable to serialize
+ *
+ * @param object
+ * - the instance of an XMLizable to serialize
* @param aOutputStream
* an OutputStream to which the JSON will be written
- * @throws SAXException - wrapping an IOException, probably
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
public static void toJSON(XMLizable object, OutputStream aOutputStream) throws SAXException {
toJSON(object, aOutputStream, false);
@@ -114,13 +133,17 @@ public class JsonMetaDataSerializer {
/**
*
- * @param object - the instance of an XMLizable to serialize
+ * @param object
+ * - the instance of an XMLizable to serialize
* @param aOutputStream
* an OutputStream to which the JSON will be written
- * @param isFormattedOutput true for pretty printing
- * @throws SAXException - wrapping an IOException, probably
+ * @param isFormattedOutput
+ * true for pretty printing
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
- public static void toJSON(XMLizable object, OutputStream aOutputStream, boolean isFormattedOutput) throws SAXException {
+ public static void toJSON(XMLizable object, OutputStream aOutputStream, boolean isFormattedOutput)
+ throws SAXException {
try {
JsonGenerator jg = new JsonFactory().createGenerator(aOutputStream);
toJSON(object, jg, isFormattedOutput);
@@ -131,9 +154,12 @@ public class JsonMetaDataSerializer {
/**
*
- * @param object - the instance of an XMLizable to serialize
- * @param file where the output goes
- * @throws SAXException - wrapping an IOException, probably
+ * @param object
+ * - the instance of an XMLizable to serialize
+ * @param file
+ * where the output goes
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
public static void toJSON(XMLizable object, File file) throws SAXException {
toJSON(object, file, false);
@@ -141,12 +167,17 @@ public class JsonMetaDataSerializer {
/**
*
- * @param object - the instance of an XMLizable to serialize
- * @param file where the output goes
- * @param isFormattedOutput true for pretty printing
- * @throws SAXException - wrapping an IOException, probably
+ * @param object
+ * - the instance of an XMLizable to serialize
+ * @param file
+ * where the output goes
+ * @param isFormattedOutput
+ * true for pretty printing
+ * @throws SAXException
+ * - wrapping an IOException, probably
*/
- public static void toJSON(XMLizable object, File file, boolean isFormattedOutput) throws SAXException {
+ public static void toJSON(XMLizable object, File file, boolean isFormattedOutput)
+ throws SAXException {
try {
JsonGenerator jg = new JsonFactory().createGenerator(file, JsonEncoding.UTF8);
toJSON(object, jg, isFormattedOutput);
diff --git a/uimaj-json/src/main/java/org/apache/uima/json/impl/JsonContentHandlerJacksonWrapper.java b/uimaj-json/src/main/java/org/apache/uima/json/impl/JsonContentHandlerJacksonWrapper.java
index 4043381..5511ccf 100644
--- a/uimaj-json/src/main/java/org/apache/uima/json/impl/JsonContentHandlerJacksonWrapper.java
+++ b/uimaj-json/src/main/java/org/apache/uima/json/impl/JsonContentHandlerJacksonWrapper.java
@@ -41,6 +41,7 @@ import com.fasterxml.jackson.core.util.DefaultIndenter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
import com.fasterxml.jackson.core.util.DefaultPrettyPrinter.FixedSpaceIndenter;
+// @formatter:off
/**
* Utility class that generates JSON output for UIMA descriptors and CASs
*
@@ -64,124 +65,151 @@ import com.fasterxml.jackson.core.util.DefaultPrettyPrinter.FixedSpaceIndenter;
*
* This class lets the underlying Jackson PrettyPrinter classes track the indent level.
* PrettyPrinting is implemented via customization of the Jackson PrettyPrinting classes
- *
*/
-public class JsonContentHandlerJacksonWrapper implements ContentHandler {
+// @formatter:on
+public class JsonContentHandlerJacksonWrapper implements ContentHandler {
private final static char[] BLANKS = new char[80];
static {
- Arrays.fill(BLANKS, ' ');
+ Arrays.fill(BLANKS, ' ');
}
-
+
public final static String SYSTEM_LINE_FEED;
static {
- String lf = System.getProperty("line.separator");
- SYSTEM_LINE_FEED = (lf == null) ? "\n" : lf;
+ String lf = System.getProperty("line.separator");
+ SYSTEM_LINE_FEED = (lf == null) ? "\n" : lf;
}
-
+
// this value is kept here, rather than in the caller, because some callers (e.g. MetaDataObject)
- // have many instances (each element could be an instance).
- private final boolean isFormattedOutput; // set true if pretty printing
-
+ // have many instances (each element could be an instance).
+ private final boolean isFormattedOutput; // set true if pretty printing
+
public boolean isFormattedOutput() {
return isFormattedOutput;
}
- private final JsonGenerator jg; // the underlying Jackson Generator
+ private final JsonGenerator jg; // the underlying Jackson Generator
+
public JsonGenerator getJsonGenerator() {
return jg;
}
-
+
private static JsonGenerator createGenerator(JsonFactory f, Object o) throws SAXException {
try {
if (o instanceof Writer) {
- return f.createGenerator((Writer)o);
+ return f.createGenerator((Writer) o);
}
if (o instanceof OutputStream) {
- return f.createGenerator((OutputStream)o);
+ return f.createGenerator((OutputStream) o);
}
if (o instanceof File) {
- return f.createGenerator((File)o, JsonEncoding.UTF8);
+ return f.createGenerator((File) o, JsonEncoding.UTF8);
}
- throw new RuntimeException(new OperationNotSupportedException(String.format("Object must be a Writer, OutputStream, or File, but was of class %s",
- o.getClass().getName())));
+ throw new RuntimeException(new OperationNotSupportedException(
+ String.format("Object must be a Writer, OutputStream, or File, but was of class %s",
+ o.getClass().getName())));
} catch (IOException e) {
throw new SAXException(e);
}
}
- private boolean doNl; // a flag set by users, that does a newline at the next "significant" output
- private final UimaJsonPrettyPrinter uimaPrettyPrinter; // set to null or an instance of the prettyprinter
+ private boolean doNl; // a flag set by users, that does a newline at the next "significant" output
+ private final UimaJsonPrettyPrinter uimaPrettyPrinter; // set to null or an instance of the
+ // prettyprinter
+ // @formatter:off
/*
* Constructors
* Variants:
* JsonFactory - a new one created, or one supplied
* isFormattedOutput - a pretty print flag, default false
*/
-
+ // @formatter:on
/**
* Makes a Json content handler that sends its output to the specified destination
- * @param destination - can be a File, an OutputStream, or a Writer
- * @throws SAXException wrapping an IOException
+ *
+ * @param destination
+ * - can be a File, an OutputStream, or a Writer
+ * @throws SAXException
+ * wrapping an IOException
*/
public JsonContentHandlerJacksonWrapper(Object destination) throws SAXException {
this(new JsonFactory(), destination);
}
-
+
/**
- * Makes a Json content handler, using a specified JsonFactory instance that can
- * be configured according to the Jackson implementation.
- * The resulting content handler will send its output to the specified destination
- * @param jsonFactory -
- * @param o - where the output goes
- * @throws SAXException wrapping an IOException
+ * Makes a Json content handler, using a specified JsonFactory instance that can be configured
+ * according to the Jackson implementation. The resulting content handler will send its output to
+ * the specified destination
+ *
+ * @param jsonFactory
+ * -
+ * @param o
+ * - where the output goes
+ * @throws SAXException
+ * wrapping an IOException
*/
public JsonContentHandlerJacksonWrapper(JsonFactory jsonFactory, Object o) throws SAXException {
this(createGenerator(jsonFactory, o));
}
/**
- * Makes a Json content handler, and
- * specifies a prettyprinting boolean flag (default is no prettyprinting).
- * The resulting content handler will send its output to the specified destination
- * @param o - where the output goes
- * @param isFormattedOutput -
- * @throws SAXException wrapping an IOException
+ * Makes a Json content handler, and specifies a prettyprinting boolean flag (default is no
+ * prettyprinting). The resulting content handler will send its output to the specified
+ * destination
+ *
+ * @param o
+ * - where the output goes
+ * @param isFormattedOutput
+ * -
+ * @throws SAXException
+ * wrapping an IOException
*/
public JsonContentHandlerJacksonWrapper(Object o, boolean isFormattedOutput) throws SAXException {
this(new JsonFactory(), o, isFormattedOutput);
}
-
+
/**
- * Makes a Json content handler, using a specified JsonFactory instance that can
- * be configured according to the Jackson implementation, and
- * specifies a prettyprinting boolean flag (default is no prettyprinting).
- * The resulting content handler will send its output to the specified destination
- * @param jsonFactory -
- * @param o where the output goes
- * @param isFormattedOutput - true for pretty printing
- * @throws SAXException wrapping an IOException
+ * Makes a Json content handler, using a specified JsonFactory instance that can be configured
+ * according to the Jackson implementation, and specifies a prettyprinting boolean flag (default
+ * is no prettyprinting). The resulting content handler will send its output to the specified
+ * destination
+ *
+ * @param jsonFactory
+ * -
+ * @param o
+ * where the output goes
+ * @param isFormattedOutput
+ * - true for pretty printing
+ * @throws SAXException
+ * wrapping an IOException
*/
- public JsonContentHandlerJacksonWrapper(JsonFactory jsonFactory, Object o, boolean isFormattedOutput) throws SAXException {
- this(
- createGenerator((null == jsonFactory) ? new JsonFactory() : jsonFactory, o),
- isFormattedOutput);
+ public JsonContentHandlerJacksonWrapper(JsonFactory jsonFactory, Object o,
+ boolean isFormattedOutput) throws SAXException {
+ this(createGenerator((null == jsonFactory) ? new JsonFactory() : jsonFactory, o),
+ isFormattedOutput);
}
-
- /* C o m m o n */
+
+ /* C o m m o n */
/**
* Makes a Json content handler, using a specified JsonGenerator instance
- * @param jsonGenerator -
- */
- public JsonContentHandlerJacksonWrapper(JsonGenerator jsonGenerator) {this(jsonGenerator, false);}
+ *
+ * @param jsonGenerator
+ * -
+ */
+ public JsonContentHandlerJacksonWrapper(JsonGenerator jsonGenerator) {
+ this(jsonGenerator, false);
+ }
/**
* Makes a Json content handler, using a specified JsonGenerator instance
- * @param jsonGenerator -
- * @param isFormattedOutput - set to true for prettyprinting, default is false
- */
- public JsonContentHandlerJacksonWrapper(JsonGenerator jsonGenerator, boolean isFormattedOutput) {
+ *
+ * @param jsonGenerator
+ * -
+ * @param isFormattedOutput
+ * - set to true for prettyprinting, default is false
+ */
+ public JsonContentHandlerJacksonWrapper(JsonGenerator jsonGenerator, boolean isFormattedOutput) {
this.jg = jsonGenerator;
this.isFormattedOutput = isFormattedOutput;
if (isFormattedOutput) {
@@ -194,33 +222,37 @@ public class JsonContentHandlerJacksonWrapper implements ContentHandler {
}
/**
- * Call this to indicate that the prettyprinter should write a new line just before the next significant output.
- * It won't do this before a "comma", and some other punctuation.
- * Has no effect if no prettyprinting is being done.
+ * Call this to indicate that the prettyprinter should write a new line just before the next
+ * significant output. It won't do this before a "comma", and some other punctuation. Has no
+ * effect if no prettyprinting is being done.
*/
public void writeNlJustBeforeNext() {
doNl = true;
}
-
+
/* prettyPrinting */
-
+
private class UimaJsonPrettyPrinter extends DefaultPrettyPrinter implements PrettyPrinter {
private static final long serialVersionUID = 1L;
-
+
/*
- * add a new line after separators, and before array or object entries
- * (non-Javadoc)
- * @see com.fasterxml.jackson.core.util.DefaultPrettyPrinter#writeObjectEntrySeparator(com.fasterxml.jackson.core.JsonGenerator)
+ * add a new line after separators, and before array or object entries (non-Javadoc)
+ *
+ * @see
+ * com.fasterxml.jackson.core.util.DefaultPrettyPrinter#writeObjectEntrySeparator(com.fasterxml.
+ * jackson.core.JsonGenerator)
*/
@Override
- public void writeObjectEntrySeparator(JsonGenerator jg) throws IOException, JsonGenerationException {
+ public void writeObjectEntrySeparator(JsonGenerator jg)
+ throws IOException, JsonGenerationException {
super.writeObjectEntrySeparator(jg);
- maybeOutputNlOrBlank(jg);
+ maybeOutputNlOrBlank(jg);
}
@Override
- public void writeArrayValueSeparator(JsonGenerator jg) throws IOException, JsonGenerationException {
+ public void writeArrayValueSeparator(JsonGenerator jg)
+ throws IOException, JsonGenerationException {
super.writeArrayValueSeparator(jg);
maybeOutputNlOrBlank(jg);
}
@@ -234,30 +266,32 @@ public class JsonContentHandlerJacksonWrapper implements ContentHandler {
public void beforeObjectEntries(JsonGenerator jg) throws IOException, JsonGenerationException {
maybeOutputNl(jg);
}
-
+
private void maybeOutputNl(JsonGenerator jg) throws IOException {
if (doNl) {
maybeOutputNlIndent();
doNl = false;
- }
+ }
}
-
+
private void maybeOutputNlOrBlank(JsonGenerator jg) throws IOException {
if (doNl) {
- maybeOutputNl(jg); // resets doNl
+ maybeOutputNl(jg); // resets doNl
} else {
jg.writeRaw(' ');
}
}
-
- private void maybeOutputNlIndent () throws IOException {
+
+ private void maybeOutputNlIndent() throws IOException {
if (isFormattedOutput) {
jg.writeRaw(SYSTEM_LINE_FEED);
- jg.writeRaw(BLANKS, 0, Math.min(BLANKS.length, _nesting << 1)); // nesting * 2 for spaces per level
+ jg.writeRaw(BLANKS, 0, Math.min(BLANKS.length, _nesting << 1)); // nesting * 2 for spaces
+ // per level
}
- }
+ }
}
-
+
+ // @formatter:off
/**
* Assumes a Json object has been started, and adds property fields to it
* This method allows reusing common code in the caller.
@@ -267,9 +301,10 @@ public class JsonContentHandlerJacksonWrapper implements ContentHandler {
* other (which are assumed to not need surrounding quotes
* @param atts
*/
+ // @formatter:on
private void outputAttrsAsProperties(Attributes atts) {
if (null != atts) {
- try {
+ try {
for (int i = 0; i < atts.getLength(); i++) {
String val = atts.getValue(i);
if (val != null && (!val.equals(""))) {
@@ -277,58 +312,86 @@ public class JsonContentHandlerJacksonWrapper implements ContentHandler {
final String attType = atts.getType(i);
if ("array".equals(atts.getType(i))) {
jg.writeArrayFieldStart(prefix);
- jg.writeRawValue(val); // assumes the caller has formatted the array values properly
- // caller
+ jg.writeRawValue(val); // assumes the caller has formatted the array values properly
+ // caller
jg.writeEndArray();
continue;
}
-
+
if ("string".equals(attType)) {
jg.writeStringField(prefix, val);
continue;
- }
-
+ }
+
if ("boolean".equals(attType)) {
jg.writeBooleanField(prefix, val.equals("true"));
continue;
- }
-
+ }
+
jg.writeFieldName(prefix);
- jg.writeRawValue(val);
+ jg.writeRawValue(val);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
- }
+ }
}
-
+ // @formatter:off
/* *****************************
* mostly unused methods to make this
* a ContentHandler
*******************************/
- private void unsupported() { throw new UnsupportedOperationException();}
+ // @formatter:on
+ private void unsupported() {
+ throw new UnsupportedOperationException();
+ }
+
@Override
- public void characters(char[] ch, int start, int length) throws SAXException {unsupported();}
+ public void characters(char[] ch, int start, int length) throws SAXException {
+ unsupported();
+ }
+
@Override
- public void endDocument() throws SAXException {}
+ public void endDocument() throws SAXException {
+ }
+
@Override
- public void endPrefixMapping(String prefix) throws SAXException {}
+ public void endPrefixMapping(String prefix) throws SAXException {
+ }
+
@Override
- public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {unsupported();}
+ public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
+ unsupported();
+ }
+
@Override
- public void processingInstruction(String target, String data) throws SAXException {unsupported();}
+ public void processingInstruction(String target, String data) throws SAXException {
+ unsupported();
+ }
+
@Override
- public void setDocumentLocator(Locator locator) {unsupported();}
+ public void setDocumentLocator(Locator locator) {
+ unsupported();
+ }
+
@Override
- public void skippedEntity(String name) throws SAXException {unsupported();}
+ public void skippedEntity(String name) throws SAXException {
+ unsupported();
+ }
+
@Override
- public void startDocument() throws SAXException {}
+ public void startDocument() throws SAXException {
+ }
+
@Override
- public void startPrefixMapping(String prefix, String uri) throws SAXException {}
+ public void startPrefixMapping(String prefix, String uri) throws SAXException {
+ }
+
@Override
- public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
+ public void startElement(String uri, String localName, String qName, Attributes atts)
+ throws SAXException {
try {
if (qName != null) {
jg.writeStartObject();
@@ -340,45 +403,45 @@ public class JsonContentHandlerJacksonWrapper implements ContentHandler {
throw new SAXException(e);
}
}
-
+
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
try {
- if (null != qName) {
+ if (null != qName) {
+ jg.writeEndObject();
+ }
jg.writeEndObject();
- }
- jg.writeEndObject();
} catch (IOException e) {
throw new SAXException(e);
}
}
-
public void withoutNl() {
if (isFormattedOutput) {
uimaPrettyPrinter.indentObjectsWith(FSIWN);
uimaPrettyPrinter.indentArraysWith(FSIWN);
}
}
-
+
public void withNl() {
if (isFormattedOutput) {
// upgrade from Lf2SpacesIndenter - removed in v 2.7
-
+
uimaPrettyPrinter.indentObjectsWith(
-// DefaultPrettyPrinter.Lf2SpacesIndenter.instance
- DefaultIndenter.SYSTEM_LINEFEED_INSTANCE
- );
+ // DefaultPrettyPrinter.Lf2SpacesIndenter.instance
+ DefaultIndenter.SYSTEM_LINEFEED_INSTANCE);
}
}
-
+
private static class FixedSpaceIndenterWithNesting extends FixedSpaceIndenter {
private static final long serialVersionUID = 1L;
@Override
- public boolean isInline() { return false; }
+ public boolean isInline() {
+ return false;
+ }
}
-
+
private static final FixedSpaceIndenterWithNesting FSIWN = new FixedSpaceIndenterWithNesting();
}
diff --git a/uimaj-json/src/main/java/org/apache/uima/json/impl/MetaDataObjectSerializer_json.java b/uimaj-json/src/main/java/org/apache/uima/json/impl/MetaDataObjectSerializer_json.java
index 9438aee..7f8af9d 100644
--- a/uimaj-json/src/main/java/org/apache/uima/json/impl/MetaDataObjectSerializer_json.java
+++ b/uimaj-json/src/main/java/org/apache/uima/json/impl/MetaDataObjectSerializer_json.java
@@ -33,8 +33,8 @@ import org.xml.sax.SAXException;
import com.fasterxml.jackson.core.JsonGenerator;
-public class MetaDataObjectSerializer_json implements MetaDataObject_impl.Serializer {
-
+public class MetaDataObjectSerializer_json implements MetaDataObject_impl.Serializer {
+
final private JsonContentHandlerJacksonWrapper jch;
final private JsonGenerator jg;
final private boolean isFormattedOutput;
@@ -44,95 +44,104 @@ public class MetaDataObjectSerializer_json implements MetaDataObject_impl.Serial
jg = jch.getJsonGenerator();
isFormattedOutput = jch.isFormattedOutput();
}
-
+
@Override
- public void outputStartElement(Node node, String nameSpace, String localName, String qName, Attributes attributes) throws SAXException {
- jch.startElement(null, null, qName, attributes);
+ public void outputStartElement(Node node, String nameSpace, String localName, String qName,
+ Attributes attributes) throws SAXException {
+ jch.startElement(null, null, qName, attributes);
}
-
+
@Override
- public void outputEndElement(Node node, String aNamespace, String localname, String qname) throws SAXException {
+ public void outputEndElement(Node node, String aNamespace, String localname, String qname)
+ throws SAXException {
jch.endElement(null, localname, qname);
}
-
@Override
- public void outputStartElementForArrayElement(Node node, String nameSpace, String localName, String qName, Attributes attributes) throws SAXException {}
-
+ public void outputStartElementForArrayElement(Node node, String nameSpace, String localName,
+ String qName, Attributes attributes) throws SAXException {
+ }
+
@Override
- public void outputEndElementForArrayElement(Node node, String aNamespace, String localname, String qname) throws SAXException {}
+ public void outputEndElementForArrayElement(Node node, String aNamespace, String localname,
+ String qname) throws SAXException {
+ }
@Override
- public void saveAndAddNodeStore(Node infoset) {}
+ public void saveAndAddNodeStore(Node infoset) {
+ }
@Override
- public void deleteNodeStore() {}
-
+ public void deleteNodeStore() {
+ }
+
@Override
public boolean indentChildElements(XmlizationInfo info, MetaDataObject_impl mdo) {
return isFormattedOutput && hasXMLizableChild(info.propertyInfo, mdo);
}
-
+
@Override
public void insertNl() {
jch.writeNlJustBeforeNext();
}
-
+
@Override
public boolean shouldBeSkipped(PropertyXmlInfo propInfo, Object val, MetaDataObject_impl mdo) {
- return mdo.valueIsNullOrEmptyArray(val);
+ return mdo.valueIsNullOrEmptyArray(val);
}
-
+
@Override
public boolean startElementProperty() {
- return false; // the start is done later for JSON in case omitted.
+ return false; // the start is done later for JSON in case omitted.
}
-
+
@Override
- public void addNodeStore() {};
-
+ public void addNodeStore() {
+ };
+
@Override
public void writeDelayedStart(String name) throws SAXException {
jgWriteFieldName(name);
}
-
+
@Override
public void writeSimpleValue(Object val) throws SAXException {
writePrimitiveJsonValue(val, jg);
}
-
+
@Override
public boolean shouldEncloseInArrayElement(Class propClass) {
- return false;
+ return false;
}
-
+
@Override
public boolean isArrayHasIndentableElements(Object array) {
Object firstElement = Array.get(array, 0);
- return !(firstElement instanceof AllowedValue) && (firstElement instanceof XMLizable);
+ return !(firstElement instanceof AllowedValue) && (firstElement instanceof XMLizable);
}
-
+
@Override
public void maybeStartArraySymbol() throws SAXException {
jgWriteStartArray();
}
-
+
@Override
public void maybeEndArraySymbol() throws SAXException {
jgWriteEndArray();
}
-
+
@Override
/*
- * (non-Javadoc)
- * write {"type" : "value}
+ * (non-Javadoc) write {"type" : "value}
*
- * @see org.apache.uima.resource.metadata.impl.MetaDataObject_impl.Serializer#writeSimpleValueWithTag(java.lang.String, java.lang.Object, org.w3c.dom.Node)
+ * @see
+ * org.apache.uima.resource.metadata.impl.MetaDataObject_impl.Serializer#writeSimpleValueWithTag(
+ * java.lang.String, java.lang.Object, org.w3c.dom.Node)
*/
public void writeSimpleValueWithTag(String className, Object o, Node node) throws SAXException {
jgWriteStartObject();
- jgWriteFieldName(className);
- String valStr = (String)o;
+ jgWriteFieldName(className);
+ String valStr = (String) o;
jgWriteString(valStr);
jgWriteEndObject();
}
@@ -141,63 +150,89 @@ public class MetaDataObjectSerializer_json implements MetaDataObject_impl.Serial
for (PropertyXmlInfo pi : ia) {
Object val = mdo.getAttributeValue(pi.propertyName);
if (val != null && val instanceof XMLizable) {
- return true;
+ return true;
}
}
return false;
}
-
+
private void jgWriteFieldName(String name) throws SAXException {
- try {jg.writeFieldName(name);} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeFieldName(name);
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
private void jgWriteStartArray() throws SAXException {
- try {jg.writeStartArray();} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeStartArray();
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
private void jgWriteEndArray() throws SAXException {
- try {jg.writeEndArray();} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeEndArray();
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
private void jgWriteString(String s) throws SAXException {
- try {jg.writeString(s);} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeString(s);
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
-
+
private void jgWriteStartObject() throws SAXException {
- try {jg.writeStartObject();} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeStartObject();
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
private void jgWriteEndObject() throws SAXException {
- try {jg.writeEndObject();} catch (IOException e) {throw new SAXException(e);}
+ try {
+ jg.writeEndObject();
+ } catch (IOException e) {
+ throw new SAXException(e);
+ }
}
-
private static void writePrimitiveJsonValue(Object val, JsonGenerator jg) throws SAXException {
try {
- if (val instanceof Boolean)
- jg.writeBoolean((Boolean) val);
- else if (val instanceof Integer)
- jg.writeNumber((Integer) val);
- else if (val instanceof Long)
- jg.writeNumber((Long) val);
- else if (val instanceof Short)
- jg.writeNumber((Short) val);
- else if (val instanceof Byte)
- jg.writeNumber((Byte) val);
- else if (val instanceof Float)
- jg.writeNumber((Float) val);
- else if (val instanceof Double)
- jg.writeNumber((Double) val);
- else if (val instanceof String)
- jg.writeString((String) val);
- else
- throw new RuntimeException("unhandled value type");
+ if (val instanceof Boolean) {
+ jg.writeBoolean((Boolean) val);
+ } else if (val instanceof Integer) {
+ jg.writeNumber((Integer) val);
+ } else if (val instanceof Long) {
+ jg.writeNumber((Long) val);
+ } else if (val instanceof Short) {
+ jg.writeNumber((Short) val);
+ } else if (val instanceof Byte) {
+ jg.writeNumber((Byte) val);
+ } else if (val instanceof Float) {
+ jg.writeNumber((Float) val);
+ } else if (val instanceof Double) {
+ jg.writeNumber((Double) val);
+ } else if (val instanceof String) {
+ jg.writeString((String) val);
+ } else {
+ throw new RuntimeException("unhandled value type");
+ }
} catch (IOException e) {
throw new SAXException(e);
}
}
@Override
- public Node findMatchingSubElement(String elementName) {return null;}
+ public Node findMatchingSubElement(String elementName) {
+ return null;
+ }
}
diff --git a/uimaj-json/src/test/java/org/apache/uima/json/JsonCasSerializerTest.java b/uimaj-json/src/test/java/org/apache/uima/json/JsonCasSerializerTest.java
index dee678f..f22892c 100644
--- a/uimaj-json/src/test/java/org/apache/uima/json/JsonCasSerializerTest.java
+++ b/uimaj-json/src/test/java/org/apache/uima/json/JsonCasSerializerTest.java
@@ -63,6 +63,7 @@ import org.junit.jupiter.api.Test;
import org.xml.sax.SAXException;
public class JsonCasSerializerTest {
+ // @formatter:off
/*********************************************************************
* I N S T R U C T I O N S *
* for regenerating the expected: *
@@ -79,12 +80,11 @@ public class JsonCasSerializerTest {
* Testing for proper format: *
* can use http://www.jsoneditoronline.org/ *
*********************************************************************/
-
+ // @formatter:on
private static final boolean GENERATE_EXPECTED = false;
-// private static final String generateDir = "src/test/resources/CasSerialization/expected/";
+ // private static final String generateDir = "src/test/resources/CasSerialization/expected/";
private static final String generateDir = "src/test/resources/CasSerialization/newExpected/";
-
private XMLParser parser = UIMAFramework.getXMLParser();
private TypeSystemDescription tsd;
private CASImpl cas;
@@ -97,18 +97,19 @@ public class JsonCasSerializerTest {
private TypeImpl tokenType;
private TypeImpl emptyIntListType;
protected boolean doJson;
- private FeatureStructure fsa1; // elements of FS Array
- private FeatureStructure fsa2; // or just extra FS; these are not initially indexed
+ private FeatureStructure fsa1; // elements of FS Array
+ private FeatureStructure fsa2; // or just extra FS; these are not initially indexed
private FeatureStructure fsa3;
- private FSArray fsaa; // a feature structure array
-
- @BeforeEach
- public void setUp() throws Exception {
+ private FSArray fsaa; // a feature structure array
+
+ @BeforeEach
+ public void setUp() throws Exception {
jcs = new JsonCasSerializer();
jcs.setOmit0Values(true);
doJson = true;
}
+ // @formatter:off
/**
* Use "all types" -
* instances of:
@@ -145,50 +146,47 @@ public class JsonCasSerializerTest {
*
* File, Writer, OutputStream
*/
+ // @formatter:on
+
+ @Test
+ public void testBasic() throws Exception {
- @Test
- public void testBasic() throws Exception {
-
// test omits: context, subtypes, and expanded names
- // also test including / excluding type-name-reference
-
+ // also test including / excluding type-name-reference
+
setupTypeSystem("nameSpaceNeeded.xml");
- serializeAndCompare("emptyCAS.txt"); // empty cas
-
+ serializeAndCompare("emptyCAS.txt"); // empty cas
+
cas.addFsToIndexes(cas.createFS(topType));
cas.addFsToIndexes(cas.createFS(tokenType));
serializeAndCompare("topAndTokenOnly.txt");
-
// same thing, omitting context
jcs.setJsonContext(JsonContextFormat.omitContext);
serializeAndCompare("topAndTokenOnlyNoContext.txt");
-
+
jcs = new JsonCasSerializer();
jcs.setJsonContext(JsonContextFormat.omitExpandedTypeNames).setOmit0Values(true);
serializeAndCompare("topAndTokenOnlyNoExpandedTypeNames.txt");
-
+
jcs = new JsonCasSerializer();
jcs.setJsonContext(JsonContextFormat.omitSubtypes).setOmit0Values(true);
serializeAndCompare("topAndTokenOnlyNoSubtypes.txt");
-
-
-
-
+
cas = (CASImpl) cas.createView("basicView");
cas.addFsToIndexes(cas.createFS(annotationType));
serializeAndCompare("topWithNamedViewOmits.txt");
cas.reset();
-
+
cas = (CASImpl) cas.getCurrentView(); // default view
cas.addFsToIndexes(cas.createFS(annotationType));
serializeAndCompare("topWithDefaultViewOmits.txt");
-
+
cas.reset();
jcs.setJsonContext(JsonContextFormat.omitContext);
cas.addFsToIndexes(cas.createFS(topType));
serializeAndCompare("topNoContext.txt");
-
+
cas.reset();
jcs = new JsonCasSerializer().setOmit0Values(true);
jcs.setTypeSystemReference("A URI to TypeSystem");
@@ -201,24 +199,24 @@ public class JsonCasSerializerTest {
serializeAndCompare("topNoExpandedTypeNames.txt");
}
-
- @Test
- public void testNameSpaceCollision() throws Exception {
+
+ @Test
+ public void testNameSpaceCollision() throws Exception {
setupTypeSystem("nameSpaceNeeded.xml");
Type t1 = tsi.getType("org.apache.uima.test.Token");
Type t2 = tsi.getType("org.apache.uimax.test.Token");
Type t3 = tsi.getType("org.apache.uima.test2.Token");
- cas = (CASImpl)cas.getCurrentView();
-
+ cas = (CASImpl) cas.getCurrentView();
+
cas.addFsToIndexes(cas.createFS(t1));
cas.addFsToIndexes(cas.createFS(t2));
cas.addFsToIndexes(cas.createFS(t3));
-
+
serializeAndCompare("nameSpaceCollisionOmits.txt");
-
+
jcs.setOmit0Values(false);
serializeAndCompare("nameSpaceCollision.txt");
-
+
cas.addFsToIndexes(cas.createFS(t3));
serializeAndCompare("nameSpaceCollision2.txt");
@@ -230,8 +228,8 @@ public class JsonCasSerializerTest {
jcs.setOmit0Values(false);
serializeAndCompare("nameSpaceCollision2pp.txt");
-
- // filtering
+
+ // filtering
TypeSystemMgr tsMgr = CASFactory.createTypeSystem();
Type a2t = tsMgr.getType(CAS.TYPE_NAME_ANNOTATION);
// filter out the 2 types causing namespaces to be needed.
@@ -240,7 +238,7 @@ public class JsonCasSerializerTest {
jcs = new JsonCasSerializer().setOmit0Values(true);
jcs.setFilterTypes(tsi);
serializeAndCompare("nameSpaceNoCollsionFiltered.txt");
-
+
// filter, but not enough - should have 1 collison
tsMgr = CASFactory.createTypeSystem();
a2t = tsMgr.getType(CAS.TYPE_NAME_ANNOTATION);
@@ -249,27 +247,27 @@ public class JsonCasSerializerTest {
tsMgr.addType("org.apache.uimax.test.Token", a2t);
tsi = (TypeSystemImpl) tsMgr.commit();
jcs.setFilterTypes(tsi);
- serializeAndCompare("nameSpaceCollsionFiltered.txt");
-
+ serializeAndCompare("nameSpaceCollsionFiltered.txt");
+
}
-
- @Test
- public void testAllValues() throws Exception {
+
+ @Test
+ public void testAllValues() throws Exception {
setupTypeSystem("allTypes.xml");
setAllValues(0);
jcs.setPrettyPrint(true).setOmit0Values(true);
serializeAndCompare("allValuesOmits.txt");
-
+
jcs.setOmit0Values(false);
serializeAndCompare("allValuesNoOmits.txt");
-
+
jcs.setStaticEmbedding();
serializeAndCompare("allValuesStaticNoOmits.txt");
-
+
}
-
- @Test
- public void testMultipleViews() throws Exception {
+
+ @Test
+ public void testMultipleViews() throws Exception {
setupTypeSystem("allTypes.xml");
setAllValues(1);
cas = (CASImpl) cas.createView("View2");
@@ -277,45 +275,48 @@ public class JsonCasSerializerTest {
jcs.setPrettyPrint(true);
serializeAndCompare("multipleViews.txt");
-
+
}
- @Test
- public void testDynamicLists() throws Exception {
+
+ @Test
+ public void testDynamicLists() throws Exception {
setupTypeSystem("allTypes.xml");
-
+
FeatureStructure[] fss = new FeatureStructure[20];
fss[0] = emptyIntList();
- fss[1] = intList(33, fss[0]); // value 33, linked to 0
- fss[2] = intList(22, fss[1]);
+ fss[1] = intList(33, fss[0]); // value 33, linked to 0
+ fss[2] = intList(22, fss[1]);
fss[3] = intList(11, fss[2]);
-
- fss[4] = intList(110, fss[2]); // joins at 2
-
- jcas.addFsToIndexes(fss[3]);;
+
+ fss[4] = intList(110, fss[2]); // joins at 2
+
+ jcas.addFsToIndexes(fss[3]);
+ ;
jcas.addFsToIndexes(fss[4]);
-
+
jcs.setPrettyPrint(true);
serializeAndCompare("twoListMerge.txt");
-
+
jcs.setStaticEmbedding();
serializeAndCompare("twoListMergeStatic.txt");
-
+
cas.reset();
jcs = new JsonCasSerializer().setOmit0Values(true);
jcs.setPrettyPrint(true);
fss[0] = emptyIntList();
- fss[1] = intList(33, fss[0]); // value 33, linked to 0
- fss[2] = intList(22, fss[1]);
+ fss[1] = intList(33, fss[0]); // value 33, linked to 0
+ fss[2] = intList(22, fss[1]);
fss[3] = intList(11, fss[2]);
cas.addFsToIndexes(fss[3]);
serializeAndCompare("indexedSingleList.txt");
-
+
jcs.setStaticEmbedding();
serializeAndCompare("indexedSingleListStatic.txt");
-
+
}
-
+
+ // @formatter:off
/**
* Testing various cases
*
@@ -325,23 +326,22 @@ public class JsonCasSerializerTest {
* FS is referenced, and in turn references a shared item
*
*/
-
- @Test
- public void testRefs() throws Exception {
+ // @formatter:on
+ @Test
+ public void testRefs() throws Exception {
setupTypeSystem("refTypes.xml");
jcs.setPrettyPrint(true);
jcs.setJsonContext(JsonContextFormat.omitContext);
-
- // make root FS that is indexed and has a ref
+ // make root FS that is indexed and has a ref
RefTypes root = new RefTypes(jcas);
root.addToIndexes();
-
+
RefTypes ref1 = new RefTypes(jcas);
- ref1.addToIndexes(); // is both referenced and indexed
+ ref1.addToIndexes(); // is both referenced and indexed
root.setAFS(ref1);
-
+
serializeAndCompare("indexedAndRef.txt");
arrayOrListRefstst(true);
@@ -349,24 +349,24 @@ public class JsonCasSerializerTest {
}
public void arrayOrListRefstst(boolean tstArray) throws Exception {
-
+
// using dynamic embedding
- // an element is multiply-referenced if it is both in the index (referenced by the "view") and is referenced
- // by an FSRef in a feature or a slot in an FSArray
-
+ // an element is multiply-referenced if it is both in the index (referenced by the "view") and
+ // is referenced
+ // by an FSRef in a feature or a slot in an FSArray
+
jcas.reset();
-
- // make root FS that is indexed and has a ref
+
+ // make root FS that is indexed and has a ref
RefTypes root = new RefTypes(jcas);
root.addToIndexes();
-
+
// Test list or array with 1 non-embeddable
RefTypes refa1 = new RefTypes(jcas);
RefTypes refa2 = new RefTypes(jcas);
RefTypes refa3 = new RefTypes(jcas);
-
-
- FSArray a = new FSArray(jcas, 3);
+
+ FSArray a = new FSArray(jcas, 3);
a.set(0, refa1);
a.set(1, refa2);
a.set(2, refa3);
@@ -374,27 +374,29 @@ public class JsonCasSerializerTest {
NonEmptyFSList l0 = new NonEmptyFSList(jcas);
NonEmptyFSList l1 = new NonEmptyFSList(jcas);
NonEmptyFSList l2 = new NonEmptyFSList(jcas);
- EmptyFSList tailEnd = new EmptyFSList(jcas);
+ EmptyFSList tailEnd = new EmptyFSList(jcas);
l0.setTail(l1);
- l1.setTail(l2);;
+ l1.setTail(l2);
+ ;
l2.setTail(tailEnd);
l0.setHead(refa1);
l1.setHead(refa2);
- l2.setHead(refa3);;
-
+ l2.setHead(refa3);
+ ;
+
if (tstArray) {
- root.setAArrayFS(a); // is not (yet) multiply referenced
+ root.setAArrayFS(a); // is not (yet) multiply referenced
} else {
root.setAListFs(l0);
}
-
+
String sfx = (tstArray) ? "a" : "l";
// all embeddable:
- // because ref1,2,3 are not index, and FSArray isn't either
+ // because ref1,2,3 are not index, and FSArray isn't either
serializeAndCompare("array-all-embeddable-" + sfx + ".txt");
// 1 not embeddable, at all 3 positions
refa1.addToIndexes();
- // ref1 is multiply indexed
+ // ref1 is multiply indexed
serializeAndCompare("array-a1-not-" + sfx + ".txt");
refa1.removeFromIndexes();
refa2.addToIndexes();
@@ -402,60 +404,58 @@ public class JsonCasSerializerTest {
refa2.removeFromIndexes();
refa3.addToIndexes();
serializeAndCompare("array-a3-not-" + sfx + ".txt");
-
+
// 3 not embeddable:
refa1.addToIndexes();
refa2.addToIndexes();
serializeAndCompare("array-non-embeddable-" + sfx + ".txt");
-
+
// FSArray not embeddable
if (tstArray) {
- a.addToIndexes();
+ a.addToIndexes();
} else {
l0.addToIndexes();
}
-
+
serializeAndCompare("array-self-non-embeddable-" + sfx + ".txt");
-
-
+
// all embeddable, FSArray not
refa1.removeFromIndexes();
refa2.removeFromIndexes();
refa3.removeFromIndexes();
- serializeAndCompare("array-self-items-all-embeddable-" + sfx + ".txt");
+ serializeAndCompare("array-self-items-all-embeddable-" + sfx + ".txt");
}
-
private FeatureStructure emptyIntList() {
return cas.createFS(emptyIntListType);
}
-
+
private FeatureStructure intList(int v, FeatureStructure next) {
NonEmptyIntegerList fs = new NonEmptyIntegerList(jcas);
fs.setHead(v);
fs.setTail((IntegerList) next);
return fs;
}
-
-// public void testDelta() throws Exception {
-// setupTypeSystem("allTypes.xml");
-//
-// setAllValues(0);
-// Marker marker = cas.createMarker();
-// setAllValues(1);
-//
-// jcs.setPrettyPrint(true);
-// String r = serialize();
-// compareWithExpected("delta.txt", r);
-//
-// jcs.setDeltaCas(marker);
-// r = serialize();
-// compareWithExpected("delta2.txt", r);
-//
-// }
-
+
+ // public void testDelta() throws Exception {
+ // setupTypeSystem("allTypes.xml");
+ //
+ // setAllValues(0);
+ // Marker marker = cas.createMarker();
+ // setAllValues(1);
+ //
+ // jcs.setPrettyPrint(true);
+ // String r = serialize();
+ // compareWithExpected("delta.txt", r);
+ //
+ // jcs.setDeltaCas(marker);
+ // r = serialize();
+ // compareWithExpected("delta2.txt", r);
+ //
+ // }
+
private FeatureStructure setAllValues(int v) throws CASException {
- cas = (CASImpl) cas.getView(CAS.NAME_DEFAULT_SOFA); // create the default initial view sofa.
+ cas = (CASImpl) cas.getView(CAS.NAME_DEFAULT_SOFA); // create the default initial view sofa.
JCas jcas = cas.getJCas();
boolean s1 = v == 0;
boolean s2 = v == 1;
@@ -463,116 +463,121 @@ public class JsonCasSerializerTest {
cas.addFsToIndexes(fs);
FeatureStructure fs2 = cas.createFS(allTypesType);
-
+
fs.setBooleanValue(allTypesType.getFeatureByBaseName("aBoolean"), s1 ? true : false);
- fs.setByteValue (allTypesType.getFeatureByBaseName("aByte"), s1 ? (byte) -117 : (byte) 0);
- fs.setShortValue (allTypesType.getFeatureByBaseName("aShort"), s1 ? (short) -112 : (short) 0);
- fs.setIntValue (allTypesType.getFeatureByBaseName("aInteger"), s1 ? 0 : 1);
- fs.setLongValue (allTypesType.getFeatureByBaseName("aLong"), s2 ? 4321 : 1234);
- fs.setFloatValue (allTypesType.getFeatureByBaseName("aFloat"), s1 ? 1.3F : Float.NaN);
- fs.setDoubleValue (allTypesType.getFeatureByBaseName("aDouble"), s2 ? Float.NEGATIVE_INFINITY : 2.6);
- fs.setStringValue (allTypesType.getFeatureByBaseName("aString"), "some \"String\"");
- fs.setFeatureValue(allTypesType.getFeatureByBaseName("aFS"), fs2);
-
+ fs.setByteValue(allTypesType.getFeatureByBaseName("aByte"), s1 ? (byte) -117 : (byte) 0);
+ fs.setShortValue(allTypesType.getFeatureByBaseName("aShort"), s1 ? (short) -112 : (short) 0);
+ fs.setIntValue(allTypesType.getFeatureByBaseName("aInteger"), s1 ? 0 : 1);
+ fs.setLongValue(allTypesType.getFeatureByBaseName("aLong"), s2 ? 4321 : 1234);
+ fs.setFloatValue(allTypesType.getFeatureByBaseName("aFloat"), s1 ? 1.3F : Float.NaN);
+ fs.setDoubleValue(allTypesType.getFeatureByBaseName("aDouble"),
+ s2 ? Float.NEGATIVE_INFINITY : 2.6);
+ fs.setStringValue(allTypesType.getFeatureByBaseName("aString"), "some \"String\"");
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aFS"), fs2);
+
FeatureStructure fsAboolean = cas.createBooleanArrayFS(s1 ? 1 : 0);
- ByteArray fsAbyte = new ByteArray(jcas, s1 ? 2 : 0);
+ ByteArray fsAbyte = new ByteArray(jcas, s1 ? 2 : 0);
if (s1) {
fsAbyte.set(0, (byte) 15);
- fsAbyte.set(1, (byte) 0xee);
+ fsAbyte.set(1, (byte) 0xee);
}
- FeatureStructure fsAshort = cas.createShortArrayFS(s2 ? 2 : 0);
- FeatureStructure fsAstring = cas.createStringArrayFS(s1 ? 1 : 0);
-
+ FeatureStructure fsAshort = cas.createShortArrayFS(s2 ? 2 : 0);
+ FeatureStructure fsAstring = cas.createStringArrayFS(s1 ? 1 : 0);
+
fsa1 = cas.createFS(allTypesType);
fsa2 = cas.createFS(allTypesType);
fsa3 = cas.createFS(allTypesType);
-
+
fsaa = new FSArray(jcas, 3);
fsaa.set(0, fsa1);
fsaa.set(1, fsa2);
- fsaa.set(2, fsa3);;
-
+ fsaa.set(2, fsa3);
+ ;
+
FeatureStructure fsMrAboolean = cas.createBooleanArrayFS(1);
- FeatureStructure fsMrAbyte = cas.createByteArrayFS(2);
- FeatureStructure fsMrAshort = cas.createShortArrayFS(0);
- FeatureStructure fsMrAstring = cas.createStringArrayFS(1);
-
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayBoolean"), fsAboolean);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayByte"), fsAbyte);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayShort"), fsAshort);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayString"), fsAstring);
-
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayMrBoolean"), fsMrAboolean);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayMrByte"), fsMrAbyte);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayMrShort"), fsMrAshort);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aArrayMrString"), fsMrAstring);
-
-
+ FeatureStructure fsMrAbyte = cas.createByteArrayFS(2);
+ FeatureStructure fsMrAshort = cas.createShortArrayFS(0);
+ FeatureStructure fsMrAstring = cas.createStringArrayFS(1);
+
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayBoolean"), fsAboolean);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayByte"), fsAbyte);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayShort"), fsAshort);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayString"), fsAstring);
+
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayMrBoolean"), fsMrAboolean);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayMrByte"), fsMrAbyte);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayMrShort"), fsMrAshort);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aArrayMrString"), fsMrAstring);
+
FeatureStructure fsLinteger0 = cas.createFS(tsi.getType(CAS.TYPE_NAME_EMPTY_INTEGER_LIST));
-
- FeatureStructure fsLstring0 = cas.createFS(tsi.getType(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST));
- FeatureStructure fsLstring1 = cas.createFS(tsi.getType(CAS.TYPE_NAME_EMPTY_STRING_LIST));
- fsLstring0.setStringValue (tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST + ":head"), "testStr");
- fsLstring0.setFeatureValue (tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST + ":tail"), fsLstring1);
-
-
- FeatureStructure fsLfs0 = cas.createFS(tsi.getType(CAS.TYPE_NAME_NON_EMPTY_FS_LIST));
- FeatureStructure fsLfs1 = cas.createFS(tsi.getType(CAS.TYPE_NAME_EMPTY_FS_LIST));
- fsLfs0.setFeatureValue (tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_FS_LIST + ":tail"), fsLfs1);
-
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aListInteger"), fsLinteger0);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aListString"), fsLstring0);
- fs.setFeatureValue (allTypesType.getFeatureByBaseName("aListFs"), fsLfs0);
-
+
+ FeatureStructure fsLstring0 = cas.createFS(tsi.getType(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST));
+ FeatureStructure fsLstring1 = cas.createFS(tsi.getType(CAS.TYPE_NAME_EMPTY_STRING_LIST));
+ fsLstring0.setStringValue(
+ tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST + ":head"), "testStr");
+ fsLstring0.setFeatureValue(
+ tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_STRING_LIST + ":tail"), fsLstring1);
+
+ FeatureStructure fsLfs0 = cas.createFS(tsi.getType(CAS.TYPE_NAME_NON_EMPTY_FS_LIST));
+ FeatureStructure fsLfs1 = cas.createFS(tsi.getType(CAS.TYPE_NAME_EMPTY_FS_LIST));
+ fsLfs0.setFeatureValue(tsi.getFeatureByFullName(CAS.TYPE_NAME_NON_EMPTY_FS_LIST + ":tail"),
+ fsLfs1);
+
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aListInteger"), fsLinteger0);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aListString"), fsLstring0);
+ fs.setFeatureValue(allTypesType.getFeatureByBaseName("aListFs"), fsLfs0);
+
cas.addFsToIndexes(fs);
return fs;
}
-
-
- private void setupTypeSystem(String tsdName) throws InvalidXMLException, IOException, ResourceInitializationException, CASException {
+
+ private void setupTypeSystem(String tsdName)
+ throws InvalidXMLException, IOException, ResourceInitializationException, CASException {
File tsdFile = JUnitExtension.getFile("CasSerialization/desc/" + tsdName);
tsd = parser.parseTypeSystemDescription(new XMLInputSource(tsdFile));
cas = (CASImpl) CasCreationUtils.createCas(tsd, null, null);
-// cas.getSofaRef(); // creates the default sofa
+ // cas.getSofaRef(); // creates the default sofa
jcas = cas.getJCas();
tsi = cas.getTypeSystemImpl();
topType = (TypeImpl) tsi.getTopType();
- annotationType = (TypeImpl) tsi.getType("uima.tcas.Annotation");
+ annotationType = (TypeImpl) tsi.getType("uima.tcas.Annotation");
allTypesType = (TypeImpl) tsi.getType("org.apache.uima.test.AllTypes");
tokenType = (TypeImpl) tsi.getType("org.apache.uima.test.Token");
emptyIntListType = (TypeImpl) tsi.getType("uima.cas.EmptyIntegerList");
-// nonEmptyIntListType = (TypeImpl) tsi.getType("uima.cas.NonEmptyIntegerList");
-// emptyFSListType = (TypeImpl) tsi.getType("uima.cas.EmptyFSList");
-// nonEmptyFSListType = (TypeImpl) tsi.getType("uima.cas.NonEmptyFSList");
-
+ // nonEmptyIntListType = (TypeImpl) tsi.getType("uima.cas.NonEmptyIntegerList");
+ // emptyFSListType = (TypeImpl) tsi.getType("uima.cas.EmptyFSList");
+ // nonEmptyFSListType = (TypeImpl) tsi.getType("uima.cas.NonEmptyFSList");
+
}
-
+
private String getExpected(String expectedResultsName, String r) throws IOException {
if (!doJson) {
expectedResultsName = expectedResultsName.replace(".txt", ".xml");
}
if (GENERATE_EXPECTED) {
- String generateDirPlus = generateDir + ((doJson) ? "json/" : "xmi/");
- File d = new File (generateDirPlus);
+ String generateDirPlus = generateDir + ((doJson) ? "json/" : "xmi/");
+ File d = new File(generateDirPlus);
d.mkdirs();
- File file = new File (generateDirPlus + expectedResultsName);
+ File file = new File(generateDirPlus + expectedResultsName);
try (Writer writer = new FileWriter(file)) {
writer.write(r);
}
return r;
} else {
- File expectedResultsFile = JUnitExtension.getFile("CasSerialization/expected/" + ((doJson) ? "json/" : "xmi/") + expectedResultsName);
- return FileUtils.file2String(expectedResultsFile, "utf-8");
+ File expectedResultsFile = JUnitExtension.getFile(
+ "CasSerialization/expected/" + ((doJson) ? "json/" : "xmi/") + expectedResultsName);
+ return FileUtils.file2String(expectedResultsFile, "utf-8");
}
}
-
+
private void serializeAndCompare(String expectedResultsName) throws Exception {
String r = serialize();
compareWithExpected(expectedResultsName, r);
}
-
- private void compareWithExpected(String expectedResultsName, String r) throws IOException, SAXException {
+
+ private void compareWithExpected(String expectedResultsName, String r)
+ throws IOException, SAXException {
r = canonicalizeNewLines(r);
String expected = getExpected(expectedResultsName, r);
String ce = canonicalizeNewLines(expected);
@@ -582,12 +587,12 @@ public class JsonCasSerializerTest {
XMLAssert.assertXMLEqual(ce, r);
}
}
-
+
private String canonicalizeNewLines(String r) {
- return r.replace("\n\r", "\n").replace("\r\n", "\n").replace('\r', '\n');
+ return r.replace("\n\r", "\n").replace("\r\n", "\n").replace('\r', '\n');
}
-
- private String serialize() throws Exception {
+
+ private String serialize() throws Exception {
StringWriter sw = null;
ByteArrayOutputStream baos = null;
try {
@@ -598,16 +603,15 @@ public class JsonCasSerializerTest {
} else {
XmiCasSerializer xcs = new XmiCasSerializer(jcs.getCss().getFilterTypes());
baos = new ByteArrayOutputStream();
-
+
XMLSerializer sax2xml = new XMLSerializer(baos, jcs.getCss().isFormattedOutput);
xcs.serialize(cas, sax2xml.getContentHandler(), null);
return baos.toString("UTF-8");
}
} catch (Exception e) {
System.err.format("Exception occurred. The string produced so far was: %n%s%n",
- (sw == null) ? baos.toString("UTF-8") : sw.toString());
+ (sw == null) ? baos.toString("UTF-8") : sw.toString());
throw e;
}
}
-
}
diff --git a/uimaj-json/src/test/java/org/apache/uima/json/JsonMetaDataObjectTest.java b/uimaj-json/src/test/java/org/apache/uima/json/JsonMetaDataObjectTest.java
index e92b785..3112934 100644
--- a/uimaj-json/src/test/java/org/apache/uima/json/JsonMetaDataObjectTest.java
+++ b/uimaj-json/src/test/java/org/apache/uima/json/JsonMetaDataObjectTest.java
@@ -45,9 +45,8 @@ public class JsonMetaDataObjectTest {
private TestFruitObject orange;
private TestFruitBagObject fruitBag;
-
- @BeforeEach
- public void setUp() throws Exception {
+ @BeforeEach
+ public void setUp() throws Exception {
// create two identical apples and an orange
apple1 = new TestFruitObject();
apple1.setAttributeValue("name", "Apple");
@@ -56,7 +55,7 @@ public class JsonMetaDataObjectTest {
apple1.setAttributeValue("avgCostCents", 40);
apple1.setAttributeValue("citrus", Boolean.FALSE);
apple1.setAttributeValue("commonUses", new String[] { "baking", "snack" });
-
+
apple2 = new TestFruitObject();
apple2.setAttributeValue("name", "Apple");
apple2.setAttributeValue("color", "red");
@@ -80,36 +79,36 @@ public class JsonMetaDataObjectTest {
}
- @Test
- public void testTypeSystemDescriptionSerialization() throws Exception {
-
- XMLInputSource in = new XMLInputSource(JUnitExtension.getFile("CASTests/desc/casTestCaseTypesystem.xml"));
+ @Test
+ public void testTypeSystemDescriptionSerialization() throws Exception {
+
+ XMLInputSource in = new XMLInputSource(
+ JUnitExtension.getFile("CASTests/desc/casTestCaseTypesystem.xml"));
TypeSystemDescription tsd;
tsd = UIMAFramework.getXMLParser().parseTypeSystemDescription(in);
in.close();
StringWriter sw = new StringWriter();
-
- JsonMetaDataSerializer.toJSON(tsd, sw, false); // no pretty print
- assertEquals(getExpected("testTypesystem-plain.json"),sw.toString());
+
+ JsonMetaDataSerializer.toJSON(tsd, sw, false); // no pretty print
+ assertEquals(getExpected("testTypesystem-plain.json"), sw.toString());
sw = new StringWriter();
JsonMetaDataSerializer.toJSON(tsd, sw, true);
- assertEquals(getExpected("testTypesystem.json"),canonicalizeNewLines(sw.toString()));
-
+ assertEquals(getExpected("testTypesystem.json"), canonicalizeNewLines(sw.toString()));
+
}
-
/**
- * Tests the {@link MetaDataObject#toJSON(Writer)} method.
+ * Tests the {@link MetaDataObject#toJSON(Writer)} method.
*/
- @Test
- public void testJsonSerialization() throws Exception {
+ @Test
+ public void testJsonSerialization() throws Exception {
try {
// write objects to JSON
StringWriter writer = new StringWriter();
- JsonMetaDataSerializer.toJSON(apple1,writer);
+ JsonMetaDataSerializer.toJSON(apple1, writer);
String apple1json = writer.getBuffer().toString();
// System.out.println(apple1json);
@@ -127,66 +126,69 @@ public class JsonMetaDataObjectTest {
// identical objects should have identical JSON
Assert.assertEquals(apple1json, apple2json);
- assertEquals("{\"fruit\":{\"name\":\"Apple\",\"color\":\"red\",\"avgWeightLbs\":0.3,\"avgCostCents\":40,\"citrus\":false,\"commonUses\":[{\"string\":\"baking\"},{\"string\":\"snack\"}]}}", apple1json);
+ assertEquals(
+ "{\"fruit\":{\"name\":\"Apple\",\"color\":\"red\",\"avgWeightLbs\":0.3,\"avgCostCents\":40,\"citrus\":false,\"commonUses\":[{\"string\":\"baking\"},{\"string\":\"snack\"}]}}",
+ apple1json);
// test special cases
-// // single-property object where property name is omitted from XML
-// String xmlStr = "<fruitBag><fruit><name>banana</name><color>yellow</color></fruit>"
-// + "<fruit><name>raspberry</name><color>red</color></fruit></fruitBag>";
-// Document xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
-// TestFruitBagObject bag = new TestFruitBagObject();
-// bag.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
-// TestFruitObject[] fruits = bag.getFruits();
-// Assert.assertEquals(2, fruits.length);
-// Assert.assertEquals("banana", fruits[0].getName());
-// Assert.assertEquals("raspberry", fruits[1].getName());
-//
-// // property name omitted but can be inferred from type of value
-// xmlStr = "<fruit><name>banana</name><string>yellow</string></fruit>";
-// xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
-// TestFruitObject banana = new TestFruitObject();
-// banana.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
-// Assert.assertEquals("yellow", banana.getColor());
-// Assert.assertEquals("banana", banana.getName());
-//
-// // env var reference
-// xmlStr = "<fruit><name>raspberry</name><string><envVarRef>test.raspberry.color</envVarRef></string></fruit>";
-// System.setProperty("test.raspberry.color", "red");
-// xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
-// TestFruitObject raspberry = new TestFruitObject();
-// raspberry.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
-// Assert.assertEquals("red", raspberry.getColor());
-// Assert.assertEquals("raspberry", raspberry.getName());
+ // // single-property object where property name is omitted from XML
+ // String xmlStr = "<fruitBag><fruit><name>banana</name><color>yellow</color></fruit>"
+ // + "<fruit><name>raspberry</name><color>red</color></fruit></fruitBag>";
+ // Document xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
+ // TestFruitBagObject bag = new TestFruitBagObject();
+ // bag.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
+ // TestFruitObject[] fruits = bag.getFruits();
+ // Assert.assertEquals(2, fruits.length);
+ // Assert.assertEquals("banana", fruits[0].getName());
+ // Assert.assertEquals("raspberry", fruits[1].getName());
+ //
+ // // property name omitted but can be inferred from type of value
+ // xmlStr = "<fruit><name>banana</name><string>yellow</string></fruit>";
+ // xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
+ // TestFruitObject banana = new TestFruitObject();
+ // banana.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
+ // Assert.assertEquals("yellow", banana.getColor());
+ // Assert.assertEquals("banana", banana.getName());
+ //
+ // // env var reference
+ // xmlStr =
+ // "<fruit><name>raspberry</name><string><envVarRef>test.raspberry.color</envVarRef></string></fruit>";
+ // System.setProperty("test.raspberry.color", "red");
+ // xmlDoc = docBuilder.parse(new ByteArrayInputStream(xmlStr.getBytes()));
+ // TestFruitObject raspberry = new TestFruitObject();
+ // raspberry.buildFromXMLElement(xmlDoc.getDocumentElement(), xmlp);
+ // Assert.assertEquals("red", raspberry.getColor());
+ // Assert.assertEquals("raspberry", raspberry.getName());
} catch (Exception e) {
JUnitExtension.handleException(e);
}
}
-
-
- @Test
- public void testToJSONWriter() {
+
+ @Test
+ public void testToJSONWriter() {
}
- @Test
- public void testToJSONJsonGeneratorBoolean() {
+ @Test
+ public void testToJSONJsonGeneratorBoolean() {
}
- @Test
- public void testToJSONOutputStream() {
+ @Test
+ public void testToJSONOutputStream() {
}
- @Test
- public void testToJSONFile() {
+ @Test
+ public void testToJSONFile() {
}
private String getExpected(String expectedResultsName) throws IOException {
- File expectedResultsFile = JUnitExtension.getFile("CASTests/json/expected/" + expectedResultsName);
+ File expectedResultsFile = JUnitExtension
+ .getFile("CASTests/json/expected/" + expectedResultsName);
return canonicalizeNewLines(FileUtils.file2String(expectedResultsFile, "utf-8"));
}
private String canonicalizeNewLines(String r) {
- return r.replace("\n\r", "\n").replace("\r\n", "\n").replace('\r', '\n');
+ return r.replace("\n\r", "\n").replace("\r\n", "\n").replace('\r', '\n');
}
}
diff --git a/uimaj-json/src/test/java/org/apache/uima/json/JsonXmiCasSerializerTest.java b/uimaj-json/src/test/java/org/apache/uima/json/JsonXmiCasSerializerTest.java
index 1033100..035d0e8 100644
--- a/uimaj-json/src/test/java/org/apache/uima/json/JsonXmiCasSerializerTest.java
+++ b/uimaj-json/src/test/java/org/apache/uima/json/JsonXmiCasSerializerTest.java
@@ -21,15 +21,17 @@ package org.apache.uima.json;
import org.junit.jupiter.api.BeforeEach;
public class JsonXmiCasSerializerTest extends JsonCasSerializerTest {
+ // @formatter:off
/*********************************************************************
* This is a version of the Json tests that does XMI
* serialization instead
*
* It extends the other JsonCasSerializerTest but sets up some flags
*********************************************************************/
- @Override
- @BeforeEach
- public void setUp() throws Exception {
+ // @formatter:on
+ @Override
+ @BeforeEach
+ public void setUp() throws Exception {
super.setUp();
jcs = new JsonCasSerializer();
doJson = false;
diff --git a/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitBagObject.java b/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitBagObject.java
index 31e98ff..ee290c2 100644
--- a/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitBagObject.java
+++ b/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitBagObject.java
@@ -31,9 +31,9 @@ public class TestFruitBagObject extends MetaDataObject_impl {
new PropertyXmlInfo[] { new PropertyXmlInfo("fruits") });
private TestFruitObject[] mFruits;
-
+
public TestFruitBagObject() {
- //do nothing
+ // do nothing
}
public TestFruitObject[] getFruits() {
@@ -44,23 +44,22 @@ public class TestFruitBagObject extends MetaDataObject_impl {
mFruits = aFruits;
}
-// /**
-// * For testing purposes - a hardcoded attribute set. Should be compared with the results of
-// * {@link #listAttributes()}.
-// */
-// static public Set<NameClassPair> getAttributeSet() {
-// Set<NameClassPair> result = new HashSet<NameClassPair>();
-// result.add(new NameClassPair("fruits", TestFruitObject[].class.getName()));
-// return result;
-// }
-
+ // /**
+ // * For testing purposes - a hardcoded attribute set. Should be compared with the results of
+ // * {@link #listAttributes()}.
+ // */
+ // static public Set<NameClassPair> getAttributeSet() {
+ // Set<NameClassPair> result = new HashSet<NameClassPair>();
+ // result.add(new NameClassPair("fruits", TestFruitObject[].class.getName()));
+ // return result;
+ // }
+
static public Set<MetaDataAttr> getMetaDataAttrSet() {
Set<MetaDataAttr> result = new HashSet<>();
try {
- result.add(new MetaDataAttr("fruits",
- TestFruitBagObject.class.getDeclaredMethod("getFruits"),
- TestFruitBagObject.class.getDeclaredMethod("setFruits", TestFruitObject[].class),
- TestFruitObject[].class));
+ result.add(new MetaDataAttr("fruits", TestFruitBagObject.class.getDeclaredMethod("getFruits"),
+ TestFruitBagObject.class.getDeclaredMethod("setFruits", TestFruitObject[].class),
+ TestFruitObject[].class));
} catch (Exception e) {
throw new RuntimeException(e);
}
diff --git a/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitObject.java b/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitObject.java
index 2eae340..f864fbe 100644
--- a/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitObject.java
+++ b/uimaj-json/src/test/java/org/apache/uima/resource/metadata/impl/TestFruitObject.java
@@ -28,11 +28,11 @@ import org.apache.uima.util.NameClassPair;
* A simple concrete MetaDataObject implementation for use in testing the MetaDataObject_impl class.
*/
public class TestFruitObject extends MetaDataObject_impl {
-
+
private static final long serialVersionUID = 1L;
public TestFruitObject() {
- //do nothing
+ // do nothing
}
public String getName() {
@@ -107,40 +107,28 @@ public class TestFruitObject extends MetaDataObject_impl {
result.add(new NameClassPair("commonUses", String[].class.getName()));
return result;
}
-
+
static public Set<MetaDataAttr> getMetaDataAttrSet() {
HashSet<MetaDataAttr> result = new HashSet<>();
try {
- result.add(new MetaDataAttr(
- "name",
- TestFruitObject.class.getDeclaredMethod("getName"),
- TestFruitObject.class.getDeclaredMethod("setName", String.class),
- String.class));
- result.add(new MetaDataAttr(
- "avgWeightLbs",
- TestFruitObject.class.getDeclaredMethod("getAvgWeightLbs"),
- TestFruitObject.class.getDeclaredMethod("setAvgWeightLbs", float.class),
- Float.class));
- result.add(new MetaDataAttr(
- "color",
- TestFruitObject.class.getDeclaredMethod("getColor"),
- TestFruitObject.class.getDeclaredMethod("setColor", String.class),
- String.class));
- result.add(new MetaDataAttr(
- "avgCostCents",
- TestFruitObject.class.getDeclaredMethod("getAvgCostCents"),
- TestFruitObject.class.getDeclaredMethod("setAvgCostCents", int.class),
- Integer.class));
- result.add(new MetaDataAttr(
- "citrus",
- TestFruitObject.class.getDeclaredMethod("isCitrus"),
- TestFruitObject.class.getDeclaredMethod("setCitrus", boolean.class),
- Boolean.class));
- result.add(new MetaDataAttr(
- "commonUses",
- TestFruitObject.class.getDeclaredMethod("getCommonUses"),
- TestFruitObject.class.getDeclaredMethod("setCommonUses", String[].class),
- String[].class));
+ result.add(new MetaDataAttr("name", TestFruitObject.class.getDeclaredMethod("getName"),
+ TestFruitObject.class.getDeclaredMethod("setName", String.class), String.class));
+ result.add(new MetaDataAttr("avgWeightLbs",
+ TestFruitObject.class.getDeclaredMethod("getAvgWeightLbs"),
+ TestFruitObject.class.getDeclaredMethod("setAvgWeightLbs", float.class),
+ Float.class));
+ result.add(new MetaDataAttr("color", TestFruitObject.class.getDeclaredMethod("getColor"),
+ TestFruitObject.class.getDeclaredMethod("setColor", String.class), String.class));
+ result.add(new MetaDataAttr("avgCostCents",
+ TestFruitObject.class.getDeclaredMethod("getAvgCostCents"),
+ TestFruitObject.class.getDeclaredMethod("setAvgCostCents", int.class),
+ Integer.class));
+ result.add(new MetaDataAttr("citrus", TestFruitObject.class.getDeclaredMethod("isCitrus"),
+ TestFruitObject.class.getDeclaredMethod("setCitrus", boolean.class), Boolean.class));
+ result.add(new MetaDataAttr("commonUses",
+ TestFruitObject.class.getDeclaredMethod("getCommonUses"),
+ TestFruitObject.class.getDeclaredMethod("setCommonUses", String[].class),
+ String[].class));
} catch (Exception e) {
throw new RuntimeException(e);
}