diff options
author | siddharth0905 <siddharth.singh4@amdocs.com> | 2018-08-21 17:55:30 +0530 |
---|---|---|
committer | Vitaly Emporopulo <Vitaliy.Emporopulo@amdocs.com> | 2018-09-13 11:00:08 +0000 |
commit | c58f445fcef56a6440f3b21d54b390700623c48c (patch) | |
tree | 9540ba4f1c7c2ec92c07ce2abcd04d02e06033cc /openecomp-be/lib | |
parent | 7678396a1df3122d80d838c958d857f03e2aefbb (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')
11 files changed, 1079 insertions, 637 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; + } } - } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java index 2d9766799d..c6d87def2b 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/CommonMethodsTest.java @@ -16,100 +16,285 @@ package org.openecomp.core.utilities; -import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertNotNull; +import static org.testng.Assert.assertNull; +import static org.testng.Assert.assertTrue; +import java.util.AbstractMap; +import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.testng.Assert.*; +import org.apache.commons.lang3.ArrayUtils; +import org.testng.Assert; +import org.testng.annotations.Test; public class CommonMethodsTest { - private static final String[] ARRAY = { "A", "B", "C" }; - - @Test - public void testPrintStackTrace() { - - String trace = CommonMethods.printStackTrace(); - assertTrue(trace.contains("org.openecomp.core.utilities" + - ".CommonMethods.printStackTrace(CommonMethods.java:")); - assertTrue(trace.contains("org.openecomp.core.utilities" + - ".CommonMethodsTest.testPrintStackTrace(CommonMethodsTest.java")); - } - - @Test - public void testArrayToCommaSeparatedString() { - assertEquals(CommonMethods.arrayToCommaSeparatedString(ARRAY), "A,B,C"); - } - - @Test - public void testArrayToCommaSeparatedStringEmpty() { - assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[0]), ""); - } - - @Test - public void testArrayToCommaSeparatedStringNulls() { - assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] { null, null }), "null,null"); - } - - @Test - public void testArrayToCommaSeparatedStringEmptyStrings() { - assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] { "", "" }), ","); - } - - @Test(expectedExceptions = NullPointerException.class) - public void testArrayToCommaSeparatedStringNull() { - CommonMethods.arrayToCommaSeparatedString(null); - } - - @Test - public void testArrayToSeparatedString() { - assertEquals(CommonMethods.arrayToSeparatedString(ARRAY, '/'),"A/B/C"); - } - - @Test - public void testArrayToSeparatedStringEmpty() { - assertEquals(CommonMethods.arrayToSeparatedString(new String[0], '/'),""); - } - - @Test - public void testArrayToSeparatedStringNulls() { - assertEquals(CommonMethods.arrayToSeparatedString(new String[] {null, null}, '/'),"null/null"); - } - - @Test - public void testArrayToSeparatedStringEmptyStrings() { - assertEquals(CommonMethods.arrayToSeparatedString(new String[] {"", ""}, '/'),"/"); - } - - @Test(expectedExceptions = NullPointerException.class) - public void testArrayToSeparatedStringNull() { - CommonMethods.arrayToSeparatedString(null, '/'); - } - - @Test - public void testCollectionToCommaSeparatedString() { - assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(ARRAY)), "A,B,C"); - } - - @Test - public void testCollectionToCommaSeparatedStringNulls() { - assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(null, null)), "null,null"); - } - - @Test - public void testCollectionToCommaSeparatedStringEmptyStrings() { - assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList("", "")), ","); - } - - @Test - public void testCollectionToCommaSeparatedStringEmtpy() { - assertEquals(CommonMethods.collectionToCommaSeparatedString(Collections.emptySet()), ""); - } - - @Test(expectedExceptions = NullPointerException.class) - public void testCollectionToCommaSeparatedStringNull() { - assertNull(CommonMethods.collectionToCommaSeparatedString(null)); - } + private static final String[] ARRAY = {"A", "B", "C"}; + private static final String JAVA_LANG_STRING = "java.lang.String"; + + @Test + public void testPrintStackTrace() { + + String trace = CommonMethods.printStackTrace(); + assertTrue(trace.contains("org.openecomp.core.utilities" + + ".CommonMethods.printStackTrace(CommonMethods.java:")); + assertTrue(trace.contains("org.openecomp.core.utilities" + + ".CommonMethodsTest.testPrintStackTrace(CommonMethodsTest.java")); + } + + @Test + public void testArrayToCommaSeparatedString() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(ARRAY), "A,B,C"); + } + + @Test + public void testArrayToCommaSeparatedStringEmpty() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[0]), ""); + } + + @Test + public void testArrayToCommaSeparatedStringNulls() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] {null, null}), "null,null"); + } + + @Test + public void testArrayToCommaSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.arrayToCommaSeparatedString(new String[] {"", ""}), ","); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testArrayToCommaSeparatedStringNull() { + CommonMethods.arrayToCommaSeparatedString(null); + } + + @Test + public void testArrayToSeparatedString() { + assertEquals(CommonMethods.arrayToSeparatedString(ARRAY, '/'), "A/B/C"); + } + + @Test + public void testArrayToSeparatedStringEmpty() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[0], '/'), ""); + } + + @Test + public void testArrayToSeparatedStringNulls() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[] {null, null}, '/'), "null/null"); + } + + @Test + public void testArrayToSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.arrayToSeparatedString(new String[] {"", ""}, '/'), "/"); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testArrayToSeparatedStringNull() { + CommonMethods.arrayToSeparatedString(null, '/'); + } + + @Test + public void testCollectionToCommaSeparatedString() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(ARRAY)), "A,B,C"); + } + + @Test + public void testCollectionToCommaSeparatedStringNulls() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList(null, null)), "null,null"); + } + + @Test + public void testCollectionToCommaSeparatedStringEmptyStrings() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Arrays.asList("", "")), ","); + } + + @Test + public void testCollectionToCommaSeparatedStringEmtpy() { + assertEquals(CommonMethods.collectionToCommaSeparatedString(Collections.emptySet()), ""); + } + + @Test(expectedExceptions = NullPointerException.class) + public void testCollectionToCommaSeparatedStringNull() { + assertNull(CommonMethods.collectionToCommaSeparatedString(null)); + } + + @Test + public void testNextUuId() { + assertNotNull(CommonMethods.nextUuId()); + } + + @Test + public void testConcatBothValuePresent() { + String []firstArray = {"1", "2"}; + String []secondArray = {"3", "4"}; + + String []resultArray = CommonMethods.concat(firstArray, secondArray); + + Assert.assertEquals(resultArray.length, 4); + Assert.assertTrue(ArrayUtils.contains(resultArray, secondArray[0]) + && ArrayUtils.contains(resultArray, firstArray[0])); + } + + @Test + public void testConcatBothFirstValuePresent() { + String []firstArray = {"1", "2"}; + + String []resultArray = CommonMethods.concat(firstArray, null); + + Assert.assertEquals(resultArray.length, 2); + Assert.assertTrue(Arrays.asList(resultArray).containsAll(Arrays.asList(firstArray))); + } + + @Test + public void testConcatBothSecondValuePresent() { + String []secondArray = {"3", "4"}; + + String []resultArray = CommonMethods.concat(null, secondArray); + + Assert.assertEquals(resultArray.length, 2); + Assert.assertTrue(Arrays.asList(resultArray).containsAll(Arrays.asList(secondArray))); + } + + @Test + public void testConcatBothValueNull() { + Assert.assertNull(CommonMethods.concat(null, null)); + } + + @Test + public void testNewInstance() { + Object obj = CommonMethods.newInstance(JAVA_LANG_STRING); + Assert.assertNotNull(obj); + Assert.assertTrue(obj instanceof String); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNewInstanceIncorrectClassProvided() { + Assert.assertNull(CommonMethods.newInstance("java.lang.Stringss")); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNewInstanceClassNotProvided() { + Assert.assertNull(CommonMethods.newInstance(null, Object.class)); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testNewInstanceObjectNotProvided() { + Assert.assertNull(CommonMethods.newInstance(JAVA_LANG_STRING, null)); + } + + @Test(expectedExceptions = ClassCastException.class) + public void testNewInstanceClassCastException() { + Assert.assertNull(CommonMethods.newInstance(JAVA_LANG_STRING, ArrayList.class)); + } + + @Test(expectedExceptions = RuntimeException.class) + public void testNewInstanceInvalidClassProvided() { + Assert.assertNull(CommonMethods.newInstance(List.class)); + } + + @Test + public void testListToSeparatedString() { + String str = "Concat,String"; + String result = CommonMethods.listToSeparatedString( + Stream.of("Concat", "String").collect(Collectors.toList()), ','); + + Assert.assertNotNull(result); + Assert.assertEquals(str, result); + } + + @Test + public void testDuplicateStringWithDelimiter() { + String duplicateStr = CommonMethods.duplicateStringWithDelimiter("Duplicate", '#', 4); + + Assert.assertNotNull(duplicateStr); + + String[] duplicateStrArray = duplicateStr.split("#"); + Assert.assertTrue(duplicateStr.contains("Duplicate")); + Assert.assertEquals(duplicateStrArray.length, 4); + } + + @Test + public void testRoSingleElement() { + Set<String> stringSet = CommonMethods.toSingleElementSet("Set Element"); + Assert.assertNotNull(stringSet); + Assert.assertTrue(stringSet.contains("Set Element")); + } + + @Test + public void testMergeListsOfMap() { + Map<String, String> map1 = new HashMap<>(); + map1.put("Port1", "NeutronPort_CP_1"); + map1.put("Port2", "NeutronPort_CP_2"); + + Map<String, String> map2 = new HashMap<>(); + map2.put("Server1", "NovaServer_1"); + map2.put("Server2", "NovaServer_2"); + + List<Map<String, String>> list1 = Stream.of(map1, map2).collect(Collectors.toList()); + + Map<String, String> map3 = new HashMap<>(); + map3.put("Port3", "NeutronPort_CP_3"); + map3.put("Port4", "NeutronPort_CP_4"); + + Map<String, String> map4 = new HashMap<>(); + map4.put("Server3", "NovaServer_3"); + map4.put("Server4", "NovaServer_4"); + map4.put("Server2", "NovaServer_2"); + + List<Map<String, String>> list2 = Stream.of(map3, map4).collect(Collectors.toList()); + + List<Map<String, String>> resultList = CommonMethods.mergeListsOfMap(list1, list2); + + Assert.assertEquals(resultList.size(), 6); + + //Verify for duplicate key + int count = 0; + for(Map<String, String> map : resultList) { + if(map.containsKey("Server2")) + count++; + } + + Assert.assertEquals(1, count); + } + + @Test + public void testMergeLists() { + List<String> list1 = Stream.of("First", "Second").collect(Collectors.toList()); + List<String> list2 = Stream.of("Third", "Fourth").collect(Collectors.toList()); + + List<String> resultList = CommonMethods.mergeLists(list1, list2); + + Assert.assertEquals(resultList.size(), 4); + Assert.assertTrue(resultList.containsAll(list1)); + Assert.assertTrue(resultList.containsAll(list2)); + } + + @Test + public void testMergeMaps() { + Map<String, String> map1 = Stream.of(new AbstractMap.SimpleEntry<>("Port", "Neutron"), + new AbstractMap.SimpleEntry<>("Compute", "NOVA")) + .collect(Collectors.toMap( + AbstractMap.SimpleEntry::getKey, + AbstractMap.SimpleEntry::getValue)); + + Map<String, String> map2 = Stream.of(new AbstractMap.SimpleEntry<>("VLAN", "VMI"), + new AbstractMap.SimpleEntry<>("Volume", "Cinder"), + new AbstractMap.SimpleEntry<>("Port", "VMI")) + .collect(Collectors.toMap( + AbstractMap.SimpleEntry::getKey, + AbstractMap.SimpleEntry::getValue)); + + Map<String, String> resultMap = CommonMethods.mergeMaps(map1, map2); + Assert.assertEquals(resultMap.size(), 4); + Assert.assertEquals(resultMap.get("Port"), "VMI"); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java index 57d69b1b68..1b06f37a16 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileContentHandlerTest.java @@ -1,13 +1,20 @@ package org.openecomp.core.utilities.file; -import org.testng.Assert; -import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; +import java.io.ByteArrayInputStream; import java.io.IOException; +import java.util.AbstractMap; import java.util.Arrays; +import java.util.Map; import java.util.Optional; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.testng.Assert.*; +import org.testng.Assert; +import org.testng.annotations.Test; /** * @author EVITALIY @@ -18,7 +25,7 @@ public class FileContentHandlerTest { private static final String FILE_NAME = "test-file.txt"; @Test - public void testProcessFileContent() throws Exception { + public void testProcessFileContent() { final int size = 13; FileContentHandler contentHandler = new FileContentHandler(); @@ -42,15 +49,71 @@ public class FileContentHandlerTest { } @Test - public void testProcessEmptyFileContent() throws Exception { + public void testProcessEmptyFileContent() { FileContentHandler contentHandler = new FileContentHandler(); contentHandler.addFile(FILE_NAME, new byte[0]); assertFalse(contentHandler.processFileContent(FILE_NAME, Optional::isPresent)); } @Test - public void testProcessNoFileContent() throws Exception { + public void testProcessNoFileContent() { FileContentHandler contentHandler = new FileContentHandler(); assertFalse(contentHandler.processFileContent("filename", Optional::isPresent)); } + + @Test + public void testAddFiles() { + FileContentHandler contentHandler = new FileContentHandler(); + contentHandler.addFile("org/openecomp/core/utilities/file/testFileUtils.txt", + new ByteArrayInputStream(new byte[100])); + + Assert.assertNotNull(contentHandler.getFiles()); + Assert.assertTrue(contentHandler.getFiles().containsKey("org/openecomp/core/utilities/file/testFileUtils.txt")); + } + + @Test + public void testSetFiles() { + FileContentHandler contentHandler = new FileContentHandler(); + Map<String, byte[]> fileMap = Stream.of(new AbstractMap.SimpleEntry<>("file1", new byte[0]), + new AbstractMap.SimpleEntry<>("file2", new byte[0])) + .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); + + contentHandler.setFiles(fileMap); + + Assert.assertEquals(contentHandler.getFiles().size(), 2); + Assert.assertEquals(contentHandler.getFileList().size(), 2); + Assert.assertFalse(contentHandler.isEmpty()); + contentHandler.remove("file1"); + Assert.assertFalse(contentHandler.containsFile("file1")); + } + + @Test + public void testAddAll() { + FileContentHandler contentHandler = new FileContentHandler(); + FileContentHandler contentHandler1 = createFileHandlerContent(); + + contentHandler.addAll(contentHandler1); + + Assert.assertTrue(contentHandler1.containsFile("file1")); + Assert.assertEquals(contentHandler.getFiles().size(), 2); + } + + @Test + public void testSetFilesUsingFIleContentHandlerObject() { + FileContentHandler contentHandler1 = createFileHandlerContent(); + + FileContentHandler contentHandler = new FileContentHandler(); + contentHandler.setFiles(contentHandler1); + + Assert.assertEquals(contentHandler.getFiles().size(), 2); + } + + private FileContentHandler createFileHandlerContent() { + FileContentHandler contentHandler1 = new FileContentHandler(); + Map<String, byte[]> fileMap = Stream.of(new AbstractMap.SimpleEntry<>("file1", new byte[0]), + new AbstractMap.SimpleEntry<>("file2", new byte[0])) + .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue)); + contentHandler1.putAll(fileMap); + return contentHandler1; + } }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java index 15ba6293ef..74c1b1424d 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/file/FileUtilsTest.java @@ -16,18 +16,25 @@ package org.openecomp.core.utilities.file; -import org.apache.commons.io.IOUtils; -import org.testng.annotations.Test; +import static org.testng.Assert.assertEquals; +import static org.testng.Assert.assertFalse; +import static org.testng.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.io.InputStream; +import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Map; import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.Stream; -import static org.testng.Assert.*; +import org.apache.commons.io.IOUtils; +import org.testng.Assert; +import org.testng.annotations.Test; /** * @author EVITALIY @@ -48,22 +55,22 @@ public class FileUtilsTest { }; @Test - public void testReadViaInputStreamWithSlash() throws Exception { + public void testReadViaInputStreamWithSlash() { assertTrue(FileUtils.readViaInputStream(TEST_RESOURCE, TEST_FUNCTION) > 0); } @Test - public void testReadViaInputStreamWithoutSlash() throws Exception { + public void testReadViaInputStreamWithoutSlash() { assertTrue(FileUtils.readViaInputStream(TEST_RESOURCE, TEST_FUNCTION) > 0); } @Test(expectedExceptions = NullPointerException.class) - public void testReadViaInputStreamNull() throws Exception { + public void testReadViaInputStreamNull() { FileUtils.readViaInputStream((String) null, TEST_FUNCTION); } @Test(expectedExceptions = IllegalArgumentException.class) - public void testReadViaInputStreamNotFound() throws Exception { + public void testReadViaInputStreamNotFound() { FileUtils.readViaInputStream("notfound.txt", TEST_FUNCTION); } @@ -91,10 +98,100 @@ public class FileUtilsTest { } @Test - public void testIsValidYamlExtension() throws IOException { + public void testIsValidYamlExtension() { assertTrue(FileUtils.isValidYamlExtension("yaml")); assertTrue(FileUtils.isValidYamlExtension("yml")); assertFalse(FileUtils.isValidYamlExtension("yml1")); assertFalse(FileUtils.isValidYamlExtension("zip")); } + + @Test + public void testGetFileWithoutExtention() { + Assert.assertEquals(FileUtils.getFileWithoutExtention("test.txt"), "test"); + } + + @Test + public void testGetFileWithoutExtentionContainsNoExtension() { + Assert.assertEquals(FileUtils.getFileWithoutExtention("test"), "test"); + } + + @Test + public void testGetFileExtention() { + Assert.assertEquals(FileUtils.getFileExtension("test.txt"), "txt"); + } + + @Test + public void testGetNetworkPackageName() { + Assert.assertEquals(FileUtils.getNetworkPackageName("heat.zip"), "heat"); + } + + @Test + public void testGetNetworkPackageNameWithoutExtension() { + Assert.assertNull(FileUtils.getNetworkPackageName("heat")); + } + + @Test + public void testToByteArrayNullStream() { + Assert.assertNotNull(FileUtils.toByteArray(null)); + } + + @Test + public void testGetAllLocations() { + List<URL> urlList = FileUtils.getAllLocations("org/openecomp/core/utilities/file/testFileUtils.txt"); + Assert.assertNotNull(urlList); + Assert.assertEquals(urlList.size(), 1); + } + + @Test + public void testConvertToBytesNullObject() { + Assert.assertNotNull(FileUtils.convertToBytes(null, null)); + } + + @Test + public void testConvertToBytes() { + byte[] bytesArray = FileUtils.convertToBytes(Stream.of("Json", "Util", "Test").collect(Collectors.toList()), + FileUtils.FileExtension.YAML); + + Assert.assertNotNull(bytesArray); + } + + @Test + public void testConvertToBytesNotYaml() { + byte[] bytesArray = FileUtils.convertToBytes(Stream.of("Json", "Util", "Test").collect(Collectors.toList()), + FileUtils.FileExtension.JSON); + + Assert.assertNotNull(bytesArray); + } + + @Test + public void testConvertToInputStreamNullObject() { + Assert.assertNull(FileUtils.convertToInputStream(null, null)); + } + + @Test + public void testConvertToInputStream() { + InputStream inputStream = FileUtils.convertToInputStream(Stream.of("Json", "Util", "Test") + .collect(Collectors.toList()), FileUtils.FileExtension.YAML); + + Assert.assertNotNull(inputStream); + } + + @Test(expectedExceptions = RuntimeException.class) + public void testLoadFileToInputStreamIncorrectFilePath() { + FileUtils.loadFileToInputStream("invalidfilepath"); + } + + @Test + public void testLoadFileToInputStream() throws IOException{ + int i; + StringBuilder builder = new StringBuilder(20); + InputStream inputStream = FileUtils.loadFileToInputStream( + "org/openecomp/core/utilities/file/testFileUtils.txt"); + while((i = inputStream.read())!=-1) { + builder.append((char)i); + } + + Assert.assertNotNull(inputStream); + Assert.assertEquals(builder.toString(), "hello-test"); + } }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java index 9b21f632cc..e57cdc2a80 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonSchemaDataGeneratorTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -28,50 +28,56 @@ import org.testng.annotations.Test; public class JsonSchemaDataGeneratorTest { - public static final String SCHEMA_WITHOUT_DEFAULTS = - readFromFile("jsonUtil/json_schema/aSchema.json"); + private static final String SCHEMA_WITHOUT_DEFAULTS = + readFromFile("jsonUtil/json_schema/aSchema.json"); - public static final String SCHEMA_WITH_REFS_AND_DEFAULTS = - readFromFile("jsonUtil/json_schema/schemaWithRefsAndDefaults.json"); + private static final String SCHEMA_WITH_REFS_AND_DEFAULTS = + readFromFile("jsonUtil/json_schema/schemaWithRefsAndDefaults.json"); - public static final String SCHEMA_WITH_INVALID_DEFAULT = - readFromFile("jsonUtil/json_schema/schemaWithInvalidDefault.json"); + private static final String SCHEMA_WITH_INVALID_DEFAULT = + readFromFile("jsonUtil/json_schema/schemaWithInvalidDefault.json"); - public static final String SCHEMA_NIC = - readFromFile("jsonUtil/json_schema/nicSchema.json"); + private static final String SCHEMA_NIC = + readFromFile("jsonUtil/json_schema/nicSchema.json"); - @Test - public void testSchemaWithoutDefaults() { - testGenerate(SCHEMA_WITHOUT_DEFAULTS, new JSONObject()); - } + @Test + public void testSchemaWithoutDefaults() { + testGenerate(SCHEMA_WITHOUT_DEFAULTS, new JSONObject()); + } - @Test - public void testSchemaWithRefsAndDefaults() { - testGenerate(SCHEMA_WITH_REFS_AND_DEFAULTS, - new JSONObject( - "{\"cityOfBirth\":\"Tel Aviv\",\"address\":{\"city\":\"Tel Aviv\"},\"phoneNumber\":[{\"code\":1,\"location\":\"Home\"},{\"code\":2,\"location\":\"Office\"}]}")); - } + @Test + public void testSchemaWithRefsAndDefaults() { + testGenerate(SCHEMA_WITH_REFS_AND_DEFAULTS, + new JSONObject("{\"cityOfBirth\":\"Tel Aviv\",\"address\":{\"city\":\"Tel Aviv\"}," + + "\"houseNumber\":1,\"pincode\":111111," + + "\"phoneNumber\":[{\"code\":1,\"location\":\"Home\"},{\"code\":2,\"location\":\"Office\"}]}")); + } - @Test(expectedExceptions = JSONException.class) - public void testSchemaWithInvalidDefault() { - testGenerate(SCHEMA_WITH_INVALID_DEFAULT, null); - } + @Test(expectedExceptions = JSONException.class) + public void testSchemaWithInvalidDefault() { + testGenerate(SCHEMA_WITH_INVALID_DEFAULT, null); + } - @Test - public void testNicQuestionnaireSchema() { - testGenerate(SCHEMA_NIC, - new JSONObject("{\"ipConfiguration\":{\"ipv4Required\":true,\"ipv6Required\":false}}")); - } + @Test + public void testNicQuestionnaireSchema() { + testGenerate(SCHEMA_NIC, + new JSONObject("{\"ipConfiguration\":{\"ipv4Required\":true,\"ipv6Required\":false}}")); + } - private void testGenerate(String schema, JSONObject expectedData) { - JsonSchemaDataGenerator jsonSchemaDataGenerator = new JsonSchemaDataGenerator(schema); - String data = jsonSchemaDataGenerator.generateData(); - System.out.println(data); - JSONObject dataJson = new JSONObject(data); - Assert.assertTrue(expectedData.similar(dataJson)); - } + @Test(expectedExceptions = IllegalArgumentException.class) + public void testConstructorException() { + Assert.assertNull(new JsonSchemaDataGenerator(null)); + } - private static String readFromFile(String filename) { - return FileUtils.readViaInputStream(filename, stream -> new String(FileUtils.toByteArray(stream))); - } + private void testGenerate(String schema, JSONObject expectedData) { + JsonSchemaDataGenerator jsonSchemaDataGenerator = new JsonSchemaDataGenerator(schema); + jsonSchemaDataGenerator.setIncludeDefaults(true); + String data = jsonSchemaDataGenerator.generateData(); + JSONObject dataJson = new JSONObject(data); + Assert.assertTrue(expectedData.similar(dataJson)); + } + + private static String readFromFile(String filename) { + return FileUtils.readViaInputStream(filename, stream -> new String(FileUtils.toByteArray(stream))); + } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java index d89019baec..02bc568c39 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/java/org/openecomp/core/utilities/json/JsonUtilTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,45 +21,120 @@ package org.openecomp.core.utilities.json; +import java.io.ByteArrayInputStream; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; +import java.util.stream.Stream; + import org.openecomp.core.utilities.file.FileUtils; import org.testng.Assert; import org.testng.annotations.Test; -import java.util.List; - public class JsonUtilTest { - @Test - public void testValidJsonValidate() throws Exception { + @Test + public void testValidJsonValidate() { + + + String json = FileUtils.readViaInputStream("jsonUtil/json/a.json", + stream -> new String(FileUtils.toByteArray(stream))); + + String jsonSchema = FileUtils.readViaInputStream("jsonUtil/json_schema/aSchema.json", + stream -> new String(FileUtils.toByteArray(stream))); + + List<String> validationErrors = JsonUtil.validate(json, jsonSchema); + Assert.assertNull(validationErrors); + } + + @Test + public void testInValidJsonValidate() { + + String json = FileUtils.readViaInputStream("jsonUtil/json/a_invalid.json", + stream -> new String(FileUtils.toByteArray(stream))); + String jsonSchema = FileUtils.readViaInputStream("jsonUtil/json_schema/aSchema.json", + stream -> new String(FileUtils.toByteArray(stream))); + + List<String> validationErrors = JsonUtil.validate(json, jsonSchema); + Assert.assertNotNull(validationErrors); + Assert.assertEquals(validationErrors.size(), 5); + Assert.assertEquals(validationErrors.get(0), + "#/cityOfBirth: Paris is not a valid value. Possible values: New York,Tel Aviv,London"); + Assert.assertEquals(validationErrors.get(1), + "#/address: {\"streetAddress\":\"21 2nd Street\",\"city\":\"Paris\"} is not a valid value. {\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\"} is the only possible value for this field"); + Assert.assertEquals(validationErrors.get(2), + "#/phoneNumber/0/code: expected type: Number, found: String"); + Assert.assertEquals(validationErrors.get(3), + "#/gender: expected type: String, found: Integer"); + Assert.assertEquals(validationErrors.get(4), "#/dateOfBirth: [20101988] is not valid value. " + + "It does not match pattern (0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)"); + } + + @Test(expectedExceptions = IllegalArgumentException.class) + public void testInValidJsonValidateNullJson() { + JsonUtil.validate(null, null); + } + + @Test + public void testObject2Json() { + List<String> list = Stream.of("Json", "Util", "Test").collect(Collectors.toList()); + + String resultStr = JsonUtil.object2Json(list); + Assert.assertNotNull(resultStr); + Assert.assertTrue(resultStr.contains("Json") && resultStr.contains("Util")); + } + @Test + public void testSbObject2Json() { + List<String> list = Stream.of("Json", "Util", "Test").collect(Collectors.toList()); + StringBuilder resultStr = JsonUtil.sbObject2Json(list); + Assert.assertNotNull(resultStr); + Assert.assertTrue(resultStr.toString().contains("Json") + && resultStr.toString().contains("Util")); + } - String json = FileUtils.readViaInputStream("jsonUtil/json/a.json", - stream -> new String(FileUtils.toByteArray(stream))); + @Test + public void testJson2Object() { + String inputStr = "[Json, Util, Test]"; + List list = JsonUtil.json2Object(inputStr, ArrayList.class); + Assert.assertNotNull(list); + Assert.assertEquals(list.size(), 3); + } - String jsonSchema = FileUtils.readViaInputStream("jsonUtil/json_schema/aSchema.json", - stream -> new String(FileUtils.toByteArray(stream))); + @Test(expectedExceptions = RuntimeException.class) + public void testJson2ObjectIncorrectJson() { + String inputStr = "{[Json, Util, Test]}"; + List list = JsonUtil.json2Object(inputStr, ArrayList.class); + Assert.assertNull(list); + } - List<String> validationErrors = JsonUtil.validate(json, jsonSchema); - Assert.assertNull(validationErrors); - } + @Test + public void testJson2ObjectInputStream() { + String inputStr = "[Json, Util, Test]"; + List list = JsonUtil.json2Object(new ByteArrayInputStream(inputStr.getBytes()), ArrayList.class); + Assert.assertNotNull(list); + Assert.assertEquals(list.size(), 3); + } - @Test - public void testInValidJsonValidate() throws Exception { + @Test(expectedExceptions = RuntimeException.class) + public void testJson2ObjectIncorrectJsonInputStream() { + String inputStr = "{[Json, Util, Test]}"; + List list = JsonUtil.json2Object(new ByteArrayInputStream(inputStr.getBytes()), ArrayList.class); + Assert.assertNull(list); + } - String json = FileUtils.readViaInputStream("jsonUtil/json/a_invalid.json", - stream -> new String(FileUtils.toByteArray(stream))); - String jsonSchema = FileUtils.readViaInputStream("jsonUtil/json_schema/aSchema.json", - stream -> new String(FileUtils.toByteArray(stream))); + @Test + public void testIsValidJson() { + String inputStr = "{\n" + + "\t\"obj\": [\"Json\", \"Util\", \"Test\"]\n" + + "}"; + Assert.assertTrue(JsonUtil.isValidJson(inputStr)); + } + @Test + public void testIsValidJsonFail() { + String inputStr = "{[Json, Util, Test]}"; + Assert.assertFalse(JsonUtil.isValidJson(inputStr)); + } - List<String> validationErrors = JsonUtil.validate(json, jsonSchema); - Assert.assertNotNull(validationErrors); - Assert.assertEquals(validationErrors.size(), 3); - Assert.assertEquals(validationErrors.get(0), - "#/cityOfBirth: Paris is not a valid value. Possible values: New York,Tel Aviv,London"); - Assert.assertEquals(validationErrors.get(1), - "#/address: {\"streetAddress\":\"21 2nd Street\",\"city\":\"Paris\"} is not a valid value. {\"streetAddress\":\"21 2nd Street\",\"city\":\"New York\"} is the only possible value for this field"); - Assert.assertEquals(validationErrors.get(2), - "#/phoneNumber/0/code: expected type: Number, found: String"); - } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json index 8a02522ea9..a9aaede74b 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json/a_invalid.json @@ -9,5 +9,7 @@ "code": "test" } ], + "dateOfBirth" : "20101988", + "gender" : 123, "cityOfBirth": "Paris" }
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json index a77e38df87..44b2c1c9cb 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/aSchema.json @@ -51,6 +51,13 @@ ] } }, + "dateOfBirth" : { + "type" : "string", + "pattern" : "(0?[1-9]|[12][0-9]|3[01])/(0?[1-9]|1[012])/((19|20)\\d\\d)" + }, + "gender" : { + "type" : "string" + }, "cityOfBirth" : { "$ref" : "#/definitions/city"} }, "required": [ diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json index de027b9d56..c051f79ce6 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/jsonUtil/json_schema/schemaWithRefsAndDefaults.json @@ -16,6 +16,14 @@ }, "type": "object", "properties": { + "pincode" : { + "type" : "integer", + "default": 111111 + }, + "houseNumber" : { + "type" : "number", + "default": 1 + }, "address": { "type": "object", "properties": { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/testFileUtils.txt b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/testFileUtils.txt new file mode 100644 index 0000000000..7794388502 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/test/resources/org/openecomp/core/utilities/file/testFileUtils.txt @@ -0,0 +1 @@ +hello-test
\ No newline at end of file |