aboutsummaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp
diff options
context:
space:
mode:
authorsiddharth0905 <siddharth.singh4@amdocs.com>2018-08-21 17:55:30 +0530
committerVitaly Emporopulo <Vitaliy.Emporopulo@amdocs.com>2018-09-13 11:00:08 +0000
commitc58f445fcef56a6440f3b21d54b390700623c48c (patch)
tree9540ba4f1c7c2ec92c07ce2abcd04d02e06033cc /openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp
parent7678396a1df3122d80d838c958d857f03e2aefbb (diff)
Test coverage
Increase test coverage Change-Id: I43e3149d0d4b07dc8e260f3d5fac025197882f3a Issue-ID: SDC-1673 Signed-off-by: siddharth0905 <siddharth.singh4@amdocs.com>
Diffstat (limited to 'openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp')
-rw-r--r--openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java606
-rw-r--r--openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java326
2 files changed, 465 insertions, 467 deletions
diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
index 5a4d3cbd0d..b2cc289676 100644
--- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
+++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java
@@ -16,344 +16,342 @@
package org.openecomp.core.utilities;
+import java.lang.reflect.Array;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.UUID;
+
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
-import java.util.*;
-
-import java.lang.reflect.Array;
/**
* This class provides auxiliary static methods.
*/
public class CommonMethods {
- private static final char[] CHARS = new char[]{
- '0', '1', '2', '3', '4', '5', '6', '7',
- '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
- };
-
- /**
- * Private default constructor to prevent instantiation of the class objects.
- */
- private CommonMethods() {
- }
-
- /**
- * Checks whether the given collection is empty.
- *
- * @param collection A collection to be checked.
- * @return <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - otherwise.
- */
- public static boolean isEmpty(Collection<?> collection) {
- return collection == null || collection.isEmpty();
- }
-
- /**
- * Gets an universally unique identifier (UUID).
- *
- * @return String representation of generated UUID.
- */
- public static String nextUuId() {
- UUID uuid = UUID.randomUUID();
-
- StringBuilder buff = new StringBuilder(32);
- long2string(uuid.getMostSignificantBits(), buff);
- long2string(uuid.getLeastSignificantBits(), buff);
-
- return buff.toString();
- }
-
- private static void long2string(long lng, StringBuilder buff) {
- long value = lng;
- for (int i = 0; i < 16; i++) {
- long nextByte = value & 0xF000000000000000L;
- value <<= 4;
- boolean isNegative = nextByte < 0;
- nextByte = nextByte >>> 60;
-
- if (isNegative) {
- nextByte |= 0x08;
- }
-
- buff.append(CHARS[(int) nextByte]);
+ private static final char[] CHARS = new char[] {
+ '0', '1', '2', '3', '4', '5', '6', '7',
+ '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
+ };
+
+ /**
+ * Private default constructor to prevent instantiation of the class objects.
+ */
+ private CommonMethods() {
}
- }
-
- /**
- * Concatenates two Java arrays. The method allocates a new array and copies
- * all elements to it or returns one of input arrays if another one is
- * empty.
- *
- * @param <T> the type parameter
- * @param left Elements of this array will be copied to positions from 0 to <tt>left.length -
- * 1</tt> in the target array.
- * @param right Elements of this array will be copied to positions from <tt>left.length</tt> to
- * <tt>left.length + right.length</tt>
- * @return A newly allocate Java array that accommodates elements of source (left/right) arrays
- orone of source arrays if another is empty, <tt>null</tt> - otherwise.
- */
- @SuppressWarnings("unchecked")
- public static <T> T[] concat(T[] left, T[] right) {
- T[] res;
-
- if (ArrayUtils.isEmpty(left)) {
- res = right;
- } else if (ArrayUtils.isEmpty(right)) {
- res = left;
- } else {
- res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length);
- System.arraycopy(left, 0, res, 0, left.length);
- System.arraycopy(right, 0, res, left.length, right.length);
+
+ /**
+ * Gets an universally unique identifier (UUID).
+ *
+ * @return String representation of generated UUID.
+ */
+ public static String nextUuId() {
+ UUID uuid = UUID.randomUUID();
+
+ StringBuilder buff = new StringBuilder(32);
+ long2string(uuid.getMostSignificantBits(), buff);
+ long2string(uuid.getLeastSignificantBits(), buff);
+
+ return buff.toString();
}
- return res;
- } // concat
-
- /**
- * New instance object.
- *
- * @param classname the classname
- * @return the object
- */
- public static Object newInstance(String classname) {
- return newInstance(classname, Object.class);
- }
-
- /**
- * New instance t.
- *
- * @param <T> the type parameter
- * @param classname the classname
- * @param cls the cls
- * @return the t
- */
- @SuppressWarnings("unchecked")
- public static <T> T newInstance(String classname, Class<T> cls) {
-
- if (StringUtils.isEmpty(classname)) {
- throw new IllegalArgumentException();
+ private static void long2string(long lng, StringBuilder buff) {
+ long value = lng;
+ for (int i = 0; i < 16; i++) {
+ long nextByte = value & 0xF000000000000000L;
+ value <<= 4;
+ boolean isNegative = nextByte < 0;
+ nextByte = nextByte >>> 60;
+
+ if (isNegative) {
+ nextByte |= 0x08;
+ }
+
+ buff.append(CHARS[(int) nextByte]);
+ }
}
- if (cls == null) {
- throw new IllegalArgumentException();
+ /**
+ * Concatenates two Java arrays. The method allocates a new array and copies
+ * all elements to it or returns one of input arrays if another one is
+ * empty.
+ *
+ * @param <T> the type parameter
+ * @param left Elements of this array will be copied to positions from 0 to <tt>left.length -
+ * 1</tt> in the target array.
+ * @param right Elements of this array will be copied to positions from <tt>left.length</tt> to
+ * <tt>left.length + right.length</tt>
+ * @return A newly allocate Java array that accommodates elements of source (left/right) arrays
+ * or one of source arrays if another is empty, <tt>null</tt> - otherwise.
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T[] concat(T[] left, T[] right) {
+ T[] res;
+
+ if (ArrayUtils.isEmpty(left)) {
+ res = right;
+ } else if (ArrayUtils.isEmpty(right)) {
+ res = left;
+ } else {
+ res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length);
+ System.arraycopy(left, 0, res, 0, left.length);
+ System.arraycopy(right, 0, res, left.length, right.length);
+ }
+
+ return res;
+ } // concat
+
+ /**
+ * New instance object.
+ *
+ * @param classname the classname
+ * @return the object
+ */
+ public static Object newInstance(String classname) {
+ return newInstance(classname, Object.class);
}
- try {
- Class<?> temp = Class.forName(classname);
+ /**
+ * New instance t.
+ *
+ * @param <T> the type parameter
+ * @param classname the classname
+ * @param cls the cls
+ * @return the t
+ */
+ @SuppressWarnings("unchecked")
+ public static <T> T newInstance(String classname, Class<T> cls) {
+
+ if (StringUtils.isEmpty(classname)) {
+ throw new IllegalArgumentException();
+ }
+
+ if (cls == null) {
+ throw new IllegalArgumentException();
+ }
+
+ try {
+ Class<?> temp = Class.forName(classname);
- if (!cls.isAssignableFrom(temp)) {
- throw new ClassCastException(
- String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
- }
+ if (!cls.isAssignableFrom(temp)) {
+ throw new ClassCastException(
+ String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
+ }
- Class<? extends T> impl = (Class<? extends T>) temp;
+ Class<? extends T> impl = (Class<? extends T>) temp;
- return newInstance(impl);
- } catch (ClassNotFoundException exception) {
- throw new IllegalArgumentException(exception);
+ return newInstance(impl);
+ } catch (ClassNotFoundException exception) {
+ throw new IllegalArgumentException(exception);
+ }
}
- }
-
- /**
- * New instance t.
- *
- * @param <T> the type parameter
- * @param cls the cls
- * @return the t
- */
- public static <T> T newInstance(Class<T> cls) {
- try {
- return cls.newInstance();
- } catch (InstantiationException | IllegalAccessException exception) {
- throw new RuntimeException(exception);
+
+ /**
+ * New instance t.
+ *
+ * @param <T> the type parameter
+ * @param cls the cls
+ * @return the t
+ */
+ public static <T> T newInstance(Class<T> cls) {
+ try {
+ return cls.newInstance();
+ } catch (InstantiationException | IllegalAccessException exception) {
+ throw new RuntimeException(exception);
+ }
}
- }
-
- /**
- * Print stack trace string.
- *
- * @return the string
- */
- public static String printStackTrace() {
- StringBuilder sb = new StringBuilder();
- StackTraceElement[] trace = Thread.currentThread().getStackTrace();
- for (StackTraceElement traceElement : trace) {
- sb.append("\t ").append(traceElement);
- sb.append(System.lineSeparator());
+
+ /**
+ * Print stack trace string.
+ *
+ * @return the string
+ */
+ public static String printStackTrace() {
+ StringBuilder sb = new StringBuilder();
+ StackTraceElement[] trace = Thread.currentThread().getStackTrace();
+ for (StackTraceElement traceElement : trace) {
+ sb.append("\t ").append(traceElement);
+ sb.append(System.lineSeparator());
+ }
+ return sb.toString();
}
- return sb.toString();
- }
-
- /**
- * Converts array of strings to comma-separated string.
- *
- * @param arr array of strings
- * @return the string
- */
- public static String arrayToCommaSeparatedString(String[] arr) {
- return arrayToSeparatedString(arr, ',');
- }
-
- /**
- * Collection to comma separated string string.
- *
- * @param elementCollection the element collection
- * @return the string
- */
- public static String collectionToCommaSeparatedString(Collection<String> elementCollection) {
- return String.join(",", elementCollection);
- }
-
- /**
- * Converts array of strings to string separated with specified character.
- *
- * @param arr array of strings
- * @param separator the separator
- * @return the string
- */
- public static String arrayToSeparatedString(String[] arr, char separator) {
- return String.join(Character.toString(separator), arr);
- }
-
- /**
- * Converts array of strings to string separated with specified character.
- *
- * @param list array of strings
- * @param separator the separator
- * @return the string
- */
- public static String listToSeparatedString(List<String> list, char separator) {
- return String.join(Character.toString(separator), list);
- }
-
- /**
- * Duplicate string with delimiter string.
- *
- * @param arg the arg
- * @param separator the separator
- * @param numberOfDuplications the number of duplications
- * @return the string
- */
- public static String duplicateStringWithDelimiter(String arg, char separator,
- int numberOfDuplications) {
- StringBuilder sb = new StringBuilder();
-
- for (int i = 0; i < numberOfDuplications; i++) {
- if (i > 0) {
- sb.append(separator);
- }
- sb.append(arg);
+
+ /**
+ * Converts array of strings to comma-separated string.
+ *
+ * @param arr array of strings
+ * @return the string
+ */
+ public static String arrayToCommaSeparatedString(String[] arr) {
+ return arrayToSeparatedString(arr, ',');
}
- return sb.toString();
- }
-
- /**
- * To single element set set.
- *
- * @param <T> the class of the objects in the set
- * @param element the single element to be contained in the returned Set
- * @return an immutable set containing only the specified object. The returned set is
- serializable.
- */
- public static <T> Set<T> toSingleElementSet(T element) {
- return Collections.singleton(element);
-
- }
-
- /**
- * Merge lists of map list.
- *
- * @param <T> the type parameter
- * @param <S> the type parameter
- * @param target the target
- * @param source the source
- * @return the list
- */
- public static <T, S> List<Map<T, S>> mergeListsOfMap(List<Map<T, S>> target,
- List<Map<T, S>> source) {
- List<Map<T, S>> retList = new ArrayList<>();
- if (Objects.nonNull(target)) {
- retList.addAll(target);
+
+ /**
+ * Collection to comma separated string string.
+ *
+ * @param elementCollection the element collection
+ * @return the string
+ */
+ public static String collectionToCommaSeparatedString(Collection<String> elementCollection) {
+ return String.join(",", elementCollection);
}
- if (Objects.nonNull(source)) {
- for (Map<T, S> sourceMap : source) {
- for (Map.Entry<T, S> entry : sourceMap.entrySet()) {
- mergeEntryInList(entry.getKey(), entry.getValue(), retList);
- }
- }
+ /**
+ * Converts array of strings to string separated with specified character.
+ *
+ * @param arr array of strings
+ * @param separator the separator
+ * @return the string
+ */
+ public static String arrayToSeparatedString(String[] arr, char separator) {
+ return String.join(Character.toString(separator), arr);
}
- return retList;
- }
-
- /**
- * Merge lists list.
- *
- * @param <T> the type parameter
- * @param target the target
- * @param source the source
- * @return the list
- */
- public static <T> List<T> mergeLists(List<T> target, List<T> source) {
- List<T> retList = new ArrayList<>();
-
- if (Objects.nonNull(source)) {
- retList.addAll(source);
+
+ /**
+ * Converts array of strings to string separated with specified character.
+ *
+ * @param list array of strings
+ * @param separator the separator
+ * @return the string
+ */
+ public static String listToSeparatedString(List<String> list, char separator) {
+ return String.join(Character.toString(separator), list);
}
- if (Objects.nonNull(target)) {
- retList.addAll(target);
+
+ /**
+ * Duplicate string with delimiter string.
+ *
+ * @param arg the arg
+ * @param separator the separator
+ * @param numberOfDuplications the number of duplications
+ * @return the string
+ */
+ public static String duplicateStringWithDelimiter(String arg, char separator,
+ int numberOfDuplications) {
+ StringBuilder sb = new StringBuilder();
+
+ for (int i = 0; i < numberOfDuplications; i++) {
+ if (i > 0) {
+ sb.append(separator);
+ }
+ sb.append(arg);
+ }
+ return sb.toString();
}
- return retList;
- }
-
- /**
- * Merge entry in list.
- *
- * @param <T> the type parameter
- * @param <S> the type parameter
- * @param key the key
- * @param value the value
- * @param target the target
- */
- public static <T, S> void mergeEntryInList(T key, S value, List<Map<T, S>> target) {
- boolean found = false;
- for (Map<T, S> map : target) {
- if (map.containsKey(key)) {
- map.put(key, value);
- found = true;
- }
+ /**
+ * To single element set set.
+ *
+ * @param <T> the class of the objects in the set
+ * @param element the single element to be contained in the returned Set
+ * @return an immutable set containing only the specified object. The returned set is
+ * serializable.
+ */
+ public static <T> Set<T> toSingleElementSet(T element) {
+ return Collections.singleton(element);
+
+ }
+
+ /**
+ * Merge lists of map list.
+ *
+ * @param <T> the type parameter
+ * @param <S> the type parameter
+ * @param target the target
+ * @param source the source
+ * @return the list
+ */
+ public static <T, S> List<Map<T, S>> mergeListsOfMap(List<Map<T, S>> target,
+ List<Map<T, S>> source) {
+ List<Map<T, S>> retList = new ArrayList<>();
+ if (Objects.nonNull(target)) {
+ retList.addAll(target);
+ }
+
+ if (Objects.nonNull(source)) {
+ for (Map<T, S> sourceMap : source) {
+ for (Map.Entry<T, S> entry : sourceMap.entrySet()) {
+ mergeEntryInList(entry.getKey(), entry.getValue(), retList);
+ }
+ }
+ }
+ return retList;
}
- if (!found) {
- Map<T, S> newMap = new HashMap<>();
- newMap.put(key, value);
- target.add(newMap);
+ /**
+ * Merge lists list.
+ *
+ * @param <T> the type parameter
+ * @param target the target
+ * @param source the source
+ * @return the list
+ */
+ public static <T> List<T> mergeLists(List<T> target, List<T> source) {
+ List<T> retList = new ArrayList<>();
+
+ if (Objects.nonNull(source)) {
+ retList.addAll(source);
+ }
+ if (Objects.nonNull(target)) {
+ retList.addAll(target);
+ }
+
+ return retList;
}
- }
-
-
- /**
- * Merge maps map.
- *
- * @param <T> the type parameter
- * @param <S> the type parameter
- * @param firstMap the firstMap
- * @param secondMap the secondMap
- * @return the map
- * Second Map is overridden data from the first map
- */
- public static <T, S> Map<T, S> mergeMaps(Map<T, S> firstMap, Map<T, S> secondMap) {
- Map<T, S> retMap = new HashMap<>();
- if (MapUtils.isNotEmpty(firstMap)) {
- retMap.putAll(firstMap);
+
+ /**
+ * Merge entry in list.
+ *
+ * @param <T> the type parameter
+ * @param <S> the type parameter
+ * @param key the key
+ * @param value the value
+ * @param target the target
+ */
+ public static <T, S> void mergeEntryInList(T key, S value, List<Map<T, S>> target) {
+ boolean found = false;
+ for (Map<T, S> map : target) {
+ if (map.containsKey(key)) {
+ map.put(key, value);
+ found = true;
+ }
+ }
+
+ if (!found) {
+ Map<T, S> newMap = new HashMap<>();
+ newMap.put(key, value);
+ target.add(newMap);
+ }
}
- if (MapUtils.isNotEmpty(secondMap)) {
- retMap.putAll(secondMap);
+
+
+ /**
+ * Merge maps map.
+ *
+ * @param <T> the type parameter
+ * @param <S> the type parameter
+ * @param firstMap the firstMap
+ * @param secondMap the secondMap
+ * @return the map
+ * Second Map is overridden data from the first map
+ */
+ public static <T, S> Map<T, S> mergeMaps(Map<T, S> firstMap, Map<T, S> secondMap) {
+ Map<T, S> retMap = new HashMap<>();
+ if (MapUtils.isNotEmpty(firstMap)) {
+ retMap.putAll(firstMap);
+ }
+ if (MapUtils.isNotEmpty(secondMap)) {
+ retMap.putAll(secondMap);
+ }
+ return retMap;
}
- return retMap;
- }
}
diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
index 83ad43ca65..b83ad2782d 100644
--- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
+++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java
@@ -12,7 +12,7 @@
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
-*/
+ */
package org.openecomp.core.utilities.json;
@@ -22,6 +22,17 @@ import com.google.gson.JsonIOException;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.Reader;
+import java.io.StringReader;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
import org.apache.commons.collections4.CollectionUtils;
import org.everit.json.schema.EnumSchema;
import org.everit.json.schema.Schema;
@@ -35,186 +46,175 @@ import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeseriali
import org.openecomp.sdc.logging.api.Logger;
import org.openecomp.sdc.logging.api.LoggerFactory;
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
-import java.io.StringReader;
-import java.util.Collections;
-import java.util.List;
-import java.util.Set;
-import java.util.stream.Collectors;
-
/**
* The type Json util.
*/
public class JsonUtil {
- private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
- private static final GsonBuilder gsonBuilder;
- private static final Gson gson;
-
- static {
- gsonBuilder = new GsonBuilder();
- gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
- RequirementDefinitionDeserializer());
- gson = gsonBuilder.create();
- }
-
- private JsonUtil() {
- }
-
- /**
- * Object 2 json string.
- *
- * @param obj the obj
- * @return the string
- */
- public static String object2Json(Object obj) {
- return sbObject2Json(obj).toString();
-
- }
-
- /**
- * Sb object 2 json string builder.
- *
- * @param obj the obj
- * @return the string builder
- */
- public static StringBuilder sbObject2Json(Object obj) {
- return new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
- }
-
- /**
- * Json 2 object t.
- *
- * @param <T> the type parameter
- * @param json the json
- * @param classOfT the class of t
- * @return the t
- */
- public static <T> T json2Object(String json, Class<T> classOfT) {
- T typ;
- try {
- try (Reader br = new StringReader(json)) {
- typ = gson.fromJson(br, classOfT);
- }
- } catch (JsonIOException | JsonSyntaxException | IOException exception) {
- throw new RuntimeException(exception);
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(JsonUtil.class);
+ private static final GsonBuilder gsonBuilder;
+ private static final Gson gson;
+
+ static {
+ gsonBuilder = new GsonBuilder();
+ gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new
+ RequirementDefinitionDeserializer());
+ gson = gsonBuilder.create();
}
- return typ;
- }
-
- /**
- * Json 2 object t.
- *
- * @param <T> the type parameter
- * @param is the is
- * @param classOfT the class of t
- * @return the t
- */
- public static <T> T json2Object(InputStream is, Class<T> classOfT) {
- T type;
- try (Reader br = new BufferedReader(new InputStreamReader(is))) {
- type = new Gson().fromJson(br, classOfT);
- }
- catch (JsonIOException | JsonSyntaxException | IOException exception) {
- throw new RuntimeException(exception);
+
+ private JsonUtil() {
}
- return type;
- }
-
-
- /**
- * Is valid json boolean.
- *
- * @param json the json
- * @return the boolean
- */
- //todo check https://github.com/stleary/JSON-java as replacement for this code
- public static boolean isValidJson(String json) {
- try {
- return new JsonParser().parse(json).isJsonObject();
- } catch (JsonSyntaxException jse) {
- LOGGER.error("Invalid json, Failed to parse json", jse);
- return false;
+
+ /**
+ * Object 2 json string.
+ *
+ * @param obj the obj
+ * @return the string
+ */
+ public static String object2Json(Object obj) {
+ return sbObject2Json(obj).toString();
+
}
- }
-
- /**
- * Validate list.
- *
- * @param json the json
- * @param jsonSchema the json schema
- * @return the list
- */
- public static List<String> validate(String json, String jsonSchema) {
- List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
- return validationErrors == null ? null
- : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
- .collect(Collectors.toList());
- }
-
- private static String mapValidationExceptionToMessage(ValidationException exception) {
- Object schema = exception.getViolatedSchema();
-
- if (schema instanceof EnumSchema) {
- return mapEnumViolationToMessage(exception);
- } else if (schema instanceof StringSchema) {
- return mapStringViolationToMessage(exception);
+
+ /**
+ * Sb object 2 json string builder.
+ *
+ * @param obj the obj
+ * @return the string builder
+ */
+ public static StringBuilder sbObject2Json(Object obj) {
+ return new StringBuilder(new GsonBuilder().setPrettyPrinting().create().toJson(obj));
}
- return exception.getMessage();
- }
-
- private static String mapEnumViolationToMessage(ValidationException exception) {
- Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
- return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
- ? String.format("value. %s is the only possible value for this field",
- possibleValues.iterator().next())
- : String.format("value. Possible values: %s", CommonMethods
- .collectionToCommaSeparatedString(
- possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
- }
-
- private static String mapStringViolationToMessage(ValidationException validationException) {
- if (ValidationType.PATTERN.getKeyword().equals(validationException.getKeyword())) {
- String message = validationException.getMessage();
- String value = message.substring(message.indexOf("["), message.indexOf("]") + 1);
- return message.replace("string " + value, value + " is not valid value. It");
+ /**
+ * Json 2 object t.
+ *
+ * @param <T> the type parameter
+ * @param json the json
+ * @param classOfT the class of t
+ * @return the t
+ */
+ public static <T> T json2Object(String json, Class<T> classOfT) {
+ T typ;
+ try {
+ try (Reader br = new StringReader(json)) {
+ typ = gson.fromJson(br, classOfT);
+ }
+ } catch (JsonIOException | JsonSyntaxException | IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ return typ;
}
- return validationException.getMessage();
- }
-
- private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
- LOGGER.debug(
- String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
- if (json == null || jsonSchema == null) {
- throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
+
+ /**
+ * Json 2 object t.
+ *
+ * @param <T> the type parameter
+ * @param is the is
+ * @param classOfT the class of t
+ * @return the t
+ */
+ public static <T> T json2Object(InputStream is, Class<T> classOfT) {
+ T type;
+ try (Reader br = new BufferedReader(new InputStreamReader(is))) {
+ type = new Gson().fromJson(br, classOfT);
+ } catch (JsonIOException | JsonSyntaxException | IOException exception) {
+ throw new RuntimeException(exception);
+ }
+ return type;
}
- Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
- try {
- schemaObj.validate(new JSONObject(json));
- } catch (ValidationException ve) {
- return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
- : ve.getCausingExceptions();
+
+ /**
+ * Is valid json boolean.
+ *
+ * @param json the json
+ * @return the boolean
+ */
+ //todo check https://github.com/stleary/JSON-java as replacement for this code
+ public static boolean isValidJson(String json) {
+ try {
+ return new JsonParser().parse(json).isJsonObject();
+ } catch (JsonSyntaxException jse) {
+ LOGGER.error("Invalid json, Failed to parse json", jse);
+ return false;
+ }
}
- return null;
- }
- private enum ValidationType {
- PATTERN("pattern");
+ /**
+ * Validate list.
+ *
+ * @param json the json
+ * @param jsonSchema the json schema
+ * @return the list
+ */
+ public static List<String> validate(String json, String jsonSchema) {
+ List<ValidationException> validationErrors = validateUsingEverit(json, jsonSchema);
+ return validationErrors == null ? null
+ : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage)
+ .collect(Collectors.toList());
+ }
- private String keyword;
+ private static String mapValidationExceptionToMessage(ValidationException exception) {
+ Object schema = exception.getViolatedSchema();
- private ValidationType(String keyword) {
- this.keyword = keyword;
+ if (schema instanceof EnumSchema) {
+ return mapEnumViolationToMessage(exception);
+ } else if (schema instanceof StringSchema) {
+ return mapStringViolationToMessage(exception);
+ }
+
+ return exception.getMessage();
+ }
+
+ private static String mapEnumViolationToMessage(ValidationException exception) {
+ Set<Object> possibleValues = ((EnumSchema) exception.getViolatedSchema()).getPossibleValues();
+ return exception.getMessage().replaceFirst("enum value", possibleValues.size() == 1
+ ? String.format("value. %s is the only possible value for this field",
+ possibleValues.iterator().next())
+ : String.format("value. Possible values: %s", CommonMethods
+ .collectionToCommaSeparatedString(
+ possibleValues.stream().map(Object::toString).collect(Collectors.toList()))));
+ }
+
+ private static String mapStringViolationToMessage(ValidationException validationException) {
+ if (ValidationType.PATTERN.getKeyword().equals(validationException.getKeyword())) {
+ String message = validationException.getMessage();
+ String value = message.substring(message.indexOf("["), message.indexOf("]") + 1);
+ return message.replace("string " + value, value + " is not valid value. It");
+ }
+ return validationException.getMessage();
}
- String getKeyword() {
- return keyword;
+ private static List<ValidationException> validateUsingEverit(String json, String jsonSchema) {
+ LOGGER.debug(
+ String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, jsonSchema));
+ if (json == null || jsonSchema == null) {
+ throw new IllegalArgumentException("Input strings json and jsonSchema can not be null");
+ }
+
+ Schema schemaObj = SchemaLoader.load(new JSONObject(jsonSchema));
+ try {
+ schemaObj.validate(new JSONObject(json));
+ } catch (ValidationException ve) {
+ return CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve)
+ : ve.getCausingExceptions();
+ }
+ return null;
+ }
+
+ private enum ValidationType {
+ PATTERN("pattern");
+
+ private String keyword;
+
+ ValidationType(String keyword) {
+ this.keyword = keyword;
+ }
+
+ String getKeyword() {
+ return keyword;
+ }
}
- }
}