diff --git a/src/main/java/io/apimatic/core/annotations/TypeCombinator.java b/src/main/java/io/apimatic/core/annotations/TypeCombinator.java index 2aa77439..1c02b977 100644 --- a/src/main/java/io/apimatic/core/annotations/TypeCombinator.java +++ b/src/main/java/io/apimatic/core/annotations/TypeCombinator.java @@ -4,6 +4,7 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; + import com.fasterxml.jackson.databind.JsonSerializer; /** @@ -13,6 +14,11 @@ public interface TypeCombinator { @Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @interface TypeCombinatorCase { + /** + * Java type of the object wrapped in the annotated TypeCombinator container. + * @return String encoded java type of the wrapped object + */ + String type() default ""; } @Retention(RetentionPolicy.RUNTIME) diff --git a/src/main/java/io/apimatic/core/types/AnyOfValidationException.java b/src/main/java/io/apimatic/core/types/AnyOfValidationException.java new file mode 100644 index 00000000..e48d093c --- /dev/null +++ b/src/main/java/io/apimatic/core/types/AnyOfValidationException.java @@ -0,0 +1,26 @@ +package io.apimatic.core.types; + +import java.io.IOException; +import java.util.List; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * This is the base class for all exceptions that represent an error response from the server. + */ +public class AnyOfValidationException extends IOException { + + /** + * UID for serialization. + */ + private static final long serialVersionUID = 1214174253911720228L; + + /** + * Initialization constructor. + * @param types List on unMapped types + * @param json Value that was not mapped by the above types + */ + public AnyOfValidationException(final List types, final JsonNode json) { + super("We could not match any acceptable type from " + + String.join(", ", types) + " on: " + json); + } +} diff --git a/src/main/java/io/apimatic/core/types/OneOfValidationException.java b/src/main/java/io/apimatic/core/types/OneOfValidationException.java new file mode 100644 index 00000000..ceddd037 --- /dev/null +++ b/src/main/java/io/apimatic/core/types/OneOfValidationException.java @@ -0,0 +1,37 @@ +package io.apimatic.core.types; + +import java.io.IOException; +import java.util.List; +import com.fasterxml.jackson.databind.JsonNode; + +/** + * This is the base class for all exceptions that represent an error response from the server. + */ +public class OneOfValidationException extends IOException { + + /** + * UID for serialization. + */ + private static final long serialVersionUID = 6424174253911720228L; + + /** + * Initialization constructor. + * @param type1 The first type that was mapped on jsonNode + * @param type2 The second type that also got mapped on jsonNode + * @param json Value that was mapped by the above two types + */ + public OneOfValidationException(final String type1, final String type2, final JsonNode json) { + super("There are more than one matching types i.e. " + + type1 + " and " + type2 + " on: " + json); + } + + /** + * Initialization constructor. + * @param types List on unMapped types + * @param json Value that was not mapped by the above types + */ + public OneOfValidationException(final List types, final JsonNode json) { + super("We could not match any acceptable type from " + + String.join(", ", types) + " on: " + json); + } +} diff --git a/src/main/java/io/apimatic/core/utilities/CoreHelper.java b/src/main/java/io/apimatic/core/utilities/CoreHelper.java index ca2b36bd..f1933c2f 100644 --- a/src/main/java/io/apimatic/core/utilities/CoreHelper.java +++ b/src/main/java/io/apimatic/core/utilities/CoreHelper.java @@ -57,6 +57,8 @@ import io.apimatic.core.annotations.TypeCombinator.FormSerialize; import io.apimatic.core.annotations.TypeCombinator.TypeCombinatorCase; import io.apimatic.core.annotations.TypeCombinator.TypeCombinatorStringCase; +import io.apimatic.core.types.AnyOfValidationException; +import io.apimatic.core.types.OneOfValidationException; import io.apimatic.core.types.http.request.MultipartFileWrapper; import io.apimatic.core.types.http.request.MultipartWrapper; import io.apimatic.coreinterfaces.http.request.ArraySerializationFormat; @@ -89,34 +91,34 @@ public class CoreHelper { /** * Deserialization of Json data. */ - private static ObjectMapper mapper = - JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .withConfigOverride(BigDecimal.class, - mutableConfigOverride -> mutableConfigOverride - .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING))) - .build(); + private static ObjectMapper mapper = JsonMapper + .builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, + false) + .withConfigOverride(BigDecimal.class, mutableConfigOverride -> mutableConfigOverride + .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING))) + .build(); /** * Strict Deserialization of Json data. */ - private static ObjectMapper strictMapper = - JsonMapper.builder().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true) - .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) - .addModule(new SimpleModule().addDeserializer(String.class, - new CoercionLessStringDeserializer())) - .withConfigOverride(BigDecimal.class, - mutableConfigOverride -> mutableConfigOverride - .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING))) - .build(); - - protected CoreHelper() {} - + private static ObjectMapper strictMapper = JsonMapper.builder() + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .addModule(new SimpleModule().addDeserializer(String.class, + new CoercionLessStringDeserializer())) + .withConfigOverride(BigDecimal.class, mutableConfigOverride -> mutableConfigOverride + .setFormat(JsonFormat.Value.forShape(JsonFormat.Shape.STRING))) + .build(); + + protected CoreHelper() { + } /** * Get a JsonSerializer instance for a collection from the provided annotation. - * @param serializerAnnotation The Annotation containing information about the custom serializer - * of a collection. + * + * @param serializerAnnotation The Annotation containing information about the + * custom serializer of a collection. * @return The JsonSerializer instance of the required type. */ private static JsonSerializer getCollectionCustomSerializer( @@ -129,18 +131,19 @@ private static JsonSerializer getCollectionCustomSerializer( } /** - * List of classes that are wrapped directly. This information is needed when traversing object - * trees for reference matching. + * List of classes that are wrapped directly. This information is needed when + * traversing object trees for reference matching. */ - private static final Set WRAPPER_TYPES = - new HashSet(Arrays.asList(Boolean.class, Character.class, Byte.class, - Short.class, String.class, Integer.class, Long.class, Float.class, Double.class, - BigDecimal.class, Void.class, File.class, MultipartWrapper.class, - MultipartFileWrapper.class)); + private static final Set WRAPPER_TYPES = new HashSet( + Arrays.asList(Boolean.class, Character.class, Byte.class, Short.class, String.class, + Integer.class, Long.class, Float.class, Double.class, BigDecimal.class, + Void.class, File.class, MultipartWrapper.class, MultipartFileWrapper.class)); /** * Get a JsonSerializer instance from the provided annotation. - * @param serializerAnnotation The Annotation containing information about the serializer. + * + * @param serializerAnnotation The Annotation containing information about the + * serializer. * @return The JsonSerializer instance of the required type. */ private static JsonSerializer getSerializer(JsonSerialize serializerAnnotation) { @@ -153,8 +156,9 @@ private static JsonSerializer getSerializer(JsonSerialize serializerAnnotatio /** * Get a JsonSerializer instance for a collection from the provided annotation. - * @param serializerAnnotation The Annotation containing information about the serializer of a - * collection. + * + * @param serializerAnnotation The Annotation containing information about the + * serializer of a collection. * @return The JsonSerializer instance of the required type. */ private static JsonSerializer getCollectionSerializer(JsonSerialize serializerAnnotation) { @@ -165,18 +169,18 @@ private static JsonSerializer getCollectionSerializer(JsonSerialize serialize } } - /** * Deserialization of Json data. + * * @return {@link ObjectMapper}. */ public static ObjectMapper getMapper() { return mapper; } - /** * Strict Deserialization of Json data. + * * @return {@link ObjectMapper}. */ public static ObjectMapper getStrictMapper() { @@ -185,9 +189,11 @@ public static ObjectMapper getStrictMapper() { /** * Json Serialization of a given object. + * * @param obj The object to serialize into Json. * @return The serialized Json String representation of the given object. - * @throws JsonProcessingException Signals that a Json Processing Exception has occurred. + * @throws JsonProcessingException Signals that a Json Processing Exception has + * occurred. */ public static String serialize(Object obj) throws JsonProcessingException { if (obj == null) { @@ -199,12 +205,14 @@ public static String serialize(Object obj) throws JsonProcessingException { /** * Json Serialization of a given object using a specified JsonSerializer. - * @param obj The object to serialize into Json. + * + * @param obj The object to serialize into Json. * @param serializer The instance of JsonSerializer to use. * @return The serialized Json string representation of the given object. - * @throws JsonProcessingException Signals that a Json Processing Exception has occurred. + * @throws JsonProcessingException Signals that a Json Processing Exception has + * occurred. */ - @SuppressWarnings({"rawtypes", "unchecked"}) + @SuppressWarnings({ "rawtypes", "unchecked" }) public static String serialize(Object obj, final JsonSerializer serializer) throws JsonProcessingException { if (obj == null || serializer == null) { @@ -229,19 +237,19 @@ public static String serialize(Object obj, final JsonSerializer serializer) return objectMapper.writeValueAsString(obj); } - /** * Xml Serialization of a given object list. - * @param Type of object to be serialized. + * + * @param Type of object to be serialized. * @param objArray Object Array to be serialized. * @param rootName Root name for the xml. * @param nodeName Node name for the array nodes. - * @param cls Class of object to be serialized. + * @param cls Class of object to be serialized. * @return The serialized Xml String representation of the given object array. * @throws IOException Signals that an IO exception occurred. */ - public static String serializeXmlArray( - T[] objArray, String rootName, String nodeName, Class cls) throws IOException { + public static String serializeXmlArray(T[] objArray, String rootName, String nodeName, + Class cls) throws IOException { try { JAXBContext context = JAXBContext.newInstance(cls); JAXBElement jaxbElement; @@ -265,10 +273,11 @@ public static String serializeXmlArray( /** * Xml Serialization of a given object. - * @param Type of object to be serialized. - * @param obj Object to be serialized. + * + * @param Type of object to be serialized. + * @param obj Object to be serialized. * @param rootName Root name for the xml. - * @param cls Class of object to be serialized. + * @param cls Class of object to be serialized. * @return The serialized Xml String representation of the given object. * @throws IOException Signals that an IOException exception occurred. */ @@ -287,20 +296,21 @@ public static String serializeXml(T obj, String rootName, Class cls) thro } } - /** * Json Serialization of a given container object based on annotation. + * * @param obj The object to serialize into Json. * @return The serialized Json String representation of the given object. - * @throws JsonProcessingException Signals that a Json Processing Exception has occurred. + * @throws JsonProcessingException Signals that a Json Processing Exception has + * occurred. */ public static String serializeTypeCombinator(Object obj) throws JsonProcessingException { if (obj == null) { return null; } - Annotation stringCaseAnnotation = - obj.getClass().getAnnotation(TypeCombinatorStringCase.class); + Annotation stringCaseAnnotation = obj.getClass() + .getAnnotation(TypeCombinatorStringCase.class); if (stringCaseAnnotation != null) { return obj.toString(); @@ -310,18 +320,20 @@ public static String serializeTypeCombinator(Object obj) throws JsonProcessingEx } /** - * Json deserialization of the given Json string using a specified JsonDerializer. - * @param jsonNode The JsonNode to deserialize. + * Json deserialization of the given Json string using a specified + * JsonDerializer. + * + * @param jsonNode The JsonNode to deserialize. * @param typeReference TypeReference of T1. - * @param The type of the object to deserialize into. - * @param The type of the custom deserializer. - * @param cls The class to attach the deserializer to. - * @param deserializer The deserializer to use. + * @param The type of the object to deserialize into. + * @param The type of the custom deserializer. + * @param cls The class to attach the deserializer to. + * @param deserializer The deserializer to use. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ - public static T1 deserialize( - JsonNode jsonNode, final TypeReference typeReference, final Class cls, + public static T1 deserialize(JsonNode jsonNode, + final TypeReference typeReference, final Class cls, final JsonDeserializer deserializer) throws IOException { if (jsonNode == null) { return null; @@ -330,20 +342,21 @@ public static T1 deserialize( return deserialize(mapper.writeValueAsString(jsonNode), typeReference, cls, deserializer); } - /** - * Json deserialization of the given Json string using a specified JsonDerializer. - * @param json The Json string to deserialize. + * Json deserialization of the given Json string using a specified + * JsonDerializer. + * + * @param json The Json string to deserialize. * @param typeReference TypeReference of T1. - * @param The type of the object to deserialize into. - * @param The type of the custom deserializer. - * @param cls The class to attach the deserializer to. - * @param deserializer The deserializer to use. + * @param The type of the object to deserialize into. + * @param The type of the custom deserializer. + * @param cls The class to attach the deserializer to. + * @param deserializer The deserializer to use. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ - public static T1 deserialize( - String json, final TypeReference typeReference, final Class cls, + public static T1 deserialize(String json, + final TypeReference typeReference, final Class cls, final JsonDeserializer deserializer) throws IOException { if (isNullOrWhiteSpace(json)) { return null; @@ -361,8 +374,9 @@ public static T1 deserialize( /** * Json deserialization of the given Json string. - * @param The type of the object to deserialize into. - * @param json The Json string to deserialize. + * + * @param The type of the object to deserialize into. + * @param json The Json string to deserialize. * @param clazz The type of the object to deserialize into. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. @@ -376,50 +390,63 @@ public static T deserialize(String json, Class clazz) thro } /** - * Strict JSON deserialization of the given JSON string with FAIL_ON_UNKNOWN_PROPERTIES flag as - * true, used particularly for type combinators. - * @param The type of the object to deserialize into - * @param json The JsonNode to deserialize + * Strict JSON deserialization of the given JSON string with + * FAIL_ON_UNKNOWN_PROPERTIES flag as true, used particularly for type + * combinators. + * + * @param The type of the object to deserialize into + * @param json The JsonNode to deserialize * @param classes The list of types of the object to deserialize into * @param isOneOf The boolean flag to validate for oneOf flow * @return The deserialized object * @throws IOException Signals if any I/O exception occurred. */ - public static T deserialize( - JsonNode json, List> classes, boolean isOneOf) throws IOException { + public static T deserialize(JsonNode json, List> classes, + boolean isOneOf) throws IOException { if (json == null) { return null; } - T deserializedObject = null; - int deserializationCount = 0; + String mappedType = ""; + List unMappedTypes = new ArrayList(); + boolean matchFound = false; for (Class clazz : classes) { + String classType = getTypeCombinatorCaseType(clazz); try { - if (isOneOf) { - deserializedObject = strictMapper.convertValue(json, clazz); - deserializationCount++; - if (deserializationCount > 1) { - throw new IOException( - "More than 1 matching one-of types found against given json"); - } - } else { - return strictMapper.convertValue(json, clazz); + deserializedObject = strictMapper.convertValue(json, clazz); + if (isOneOf && matchFound) { + throw new OneOfValidationException(mappedType, classType, json); + } + mappedType = classType; + matchFound = true; + if (!isOneOf) { + break; } } catch (IllegalArgumentException e) { - // Ignoring the exception + unMappedTypes.add(classType); } } - if (deserializationCount == 0) { - throw new IOException("No " + (isOneOf ? "one-of" : "any-of") - + " type deserializer found against given json"); + if (matchFound) { + return deserializedObject; } + if (isOneOf) { + throw new OneOfValidationException(unMappedTypes, json); + } + throw new AnyOfValidationException(unMappedTypes, json); + } - return deserializedObject; + private static String getTypeCombinatorCaseType(Class clazz) { + TypeCombinatorCase caseAnnotation = clazz.getAnnotation(TypeCombinatorCase.class); + if (caseAnnotation == null) { + return ""; + } + return caseAnnotation.type(); } /** * Json deserialization of the given Json string. + * * @param json The Json string to deserialize. * @return The deserialized Json as a Map. * @throws IOException Signals if any I/O exception occurred. @@ -436,9 +463,10 @@ public static LinkedHashMap deserialize(String json) throws IOEx /** * JSON Deserialization of the given json string. - * @param json The json string to deserialize. + * + * @param json The json string to deserialize. * @param typeReference TypeReference of T. - * @param The type of the object to deserialize into. + * @param The type of the object to deserialize into. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ @@ -452,15 +480,17 @@ public static T deserialize(String json, TypeReference typ } /** - * JSON Deserialization of the given json string with FAIL_ON_UNKNOWN_PROPERTIES flag as true. - * @param jsonNode The Json Node to deserialize. + * JSON Deserialization of the given json string with FAIL_ON_UNKNOWN_PROPERTIES + * flag as true. + * + * @param jsonNode The Json Node to deserialize. * @param typeReference TypeReference of T. - * @param The type of the object to deserialize into. + * @param The type of the object to deserialize into. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ - public static T deserialize( - JsonNode jsonNode, TypeReference typeReference) throws IOException { + public static T deserialize(JsonNode jsonNode, + TypeReference typeReference) throws IOException { if (jsonNode == null) { return null; } @@ -469,10 +499,12 @@ public static T deserialize( } /** - * JSON deserialization of the given JsonNode with FAIL_ON_UNKNOWN_PROPERTIES flag as true. - * @param The type of the object to deserialize into. + * JSON deserialization of the given JsonNode with FAIL_ON_UNKNOWN_PROPERTIES + * flag as true. + * + * @param The type of the object to deserialize into. * @param jsonNode The Json Node to deserialize. - * @param clazz The type of the object to deserialize into. + * @param clazz The type of the object to deserialize into. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ @@ -481,12 +513,12 @@ public static T deserialize(JsonNode jsonNode, Class clazz if (jsonNode == null) { return null; } - return strictMapper.convertValue(jsonNode, clazz); } /** * XML Deserialization of the given xml string. + * * @param The class of the object to deserialize into. * @param xml The xml string to deserialize. * @param cls The class of the object to deserialize into. @@ -508,6 +540,7 @@ public static T deserializeXml(String xml, Class cls) thro /** * XML Deserialization of the given xml string. + * * @param The class of the object to deserialize into. * @param xml The xml string to deserialize. * @param cls The class of the object to deserialize into. @@ -520,8 +553,8 @@ public static List deserializeXmlArray(String xml, Class jaxbElement = - jaxbUnmarshaller.unmarshal(new StreamSource(reader), cls); + JAXBElement jaxbElement = jaxbUnmarshaller.unmarshal(new StreamSource(reader), + cls); return Arrays.asList(jaxbElement.getValue()); } catch (JAXBException jaxbException) { @@ -531,14 +564,15 @@ public static List deserializeXmlArray(String xml, Class The class of the object to deserialize into. * @param xml The xml string to deserialize. * @param cls The class of the object to deserialize into. * @return The deserialized simple types object list. * @throws IOException Signals if any I/O exception occurred. */ - public static List deserializeXmlSimpleTypesArray( - String xml, Class cls) throws IOException { + public static List deserializeXmlSimpleTypesArray(String xml, + Class cls) throws IOException { try { JAXBContext jaxbContext = JAXBContext.newInstance(cls); Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller(); @@ -547,8 +581,8 @@ public static List deserializeXmlSimpleTypesArray( Matcher patternMatcher = pattern.matcher(xml); while (patternMatcher.find()) { StringReader reader = new StringReader(patternMatcher.group()); - T unmarshalledElement = - jaxbUnmarshaller.unmarshal(new StreamSource(reader), cls).getValue(); + T unmarshalledElement = jaxbUnmarshaller.unmarshal(new StreamSource(reader), cls) + .getValue(); deserializedList.add(unmarshalledElement); } return deserializedList; @@ -558,22 +592,25 @@ public static List deserializeXmlSimpleTypesArray( } /** - * JSON Deserialization from custom deserializer based on given discriminator and registry. - * @param jp Parsed used for reading JSON content. - * @param ctxt Context that can be used to access information about this deserialization - * activity. - * @param discriminator The model's discriminator. - * @param registry The map containing all discriminators as keys and associated classes as - * values. - * @param typesWithoutDiscriminator The list containing all types without discriminators. - * @param isOneOf The boolean flag to validate for oneOf flow. - * @param the deserialized response type. + * JSON Deserialization from custom deserializer based on given discriminator + * and registry. + * + * @param jp Parsed used for reading JSON content. + * @param ctxt Context that can be used to access + * information about this deserialization + * activity. + * @param discriminator The model's discriminator. + * @param registry The map containing all discriminators as + * keys and associated classes as values. + * @param typesWithoutDiscriminator The list containing all types without + * discriminators. + * @param isOneOf The boolean flag to validate for oneOf flow. + * @param the deserialized response type. * @return The deserialized object. * @throws IOException Signals if any I/O exception occurred. */ - public static T deserialize( - JsonParser jp, DeserializationContext ctxt, String discriminator, - List>> registry, + public static T deserialize(JsonParser jp, DeserializationContext ctxt, + String discriminator, List>> registry, List> typesWithoutDiscriminator, boolean isOneOf) throws IOException { ObjectCodec oc = jp.getCodec(); @@ -593,6 +630,7 @@ public static T deserialize( /** * Json deserialization of the given Json string. + * * @param json The Json string to deserialize. * @return The deserialized Json as an Object. */ @@ -601,7 +639,8 @@ public static Object deserializeAsObject(String json) { return null; } try { - return CoreHelper.deserialize(json, new TypeReference() {}); + return CoreHelper.deserialize(json, new TypeReference() { + }); } catch (IOException e) { // Failed to deserialize when json is not representing a JSON object. // i.e. either its string or any primitive type. @@ -611,8 +650,9 @@ public static Object deserializeAsObject(String json) { /** * JSON Deserialization of the given json string. - * @param The type of the object to deserialize into. - * @param json The Json string to deserialize. + * + * @param The type of the object to deserialize into. + * @param json The Json string to deserialize. * @param classArray The class of the array of objects to deserialize into. * @return The deserialized list of objects. * @throws IOException Signals if any I/O exception occurred.. @@ -626,15 +666,15 @@ public static List deserializeArray(String json, Class> parameters) { + public static void appendUrlWithTemplateParameters(StringBuilder queryBuilder, + Map> parameters) { // Perform parameter validation if (null == queryBuilder) { throw new IllegalArgumentException( @@ -656,8 +696,8 @@ public static void appendUrlWithTemplateParameters( if (null == element) { replaceValue = ""; } else if (element instanceof Collection) { - replaceValue = - flattenCollection("", (Collection) element, shouldEncode, "%s%s%s", '/'); + replaceValue = flattenCollection("", (Collection) element, shouldEncode, + "%s%s%s", '/'); } else { if (shouldEncode) { replaceValue = tryUrlEncode(element.toString(), false); @@ -673,13 +713,14 @@ public static void appendUrlWithTemplateParameters( /** * Appends the given set of parameters to the given query string. - * @param queryBuilder The query URL string to append the parameters. - * @param parameters The parameters to append. + * + * @param queryBuilder The query URL string to append the + * parameters. + * @param parameters The parameters to append. * @param arraySerializationFormat the array serialization format. */ - public static void appendUrlWithQueryParameters( - StringBuilder queryBuilder, Map parameters, - ArraySerializationFormat arraySerializationFormat) { + public static void appendUrlWithQueryParameters(StringBuilder queryBuilder, + Map parameters, ArraySerializationFormat arraySerializationFormat) { // Perform parameter validation if (queryBuilder == null) { throw new IllegalArgumentException( @@ -698,6 +739,7 @@ public static void appendUrlWithQueryParameters( /** * Validates if the string is null, empty or whitespace. + * * @param s The string to validate. * @return The result of validation. */ @@ -708,8 +750,8 @@ public static boolean isNullOrWhiteSpace(String s) { int length = s.length(); if (length > 0) { - for (int start = 0, middle = length / 2, - end = length - 1; start <= middle; start++, end--) { + for (int start = 0, middle = length / 2, end = length + - 1; start <= middle; start++, end--) { if (s.charAt(start) > ' ' || s.charAt(end) > ' ') { return false; } @@ -721,12 +763,13 @@ public static boolean isNullOrWhiteSpace(String s) { /** * Replaces all occurrences of the given string in the string builder. + * * @param stringBuilder The string builder to update with replaced strings. - * @param toReplace The string to replace in the string builder. - * @param replaceWith The string to replace with. + * @param toReplace The string to replace in the string builder. + * @param replaceWith The string to replace with. */ - public static void replaceAll( - StringBuilder stringBuilder, String toReplace, String replaceWith) { + public static void replaceAll(StringBuilder stringBuilder, String toReplace, + String replaceWith) { int index = stringBuilder.indexOf(toReplace); while (index != -1) { @@ -738,7 +781,8 @@ public static void replaceAll( /** * Updates the user agent header value. - * @param apiUserAgent the String value of apiUserAgent. + * + * @param apiUserAgent the String value of apiUserAgent. * @param userAgentConfig the Map of user agent config. * @return {@link String}. */ @@ -747,8 +791,8 @@ public static String updateUserAgent(String apiUserAgent, Map us String osName = System.getProperty("os.name") + "-" + System.getProperty("os.version"); userAgent = apiUserAgent; userAgent = userAgent.replace("{engine}", "JRE"); - userAgent = - userAgent.replace("{engine-version}", engineVersion != null ? engineVersion : ""); + userAgent = userAgent.replace("{engine-version}", + engineVersion != null ? engineVersion : ""); userAgent = userAgent.replace("{os-info}", osName != null ? osName : ""); if (userAgentConfig != null) { @@ -762,6 +806,7 @@ public static String updateUserAgent(String apiUserAgent, Map us /** * Removes null values from the given map. + * * @param map Map of values. */ public static void removeNullValues(Map map) { @@ -774,6 +819,7 @@ public static void removeNullValues(Map map) { /** * Validates and processes the given URL. + * * @param url The given URL to process. * @return Pre-process URL as string. */ @@ -798,12 +844,13 @@ public static String cleanUrl(StringBuilder url) { /** * Prepares Array style form fields from a given array of values. - * @param value Value for the form fields. + * + * @param value Value for the form fields. * @param arraySerializationFormat serialization format. * @return Dictionary of form fields created from array elements. */ - public static List> prepareFormFields( - Map value, ArraySerializationFormat arraySerializationFormat) { + public static List> prepareFormFields(Map value, + ArraySerializationFormat arraySerializationFormat) { List> formFields = new ArrayList<>(); if (value != null) { objectToList("", value, formFields, new HashSet(), arraySerializationFormat); @@ -812,9 +859,11 @@ public static List> prepareFormFields( } /** - * JSON Deserialization of the given json string with FAIL_ON_UNKNOWN_PROPERTIES flag as true. - * @param The type of the object to deserialize into. - * @param json The Json string to deserialize. + * JSON Deserialization of the given json string with FAIL_ON_UNKNOWN_PROPERTIES + * flag as true. + * + * @param The type of the object to deserialize into. + * @param json The Json string to deserialize. * @param classArray The class of the array of objects to deserialize into. * @return The deserialized list of objects. * @throws IOException Signals if any I/O exception occurred. @@ -830,17 +879,17 @@ public static List deserializeArray(JsonNode json, Class The type of the object to deserialize into. + * @param registry The Map containing all discriminators as keys and + * associated classes as values. + * @param The type of the object to deserialize into. * @return The type to deserialize into. * @throws IOException Signals if any I/O exception occurred. */ - private static List> deduceType( - JsonNode jsonNode, String discriminator, List>> registry) - throws IOException { + private static List> deduceType(JsonNode jsonNode, String discriminator, + List>> registry) throws IOException { if (jsonNode == null || registry == null) { return null; } @@ -869,7 +918,8 @@ private static List> deduceType( /** * Deduces the type from immediate child if exists based on given discriminator. - * @param jsonNode The json to check against. + * + * @param jsonNode The json to check against. * @param discriminator The model's discriminator. * @return The type to deserialize into. * @throws IOException Signals if any I/O exception occurred. @@ -895,13 +945,13 @@ private static String deduceTypeFromImmidiateChild(JsonNode jsonNode, String dis /** * Encodes a given object to URL encoded string. - * @param name Name of the object. - * @param obj Raw object sent from caller. - * @param objBuilder String of elements. + * + * @param name Name of the object. + * @param obj Raw object sent from caller. + * @param objBuilder String of elements. * @param arraySerializationFormat The array serialization format. */ - private static void encodeObjectAsQueryString( - String name, Object obj, StringBuilder objBuilder, + private static void encodeObjectAsQueryString(String name, Object obj, StringBuilder objBuilder, ArraySerializationFormat arraySerializationFormat) { List> objectList = new ArrayList<>(); @@ -920,7 +970,6 @@ private static void encodeObjectAsQueryString( hasParam = true; // Load element value as string - if (accessor.matches(".*?\\[\\d+\\]$") && isDelimeterFormat(arraySerializationFormat)) { String arrayName = accessor.substring(0, accessor.lastIndexOf('[')); @@ -948,25 +997,26 @@ private static void encodeObjectAsQueryString( } } - private static void appendParamKeyValuePair( - String formatString, StringBuilder objBuilder, String accessor, Object value) { + private static void appendParamKeyValuePair(String formatString, StringBuilder objBuilder, + String accessor, Object value) { - String paramKeyValPair = - String.format(formatString, accessor, tryUrlEncode(value.toString(), false)); + String paramKeyValPair = String.format(formatString, accessor, + tryUrlEncode(value.toString(), false)); objBuilder.append(paramKeyValPair); } /** * Flattening a collection of objects into a string. - * @param elemName The element name of collection. - * @param array Array of elements to flatten. - * @param encode Need to encode?. - * @param fmt Format string to use for array flattening. + * + * @param elemName The element name of collection. + * @param array Array of elements to flatten. + * @param encode Need to encode?. + * @param fmt Format string to use for array flattening. * @param separator Separator to use for string concatenation. * @return Representative string made up of array elements. */ - private static String flattenCollection( - String elemName, Collection array, boolean encode, String fmt, char separator) { + private static String flattenCollection(String elemName, Collection array, boolean encode, + String fmt, char separator) { StringBuilder builder = new StringBuilder(); // Append all elements of the array into a string @@ -995,7 +1045,8 @@ private static String flattenCollection( /** * Tries URL encode using UTF-8. - * @param value The value to URL encode. + * + * @param value The value to URL encode. * @param spaceAsPercentEncoded The flag get space character as percent encoded. * @return Encoded url. */ @@ -1013,19 +1064,20 @@ public static String tryUrlEncode(String value, boolean spaceAsPercentEncoded) { /** * Responsible to encode into base64 the username and password + * * @param basicAuthUserName The auth username * @param basicAuthPassword The auth password * @return The base64 encoded String */ - public static String getBase64EncodedCredentials( - String basicAuthUserName, String basicAuthPassword) { + public static String getBase64EncodedCredentials(String basicAuthUserName, + String basicAuthPassword) { String authCredentials = basicAuthUserName + ":" + basicAuthPassword; return "Basic " + Base64.getEncoder().encodeToString(authCredentials.getBytes()); } - private static void objectToList( - String objName, Collection obj, List> objectList, - HashSet processed, ArraySerializationFormat arraySerializationFormat) { + private static void objectToList(String objName, Collection obj, + List> objectList, HashSet processed, + ArraySerializationFormat arraySerializationFormat) { Collection array = obj; // Append all elements of the array into a string @@ -1037,10 +1089,9 @@ private static void objectToList( if (isWrapperType(element) && (arraySerializationFormat == ArraySerializationFormat.UNINDEXED || arraySerializationFormat == ArraySerializationFormat.PLAIN)) { - key = - arraySerializationFormat == ArraySerializationFormat.UNINDEXED - ? String.format("%s[]", objName) - : objName; + key = arraySerializationFormat == ArraySerializationFormat.UNINDEXED + ? String.format("%s[]", objName) + : objName; } else { key = String.format("%s[%d]", objName, index++); } @@ -1050,9 +1101,9 @@ private static void objectToList( } - private static void objectToList( - String objName, Map obj, List> objectList, - HashSet processed, ArraySerializationFormat arraySerializationFormat) { + private static void objectToList(String objName, Map obj, + List> objectList, HashSet processed, + ArraySerializationFormat arraySerializationFormat) { // Process map Map map = obj; // Append all elements of the array into a string @@ -1068,15 +1119,17 @@ private static void objectToList( /** * Converts a given object to a form encoded map. - * @param objName Name of the object. - * @param obj The object to convert into a map. - * @param objectList The object list to populate. - * @param processed List of object hashCodes that are already parsed. + * + * @param objName Name of the object. + * @param obj The object to convert into a map. + * @param objectList The object list to populate. + * @param processed List of object hashCodes that are already + * parsed. * @param arraySerializationFormat The array serialization format. */ - private static void objectToList( - String objName, Object obj, List> objectList, - HashSet processed, ArraySerializationFormat arraySerializationFormat) { + private static void objectToList(String objName, Object obj, + List> objectList, HashSet processed, + ArraySerializationFormat arraySerializationFormat) { // Null values need not to be processed if (obj == null) { return; @@ -1177,8 +1230,8 @@ private static void objectToList( // Load value by invoking getter method method.setAccessible(true); Object value = method.invoke(obj); - JsonSerialize serializerAnnotation = - method.getAnnotation(JsonSerialize.class); + JsonSerialize serializerAnnotation = method + .getAnnotation(JsonSerialize.class); // Load key value pair into objectList if (serializerAnnotation != null) { loadKeyValuePairForEncoding(attribName, value, objectList, processed, @@ -1203,14 +1256,14 @@ private static void objectToList( private static String getAccessorStringFormat( ArraySerializationFormat arraySerializationFormat) { switch (arraySerializationFormat) { - case CSV: - return CSV_FORMAT; - case PSV: - return PSV_FORMAT; - case TSV: - return TSV_FORMAT; - default: - return ""; + case CSV: + return CSV_FORMAT; + case PSV: + return PSV_FORMAT; + case TSV: + return TSV_FORMAT; + default: + return ""; } } @@ -1222,18 +1275,22 @@ private static boolean isDelimeterFormat(ArraySerializationFormat arraySerializa /** * Processes the value and load into objectList against key. - * @param key The key to used for creation of key value pair. - * @param value The value to process against the given key. - * @param objectList The object list to process with key value pair. - * @param processed List of processed objects hashCodes. - * @param serializer The serializer for serialize the object. + * + * @param key The key to used for creation of key value + * pair. + * @param value The value to process against the given key. + * @param objectList The object list to process with key value + * pair. + * @param processed List of processed objects hashCodes. + * @param serializer The serializer for serialize the object. * @param arraySerializationFormat The array serialization format. - * @throws JsonProcessingException Signals that a Json Processing Exception has occurred. + * @throws JsonProcessingException Signals that a Json Processing Exception has + * occurred. */ - private static void loadKeyValueUsingSerializer( - String key, Object value, List> objectList, - HashSet processed, JsonSerializer serializer, - ArraySerializationFormat arraySerializationFormat) throws JsonProcessingException { + private static void loadKeyValueUsingSerializer(String key, Object value, + List> objectList, HashSet processed, + JsonSerializer serializer, ArraySerializationFormat arraySerializationFormat) + throws JsonProcessingException { value = serialize(value, serializer); Object obj = deserializeAsObject(value.toString()); @@ -1247,19 +1304,21 @@ private static void loadKeyValueUsingSerializer( } } - /** * While processing objects to map, loads value after serializing. - * @param key The key to used for creation of key value pair. - * @param value The value to process against the given key. - * @param objectList The object list to process with key value pair. - * @param processed List of processed objects hashCodes. + * + * @param key The key to used for creation of key value + * pair. + * @param value The value to process against the given key. + * @param objectList The object list to process with key value + * pair. + * @param processed List of processed objects hashCodes. * @param formSerializerAnnotation Annotation for serializer. * @param arraySerializationFormat The array serialization format. */ - private static void loadKeyValuePairForEncoding( - String key, Object value, List> objectList, - HashSet processed, FormSerialize formSerializerAnnotation, + private static void loadKeyValuePairForEncoding(String key, Object value, + List> objectList, HashSet processed, + FormSerialize formSerializerAnnotation, ArraySerializationFormat arraySerializationFormat) { if (value == null) { return; @@ -1274,18 +1333,20 @@ private static void loadKeyValuePairForEncoding( } } - /** - * While processing objects to map, decides whether to perform recursion or load value. - * @param key The key for creating key value pair. - * @param value The value to process against the given key. - * @param objectList The object list to process with key value pair. - * @param processed List of processed objects hashCodes. + * While processing objects to map, decides whether to perform recursion or load + * value. + * + * @param key The key for creating key value pair. + * @param value The value to process against the given key. + * @param objectList The object list to process with key value + * pair. + * @param processed List of processed objects hashCodes. * @param arraySerializationFormat The array serialization format. */ - private static void loadKeyValuePairForEncoding( - String key, Object value, List> objectList, - HashSet processed, ArraySerializationFormat arraySerializationFormat) { + private static void loadKeyValuePairForEncoding(String key, Object value, + List> objectList, HashSet processed, + ArraySerializationFormat arraySerializationFormat) { if (value == null) { return; } @@ -1311,17 +1372,19 @@ private static void loadKeyValuePairForEncoding( /** * While processing objects to map, loads value after serializing. - * @param key The key to used for creation of key value pair. - * @param value The value to process against the given key. - * @param objectList The object list to process with key value pair. - * @param processed List of processed objects hashCodes. - * @param serializerAnnotation Annotation for serializer. + * + * @param key The key to used for creation of key value + * pair. + * @param value The value to process against the given key. + * @param objectList The object list to process with key value + * pair. + * @param processed List of processed objects hashCodes. + * @param serializerAnnotation Annotation for serializer. * @param arraySerializationFormat The array serialization format. */ - private static void loadKeyValuePairForEncoding( - String key, Object value, List> objectList, - HashSet processed, JsonSerialize serializerAnnotation, - ArraySerializationFormat arraySerializationFormat) { + private static void loadKeyValuePairForEncoding(String key, Object value, + List> objectList, HashSet processed, + JsonSerialize serializerAnnotation, ArraySerializationFormat arraySerializationFormat) { if (value == null) { return; } @@ -1341,6 +1404,7 @@ private static void loadKeyValuePairForEncoding( /** * Check if the given object can be wrapped directly. + * * @param object The given object. * @return true if the class is an autoboxed class e.g., Integer. */ @@ -1354,9 +1418,11 @@ private static boolean isWrapperType(Object object) { /** * Json Serialization of an ENUM defined under oneOf/anyOf container. + * * @param value The object to serialize into Json String. * @return The serialized Json String representation of the given object. - * @throws JsonProcessingException Signals that a Json Processing Exception has occurred. + * @throws JsonProcessingException Signals that a Json Processing Exception has + * occurred. */ public static String serializeEnumContainer(Object value) throws JsonProcessingException { if (value instanceof String || value instanceof Integer) { @@ -1367,7 +1433,8 @@ public static String serializeEnumContainer(Object value) throws JsonProcessingE } /** - * Custom deserializer class of any string property for disallowing implicit type conversion. + * Custom deserializer class of any string property for disallowing implicit + * type conversion. */ private static class CoercionLessStringDeserializer extends StringDeserializer { private static final long serialVersionUID = 1L; diff --git a/src/test/java/apimatic/core/models/AtomCase.java b/src/test/java/apimatic/core/models/AtomCase.java index b951f6cc..cc496799 100644 --- a/src/test/java/apimatic/core/models/AtomCase.java +++ b/src/test/java/apimatic/core/models/AtomCase.java @@ -15,7 +15,7 @@ * This is a implementation class for AtomCase. */ @JsonDeserialize(using = JsonDeserializer.None.class) -@TypeCombinatorCase +@TypeCombinatorCase(type = "Map") public class AtomCase { @JsonValue diff --git a/src/test/java/apimatic/core/models/OrbitCase.java b/src/test/java/apimatic/core/models/OrbitCase.java index 923e6935..41ab7bab 100644 --- a/src/test/java/apimatic/core/models/OrbitCase.java +++ b/src/test/java/apimatic/core/models/OrbitCase.java @@ -13,7 +13,7 @@ * This is a implementation class for OrbitCase. */ @JsonDeserialize(using = JsonDeserializer.None.class) -@TypeCombinatorCase +@TypeCombinatorCase(type = "Orbit") public class OrbitCase { @JsonValue diff --git a/src/test/java/apimatic/core/utilities/CoreHelperTest.java b/src/test/java/apimatic/core/utilities/CoreHelperTest.java index 8c400dcc..6abdf7b8 100644 --- a/src/test/java/apimatic/core/utilities/CoreHelperTest.java +++ b/src/test/java/apimatic/core/utilities/CoreHelperTest.java @@ -41,6 +41,8 @@ import apimatic.core.models.Person; import apimatic.core.models.containers.SendParamsFormDateTime; import apimatic.core.models.containers.SendScalarParamBody; +import io.apimatic.core.types.AnyOfValidationException; +import io.apimatic.core.types.OneOfValidationException; import io.apimatic.core.utilities.CoreHelper; import io.apimatic.core.utilities.CoreJsonObject; import io.apimatic.core.utilities.CoreJsonValue; @@ -70,29 +72,28 @@ public class CoreHelperTest { private static final long UNIQUE_UUID_NUMBER2 = 87866L; private static final long UNIQUE_UUID_NUMBER1 = 876547L; private static final List LIST_OF_INTEGERS = Arrays.asList(1, 2, 3, 4, 5); - private static final String XML_ARRAY = - "\r\n" + " \r\n" - + " 6\r\n" + " Data\r\n" + "\r\n" - + ""; - private static final String INVALID_XML = - "\r\n" + " item number=\"3\" string=\"XMLRootName\"\r\n" + " number>6\r\n" - + " Data\r\n" + "\r\n" + ""; + private static final String XML_ARRAY = "\r\n" + + " \r\n" + " 6\r\n" + + " Data\r\n" + "\r\n" + ""; + private static final String INVALID_XML = "\r\n" + + " item number=\"3\" string=\"XMLRootName\"\r\n" + " number>6\r\n" + + " Data\r\n" + "\r\n" + ""; private static final String XML = "\r\n" - + "\r\n" - + " 6\r\n" + " Data\r\n" - + "\r\n" + ""; + + "\r\n" + + " 6\r\n" + " Data\r\n" + + "\r\n" + ""; private static final String JSON_OBJECT = "https://localhost:3000/query?operations[$id]=https%3A%2F%2Fexample.com%2Fperson." - + "schema.json&operations[$schema]=https%3A%2F%2Fjson-schema" - + ".org%2Fdraft%2F2020-12%2Fschema&operations[title]=Person&operations" - + "[type]=object&operations[properties][firstName][type]=string&operations" - + "[properties][firstName][description]=The+person%27s+first+name.&" - + "operations[properties][lastName][type]=string&operations[properties]" - + "[lastName][description]=The+person%27s+last+name.&operations" - + "[properties][age][type]=integer&operations[properties][age][description]" - + "=Age+in+years&operations[properties][age][minimum]=0"; + + "schema.json&operations[$schema]=https%3A%2F%2Fjson-schema" + + ".org%2Fdraft%2F2020-12%2Fschema&operations[title]=Person&operations" + + "[type]=object&operations[properties][firstName][type]=string&operations" + + "[properties][firstName][description]=The+person%27s+first+name.&" + + "operations[properties][lastName][type]=string&operations[properties]" + + "[lastName][description]=The+person%27s+last+name.&operations" + + "[properties][age][type]=integer&operations[properties][age][description]" + + "=Age+in+years&operations[properties][age][minimum]=0"; private static final String JSON_VALUE = "https://localhost:3000/query?operations=test-JsonValue"; @@ -102,7 +103,6 @@ public void testSerializeNullObject() throws JsonProcessingException { assertNull(CoreHelper.serialize(obj)); } - @Test public void testIsWhiteSpace() { String whiteSpaceString = " "; @@ -132,7 +132,6 @@ public void testBase64Encoding() { String username = "username"; String password = "password"; - String expectedEncodedString = "Basic dXNlcm5hbWU6cGFzc3dvcmQ="; String actualEncodedString = CoreHelper.getBase64EncodedCredentials(username, password); assertEquals(actualEncodedString, expectedEncodedString); @@ -160,7 +159,6 @@ public void testInvalidUrlEncoding() { assertEquals(actual, expected); } - @Test public void testUrlEncodingPercentage() { String urlString = "https://localhost:8080/query=0"; @@ -180,7 +178,6 @@ public void testCleanUrl() { stringBuilder.append(server); stringBuilder.append(path); - String expected = "https://localhost:3000/query/basic/body"; String actual = CoreHelper.cleanUrl(stringBuilder); @@ -223,9 +220,8 @@ public void testRemoveNullValues1() { public void testUpdateUserAgent() { String userAgent = "Java|31.8.0|{engine}|{engine-version}|{os-info}"; - String expected = - "Java|31.8.0|JRE|" + System.getProperty("java.runtime.version") + "|" - + System.getProperty("os.name") + "-" + System.getProperty("os.version"); + String expected = "Java|31.8.0|JRE|" + System.getProperty("java.runtime.version") + "|" + + System.getProperty("os.name") + "-" + System.getProperty("os.version"); String actual = CoreHelper.updateUserAgent(userAgent, null); @@ -238,17 +234,15 @@ public void testUpdateUserAgent1() { Map userAgentConfig = new HashMap<>(); userAgentConfig.put("{square-version}", "17.2.6"); - String expected = - "Java|31.8.0|JRE|" + System.getProperty("java.runtime.version") + "|" - + System.getProperty("os.name") + "-" + System.getProperty("os.version") - + "|17.2.6"; + String expected = "Java|31.8.0|JRE|" + System.getProperty("java.runtime.version") + "|" + + System.getProperty("os.name") + "-" + System.getProperty("os.version") + + "|17.2.6"; String actual = CoreHelper.updateUserAgent(userAgent, userAgentConfig); assertEquals(actual, expected); } - @Test public void testAppendTemplateParameters() { String baseUri = "https://localhost:3000"; @@ -283,7 +277,6 @@ public void testAppendTemplateParameters1() { assertEquals(actual, expected); } - @Test public void testAppendTemplateParameters2() { String baseUri = "https://localhost:3000"; @@ -318,7 +311,6 @@ public void testAppendTemplateParameters3() { assertEquals(actual, expected); } - @Test(expected = IllegalArgumentException.class) public void testAppendTemplateParameters4() { String templateStringValue = "strings"; @@ -331,7 +323,6 @@ public void testAppendTemplateParameters4() { CoreHelper.appendUrlWithTemplateParameters(queryBuilder, templateParameters); } - @Test public void testAppendTemplateParametersShouldNotEncode() { String baseUri = "https://localhost:3000"; @@ -349,7 +340,6 @@ public void testAppendTemplateParametersShouldNotEncode() { assertEquals(actual, expected); } - @Test public void testAppendTemplateParameters5() { String baseUri = "https://localhost:3000"; @@ -363,11 +353,10 @@ public void testAppendTemplateParameters5() { assertEquals(actual, expected); } - @Test public void testptionalNullable() throws IOException { - ChildClass child = - CoreHelper.deserialize( + ChildClass child = CoreHelper + .deserialize( "{\"Grand_Parent_Required_Nullable\":null,\"Grand_Parent_Required\":" + "\"not nullable and required\",\"class\":23,\"" + "Parent_Optional_Nullable_With_Default_Value\":" @@ -379,14 +368,13 @@ public void testptionalNullable() throws IOException { + "nullable and required\",\"Child_Class_Array\":null}", ChildClass.class); - String expected = - "{\"Grand_Parent_Required_Nullable\":null,\"Grand_Parent_Required\":" - + "\"not nullable and required\",\"Parent_Optional_Nullable_With_" - + "Default_Value\":\"Has default value\",\"Parent_Required_Nullable" - + "\":null,\"Parent_Required\":\"not nullable and required\"," - + "\"Optional_Nullable\":null,\"Optional_Nullable_With_Default_Value\":" - + "\"With default value\",\"Required_Nullable\":null,\"Required\":" - + "\"not nullable and required\",\"Child_Class_Array\":null,\"class\":23}"; + String expected = "{\"Grand_Parent_Required_Nullable\":null,\"Grand_Parent_Required\":" + + "\"not nullable and required\",\"Parent_Optional_Nullable_With_" + + "Default_Value\":\"Has default value\",\"Parent_Required_Nullable" + + "\":null,\"Parent_Required\":\"not nullable and required\"," + + "\"Optional_Nullable\":null,\"Optional_Nullable_With_Default_Value\":" + + "\"With default value\",\"Required_Nullable\":null,\"Required\":" + + "\"not nullable and required\",\"Child_Class_Array\":null,\"class\":23}"; String actual = CoreHelper.serialize(child); assertEquals(actual, expected); @@ -617,8 +605,6 @@ public void testCommaSeperated() throws IOException { assertTrue(actual.contains(",")); } - - @Test(expected = IllegalArgumentException.class) public void testAppendQueryParameters4() { String queryValue = "x+y"; @@ -630,7 +616,6 @@ public void testAppendQueryParameters4() { ArraySerializationFormat.INDEXED); } - @Test public void testPrepareFormFields() { String body = "test for prepare form fields"; @@ -639,8 +624,8 @@ public void testPrepareFormFields() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body", body)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } @@ -652,12 +637,11 @@ public void testPrepareFormFieldsUUID() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body", body.toString())); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } - @Test public void testPrepareFormFieldsModel() { DeleteBody body = new DeleteBody.Builder().name("ali").field("QA").build(); @@ -667,12 +651,11 @@ public void testPrepareFormFieldsModel() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[name]", "ali")); expected.add(new SimpleEntry("body[field]", "QA")); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } - @Test public void testPrepareFormFieldsIndexedSerialization() { String bodyText = "test for prepare form fields"; @@ -683,8 +666,8 @@ public void testPrepareFormFieldsIndexedSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[0]", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } @@ -696,8 +679,8 @@ public void testPrepareFormFieldsIndexedSerialization1() { formParameters.put("body", body); List> expected = new ArrayList>(); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } @@ -710,8 +693,8 @@ public void testPrepareFormFieldsPlainSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.PLAIN); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.PLAIN); assertEquals(actual, expected); } @@ -724,8 +707,8 @@ public void testPrepareFormFieldsUnindexedSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[]", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.UNINDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.UNINDEXED); assertEquals(actual, expected); } @@ -739,8 +722,8 @@ public void testPrepareFormFieldsCSVSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[0]", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.CSV); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.CSV); assertEquals(actual, expected); } @@ -753,8 +736,8 @@ public void testPrepareFormFieldPSVSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[0]", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.PSV); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.PSV); assertEquals(actual, expected); } @@ -767,19 +750,18 @@ public void testPrepareFormFieldTSVSerialization() { List> expected = new ArrayList>(); expected.add(new SimpleEntry("body[0]", bodyText)); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.TSV); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.TSV); assertEquals(actual, expected); } - @Test public void testPrepareFormFields1() { Map formParameters = null; List> expected = new ArrayList>(); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } @@ -802,9 +784,8 @@ public void testSerializeMapOfString() throws JsonProcessingException { @Test public void testUnixTimeStampSerializer() throws JsonProcessingException { - LocalDateTime localDateTime = - TestDateTimeHelper.getLocalDateTimeFromGMT(ZonedDateTime.of(YEAR1, MONTH1, DAY1, - HOUR1, MINUTES, 0, 0, ZoneId.of("GMT"))); + LocalDateTime localDateTime = TestDateTimeHelper.getLocalDateTimeFromGMT( + ZonedDateTime.of(YEAR1, MONTH1, DAY1, HOUR1, MINUTES, 0, 0, ZoneId.of("GMT"))); JsonSerializer serializer = new LocalDateTimeHelper.UnixTimestampSerializer(); String expected = "868756200"; String actual = CoreHelper.serialize(localDateTime, serializer); @@ -847,8 +828,8 @@ public void testUnixTimeStampSerializerNullObject() throws JsonProcessingExcepti @Test public void testUnixTimeStampSerializerNull() throws JsonProcessingException { - LocalDateTime localDateTime = - LocalDateTime.of(YEAR1, MONTH1, DAY1, XML_NO_OF_ELEMENT, MINUTES); + LocalDateTime localDateTime = LocalDateTime.of(YEAR1, MONTH1, DAY1, XML_NO_OF_ELEMENT, + MINUTES); JsonSerializer serializer = null; String actual = CoreHelper.serialize(localDateTime, serializer); @@ -860,10 +841,9 @@ public void testSimpleDateDeserializer() throws IOException { List expectedDates = new ArrayList<>(); expectedDates.add(LocalDate.of(YEAR2, MONTH2, DAY1)); expectedDates.add(LocalDate.of(YEAR2, MONTH2, DAY1)); - List actualDates = - CoreHelper.deserialize("[\"1994-02-13\",\"1994-02-13\"]", - new TypeReference>() {}, LocalDate.class, - new DateHelper.SimpleDateDeserializer()); + List actualDates = CoreHelper.deserialize("[\"1994-02-13\",\"1994-02-13\"]", + new TypeReference>() { + }, LocalDate.class, new DateHelper.SimpleDateDeserializer()); assertEquals(actualDates, expectedDates); } @@ -884,9 +864,9 @@ public void testDeserializerArrayNull() throws IOException { @Test public void testSimpleDateDeserializerNull() throws IOException { String json = null; - List actualDates = - CoreHelper.deserialize(json, new TypeReference>() {}, - LocalDate.class, new DateHelper.SimpleDateDeserializer()); + List actualDates = CoreHelper.deserialize(json, + new TypeReference>() { + }, LocalDate.class, new DateHelper.SimpleDateDeserializer()); assertNull(actualDates); } @@ -894,8 +874,8 @@ public void testSimpleDateDeserializerNull() throws IOException { public void testDeserializerWithClass() throws IOException { DeleteBody expected = new DeleteBody.Builder("ali", "QA").build(); - DeleteBody actual = - CoreHelper.deserialize("{\"name\": \"ali\", \"field\": \"QA\"}", DeleteBody.class); + DeleteBody actual = CoreHelper.deserialize("{\"name\": \"ali\", \"field\": \"QA\"}", + DeleteBody.class); assertEquals(actual.getName(), expected.getName()); assertEquals(actual.getField(), expected.getField()); } @@ -907,8 +887,6 @@ public void testDeserializerWithClass1() throws IOException { assertNull(actual); } - - @Test public void testDeserializeAsObject() { String json = "{\"name\": \"ali\", \"field\": \"QA\"}"; @@ -949,14 +927,16 @@ public void testDeserialize1() throws IOException { LinkedHashMap expected = new LinkedHashMap<>(); expected.put("name", "ali"); expected.put("field", "QA"); - Object actual = CoreHelper.deserialize(json, new TypeReference() {}); + Object actual = CoreHelper.deserialize(json, new TypeReference() { + }); assertEquals(actual, expected); } @Test public void testDeserialize2() throws IOException { String json = null; - Object actual = CoreHelper.deserialize(json, new TypeReference() {}); + Object actual = CoreHelper.deserialize(json, new TypeReference() { + }); assertNull(actual); } @@ -967,108 +947,120 @@ public void testDeserializeNullJson() throws IOException { assertNull(actual); } - @Test - public void testDeserializeOneOf() throws IOException { - String json = - "{\"key1\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}," - + "\"key2\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}}"; - ObjectMapper objectMapper = new ObjectMapper(); - JsonNode jsonNode = objectMapper.readTree(json); - - Object result = - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), - true); - assertNotNull(result); - } - @Test public void testDeserializeOneOfNull() throws IOException { JsonNode jsonNode = null; - Object result = - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), - true); + Object result = CoreHelper.deserialize(jsonNode, + Arrays.asList(AtomCase.class, OrbitCase.class), true); assertNull(result); } + @Test + public void testDeserializeOneOfA() throws IOException { + String json = "{\"key1\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}," + + "\"key2\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}}"; + ObjectMapper objectMapper = new ObjectMapper(); + JsonNode jsonNode = objectMapper.readTree(json); + + Object result = CoreHelper.deserialize(jsonNode, + Arrays.asList(AtomCase.class, OrbitCase.class), true); + assertEquals("{key1=Atom [numberOfElectrons=2, numberOfProtons=2], " + + "key2=Atom [numberOfElectrons=2, numberOfProtons=2]}", result.toString()); + } @Test - public void testDeserializeOneOf1() throws IOException { + public void testDeserializeOneOfB() throws IOException { String json = "{\"NumberOfElectrons\":2}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - Object result = - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), - true); - assertNotNull(result); + Object result = CoreHelper.deserialize(jsonNode, + Arrays.asList(AtomCase.class, OrbitCase.class), true); + assertEquals("Orbit [numberOfElectrons=2]", result.toString()); } - @Test(expected = IOException.class) - public void testDeserializeOneOf2() throws IOException { + @Test(expected = OneOfValidationException.class) + public void testDeserializeOneOfFailA() throws IOException { String json = "{\"RandomKey\":2}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), true); + try { + CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), true); + } catch (Exception e) { + assertEquals("We could not match any acceptable type from " + + "Map, Orbit on: {\"RandomKey\":2}", e.getMessage()); + throw e; + } } - @Test(expected = IOException.class) - public void testDeserializeOneOf3() throws IOException { - String json = - "[{\"NumberOfElectrons\":2},{\"NumberOfElectrons\":2, \"NumberOfProtons\":2}]"; + @Test(expected = OneOfValidationException.class) + public void testDeserializeOneOfFailB() throws IOException { + String json = "{\"NumberOfElectrons\":2}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), true); + try { + CoreHelper.deserialize(jsonNode, Arrays.asList(OrbitCase.class, OrbitCase.class), true); + } catch (Exception e) { + assertEquals("There are more than one matching types i.e. Orbit and " + + "Orbit on: {\"NumberOfElectrons\":2}", e.getMessage()); + throw e; + } } - @Test - public void testDeserializeAnyOf() throws IOException { - String json = - "{\"key1\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}," - + "\"key2\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}}"; + public void testDeserializeAnyOfA() throws IOException { + String json = "{\"key1\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}," + + "\"key2\":{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - Object result = - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), - false); - assertNotNull(result); + Object result = CoreHelper.deserialize(jsonNode, + Arrays.asList(AtomCase.class, OrbitCase.class), false); + assertEquals("{key1=Atom [numberOfElectrons=2, numberOfProtons=2], " + + "key2=Atom [numberOfElectrons=2, numberOfProtons=2]}", result.toString()); } @Test - public void testDeserializeOneOfAnyOf1() throws IOException { + public void testDeserializeAnyOfB() throws IOException { String json = "{\"NumberOfElectrons\":2}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - Object result = - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), - false); - assertNotNull(result); + Object result = CoreHelper.deserialize(jsonNode, + Arrays.asList(AtomCase.class, OrbitCase.class), false); + assertEquals("Orbit [numberOfElectrons=2]", result.toString()); } - @Test(expected = IOException.class) - public void testDeserializeOneOfAnyOf2() throws IOException { + @Test(expected = AnyOfValidationException.class) + public void testDeserializeAnyOfFailA() throws IOException { String json = "{\"RandomKey\":2}"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), false); + try { + CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), false); + } catch (Exception e) { + assertEquals("We could not match any acceptable type from " + + "Map, Orbit on: {\"RandomKey\":2}", e.getMessage()); + throw e; + } } - @Test(expected = IOException.class) - public void testDeserializeAnyOf3() throws IOException { + @Test(expected = AnyOfValidationException.class) + public void testDeserializeAnyOfFailB() throws IOException { String json = "[{\"NumberOfElectrons\":2},{\"NumberOfElectrons\":2, \"NumberOfProtons\":2}]"; ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - - CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), false); + try { + CoreHelper.deserialize(jsonNode, Arrays.asList(AtomCase.class, OrbitCase.class), false); + } catch (Exception e) { + assertEquals("We could not match any acceptable type " + + "from Map, Orbit on: [{\"NumberOfElectrons\":2}," + + "{\"NumberOfElectrons\":2,\"NumberOfProtons\":2}]", e.getMessage()); + throw e; + } } - @Test public void testTypeCombinatorSerializationString() throws JsonProcessingException { SendScalarParamBody body = SendScalarParamBody.fromMString("some string"); @@ -1092,15 +1084,15 @@ public void testTypeCombinatorSerializationString1() throws JsonProcessingExcept Map mapOfTypes = new HashMap<>(); mapOfTypes.put("key1", body); - List> actual = - CoreHelper.prepareFormFields(mapOfTypes, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(mapOfTypes, + ArraySerializationFormat.INDEXED); assertEquals(actual, expected); } @Test public void testTypeCombinatorSerializationInteger() throws JsonProcessingException { - SendScalarParamBody body = - SendScalarParamBody.fromPrecision(Arrays.asList(PRECISION_NUMBER)); + SendScalarParamBody body = SendScalarParamBody + .fromPrecision(Arrays.asList(PRECISION_NUMBER)); String expected = "[1.2]"; String actual = CoreHelper.serializeTypeCombinator(body); assertEquals(actual, expected); @@ -1112,7 +1104,8 @@ public void testDeserializeTypeReferenceJsonNode() throws IOException { ObjectMapper objectMapper = new ObjectMapper(); JsonNode jsonNode = objectMapper.readTree(json); - Object result = CoreHelper.deserialize(jsonNode, new TypeReference() {}); + Object result = CoreHelper.deserialize(jsonNode, new TypeReference() { + }); assertNotNull(result); } @@ -1120,7 +1113,8 @@ public void testDeserializeTypeReferenceJsonNode() throws IOException { public void testDeserializeTypeReferenceJsonNode1() throws IOException { JsonNode jsonNode = null; - Object result = CoreHelper.deserialize(jsonNode, new TypeReference() {}); + Object result = CoreHelper.deserialize(jsonNode, new TypeReference() { + }); assertNull(result); } @@ -1131,10 +1125,9 @@ public void testDeserializeThroughParser() throws IOException { DeserializationContext context = mapper.getDeserializationContext(); JsonParser jsonParser = mapper.createParser("{\"NumberOfTyres\":\"4\",\"HaveTrunk\":true}"); - Object actual = - CoreHelper.deserialize(jsonParser, context, discriminator, - Arrays.asList(Collections.singletonMap("Morning", MorningCase.class)), - Arrays.asList(CarCase.class, AtomCase.class), true); + Object actual = CoreHelper.deserialize(jsonParser, context, discriminator, + Arrays.asList(Collections.singletonMap("Morning", MorningCase.class)), + Arrays.asList(CarCase.class, AtomCase.class), true); assertNotNull(actual); } @@ -1151,7 +1144,6 @@ public void testDeserializeThroughParser1() throws IOException { Arrays.asList(), true); } - @Test public void testDeserializeThroughParser2() throws IOException { String discriminator = ""; @@ -1169,8 +1161,8 @@ public void testDeserializeThroughParser3() throws IOException { String discriminator = ""; ObjectMapper mapper = new ObjectMapper(); DeserializationContext context = mapper.getDeserializationContext(); - JsonParser jsonParser = - mapper.createParser("[{\"NumberOfTyres\":\"4\",\"HaveTrunk\":true}]"); + JsonParser jsonParser = mapper + .createParser("[{\"NumberOfTyres\":\"4\",\"HaveTrunk\":true}]"); CoreHelper.deserialize(jsonParser, context, discriminator, Arrays.asList(Collections.singletonMap("Morning", MorningCase.class)), @@ -1182,8 +1174,8 @@ public void testDeserializeThroughParser4() throws IOException { String discriminator = ""; ObjectMapper mapper = new ObjectMapper(); DeserializationContext context = mapper.getDeserializationContext(); - JsonParser jsonParser = - mapper.createParser("[{\"NumberOfTyres\":\"4\",\"HaveTrunk\":true}]"); + JsonParser jsonParser = mapper + .createParser("[{\"NumberOfTyres\":\"4\",\"HaveTrunk\":true}]"); CoreHelper.deserialize(jsonParser, context, discriminator, Arrays.asList(Collections.singletonMap("Morning", MorningCase.class)), null, true); @@ -1198,37 +1190,35 @@ public void testDeserializeThroughParser5() throws IOException { @Test public void testPrepareFormFieldOneOfAnyOf() throws IOException { - NonScalarModel formNonScalarModel = - CoreHelper.deserialize( - "{\"outerMap" + "\":{\"key1\":{\"startsAt\":\"15:00\",\"endsAt\":" - + "\"21:00\",\"offerLunch\":true,\"sessionType\":\"Noon\"}" - + ",\"key2\":{\"startsAt\":\"6:00\",\"endsAt\":\"11:00\"," - + "\"offerTeaBreak\":true,\"sessionType\":\"Morning\"}}}", - NonScalarModel.class); + NonScalarModel formNonScalarModel = CoreHelper.deserialize( + "{\"outerMap" + "\":{\"key1\":{\"startsAt\":\"15:00\",\"endsAt\":" + + "\"21:00\",\"offerLunch\":true,\"sessionType\":\"Noon\"}" + + ",\"key2\":{\"startsAt\":\"6:00\",\"endsAt\":\"11:00\"," + + "\"offerTeaBreak\":true,\"sessionType\":\"Morning\"}}}", + NonScalarModel.class); Map formParameters = new HashMap<>(); formParameters.put("Key1", formNonScalarModel); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertNotNull(actual); } @Test public void testPrepareFormFieldOneOfAnyOfDateTime() throws IOException { - DateTimeCases formDateTimeCases = - CoreHelper.deserialize( + DateTimeCases formDateTimeCases = CoreHelper + .deserialize( "{\"mapvsArray\":{\"key1\":" + "\"Sun, 06 Nov 1994 08:49:37 GMT\"," + "\"key2\":\"Sun, 06 Nov 1994 08:49:37 GMT\"}}", DateTimeCases.class); Map formParameters = new HashMap<>(); formParameters.put("DateTime", formDateTimeCases); - List> actual = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.INDEXED); + List> actual = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.INDEXED); assertNotNull(actual); } - @Test public void testDeserializeArrayJsonNode() throws IOException { String json = "[1.6, 2.3]"; @@ -1239,7 +1229,6 @@ public void testDeserializeArrayJsonNode() throws IOException { assertEquals(actualArray, expectedArray); } - @Test public void testDeserializeArrayJsonNode1() throws IOException { JsonNode jsonNode = null; @@ -1275,8 +1264,8 @@ public void testFormSerializationAnnotation() throws IOException { Map formParameters = new HashMap<>(); formParameters.put("date", formDateTime); - List> formFields = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.PLAIN); + List> formFields = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.PLAIN); assertNotNull(formFields); } @@ -1292,44 +1281,40 @@ public void testFormSerializationAnnotation1() throws IOException { Map formParameters = new HashMap<>(); formParameters.put("date", formDateTime); - List> formFields = - CoreHelper.prepareFormFields(formParameters, ArraySerializationFormat.PLAIN); + List> formFields = CoreHelper.prepareFormFields(formParameters, + ArraySerializationFormat.PLAIN); assertNotNull(formFields); } @Test public void testSerializeXMLArray() throws IOException { String expected = XML_ARRAY.replace("\r\n", ""); - AttributesAndElements elements = - new AttributesAndElements.Builder("XMLRootName", XML_NO_OF_ATTRIBUTE, "Data", - XML_NO_OF_ELEMENT).build(); + AttributesAndElements elements = new AttributesAndElements.Builder("XMLRootName", + XML_NO_OF_ATTRIBUTE, "Data", XML_NO_OF_ELEMENT).build(); List attributesAndElements = new ArrayList<>(); attributesAndElements.add(elements); - String actual = - CoreHelper.serializeXmlArray( - attributesAndElements - .toArray(new AttributesAndElements[attributesAndElements.size()]), - "arrayOfModels", "item", AttributesAndElements.class); + String actual = CoreHelper.serializeXmlArray( + attributesAndElements + .toArray(new AttributesAndElements[attributesAndElements.size()]), + "arrayOfModels", "item", AttributesAndElements.class); assertEquals(actual.replace("\n", ""), expected); } @Test public void testSerializeXML() throws IOException { String expected = XML.replace("\r\n", ""); - AttributesAndElements elements = - new AttributesAndElements.Builder("XMLRootName", XML_NO_OF_ATTRIBUTE, "Data", - XML_NO_OF_ELEMENT).build(); + AttributesAndElements elements = new AttributesAndElements.Builder("XMLRootName", + XML_NO_OF_ATTRIBUTE, "Data", XML_NO_OF_ELEMENT).build(); - String actual = - CoreHelper.serializeXml(elements, "arrayOfModels", AttributesAndElements.class); + String actual = CoreHelper.serializeXml(elements, "arrayOfModels", + AttributesAndElements.class); assertEquals(actual.replace("\n", ""), expected); } @Test public void testDeserializeXML() throws IOException { - AttributesAndElements expected = - new AttributesAndElements.Builder("XMLRootName", XML_NO_OF_ATTRIBUTE, "Data", - XML_NO_OF_ELEMENT).build(); + AttributesAndElements expected = new AttributesAndElements.Builder("XMLRootName", + XML_NO_OF_ATTRIBUTE, "Data", XML_NO_OF_ELEMENT).build(); AttributesAndElements actual = CoreHelper.deserializeXml(XML, AttributesAndElements.class); assertEquals(actual.getNumberAttr(), expected.getNumberAttr()); @@ -1340,14 +1325,13 @@ public void testDeserializeXML() throws IOException { @Test public void testDeserializeXMLArray() throws IOException { - AttributesAndElements elements = - new AttributesAndElements.Builder("XMLRootName", XML_NO_OF_ATTRIBUTE, "Data", - XML_NO_OF_ELEMENT).build(); + AttributesAndElements elements = new AttributesAndElements.Builder("XMLRootName", + XML_NO_OF_ATTRIBUTE, "Data", XML_NO_OF_ELEMENT).build(); List expected = new ArrayList<>(); expected.add(elements); - List actual = - CoreHelper.deserializeXmlArray(XML_ARRAY, AttributesAndElements[].class); + List actual = CoreHelper.deserializeXmlArray(XML_ARRAY, + AttributesAndElements[].class); assertEquals(actual.get(0).getNumberAttr(), expected.get(0).getNumberAttr()); } @@ -1370,16 +1354,15 @@ public void testDeserializeXMLArrayTypes() throws IOException { @Test public void testJSonObjectDeserialization() throws IOException { - CoreJsonObject body = - CoreJsonObject.fromJsonString( - "{\"$id\":\"https://example.com/person.schema.json\",\"$schema\":" - + "\"https://json-schema.org/draft/2020-12/schema\",\"title\":" - + "\"Person\",\"type\":\"object\",\"properties\":" - + "{\"firstName\":{\"type\":\"string\",\"description\":" - + "\"The person's first name.\"},\"lastName\":" - + "{\"type\":\"string\",\"description\":\"The person's last n" - + "ame.\",\"test\":null},\"age\":{\"type\":\"integer\"," - + "\"description\":\"Age in years\",\"minimum\":0}}}"); + CoreJsonObject body = CoreJsonObject + .fromJsonString("{\"$id\":\"https://example.com/person.schema.json\",\"$schema\":" + + "\"https://json-schema.org/draft/2020-12/schema\",\"title\":" + + "\"Person\",\"type\":\"object\",\"properties\":" + + "{\"firstName\":{\"type\":\"string\",\"description\":" + + "\"The person's first name.\"},\"lastName\":" + + "{\"type\":\"string\",\"description\":\"The person's last n" + + "ame.\",\"test\":null},\"age\":{\"type\":\"integer\"," + + "\"description\":\"Age in years\",\"minimum\":0}}}"); String baseUri = "https://localhost:3000"; StringBuilder queryBuilder = new StringBuilder(baseUri + "/query"); @@ -1410,52 +1393,51 @@ public void testJSonValueDeserialization() throws IOException { } private Map getComplexType() throws IOException { - Map complexType = - CoreHelper.deserialize( - "{\"key1\": {\"numberListType\":[555,666,777],\"numberMapType\":" - + "{\"num1\":1,\"num3\":2,\"num2\":3},\"innerComplexType" - + "\":{\"stringType\":\"MyString1\",\"booleanTyp" - + "e\":true,\"dateTimeType\":\"1994-11-06T08:49:37Z\"" - + ",\"dateType\":\"1994-02-13\",\"uuidType\":" - + "\"a5e48529-745b-4dfb-aac0-a7d844debd8b\"," - + "\"longType\":500000000,\"precisionType\":5.43," - + "\"objectType\":{\"long2\":1000000000,\"long1\":500000000}," - + "\"stringListType\":[\"Item1\",\"Item2\"]}," - + "\"innerComplexListType\":[{\"stringTyp" - + "e\":\"MyString1\",\"booleanType\":true,\"dateTimeType\":" - + "\"1994-11-06T08:49:37Z\",\"dateType\":\"1994-02-13\"," - + "\"uuidType\":\"a5e48529-745b-4dfb-aac0-a7d844debd" - + "8b\",\"longType\":500000000,\"precisionType\":5.43," - + "\"objectType\":{\"long2\":1000000000,\"long1\":500000000}" - + ",\"stringListType\":[\"Item1\",\"Item2\"]},{\"string" - + "Type\":\"MyString2\",\"booleanType\":false," - + "\"dateTimeType\":\"1994-11-07T08:49:37Z\",\"dateType\":" - + "\"1994-02-12\",\"uuidType\":\"b46ba2d3-b4ac-4b40-ae62-6326e88c" - + "89a6\",\"longType\":1000000000,\"precisionType\":5.43," - + "\"objectType\":{\"bool1\":true,\"bool2\":false}," - + "\"stringListType\":[\"Item1\",\"Item2\"]}]}, \"key2\": {" - + "\"numberListType\":[555,666,777],\"numberMapType\":" - + "{\"num1\":1,\"num3\":2,\"num2\":3},\"innerComplexType\":" - + "{\"stringType\":\"MyString1\",\"booleanType\":true," - + "\"dateTimeType\":\"1994-11-06T08:49:37Z\",\"dateType\":" - + "\"1994-02-13\",\"uuidType\":\"a5e48529-745b-4dfb-aac0-" - + "a7d844debd8b\",\"longType\":500000000,\"precisionType\":" - + "5.43,\"objectType\":{\"long2\":1000000000,\"long1\":500000000}" - + ",\"stringListType\":[\"Item1\",\"Item2\"]}," - + "\"innerComplexListType\":[{\"stringType\":\"MyString1\"," - + "\"booleanType\":true,\"dateTimeType\":\"1994-11-06T08" - + ":49:37Z\",\"dateType\":\"1994-02-13\",\"uuidType\":" - + "\"a5e48529-745b-4dfb-aac0-a7d844debd8b\",\"longTy" - + "pe\":500000000,\"precisionType\":5.43,\"objectType\"" - + ":{\"long2\":1000000000,\"long1\":500000000},\"stringListType\"" - + ":[\"Item1\",\"Item2\"]},{\"stringType\":\"MySt" - + "ring2\",\"booleanType\":false,\"dateTimeType\":" - + "\"1994-11-07T08:49:37Z\",\"dateType\":\"1994-02-12\"," - + "\"uuidType\":\"b46ba2d3-b4ac-4b40-ae62-6326e88c89a6\",\"long" - + "Type\":1000000000,\"precisionType\":5.43,\"objectType\":" - + "{\"bool1\":true,\"bool2\":false},\"stringListType\":[\"Item1\"," - + "\"Item2\"]}]}}", - new TypeReference>() {}); + Map complexType = CoreHelper + .deserialize("{\"key1\": {\"numberListType\":[555,666,777],\"numberMapType\":" + + "{\"num1\":1,\"num3\":2,\"num2\":3},\"innerComplexType" + + "\":{\"stringType\":\"MyString1\",\"booleanTyp" + + "e\":true,\"dateTimeType\":\"1994-11-06T08:49:37Z\"" + + ",\"dateType\":\"1994-02-13\",\"uuidType\":" + + "\"a5e48529-745b-4dfb-aac0-a7d844debd8b\"," + + "\"longType\":500000000,\"precisionType\":5.43," + + "\"objectType\":{\"long2\":1000000000,\"long1\":500000000}," + + "\"stringListType\":[\"Item1\",\"Item2\"]}," + + "\"innerComplexListType\":[{\"stringTyp" + + "e\":\"MyString1\",\"booleanType\":true,\"dateTimeType\":" + + "\"1994-11-06T08:49:37Z\",\"dateType\":\"1994-02-13\"," + + "\"uuidType\":\"a5e48529-745b-4dfb-aac0-a7d844debd" + + "8b\",\"longType\":500000000,\"precisionType\":5.43," + + "\"objectType\":{\"long2\":1000000000,\"long1\":500000000}" + + ",\"stringListType\":[\"Item1\",\"Item2\"]},{\"string" + + "Type\":\"MyString2\",\"booleanType\":false," + + "\"dateTimeType\":\"1994-11-07T08:49:37Z\",\"dateType\":" + + "\"1994-02-12\",\"uuidType\":\"b46ba2d3-b4ac-4b40-ae62-6326e88c" + + "89a6\",\"longType\":1000000000,\"precisionType\":5.43," + + "\"objectType\":{\"bool1\":true,\"bool2\":false}," + + "\"stringListType\":[\"Item1\",\"Item2\"]}]}, \"key2\": {" + + "\"numberListType\":[555,666,777],\"numberMapType\":" + + "{\"num1\":1,\"num3\":2,\"num2\":3},\"innerComplexType\":" + + "{\"stringType\":\"MyString1\",\"booleanType\":true," + + "\"dateTimeType\":\"1994-11-06T08:49:37Z\",\"dateType\":" + + "\"1994-02-13\",\"uuidType\":\"a5e48529-745b-4dfb-aac0-" + + "a7d844debd8b\",\"longType\":500000000,\"precisionType\":" + + "5.43,\"objectType\":{\"long2\":1000000000,\"long1\":500000000}" + + ",\"stringListType\":[\"Item1\",\"Item2\"]}," + + "\"innerComplexListType\":[{\"stringType\":\"MyString1\"," + + "\"booleanType\":true,\"dateTimeType\":\"1994-11-06T08" + + ":49:37Z\",\"dateType\":\"1994-02-13\",\"uuidType\":" + + "\"a5e48529-745b-4dfb-aac0-a7d844debd8b\",\"longTy" + + "pe\":500000000,\"precisionType\":5.43,\"objectType\"" + + ":{\"long2\":1000000000,\"long1\":500000000},\"stringListType\"" + + ":[\"Item1\",\"Item2\"]},{\"stringType\":\"MySt" + + "ring2\",\"booleanType\":false,\"dateTimeType\":" + + "\"1994-11-07T08:49:37Z\",\"dateType\":\"1994-02-12\"," + + "\"uuidType\":\"b46ba2d3-b4ac-4b40-ae62-6326e88c89a6\",\"long" + + "Type\":1000000000,\"precisionType\":5.43,\"objectType\":" + + "{\"bool1\":true,\"bool2\":false},\"stringListType\":[\"Item1\"," + + "\"Item2\"]}]}}", new TypeReference>() { + }); return complexType; } }