From d378c37fbd1ecec7b43394926f1ca32a695e07de Mon Sep 17 00:00:00 2001 From: vasraz Date: Mon, 22 Mar 2021 15:33:06 +0000 Subject: Reformat openecomp-be Signed-off-by: Vasyl Razinkov Issue-ID: SDC-3449 Change-Id: I13e02322f8e00820cc5a1d85752caaeda9bf10d1 --- .../openecomp/core/utilities/CommonMethods.java | 56 +-- .../RequirementDefinitionDeserializer.java | 115 +++-- .../exception/NewInstanceRuntimeException.java | 1 - .../core/utilities/file/FileContentHandler.java | 10 +- .../openecomp/core/utilities/file/FileUtils.java | 477 ++++++++++----------- .../utilities/json/JsonSchemaDataGenerator.java | 253 ++++++----- .../openecomp/core/utilities/json/JsonUtil.java | 33 +- .../orchestration/OnboardingTypesEnum.java | 15 +- 8 files changed, 426 insertions(+), 534 deletions(-) (limited to 'openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib') 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 0bcdf8ebbf..6065426e9a 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 @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.utilities; import java.lang.reflect.Array; @@ -27,7 +26,6 @@ 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; @@ -38,10 +36,7 @@ import org.openecomp.core.utilities.exception.NewInstanceRuntimeException; */ 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 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. @@ -56,11 +51,9 @@ public class CommonMethods { */ public static String nextUuId() { UUID uuid = UUID.randomUUID(); - StringBuilder buff = new StringBuilder(32); long2string(uuid.getMostSignificantBits(), buff); long2string(uuid.getLeastSignificantBits(), buff); - return buff.toString(); } @@ -71,32 +64,27 @@ public class CommonMethods { value <<= 4; boolean isNegative = nextByte < 0; nextByte = nextByte >>> 60; - if (isNegative) { nextByte |= 0x08; } - buff.append(CHARS[(int) nextByte]); } } /** - * 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 + * 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 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) arrays - * or one of source arrays if another is empty, null - otherwise. + * @return A newly allocate Java array that accommodates elements of source (left/right) arrays or one of source arrays if another is empty, + * null - otherwise. */ @SuppressWarnings("unchecked") public static T[] concat(T[] left, T[] right) { T[] res; - if (ArrayUtils.isEmpty(left)) { res = right; } else if (ArrayUtils.isEmpty(right)) { @@ -106,7 +94,6 @@ public class CommonMethods { System.arraycopy(left, 0, res, 0, left.length); System.arraycopy(right, 0, res, left.length, right.length); } - return res; } // concat @@ -130,25 +117,18 @@ public class CommonMethods { */ @SuppressWarnings("unchecked") public static T newInstance(String classname, Class 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())); + throw new ClassCastException(String.format("Failed to cast from '%s' to '%s'", classname, cls.getName())); } - Class impl = (Class) temp; - return newInstance(impl); } catch (ClassNotFoundException exception) { throw new IllegalArgumentException(exception); @@ -166,8 +146,7 @@ public class CommonMethods { try { return cls.getDeclaredConstructor().newInstance(); } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) { - throw new NewInstanceRuntimeException(String.format("Could not create instance for '%s'", cls.getName()) - , ex); + throw new NewInstanceRuntimeException(String.format("Could not create instance for '%s'", cls.getName()), ex); } } @@ -236,10 +215,8 @@ public class CommonMethods { * @param numberOfDuplications the number of duplications * @return the string */ - public static String duplicateStringWithDelimiter(String arg, char separator, - int numberOfDuplications) { + 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); @@ -254,12 +231,10 @@ public class CommonMethods { * * @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. + * @return an immutable set containing only the specified object. The returned set is serializable. */ public static Set toSingleElementSet(T element) { return Collections.singleton(element); - } /** @@ -271,13 +246,11 @@ public class CommonMethods { * @param source the source * @return the list */ - public static List> mergeListsOfMap(List> target, - List> source) { + public static List> mergeListsOfMap(List> target, List> source) { List> retList = new ArrayList<>(); if (Objects.nonNull(target)) { retList.addAll(target); } - if (Objects.nonNull(source)) { for (Map sourceMap : source) { for (Map.Entry entry : sourceMap.entrySet()) { @@ -298,14 +271,12 @@ public class CommonMethods { */ public static List mergeLists(List target, List source) { List retList = new ArrayList<>(); - if (Objects.nonNull(source)) { retList.addAll(source); } if (Objects.nonNull(target)) { retList.addAll(target); } - return retList; } @@ -326,7 +297,6 @@ public class CommonMethods { found = true; } } - if (!found) { Map newMap = new HashMap<>(); newMap.put(key, value); @@ -334,7 +304,6 @@ public class CommonMethods { } } - /** * Merge maps map. * @@ -342,8 +311,7 @@ public class CommonMethods { * @param the type parameter * @param firstMap the firstMap * @param secondMap the secondMap - * @return the map - * Second Map is overridden data from the first map + * @return the map Second Map is overridden data from the first map */ public static Map mergeMaps(Map firstMap, Map secondMap) { Map retMap = new HashMap<>(); @@ -355,6 +323,4 @@ public class CommonMethods { } return retMap; } - } - diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java index 1176a6ba8b..93bc29c958 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/deserializers/RequirementDefinitionDeserializer.java @@ -19,85 +19,68 @@ */ package org.openecomp.core.utilities.deserializers; -import java.lang.reflect.Type; -import java.util.Objects; -import java.util.Optional; -import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; import com.google.gson.JsonArray; import com.google.gson.JsonDeserializationContext; import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonPrimitive; +import java.lang.reflect.Type; +import java.util.Objects; +import java.util.Optional; +import org.onap.sdc.tosca.datatypes.model.RequirementDefinition; public class RequirementDefinitionDeserializer implements JsonDeserializer { - static final String CAPABILITY = "capability"; - static final String NODE = "node"; - static final String RELATIONSHIP = "relationship"; - private static final String OCCURRENCES = "occurrences"; - - @Override - public RequirementDefinition deserialize(JsonElement jsonElement, Type type, - JsonDeserializationContext jsonDeserializationContext) { - - JsonObject jsonObject = jsonElement.getAsJsonObject(); - - RequirementDefinition requirementDefinition = new RequirementDefinition(); - setRequirementValues(jsonObject, requirementDefinition); - - Optional occurrences = handleOccurrences(jsonObject); - occurrences.ifPresent(requirementDefinition::setOccurrences); - - return requirementDefinition; - } - - - private void setRequirementValues(JsonObject jsonObject, - RequirementDefinition requirementDefinition) { - - JsonElement capabilityElement = jsonObject.get(CAPABILITY); - if (!Objects.isNull(capabilityElement)) { - requirementDefinition.setCapability(capabilityElement.getAsString()); - } - - JsonElement nodeElement = jsonObject.get(NODE); - if (!Objects.isNull(nodeElement)) { - requirementDefinition.setNode(nodeElement.getAsString()); - } - - JsonElement relationshipElement = jsonObject.get(RELATIONSHIP); - if (!Objects.isNull(relationshipElement)) { - requirementDefinition.setRelationship(relationshipElement.getAsString()); + static final String CAPABILITY = "capability"; + static final String NODE = "node"; + static final String RELATIONSHIP = "relationship"; + private static final String OCCURRENCES = "occurrences"; + + @Override + public RequirementDefinition deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) { + JsonObject jsonObject = jsonElement.getAsJsonObject(); + RequirementDefinition requirementDefinition = new RequirementDefinition(); + setRequirementValues(jsonObject, requirementDefinition); + Optional occurrences = handleOccurrences(jsonObject); + occurrences.ifPresent(requirementDefinition::setOccurrences); + return requirementDefinition; } - } - - private Optional handleOccurrences(JsonObject jsonObject) { - JsonElement occurrencesElement = jsonObject.get(OCCURRENCES); - - if(Objects.isNull(occurrencesElement)){ - return Optional.empty(); + private void setRequirementValues(JsonObject jsonObject, RequirementDefinition requirementDefinition) { + JsonElement capabilityElement = jsonObject.get(CAPABILITY); + if (!Objects.isNull(capabilityElement)) { + requirementDefinition.setCapability(capabilityElement.getAsString()); + } + JsonElement nodeElement = jsonObject.get(NODE); + if (!Objects.isNull(nodeElement)) { + requirementDefinition.setNode(nodeElement.getAsString()); + } + JsonElement relationshipElement = jsonObject.get(RELATIONSHIP); + if (!Objects.isNull(relationshipElement)) { + requirementDefinition.setRelationship(relationshipElement.getAsString()); + } } - JsonArray occurrences = occurrencesElement.getAsJsonArray(); - Object[] fixedOccurrences = new Object[occurrences.size()]; - - for (int i = 0; i < occurrences.size(); i++) { - JsonElement currElement = occurrences.get(i); - - // values inside occurrences array can be either String or Integer - if (currElement.isJsonPrimitive()) { - JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive(); - - if (jsonPrimitive.isNumber()) { - fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue(); - } else { - fixedOccurrences[i] = jsonPrimitive.getAsString(); + private Optional handleOccurrences(JsonObject jsonObject) { + JsonElement occurrencesElement = jsonObject.get(OCCURRENCES); + if (Objects.isNull(occurrencesElement)) { + return Optional.empty(); + } + JsonArray occurrences = occurrencesElement.getAsJsonArray(); + Object[] fixedOccurrences = new Object[occurrences.size()]; + for (int i = 0; i < occurrences.size(); i++) { + JsonElement currElement = occurrences.get(i); + // values inside occurrences array can be either String or Integer + if (currElement.isJsonPrimitive()) { + JsonPrimitive jsonPrimitive = currElement.getAsJsonPrimitive(); + if (jsonPrimitive.isNumber()) { + fixedOccurrences[i] = jsonPrimitive.getAsNumber().intValue(); + } else { + fixedOccurrences[i] = jsonPrimitive.getAsString(); + } + } } - } + return Optional.of(fixedOccurrences); } - - return Optional.of(fixedOccurrences); - } } diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java index 386486ff9e..97191fd2a5 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/exception/NewInstanceRuntimeException.java @@ -16,7 +16,6 @@ * SPDX-License-Identifier: Apache-2.0 * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.exception; public class NewInstanceRuntimeException extends RuntimeException { 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 index 2a3a3bd19e..89f1f3a293 100644 --- 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 @@ -17,7 +17,6 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.file; import java.io.ByteArrayInputStream; @@ -54,7 +53,6 @@ public class FileContentHandler { if (content == null || content.length == 0) { return null; } - return new ByteArrayInputStream(content); } @@ -101,7 +99,7 @@ public class FileContentHandler { * Adds a file. * * @param filePath the file path - * @param content the file content + * @param content the file content */ public void addFile(final String filePath, final byte[] content) { files.put(filePath, content == null ? new byte[0] : content); @@ -110,7 +108,7 @@ public class FileContentHandler { /** * Adds a file. * - * @param filePath the file path + * @param filePath the file path * @param fileInputStream the file input stream */ public void addFile(final String filePath, final InputStream fileInputStream) { @@ -123,8 +121,7 @@ public class FileContentHandler { * @return a file path:content map */ public Map getFiles() { - return files.entrySet().stream().filter(entry -> entry.getValue() != null) - .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); + return files.entrySet().stream().filter(entry -> entry.getValue() != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); } public void setFiles(final Map files) { @@ -190,5 +187,4 @@ public class FileContentHandler { public boolean containsFile(final String filePath) { return files.containsKey(filePath); } - } 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 index f69a2a060a..60ff1c172a 100644 --- 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 @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.utilities.file; import java.io.ByteArrayInputStream; @@ -43,284 +42,262 @@ import org.openecomp.sdc.common.zip.exception.ZipException; */ public class FileUtils { - /** - * Allows to consume an input stream open against a resource with a given file name. - * - * @param fileName the file name - * @param function logic to be applied to the input stream - */ - public static T readViaInputStream(String fileName, Function function) { - - Objects.requireNonNull(fileName); - - // the leading slash doesn't make sense and doesn't work when used with a class loader - URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") - ? fileName.substring(1) : fileName); - if (resource == null) { - throw new IllegalArgumentException("Resource not found: " + fileName); + /** + * Allows to consume an input stream open against a resource with a given file name. + * + * @param fileName the file name + * @param function logic to be applied to the input stream + */ + public static T readViaInputStream(String fileName, Function function) { + Objects.requireNonNull(fileName); + // the leading slash doesn't make sense and doesn't work when used with a class loader + URL resource = FileUtils.class.getClassLoader().getResource(fileName.startsWith("/") ? fileName.substring(1) : fileName); + if (resource == null) { + throw new IllegalArgumentException("Resource not found: " + fileName); + } + return readViaInputStream(resource, function); } - return readViaInputStream(resource, function); - } - - /** - * Allows to consume an input stream open against a resource with a given URL. - * - * @param urlFile the url file - * @param function logic to be applied to the input stream - */ - public static T readViaInputStream(URL urlFile, Function function) { - - Objects.requireNonNull(urlFile); - try (InputStream is = urlFile.openStream()) { - return function.apply(is); - } catch (IOException exception) { - throw new RuntimeException(exception); + /** + * Allows to consume an input stream open against a resource with a given URL. + * + * @param urlFile the url file + * @param function logic to be applied to the input stream + */ + public static T readViaInputStream(URL urlFile, Function function) { + Objects.requireNonNull(urlFile); + try (InputStream is = urlFile.openStream()) { + return function.apply(is); + } catch (IOException exception) { + throw new RuntimeException(exception); + } } - } - - /** - * Gets file input streams. - * - * @param fileName the file name - * @return the file input streams - */ - public static List getAllLocations(String fileName) { - - List urls = new LinkedList<>(); - Enumeration urlFiles; - - try { - urlFiles = FileUtils.class.getClassLoader().getResources(fileName); - while (urlFiles.hasMoreElements()) { - urls.add(urlFiles.nextElement()); - } - - } catch (IOException exception) { - throw new RuntimeException(exception); + /** + * Gets file input streams. + * + * @param fileName the file name + * @return the file input streams + */ + public static List getAllLocations(String fileName) { + List urls = new LinkedList<>(); + Enumeration urlFiles; + try { + urlFiles = FileUtils.class.getClassLoader().getResources(fileName); + while (urlFiles.hasMoreElements()) { + urls.add(urlFiles.nextElement()); + } + } catch (IOException exception) { + throw new RuntimeException(exception); + } + return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls); } - return urls.isEmpty() ? Collections.emptyList() : Collections.unmodifiableList(urls); - } - - /** - * 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 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; + /** + * 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 = Thread.currentThread().getContextClassLoader().getResource(fileName); - try { - Enumeration en = Thread.currentThread().getContextClassLoader().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); + /** + * Load file to input stream input stream. + * + * @param fileName the file name + * @return the input stream + */ + public static InputStream loadFileToInputStream(String fileName) { + URL urlFile = Thread.currentThread().getContextClassLoader().getResource(fileName); + try { + Enumeration en = Thread.currentThread().getContextClassLoader().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) { - if (input == null) { - return new byte[0]; - } - try { - return IOUtils.toByteArray(input); - } catch (IOException exception) { - throw new RuntimeException( - "error while converting input stream to byte array", exception); + /** + * To byte array byte [ ]. + * + * @param input the input + * @return the byte [ ] + */ + public static byte[] toByteArray(InputStream input) { + if (input == null) { + return new byte[0]; + } + try { + return IOUtils.toByteArray(input); + } catch (IOException exception) { + throw new RuntimeException("error while converting input stream to byte array", exception); + } } - } - /** - * 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; + /** + * 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('.')); } - return fileName.substring(0, fileName.lastIndexOf('.')); - } - public static String getFileExtension(String filename) { - return FilenameUtils.getExtension(filename); - } - - public static String getNetworkPackageName(String filename) { - String[] split = filename.split("\\."); - String name = null; - if (split.length > 1) { - name = split[0]; + public static String getFileExtension(String filename) { + return FilenameUtils.getExtension(filename); } - return name; - } - - /** - * Gets file content map from zip. - * - * @param zipData the zip data - * @return the file content map from zip - * @throws ZipException when an error occurs while extracting zip files - */ - public static FileContentHandler getFileContentMapFromZip(byte[] zipData) - throws ZipException { - final Map zipFileAndByteMap = ZipUtils.readZip(zipData, true); - final FileContentHandler fileContentHandler = new FileContentHandler(); - zipFileAndByteMap.forEach((path, bytes) -> { - if (bytes == null) { - fileContentHandler.addFolder(path); - } else { - fileContentHandler.addFile(path, bytes); - } - }); - return fileContentHandler; - } - - /** - * The enum File extension. - */ - public enum FileExtension { + public static String getNetworkPackageName(String filename) { + String[] split = filename.split("\\."); + String name = null; + if (split.length > 1) { + name = split[0]; + } + return name; + } /** - * Json file extension. - */ - JSON("json"), - /** - * Yaml file extension. + * Gets file content map from zip. + * + * @param zipData the zip data + * @return the file content map from zip + * @throws ZipException when an error occurs while extracting zip files */ - YAML("yaml"), + public static FileContentHandler getFileContentMapFromZip(byte[] zipData) throws ZipException { + final Map zipFileAndByteMap = ZipUtils.readZip(zipData, true); + final FileContentHandler fileContentHandler = new FileContentHandler(); + zipFileAndByteMap.forEach((path, bytes) -> { + if (bytes == null) { + fileContentHandler.addFolder(path); + } else { + fileContentHandler.addFile(path, bytes); + } + }); + return fileContentHandler; + } + /** - * Yml file extension. + * Write files and folders map to disk in the given path + * + * @param fileContentHandler the file content handler + * @param dir the dir + * @return a map containing file names and their absolute paths + * @throws IOException the io exception */ - YML("yml"); - - private final String displayName; - - FileExtension(String displayName) { - this.displayName = displayName; + public static Map writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler, final Path dir) + throws IOException { + final File dirFile = dir.toFile(); + final Map filePaths = new HashMap<>(); + File file; + for (final String folderPath : fileContentHandler.getFolderList()) { + file = new File(dirFile, folderPath); + filePaths.put(folderPath, file.getAbsolutePath()); + if (!file.exists() && !file.mkdirs()) { + throw new IOException("Could not create directory " + file.getAbsolutePath()); + } + } + for (final Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) { + file = new File(dirFile, fileEntry.getKey()); + filePaths.put(fileEntry.getKey(), file.getAbsolutePath()); + final byte[] fileBytes = fileEntry.getValue(); + if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { + throw new IOException("Could not create parent directory for " + file.getAbsolutePath()); + } + try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) { + fop.write(fileBytes); + fop.flush(); + } + } + return filePaths; } /** - * Gets display name. + * Verify whether the provided extension is valid Yaml/Yml extension or not. * - * @return the display name + * @param fileExtension the file extension + * @return the boolean */ - public String getDisplayName() { - return displayName; + public static boolean isValidYamlExtension(String fileExtension) { + return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) || fileExtension + .equalsIgnoreCase(FileExtension.YAML.getDisplayName()); } - } - - /** - * Write files and folders map to disk in the given path - * - * @param fileContentHandler the file content handler - * @param dir the dir - * @return a map containing file names and their absolute paths - * @throws IOException the io exception - */ - public static Map writeFilesFromFileContentHandler(final FileContentHandler fileContentHandler, - final Path dir) throws IOException { - final File dirFile = dir.toFile(); - final Map filePaths = new HashMap<>(); - File file; - for (final String folderPath : fileContentHandler.getFolderList()) { - file = new File(dirFile, folderPath); - filePaths.put(folderPath, file.getAbsolutePath()); - if (!file.exists() && !file.mkdirs()) { - throw new IOException("Could not create directory " + file.getAbsolutePath()); - } - } - for (final Map.Entry fileEntry : fileContentHandler.getFiles().entrySet()) { - file = new File(dirFile, fileEntry.getKey()); - filePaths.put(fileEntry.getKey(), file.getAbsolutePath()); - final byte[] fileBytes = fileEntry.getValue(); - if (!file.getParentFile().exists() && !file.getParentFile().mkdirs()) { - throw new IOException("Could not create parent directory for " + file.getAbsolutePath()); - } - try (final FileOutputStream fop = new FileOutputStream(file.getAbsolutePath());) { - fop.write(fileBytes); - fop.flush(); - } + /** + * The enum File extension. + */ + public enum FileExtension { + /** + * Json file extension. + */ + JSON("json"), + /** + * Yaml file extension. + */ + YAML("yaml"), + /** + * Yml file extension. + */ + YML("yml"); + private final String displayName; + + FileExtension(String displayName) { + this.displayName = displayName; + } + + /** + * Gets display name. + * + * @return the display name + */ + public String getDisplayName() { + return displayName; + } } - - return filePaths; - } - - /** - * Verify whether the provided extension is valid Yaml/Yml extension or not. - * - * @param fileExtension the file extension - * @return the boolean - */ - public static boolean isValidYamlExtension(String fileExtension){ - return fileExtension.equalsIgnoreCase(FileExtension.YML.getDisplayName()) || - fileExtension.equalsIgnoreCase(FileExtension.YAML.getDisplayName()); - } - } 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 index 2db691a781..fceef8bb51 100644 --- 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 @@ -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. @@ -17,160 +17,149 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - package org.openecomp.core.utilities.json; +import java.util.HashMap; +import java.util.Map; import org.json.JSONException; import org.json.JSONObject; import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; -import java.util.HashMap; -import java.util.Map; - public class JsonSchemaDataGenerator { - private static final String ROOT = "root"; - private static final Logger logger = - LoggerFactory.getLogger(JsonSchemaDataGenerator.class); - 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"); + private static final String ROOT = "root"; + private static final Logger logger = LoggerFactory.getLogger(JsonSchemaDataGenerator.class); + 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); } - root = new JSONObject(jsonSchema); - } - 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); + public void setIncludeDefaults(boolean includeDefaults) { + this.includeDefaults = includeDefaults; } - } - - 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); + /** + * 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(); } - if (subPropertiesData.length() > 0) { - propertyData.put(propertyName, subPropertiesData); + 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 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 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 JSONObject resolveReference(String referencePath) { - String[] keys = referencePath.replaceFirst("#/", "").split("/"); - - JSONObject reference = root; - for (String key : keys) { - reference = reference.getJSONObject(key); + 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)); + } } - return reference; - } - private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, - JSONObject propertyData) { - if (includeDefaults) { - populateWithDefaultValue(propertyType, propertyName, property, propertyData); + 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 populateWithDefaultValue(String propertyType, String propertyName, - JSONObject property, JSONObject propertyData) { - if (!property.has(JsonSchemaKeyword.DEFAULT)) { - return; + private void generatePrimitiveData(String propertyType, String propertyName, JSONObject property, JSONObject propertyData) { + if (includeDefaults) { + populateWithDefaultValue(propertyType, propertyName, property, propertyData); + } } - 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 exception) { - 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), exception); - throw exception; + + 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 exception) { + 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), exception); + throw exception; + } } - } - 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"; - } + 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 index b83ad2782d..b148d6457d 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 @@ -13,7 +13,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.utilities.json; import com.google.gson.Gson; @@ -21,7 +20,6 @@ import com.google.gson.GsonBuilder; 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; @@ -32,7 +30,6 @@ 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; @@ -46,7 +43,6 @@ import org.openecomp.core.utilities.deserializers.RequirementDefinitionDeseriali import org.openecomp.sdc.logging.api.Logger; import org.openecomp.sdc.logging.api.LoggerFactory; - /** * The type Json util. */ @@ -58,8 +54,7 @@ public class JsonUtil { static { gsonBuilder = new GsonBuilder(); - gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new - RequirementDefinitionDeserializer()); + gsonBuilder.registerTypeAdapter(RequirementDefinition.class, new RequirementDefinitionDeserializer()); gson = gsonBuilder.create(); } @@ -74,7 +69,6 @@ public class JsonUtil { */ public static String object2Json(Object obj) { return sbObject2Json(obj).toString(); - } /** @@ -125,13 +119,13 @@ public class 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 { @@ -152,30 +146,25 @@ public class JsonUtil { 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()); + : 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); } - return exception.getMessage(); } private static String mapEnumViolationToMessage(ValidationException exception) { Set 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())))); + 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) { @@ -188,25 +177,21 @@ public class JsonUtil { } private static List validateUsingEverit(String json, String jsonSchema) { - LOGGER.debug( - String.format("validateUsingEverit start, json=%s, jsonSchema=%s", json, 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 CollectionUtils.isEmpty(ve.getCausingExceptions()) ? Collections.singletonList(ve) : ve.getCausingExceptions(); } return null; } private enum ValidationType { PATTERN("pattern"); - private String keyword; ValidationType(String keyword) { diff --git a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java index 1fa96103ab..4ed85f939b 100644 --- a/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java +++ b/openecomp-be/lib/openecomp-core-lib/openecomp-utilities-lib/src/main/java/org/openecomp/core/utilities/orchestration/OnboardingTypesEnum.java @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package org.openecomp.core.utilities.orchestration; import java.util.Arrays; import org.apache.commons.lang3.StringUtils; + public enum OnboardingTypesEnum { CSAR("csar"), ZIP("zip"), MANUAL("manual"), NONE("none"), SIGNED_CSAR("signed-csar"); private final String type; @@ -26,19 +26,16 @@ public enum OnboardingTypesEnum { this.type = type; } - @Override - public String toString() { - return type; - } - public static OnboardingTypesEnum getOnboardingTypesEnum(final String type) { if (StringUtils.isEmpty(type)) { return null; } - - return Arrays.stream(OnboardingTypesEnum.values()) - .filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equalsIgnoreCase(type)) + return Arrays.stream(OnboardingTypesEnum.values()).filter(onboardingTypesEnum -> onboardingTypesEnum.toString().equalsIgnoreCase(type)) .findAny().orElse(null); } + @Override + public String toString() { + return type; + } } -- cgit 1.2.3-korg