From f5f13c4f6b6fe3b4d98e349dfd7db59339803436 Mon Sep 17 00:00:00 2001 From: Michael Lando Date: Sun, 19 Feb 2017 12:35:04 +0200 Subject: push addional code Change-Id: Ia427bb3460cda3a896f8faced2de69eaf3807b74 Signed-off-by: Michael Lando --- .../openecomp/core/utilities/CommonMethods.java | 555 +++++++++++++++++++++ .../core/utilities/file/FileContentHandler.java | 88 ++++ .../openecomp/core/utilities/file/FileUtils.java | 286 +++++++++++ .../utilities/json/JsonSchemaDataGenerator.java | 185 +++++++ .../openecomp/core/utilities/json/JsonUtil.java | 187 +++++++ .../openecomp/core/utilities/yaml/YamlUtil.java | 289 +++++++++++ 6 files changed, 1590 insertions(+) create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java create mode 100644 openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java (limited to 'openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java') 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 new file mode 100644 index 0000000000..343636bd15 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/CommonMethods.java @@ -0,0 +1,555 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities; + +import org.apache.commons.codec.binary.Base64; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.PrintWriter; +import java.io.Serializable; +import java.io.StringWriter; +import java.lang.reflect.Array; +import java.net.URL; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.UUID; + +/** + * This class provides auxiliary static methods. + */ +public class CommonMethods { + //private static final Logger logger = LoggerFactory.getLogger(CommonMethods.class); + + private static final char[] hexArray = "0123456789ABCDEF".toCharArray(); + + 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() { + } + + /** + * Serializes an object instance into byte array. + * + * @param object An instance to be serialized. + * @return Java array of bytes. + * @see #deserializeObject(byte[]) #deserializeObject(byte[]) + */ + public static byte[] serializeObject(Serializable object) { + ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048); + try { + ObjectOutputStream ds = new ObjectOutputStream(byteArray); + ds.writeObject(object); + ds.close(); + } catch (IOException e0) { + throw new RuntimeException(e0); + } + + return byteArray.toByteArray(); + } // serializeObject + + /** + * Deserializes an object instance. + * + * @param bytes Java array of bytes. + * @return Deserialized instance of an object. + * @see #serializeObject(Serializable) #serializeObject(Serializable) + */ + public static Serializable deserializeObject(byte[] bytes) { + Serializable obj = null; + try { + ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes)); + obj = (Serializable) stream.readObject(); + stream.close(); + } catch (IOException | ClassNotFoundException e0) { + throw new RuntimeException(e0); + } + + return obj; + } // deserializeObject + + /** + * Encodes binary byte stream to ASCII format. + * + * @param binary An Java array of bytes in binary format. + * @return An Java array of bytes encoded in ASCII format. + * @see #decode(byte[]) #decode(byte[]) + */ + public static byte[] encode(byte[] binary) { + return Base64.encodeBase64(binary); + } + + /** + * Decodes ASCII byte stream into binary format. + * + * @param ascii An Java array of bytes in ASCII format. + * @return An Java array of bytes encoded in binary format. + * @see #encode(byte[]) #encode(byte[]) + */ + public static byte[] decode(byte[] ascii) { + return Base64.decodeBase64(ascii); + } + + /** + * Checks whether the given Object is empty. + * + * @param obj Object to be checked. + * @return true - if the Object is null, false otherwise. + */ + public static boolean isEmpty(Object obj) { + return obj == null; + } + + /** + * Checks whether the given Object is empty. + * + * @param byteArray Object to be checked. + * @return true - if the Object is null, false otherwise. + */ + public static boolean isEmpty(byte[] byteArray) { + return (byteArray == null || byteArray.length == 0); + } + + /** + * Checks whether the given String is empty. + * + * @param str String object to be checked. + * @return true - if the String is null or empty, false - otherwise. + */ + public static boolean isEmpty(String str) { + return str == null || str.length() == 0; + } + + /** + * Checks whether the given Java array is empty. + * + * @param array Java array to be checked. + * @return true - if the array is null or empty, false - otherwise. + */ + public static boolean isEmpty(Object[] array) { + return array == null || array.length == 0; + } + + /** + * Checks whether the given collection is empty. + * + * @param collection A collection to be checked. + * @return true - if the collection is null or empty, false - otherwise. + */ + public static boolean isEmpty(Collection collection) { + return collection == null || collection.isEmpty(); + } + + /** + * Checks whether the given map is empty. + * + * @param map A map to be checked. + * @return true - if the map is null or empty, false - otherwise. + */ + public static boolean isEmpty(Map map) { + return map == null || map.isEmpty(); + } + + /** + * Converts the array with Long elements to the array with long (primitive type). + * + * @param array input array with Long elements. + * @return array with the same elements converted to the long type (primitive). + */ + public static long[] toPrimitive(Long[] array) { + if (array == null) { + return null; + } + + long[] result = new long[array.length]; + for (int i = 0; i < array.length; i++) { + result[i] = array[i] != null ? array[i] : 0L; + } + return result; + } + + /** + * Converts a collection to Java array. + * + * @param Java type of the collection element. + * @param col Collection to be converted to array + * @param type Java type of collection/array element + * @return An Java array of collection elements, or empty array if collection is null or empty. + */ + @SuppressWarnings("unchecked") + public static T[] toArray(Collection col, Class type) { + int length = isEmpty(col) ? 0 : col.size(); + T[] array = (T[]) Array.newInstance(type, length); + return col != null ? col.toArray(array) : array; + } + + /** + * 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) { + for (int i = 0; i < 16; i++) { + long nextByte = lng & 0xF000000000000000L; + lng <<= 4; + boolean isNegative = nextByte < 0; + nextByte = rightShift(nextByte, 60); + + if (isNegative) { + nextByte |= 0x08; + } + + buff.append(CHARS[(int) nextByte]); + } + } + + private static long rightShift(long lng, int num) { + return lng >>> num; + } + + /** + * 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 the type parameter + * @param left Elements of this array will be copied to positions from 0 to + * left.length - 1 in the target array. + * @param right Elements of this array will be copied to positions from + * left.length to left.length + right.length + * @return A newly allocate Java array that accommodates elements of source (left/right) + arraysor one of source arrays if another is empty, null - otherwise. + */ + @SuppressWarnings("unchecked") + public static T[] concat(T[] left, T[] right) { + T[] res = null; + + if (isEmpty(left)) { + res = right; + } else if (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 + + /** + * Casts an object to the class or interface represented by the specified + * Class object. The method logic is similar to Java method + * Class.cast(Object) with the only difference that unlike Java's + * version the type name of the current object instance is specified in the + * error message if casting fails to simplify error tracking. + * + * @param the type parameter + * @param the type parameter + * @param b0 An object instance to be casted to the specified Java type. + * @param cls Target Java type. + * @return Object instance safely casted to the requested Java type. + * @throws ClassCastException In case which is the given object is not instance of the + * specified Java type. + */ + @SuppressWarnings("unchecked") + public static D cast(B b0, Class cls) { + D d0 = null; + if (b0 != null) { + if (!cls.isInstance(b0)) { + throw new ClassCastException(String + .format("Failed to cast from '%s' to '%s'", b0.getClass().getName(), cls.getName())); + } else { + d0 = (D) b0; + } + } + + return d0; + } // cast + + /** + * 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 the type parameter + * @param classname the classname + * @param cls the cls + * @return the t + */ + @SuppressWarnings("unchecked") + public static T newInstance(String classname, Class cls) { + + if (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())); + } + + Class impl = (Class) temp; + + return newInstance(impl); + } catch (ClassNotFoundException e0) { + throw new IllegalArgumentException(e0); + } + } + + /** + * New instance t. + * + * @param the type parameter + * @param cls the cls + * @return the t + */ + public static T newInstance(Class cls) { + try { + return cls.newInstance(); + } catch (InstantiationException e0) { + throw new RuntimeException(e0); + } catch (IllegalAccessException e0) { + throw new RuntimeException(e0); + } + } + + /** + * Gets resources path. + * + * @param resourceName the resource name + * @return the resources path + */ + public static String getResourcesPath(String resourceName) { + URL resourceUrl = CommonMethods.class.getClassLoader().getResource(resourceName); + String resourcePath = resourceUrl.getPath(); + String dirPath = resourcePath.substring(0, resourcePath.lastIndexOf("/") + 1); + + return dirPath; + } + + /** + * Gets stack trace. + * + * @param t0 the t 0 + * @return the stack trace + */ + public static String getStackTrace(Throwable t0) { + if (null == t0) { + return ""; + } + StringWriter sw = new StringWriter(); + t0.printStackTrace(new PrintWriter(sw)); + return sw.toString(); + } + + /** + * Print stack trace string. + * + * @return the string + */ + public static String printStackTrace() { + + StringWriter sw = new StringWriter(); + StackTraceElement[] trace = Thread.currentThread().getStackTrace(); + for (StackTraceElement traceElement : trace) { + sw.write("\t " + traceElement); + sw.write(System.lineSeparator()); + } + String str = sw.toString(); + try { + sw.close(); + } catch (IOException e0) { + System.err.println(e0); + } + return str; + + } + + /** + * Is equal object boolean. + * + * @param obj1 the obj 1 + * @param obj2 the obj 2 + * @return the boolean + */ + public static boolean isEqualObject(Object obj1, Object obj2) { + boolean isEqualValue = false; + if (obj1 == null && obj2 == null) { + isEqualValue = true; + } + + if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) { + isEqualValue = true; + } + return isEqualValue; + } + + /** + * 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 elementCollection) { + List list = new ArrayList<>(); + elementCollection.stream().forEach(element -> list.add(element)); + return listToSeparatedString(list, ','); + } + + /** + * 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 listToSeparatedString(Arrays.asList(arr), separator); + } + + /** + * 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 list, char separator) { + String res = null; + if (null != list) { + StringBuilder sb = new StringBuilder(); + int sz = list.size(); + for (int i = 0; i < sz; i++) { + if (i > 0) { + sb.append(separator); + } + sb.append(list.get(i)); + } + res = sb.toString(); + } + return res; + } + + /** + * 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) { + String res = null; + StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < numberOfDuplications; i++) { + if (i > 0) { + sb.append(separator); + } + sb.append(arg); + } + res = sb.toString(); + return res; + } + + /** + * Bytes to hex string. + * + * @param bytes the bytes + * @return the string + */ + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v0 = bytes[j] & 0xFF; + int x0 = j << 1; + hexChars[x0] = hexArray[v0 >>> 4]; + hexChars[x0 + 1] = hexArray[v0 & 0x0F]; + } + return new String(hexChars); + } + + /** + * To single element set set. + * + * @param 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 Set toSingleElementSet(T element) { + return Collections.singleton(element); + + } + + +} + diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java new file mode 100644 index 0000000000..67a79875d4 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileContentHandler.java @@ -0,0 +1,88 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.file; + +import org.apache.commons.collections4.MapUtils; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +public class FileContentHandler { + private Map files = new HashMap<>(); + + /** + * Gets file content. + * + * @param fileName the file name + * @return the file content + */ + public InputStream getFileContent(String fileName) { + + byte[] content = files.get(fileName); + if (content == null || content.length == 0) { + return null; + } + + ByteArrayInputStream is = new ByteArrayInputStream(content); + return is; + } + + public void addFile(String fileName, byte[] contect) { + files.put(fileName, contect); + } + + public void addFile(String fileName, InputStream is) { + + files.put(fileName, FileUtils.toByteArray(is)); + } + + public void setFiles(FileContentHandler extFiles) { + extFiles.getFileList().stream() + .forEach(fileName -> this.addFile(fileName, extFiles.getFileContent(fileName))); + } + + public Set getFileList() { + return files.keySet(); + } + + public void putAll(Map files) { + this.files = files; + } + + public void addAll(FileContentHandler other) { + this.files.putAll(other.files); + } + + public boolean isEmpty() { + return MapUtils.isEmpty(this.files); + } + + public void remove(String fileName) { + files.remove(fileName); + } + + public boolean containsFile(String fileName) { + return files.containsKey(fileName); + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java new file mode 100644 index 0000000000..72fa9ac7b8 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/file/FileUtils.java @@ -0,0 +1,286 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.file; + +import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.core.utilities.yaml.YamlUtil; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.zip.ZipEntry; +import java.util.zip.ZipInputStream; + +/** + * The type File utils. + */ +public class FileUtils { + + /** + * Gets file input stream. + * + * @param fileName the file name + * @return the file input stream + */ + public static InputStream getFileInputStream(String fileName) { + URL urlFile = FileUtils.class.getClassLoader().getResource(fileName); + InputStream is; + try { + assert urlFile != null; + is = urlFile.openStream(); + } catch (IOException exception) { + throw new RuntimeException(exception); + } + return is; + } + + /** + * Gets file input streams. + * + * @param fileName the file name + * @return the file input streams + */ + public static List getFileInputStreams(String fileName) { + Enumeration urlFiles; + List streams = new ArrayList<>(); + InputStream is; + URL url; + try { + urlFiles = FileUtils.class.getClassLoader().getResources(fileName); + while (urlFiles.hasMoreElements()) { + url = urlFiles.nextElement(); + is = url.openStream(); + streams.add(is); + } + + + } catch (IOException exception) { + throw new RuntimeException(exception); + } + return streams; + } + + /** + * Convert to bytes byte [ ]. + * + * @param object the object + * @param extension the extension + * @return the byte [ ] + */ + public static byte[] convertToBytes(Object object, FileExtension extension) { + if (object != null) { + if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) { + return new YamlUtil().objectToYaml(object).getBytes(); + } else { + return JsonUtil.object2Json(object).getBytes(); + } + } else { + return new byte[]{}; + } + } + + /** + * Convert to input stream input stream. + * + * @param object the object + * @param extension the extension + * @return the input stream + */ + public static InputStream convertToInputStream(Object object, FileExtension extension) { + if (object != null) { + + byte[] content; + + if (extension.equals(FileExtension.YAML) || extension.equals(FileExtension.YML)) { + content = new YamlUtil().objectToYaml(object).getBytes(); + } else { + content = JsonUtil.object2Json(object).getBytes(); + + } + return new ByteArrayInputStream(content); + } else { + return null; + } + } + + /** + * Load file to input stream input stream. + * + * @param fileName the file name + * @return the input stream + */ + public static InputStream loadFileToInputStream(String fileName) { + URL urlFile = FileUtils.class.getClassLoader().getResource(fileName); + try { + Enumeration en = FileUtils.class.getClassLoader().getResources(fileName); + while (en.hasMoreElements()) { + urlFile = en.nextElement(); + } + } catch (IOException | NullPointerException exception) { + throw new RuntimeException(exception); + } + try { + if (urlFile != null) { + return urlFile.openStream(); + } else { + throw new RuntimeException(); + } + } catch (IOException | NullPointerException exception) { + throw new RuntimeException(exception); + } + + } + + /** + * To byte array byte [ ]. + * + * @param input the input + * @return the byte [ ] + */ + public static byte[] toByteArray(InputStream input) { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + try { + copy(input, output); + } catch (IOException exception) { + throw new RuntimeException( + "error will convertion input stream to byte array:" + exception.getMessage()); + } + return output.toByteArray(); + } + + /** + * Copy int. + * + * @param input the input + * @param output the output + * @return the int + * @throws IOException the io exception + */ + public static int copy(InputStream input, OutputStream output) throws IOException { + long count = copyLarge(input, output); + return count > 2147483647L ? -1 : (int) count; + } + + private static long copyLarge(InputStream input, OutputStream output) throws IOException { + return copyLarge(input, output, new byte[4096]); + } + + private static long copyLarge(InputStream input, OutputStream output, byte[] buffer) + throws IOException { + long count = 0L; + + int n1; + if (input == null) { + return count; + } + for (; -1 != (n1 = input.read(buffer)); count += (long) n1) { + output.write(buffer, 0, n1); + } + + return count; + + + } + + /** + * Gets file without extention. + * + * @param fileName the file name + * @return the file without extention + */ + public static String getFileWithoutExtention(String fileName) { + if (!fileName.contains(".")) { + return fileName; + } + return fileName.substring(0, fileName.lastIndexOf(".")); + } + + /** + * Gets file content map from zip. + * + * @param zipData the zip data + * @return the file content map from zip + * @throws IOException the io exception + */ + public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws IOException { + ZipEntry zipEntry; + FileContentHandler mapFileContent = new FileContentHandler(); + try { + ZipInputStream inputZipStream; + + byte[] fileByteContent; + String currentEntryName; + inputZipStream = new ZipInputStream(new ByteArrayInputStream(zipData)); + + while ((zipEntry = inputZipStream.getNextEntry()) != null) { + currentEntryName = zipEntry.getName(); + fileByteContent = FileUtils.toByteArray(inputZipStream); + mapFileContent.addFile(currentEntryName, fileByteContent); + } + + } catch (RuntimeException exception) { + throw new IOException(exception); + } + return mapFileContent; + } + + /** + * The enum File extension. + */ + public enum FileExtension { + + /** + * Json file extension. + */ + JSON("json"), + /** + * Yaml file extension. + */ + YAML("yaml"), + /** + * Yml file extension. + */ + YML("yml"); + + private String displayName; + + FileExtension(String displayName) { + this.displayName = displayName; + } + + /** + * Gets display name. + * + * @return the display name + */ + public String getDisplayName() { + return displayName; + } + } + + +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java new file mode 100644 index 0000000000..8968eeb323 --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonSchemaDataGenerator.java @@ -0,0 +1,185 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.json; + +import org.json.JSONException; +import org.json.JSONObject; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.HashMap; +import java.util.Map; + +/** + * The type Json schema data generator. + */ +public class JsonSchemaDataGenerator { + + private static final String ROOT = "root"; + private static final Logger logger = LoggerFactory.getLogger(JsonSchemaDataGenerator.class); + /** + * The Include defaults. + */ + boolean includeDefaults = true; + private JSONObject root; + private Map referencesData; + + /** + * Instantiates a new Json schema data generator. + * + * @param jsonSchema the json schema + */ + public JsonSchemaDataGenerator(String jsonSchema) { + if (jsonSchema == null) { + throw new IllegalArgumentException("Input string jsonSchema can not be null"); + } + root = new JSONObject(jsonSchema); + } + + /** + * Sets include defaults. + * + * @param includeDefaults the include defaults + */ + public void setIncludeDefaults(boolean includeDefaults) { + this.includeDefaults = includeDefaults; + } + + /** + * Generates json data that conform to the schema according to turned on flags. + * + * @return json that conform to the schema. + */ + public String generateData() { + referencesData = new HashMap<>(); + JSONObject data = new JSONObject(); + + generateData(ROOT, root, + data); // "root" is dummy name to represent the top level object (which, as apposed to + // inner objects, doesn't have a name in the schema) + return data.has(ROOT) ? data.get(ROOT).toString() : data.toString(); + } + + private void generateData(String propertyName, JSONObject property, JSONObject propertyData) { + if (property.has(JsonSchemaKeyword.TYPE)) { + String propertyType = property.getString(JsonSchemaKeyword.TYPE); + if (JsonSchemaKeyword.OBJECT.equals(propertyType)) { + generateObjectData(propertyName, property, propertyData); + } else { + generatePrimitiveData(propertyType, propertyName, property, propertyData); + } + } else if (property.has(JsonSchemaKeyword.REF)) { + generateReferenceData(propertyName, property.getString(JsonSchemaKeyword.REF), propertyData); + } + } + + private void generateObjectData(String propertyName, JSONObject property, + JSONObject propertyData) { + JSONObject subProperties = property.getJSONObject(JsonSchemaKeyword.PROPERTIES); + + JSONObject subPropertiesData = new JSONObject(); + for (String subPropertyName : subProperties.keySet()) { + generateData(subPropertyName, subProperties.getJSONObject(subPropertyName), + subPropertiesData); + } + + if (subPropertiesData.length() > 0) { + propertyData.put(propertyName, subPropertiesData); + } + } + + private void generateReferenceData(String propertyName, String referencePath, + JSONObject propertyData) { + if (referencesData.containsKey(referencePath)) { + Object referenceData = referencesData.get(referencePath); + if (referenceData != null) { + propertyData.put(propertyName, referenceData); + } + } else { + generateData(propertyName, resolveReference(referencePath), propertyData); + referencesData.put(referencePath, propertyData.opt(propertyName)); + } + } + + private JSONObject resolveReference(String referencePath) { + String[] keys = referencePath.replaceFirst("#/", "").split("/"); + + JSONObject reference = root; + for (String key : keys) { + reference = reference.getJSONObject(key); + } + return reference; + } + + private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, + JSONObject propertyData) { + if (includeDefaults) { + populateWithDefaultValue(propertyType, propertyName, property, propertyData); + } + } + + private void populateWithDefaultValue(String propertyType, String propertyName, + JSONObject property, JSONObject propertyData) { + if (!property.has(JsonSchemaKeyword.DEFAULT)) { + return; + } + try { + switch (propertyType) { + case JsonSchemaKeyword.ARRAY: + propertyData.put(propertyName, property.getJSONArray(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.BOOLEAN: + propertyData.put(propertyName, property.getBoolean(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.INTEGER: + propertyData.put(propertyName, property.getInt(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.NUMBER: + propertyData.put(propertyName, property.getDouble(JsonSchemaKeyword.DEFAULT)); + break; + case JsonSchemaKeyword.STRING: + propertyData.put(propertyName, property.getString(JsonSchemaKeyword.DEFAULT)); + break; + default: + break; + } + } catch (JSONException e0) { + Object defaultValue = property.get(JsonSchemaKeyword.DEFAULT); + logger.error(String.format( + "Invalid schema: '%s' property type is '%s' but it has a default value which is not: %s.", + propertyName, propertyType, defaultValue), e0); + throw e0; + } + } + + private static class JsonSchemaKeyword { + private static final String DEFAULT = "default"; + private static final String TYPE = "type"; + private static final String PROPERTIES = "properties"; + private static final String ARRAY = "array"; + private static final String BOOLEAN = "boolean"; + private static final String INTEGER = "integer"; + private static final String NUMBER = "number"; + private static final String STRING = "string"; + private static final String OBJECT = "object"; + private static final String REF = "$ref"; + } +} 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 new file mode 100644 index 0000000000..6ae3677a8d --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/json/JsonUtil.java @@ -0,0 +1,187 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.json; + + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonIOException; +import com.google.gson.JsonParser; +import com.google.gson.JsonSyntaxException; + +import org.apache.commons.collections.CollectionUtils; +import org.everit.json.schema.EnumSchema; +import org.everit.json.schema.Schema; +import org.everit.json.schema.ValidationException; +import org.everit.json.schema.loader.SchemaLoader; +import org.json.JSONObject; +import org.openecomp.core.utilities.CommonMethods; + +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 { + + /** + * Object 2 json string. + * + * @param obj the obj + * @return the string + */ + //TODO: refactor all other ugly code to use this + public static String object2Json(Object obj) { + return sbObject2Json(obj).toString(); + + } + + /** + * Sb object 2 json string buffer. + * + * @param obj the obj + * @return the string buffer + */ + public static StringBuffer sbObject2Json(Object obj) { + return new StringBuffer((new GsonBuilder()).setPrettyPrinting().create().toJson(obj)); + } + + /** + * Json 2 object t. + * + * @param the type parameter + * @param json the json + * @param classOfT the class of t + * @return the t + */ + public static T json2Object(String json, Class classOfT) { + T type; + try { + try (Reader br = new StringReader(json)) { + type = new Gson().fromJson(br, classOfT); + } catch (IOException e0) { + throw e0; + } + } catch (JsonIOException | JsonSyntaxException | IOException e0) { + throw new RuntimeException(e0); + } + return type; + } + + /** + * Json 2 object t. + * + * @param the type parameter + * @param is the is + * @param classOfT the class of t + * @return the t + */ + public static T json2Object(InputStream is, Class classOfT) { + T type; + try { + try (Reader br = new BufferedReader(new InputStreamReader(is))) { + type = new Gson().fromJson(br, classOfT); + } + } catch (JsonIOException | JsonSyntaxException | IOException e0) { + throw new RuntimeException(e0); + } finally { + if (is != null) { + try { + is.close(); + } catch (IOException ignore) { + //do nothing + } + } + } + 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) { + return false; + } + } + + /** + * Validate list. + * + * @param json the json + * @param jsonSchema the json schema + * @return the list + */ + public static List validate(String json, String jsonSchema) { + List validationErrors = validateUsingEverit(json, jsonSchema); + return validationErrors == null ? null + : validationErrors.stream().map(JsonUtil::mapValidationExceptionToMessage) + .collect(Collectors.toList()); + } + + private static String mapValidationExceptionToMessage(ValidationException e0) { + if (e0.getViolatedSchema() instanceof EnumSchema) { + return mapEnumViolationToMessage(e0); + } + return e0.getMessage(); + } + + private static String mapEnumViolationToMessage(ValidationException e1) { + Set possibleValues = ((EnumSchema) e1.getViolatedSchema()).getPossibleValues(); + return e1.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 List validateUsingEverit(String json, String 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; + } +} diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java new file mode 100644 index 0000000000..56261f08de --- /dev/null +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/yaml/YamlUtil.java @@ -0,0 +1,289 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * 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. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.core.utilities.yaml; + +import org.openecomp.core.utilities.CommonMethods; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.yaml.snakeyaml.DumperOptions; +import org.yaml.snakeyaml.TypeDescription; +import org.yaml.snakeyaml.Yaml; +import org.yaml.snakeyaml.constructor.Constructor; +import org.yaml.snakeyaml.introspector.BeanAccess; +import org.yaml.snakeyaml.introspector.Property; +import org.yaml.snakeyaml.introspector.PropertyUtils; +import org.yaml.snakeyaml.nodes.MappingNode; +import org.yaml.snakeyaml.nodes.NodeTuple; +import org.yaml.snakeyaml.nodes.Tag; +import org.yaml.snakeyaml.parser.ParserException; +import org.yaml.snakeyaml.representer.Representer; + +import java.beans.IntrospectionException; +import java.io.IOException; +import java.io.InputStream; +import java.util.AbstractMap; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.Map; +import java.util.Set; + +/** + * The type Yaml util. + */ +public class YamlUtil { + + private static Logger logger = LoggerFactory.getLogger(YamlUtil.class); + + /** + * Yaml to object t. + * + * @param the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public T yamlToObject(String yamlContent, Class typClass) { + Constructor constructor = getConstructor(typClass); + constructor.setPropertyUtils(getPropertyUtils()); + TypeDescription yamlFileDescription = new TypeDescription(typClass); + constructor.addTypeDescription(yamlFileDescription); + Yaml yaml = new Yaml(constructor); + T yamlObj = (T) yaml.load(yamlContent); + yamlObj.toString(); + return yamlObj; + } + + /** + * Yaml to object t. + * + * @param the type parameter + * @param yamlContent the yaml content + * @param typClass the typ class + * @return the t + */ + public T yamlToObject(InputStream yamlContent, Class typClass) { + try { + Constructor constructor = getConstructor(typClass); + constructor.setPropertyUtils(getPropertyUtils()); + TypeDescription yamlFileDescription = new TypeDescription(typClass); + constructor.addTypeDescription(yamlFileDescription); + Yaml yaml = new Yaml(constructor); + T yamlObj = (T) yaml.load(yamlContent); + if (yamlObj != null) { + yamlObj.toString(); + return yamlObj; + } else { + throw new RuntimeException(); + } + } catch (Exception exception) { + logger.error("Error will trying to convert yaml to object:" + exception.getMessage()); + throw new RuntimeException(exception); + } finally { + try { + if (yamlContent != null) { + yamlContent.close(); + } + } catch (IOException ignore) { + //nothing to dd + } + } + } + + + /** + * Gets constructor. + * + * @param the type parameter + * @param typClass the typ class + * @return the constructor + */ + public Constructor getConstructor(Class typClass) { + return new StrictMapAppenderConstructor(typClass); + } + + /** + * Gets property utils. + * + * @return the property utils + */ + protected PropertyUtils getPropertyUtils() { + return new MyPropertyUtils(); + } + + /** + * Yaml to map map. + * + * @param yamlContent the yaml content + * @return the map + */ + public Map> yamlToMap(InputStream yamlContent) { + Yaml yaml = new Yaml(); + Map> yamlData = + (Map>) yaml.load(yamlContent); + return yamlData; + } + + /** + * Object to yaml string. + * + * @param the type parameter + * @param obj the obj + * @return the string + */ + public String objectToYaml(Object obj) { + DumperOptions options = new DumperOptions(); + options.setPrettyFlow(true); + options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); + Representer representer = new CustomRepresenter(); + representer.addClassTag(obj.getClass(), Tag.MAP); + representer.setPropertyUtils(new MyPropertyUtils()); + + Yaml yaml = new Yaml(representer, options); + return yaml.dump(obj); + } + + /** + * Load yaml file is input stream. + * + * @param yamlFullFileName the yaml full file name + * @return the input stream + */ + public InputStream loadYamlFileIs(String yamlFullFileName) { + return CommonMethods.class.getResourceAsStream(yamlFullFileName); + } + + /** + * Is yaml file content valid boolean. + * + * @param yamlFullFileName the yaml full file name + * @return the boolean + */ + public boolean isYamlFileContentValid(String yamlFullFileName) { + Yaml yaml = new Yaml(); + try { + Object loadResult = yaml.load(yamlFullFileName); + if (loadResult == null) { + return false; + } + return true; + } catch (Exception exception) { + return false; + } + } + + + private class CustomRepresenter extends Representer { + @Override + protected NodeTuple representJavaBeanProperty(Object javaBean, Property property, + Object propertyValue, Tag customTag) { + if (propertyValue == null) { + return null; + } else { + NodeTuple defaultNode = + super.representJavaBeanProperty(javaBean, property, propertyValue, customTag); + + return property.getName().equals("_default") + ? new NodeTuple(representData("default"), defaultNode.getValueNode()) + : defaultNode; + } + } + + @Override + protected MappingNode representJavaBean(Set properties, Object javaBean) { + //remove the bean type from the output yaml (!! ...) + if (!classTags.containsKey(javaBean.getClass())) { + addClassTag(javaBean.getClass(), Tag.MAP); + } + + return super.representJavaBean(properties, javaBean); + } + } + + + /** + * The type My property utils. + */ + public class MyPropertyUtils extends PropertyUtils { + @Override + public Property getProperty(Class type, String name) throws IntrospectionException { + if (name.equals("default")) { + name = "_default"; + } + return super.getProperty(type, name); + } + + //Unsorted properties + @Override + protected Set createPropertySet(Class type, BeanAccess beanAccess) + throws IntrospectionException { + return new LinkedHashSet(getPropertiesMap(type, + BeanAccess.FIELD).values()); + } + + } + + /** + * The type Strict map appender constructor. + */ + protected class StrictMapAppenderConstructor extends Constructor { + + /** + * Instantiates a new Strict map appender constructor. + * + * @param theRoot the the root + */ + public StrictMapAppenderConstructor(Class theRoot) { + super(theRoot); + } + + @Override + protected Map constructMapping(MappingNode node) { + try { + return super.constructMapping(node); + } catch (IllegalStateException exception) { + throw new ParserException("while parsing MappingNode", node.getStartMark(), + exception.getMessage(), node.getEndMark()); + } + } + + @Override + protected Map createDefaultMap() { + final Map delegate = super.createDefaultMap(); + return new AbstractMap() { + @Override + public Object put(Object key, Object value) { + if (delegate.containsKey(key)) { + throw new IllegalStateException("duplicate key: " + key); + } + return delegate.put(key, value); + } + + @Override + public Set> entrySet() { + return delegate.entrySet(); + } + }; + } + } +} + + + -- cgit 1.2.3-korg