diff options
Diffstat (limited to 'common-app-api/src/main/java/org/openecomp/sdc/common/util')
15 files changed, 1287 insertions, 1169 deletions
diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java index a79e1ee22b..cb78b8ed9b 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/CapabilityTypeNameEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,26 +21,26 @@ package org.openecomp.sdc.common.util; public enum CapabilityTypeNameEnum { - ROOT("tosca.capabilities.Root"), - NODE("tosca.capabilities.Node"), - CONTAINER("tosca.capabilities.Container"), - ENDPOINT("tosca.capabilities.Endpoint"), - ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), - ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), - ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), - OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), - SCALABLE("tosca.capabilities.Scalable"), - BINDABLE("tosca.capabilities.network.Bindable"), - DOCKER("tosca.capabilities.Container.Docker"), - ATTACHMENT("tosca.capabilities.Attachment"); + ROOT("tosca.capabilities.Root"), + NODE("tosca.capabilities.Node"), + CONTAINER("tosca.capabilities.Container"), + ENDPOINT("tosca.capabilities.Endpoint"), + ENDPOINT_PUBLIC("tosca.capabilities.Endpoint.Public"), + ENDPOINT_ADMIN("tosca.capabilities.Endpoint.Admin"), + ENDPOINT_DATABASE("tosca.capabilities.Endpoint.Database"), + OPERATING_SYSTEM("tosca.capabilities.OperatingSystem"), + SCALABLE("tosca.capabilities.Scalable"), + BINDABLE("tosca.capabilities.network.Bindable"), + DOCKER("tosca.capabilities.Container.Docker"), + ATTACHMENT("tosca.capabilities.Attachment"); - private String capabilityName; + private String capabilityName; - CapabilityTypeNameEnum(String capName) { - this.capabilityName = capName; - } + private CapabilityTypeNameEnum(String capName) { + this.capabilityName = capName; + } - public String getCapabilityName() { - return capabilityName; - } + public String getCapabilityName() { + return capabilityName; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java index 7ff19ace72..d82538a355 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GeneralUtility.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. @@ -22,145 +22,194 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; import org.apache.commons.io.FileUtils; +import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.openecomp.sdc.common.api.Constants; +import org.openecomp.sdc.common.log.api.ILogConfiguration; +import org.slf4j.MDC; import java.io.File; import java.io.IOException; +import java.util.ArrayList; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.regex.Pattern; public class GeneralUtility { - private static final int STRING_LENGTH_MULTIPLIER = 4; - - public static boolean generateTextFile(String fileName, String fileData) { - boolean isSuccessfull = true; - try { - FileUtils.writeStringToFile(new File(fileName), fileData); - } catch (IOException e) { - isSuccessfull = false; - } - return isSuccessfull; + public static boolean generateTextFile(String fileName, String fileData) { + boolean isSuccessfull = true; + try { + FileUtils.writeStringToFile(new File(fileName), fileData); + } catch (IOException e) { + isSuccessfull = false; + } + return isSuccessfull; + } + + /** + * Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(byte[] data) { + return Base64.isBase64(data); + } + + /** + *Use with care, usage is not advised!!! + * The method only checks if String does not contain special characters + length divided by 4 with no remainder. + * The methods contained in other common libraries do the same. + */ + public static boolean isBase64Encoded(String str) { + boolean isEncoded = false; + try { + // checks if the string was properly padded to the + isEncoded = ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); + if (isEncoded) { + // If no exception is caught, then it is possibly a base64 + // encoded string + byte[] data = Base64.decodeBase64(str); + } + + } catch (Exception e) { + // If exception is caught, then it is not a base64 encoded string + isEncoded = false; + } + return isEncoded; + } + + /** + * Checks whether the passed string exceeds a limit of number of characters. + * + * @param str + * @param limit + * @return the result of comparison, or false if str is null. + */ + public static boolean isExceedingLimit(String str, int limit) { + if (str == null) { + return false; + } + return str.length() > limit; + } + + /** + * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated + * 3+1+3+1+5=13 + * + * @param strList + * @param limit + * @param delimiterLength + * - 0 if there is no delimeter. + * @return the result of comparison, or false if strList is null. + */ + public static boolean isExceedingLimit(List<String> strList, int limit, int delimiterLength) { + if (strList == null || strList.isEmpty()) { + return false; + } + int sum = 0; + int size = strList.size(); + for (int i = 0; i < size - 1; i++) { + String str = strList.get(i); + if (str != null) { + sum += str.length(); + } + sum += delimiterLength; + } + String str = strList.get(size - 1); + if (str != null) { + sum += str.length(); + } + return sum > limit; + } + + /** + * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. + * + * @param fileName + * @return extension + */ + public static String getFilenameExtension(String fileName) { + String res = Constants.EMPTY_STRING; + if (fileName != null) { + int indexOf = fileName.lastIndexOf('.'); + if (indexOf != -1 && indexOf < (fileName.length() - 1)) { + res = fileName.substring(indexOf + 1); + } + } + return res; + } + + public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { + String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); + byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); + return new String(encodeMd5); + + } + + /** + * + * @param data + * @return + */ + public static String calculateMD5Base64EncodedByString(String data) { + String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + + // encode base-64 result + byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); + return new String(encodeBase64); + } + + + /** + * + * @param String + * @return String is null or Empty + */ + public static boolean isEmptyString(String str) { + return str == null || str.trim().isEmpty(); } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(byte[] data) { - return Base64.isBase64(data); - } + public static String getEcompRequestId() { + return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID); + } - /** - * Use with care, usage is not advised!!! - * The method only checks if String does not contain special characters + length divided by 4 with no remainder. - * The methods contained in other common libraries do the same. - */ - public static boolean isBase64Encoded(String str) { - boolean isEncoded = false; - try { - // checks if the string was properly padded to the - isEncoded = ((str.length() % STRING_LENGTH_MULTIPLIER == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str))); - if (isEncoded) { - // If no exception is caught, then it is possibly a base64 - // encoded string - byte[] data = Base64.decodeBase64(str); - } - - } catch (Exception e) { - // If exception is caught, then it is not a base64 encoded string - isEncoded = false; - } - return isEncoded; - } - /** - * Checks whether the passed string exceeds a limit of number of characters. - * - * @param str - * @param limit - * @return the result of comparison, or false if str is null. - */ - public static boolean isExceedingLimit(String str, int limit) { - if (str == null) { - return false; - } - return str.length() > limit; - } - /** - * Checks the passed string list whether the cumulative length of strings and delimiters between them exceeds a limit of number of characters. For example for list ("one","two","three") with delimiter "," the length of list is calculated - * 3+1+3+1+5=13 - * - * @param strList - * @param limit - * @param delimiterLength - 0 if there is no delimeter. - * @return the result of comparison, or false if strList is null. - */ - public static boolean isExceedingLimit(List<String> strList, int limit, int delimiterLength) { - if (strList == null || strList.isEmpty()) { - return false; - } - int sum = 0; - int size = strList.size(); - for (int i = 0; i < size - 1; i++) { - String str = strList.get(i); - if (str != null) { - sum += str.length(); - } - sum += delimiterLength; - } - String str = strList.get(size - 1); - if (str != null) { - sum += str.length(); - } - return sum > limit; - } - /** - * Return the extension as the substring from the last dot. For input "kuku.txt", "txt" will be returned. If no dot is found or input is null, empty string is returned. - * - * @param fileName - * @return extension - */ - public static String getFilenameExtension(String fileName) { - String res = Constants.EMPTY_STRING; - if (fileName != null) { - int indexOf = fileName.lastIndexOf('.'); - if (indexOf != -1 && indexOf < (fileName.length() - 1)) { - res = fileName.substring(indexOf + 1); - } - } - return res; - } + public static <T extends ICategorizedElement> Map<String,Map<String,List<T>>> getCategorizedComponents(List<T> components) { - public static String calculateMD5Base64EncodedByByteArray(byte[] payload) { - String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload); - byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes()); - return new String(encodeMd5); + Map<String, Map<String, List<T>>> categorizedMap = new HashMap<>(); + components.forEach(component -> categorizeComponent(component, categorizedMap)); + return categorizedMap; + } - } + private static <T extends ICategorizedElement> void categorizeComponent(T component, Map<String, Map<String, List<T>>> categorizedMap) { + if(component.getComponentTypeAsString().equals("SERVICE")){ + categorizeService(component, categorizedMap); + }else if(component.getComponentTypeAsString().equals("RESOURCE")){ + categorizeResource(component, categorizedMap); + } + } - /** - * @param data - * @return - */ - public static String calculateMD5Base64EncodedByString(String data) { - String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data); + private static <T extends ICategorizedElement> void categorizeResource(T component, Map<String, Map<String, List<T>>> categorizedMap) { + String category = component.getCategoryName(); + String subCategory = component.getSubcategoryName(); + putComponentToMap(component, categorizedMap, category, subCategory); + } - // encode base-64 result - byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes()); - return new String(encodeBase64); - } + private static <T extends ICategorizedElement> void categorizeService(T component, Map<String, Map<String, List<T>>> categorizedMap) { + String category = "Generic"; + String subCategory = "Generic"; + putComponentToMap(component, categorizedMap, category, subCategory); + } + private static <T extends ICategorizedElement> void putComponentToMap(T component, Map<String, Map<String, List<T>>> categorizedMap, + String category, String subCategory) { - /** - * @param String - * @return String is null or Empty - */ - public static boolean isEmptyString(String str) { - return str == null || str.trim().isEmpty(); - } + Map<String, List<T>> categoryMap = categorizedMap.computeIfAbsent(category, k -> new HashMap<>()); + List<T> subCategoryList = categoryMap.computeIfAbsent(subCategory, k -> new ArrayList<>()); + subCategoryList.add(component); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java index e7877e4fad..7c3bcb6cad 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/GsonFactory.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. @@ -24,17 +24,17 @@ import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class GsonFactory { - private static Gson gson = null; + private static Gson gson = null; - public static Gson getGson() { - if (gson == null) { - synchronized (GsonFactory.class) { - if (gson == null) { - gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); - } - } - } + public static Gson getGson() { + if (gson == null) { + synchronized (GsonFactory.class) { + if (gson == null) { + gson = new GsonBuilder().disableHtmlEscaping().serializeNulls().create(); + } + } + } - return gson; - } + return gson; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java index 7474d38372..00a03de7cf 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HealthCheckUtil.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. @@ -33,7 +33,6 @@ import static org.openecomp.sdc.common.api.HealthCheckInfo.HealthCheckStatus.DOW public class HealthCheckUtil { private static Logger log = Logger.getLogger(HealthCheckUtil.class.getName()); - public boolean getAggregateStatus(List<HealthCheckInfo> healthCheckInfos, Collection<String> excludes) { boolean status = true; excludes = CollectionUtils.isEmpty(excludes) ? new ArrayList<>() : excludes; @@ -48,7 +47,7 @@ public class HealthCheckUtil { return status; } - public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos, String parentDescription) { + public String getAggregateDescription(List<HealthCheckInfo> healthCheckInfos) { StringBuilder sb = new StringBuilder(); healthCheckInfos.forEach(x -> { diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java index 5a7c426949..c9086fc272 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HtmlCleaner.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. @@ -31,81 +31,81 @@ import java.util.regex.Pattern; public class HtmlCleaner { - private static Set<String> htmlTags = new HashSet<>(); + private static Set<String> htmlTags = new HashSet<>(); - private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; + private static String patternHtmlFullTagStr = "</?\\w+((\\s+\\w+(\\s*=\\s*(?:\".*?\"|'.*?'|[\\^'\">\\s]+))?)+\\s*|\\s*)/?>"; - private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; + private static String patternHtmlTagOnlyStr = "</?(\\w+)[^>]*/?>"; - private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); + private static Pattern onlyTagPattern = Pattern.compile(patternHtmlTagOnlyStr); - private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); + private static Pattern fullTagPattern = Pattern.compile(patternHtmlFullTagStr); - static { - Tag[] allTags = HTML.getAllTags(); - for (Tag tag : allTags) { - htmlTags.add(tag.toString().toLowerCase()); - } - } + static { + Tag[] allTags = HTML.getAllTags(); + for (Tag tag : allTags) { + htmlTags.add(tag.toString().toLowerCase()); + } + } - public static String stripHtml(String input) { + public static String stripHtml(String input) { - return stripHtml(input, false); + return stripHtml(input, false); - } + } - public static String stripHtml(String input, boolean toEscape) { + public static String stripHtml(String input, boolean toEscape) { - if (input == null || input.isEmpty()) { - return input; - } + if (input == null || input.isEmpty()) { + return input; + } - Matcher matcher = onlyTagPattern.matcher(input); + Matcher matcher = onlyTagPattern.matcher(input); - Set<String> tagsToRemove = new HashSet<>(); + Set<String> tagsToRemove = new HashSet<>(); - while (matcher.find()) { + while (matcher.find()) { - int start = matcher.start(); - int end = matcher.end(); + int start = matcher.start(); + int end = matcher.end(); - String matchTag = input.substring(start, end); + String matchTag = input.substring(start, end); - int groupCount = matcher.groupCount(); + int groupCount = matcher.groupCount(); - if (groupCount > 0) { - String tag = matcher.group(1); - if (tag != null && htmlTags.contains(tag.toLowerCase())) { - if (!tagsToRemove.contains(matchTag)) { - tagsToRemove.add(matchTag); - } - } - } - } + if (groupCount > 0) { + String tag = matcher.group(1); + if (tag != null && htmlTags.contains(tag.toLowerCase())) { + if (!tagsToRemove.contains(matchTag)) { + tagsToRemove.add(matchTag); + } + } + } + } - String stripHtmlStr = removeTagsFromString(tagsToRemove, input); + String stripHtmlStr = removeTagsFromString(tagsToRemove, input); - if (stripHtmlStr != null) { - if (toEscape) { - stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); - } - } + if (stripHtmlStr != null) { + if (toEscape) { + stripHtmlStr = StringEscapeUtils.escapeHtml4(stripHtmlStr); + } + } - return stripHtmlStr; + return stripHtmlStr; - } + } - private static String removeTagsFromString(Set<String> tagsToRemove, String input) { + private static String removeTagsFromString(Set<String> tagsToRemove, String input) { - String stripStr = input; - if (input == null || tagsToRemove.isEmpty()) { - return input; - } + String stripStr = input; + if (input == null || tagsToRemove.isEmpty()) { + return input; + } - for (String tag : tagsToRemove) { - stripStr = stripStr.replaceAll(tag, ""); - } - return stripStr; - } + for (String tag : tagsToRemove) { + stripStr = stripStr.replaceAll(tag, ""); + } + return stripStr; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java index 5bd3b87fc4..d9f099876a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/HttpUtil.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. @@ -30,50 +30,50 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; public class HttpUtil { - public static Either<String, IOException> readJsonStringFromRequest(HttpServletRequest request) { - Either<String, IOException> eitherResult; - try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { - ServletInputStream reader = request.getInputStream(); - int value; - while ((value = reader.read()) != -1) { - stream.write(value); - } - eitherResult = Either.left(new String(stream.toByteArray())); - } catch (IOException e) { - eitherResult = Either.right(e); - } - return eitherResult; + public static Either<String, IOException> readJsonStringFromRequest(HttpServletRequest request) { + Either<String, IOException> eitherResult; + try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) { + ServletInputStream reader = request.getInputStream(); + int value; + while ((value = reader.read()) != -1) { + stream.write(value); + } + eitherResult = Either.left(new String(stream.toByteArray())); + } catch (IOException e) { + eitherResult = Either.right(e); + } + return eitherResult; - } + } - /** - * Builds an object from a JSON in the POST Body of the request. - */ - public static <T> Either<T, Exception> getObjectFromJson(HttpServletRequest request, Class<T> classOfT) { - Either<T, Exception> eitherResult; - try { - Either<String, IOException> eitherReadJson = readJsonStringFromRequest(request); - if (eitherReadJson.isLeft()) { - eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); - } else { - eitherResult = Either.right((Exception) eitherReadJson.right().value()); - } - } catch (Exception e) { - eitherResult = Either.right(e); - } + /** + * Builds an object from a JSON in the POST Body of the request. + */ + public static <T> Either<T, Exception> getObjectFromJson(HttpServletRequest request, Class<T> classOfT) { + Either<T, Exception> eitherResult; + try { + Either<String, IOException> eitherReadJson = readJsonStringFromRequest(request); + if (eitherReadJson.isLeft()) { + eitherResult = convertJsonStringToObject(eitherReadJson.left().value(), classOfT); + } else { + eitherResult = Either.right((Exception) eitherReadJson.right().value()); + } + } catch (Exception e) { + eitherResult = Either.right(e); + } - return eitherResult; - } + return eitherResult; + } - public static <T> Either<T, Exception> convertJsonStringToObject(String sentJson, Class<T> classOfT) { - Either<T, Exception> eitherResult; - try { - Gson gson = new GsonBuilder().setPrettyPrinting().create(); - T object = gson.fromJson(sentJson, classOfT); - eitherResult = Either.left(object); - } catch (Exception e) { - eitherResult = Either.right(e); - } - return eitherResult; - } + public static <T> Either<T, Exception> convertJsonStringToObject(String sentJson, Class<T> classOfT) { + Either<T, Exception> eitherResult; + try { + Gson gson = new GsonBuilder().setPrettyPrinting().create(); + T object = gson.fromJson(sentJson, classOfT); + eitherResult = Either.left(object); + } catch (Exception e) { + eitherResult = Either.right(e); + } + return eitherResult; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java new file mode 100644 index 0000000000..0121af702a --- /dev/null +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ICategorizedElement.java @@ -0,0 +1,15 @@ +package org.openecomp.sdc.common.util; + +import java.util.List; + +public interface ICategorizedElement { + + String getComponentTypeAsString(); + + String getCategoryName(); + + String getSubcategoryName(); + + + +} diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java index b992f7dc7c..fbf94eaaed 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/JsonUtils.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. @@ -25,38 +25,38 @@ import com.google.gson.JsonObject; public class JsonUtils { - public static String toString(JsonElement jsonElement) { + public static String toString(JsonElement jsonElement) { - if (jsonElement == null) { - return null; - } + if (jsonElement == null) { + return null; + } - if (!jsonElement.isJsonNull()) { - if (!jsonElement.isJsonObject()) { - return jsonElement.getAsString(); - } else { - return jsonElement.toString(); - } - } else { - return null; - } + if (!jsonElement.isJsonNull()) { + if (!jsonElement.isJsonObject()) { + return jsonElement.getAsString(); + } else { + return jsonElement.toString(); + } + } else { + return null; + } - } + } - public static boolean containsEntry(JsonObject json, String key) { - return json.get(key) != null; - } + public static boolean containsEntry(JsonObject json, String key) { + return json.get(key) != null; + } - public static boolean isEmptyJson(JsonObject json) { - return json.entrySet().isEmpty(); - } + public static boolean isEmptyJson(JsonObject json) { + return json.entrySet().isEmpty(); + } - public static boolean isEmptyJson(JsonElement json) { - return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); - } + public static boolean isEmptyJson(JsonElement json) { + return json.isJsonPrimitive() ? false : JsonUtils.isEmptyJson(json.getAsJsonObject()); + } - public static boolean isJsonNullOrEmpty(JsonObject json) { - return json.isJsonNull() || isEmptyJson(json); - } + public static boolean isJsonNullOrEmpty(JsonObject json) { + return json.isJsonNull() || isEmptyJson(json); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java index 758b33bbd3..bba04fa359 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/MethodActivationStatusEnum.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,5 +21,5 @@ package org.openecomp.sdc.common.util; public enum MethodActivationStatusEnum { - SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; + SUCCESS, NOT_ALLOWED, FAILED, NOT_FOUND; } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java index 7fee13fc0d..eb6c29ce4a 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/PairUtils.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. diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java index 42eb6086fa..cf49718600 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/SerializationUtils.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. @@ -26,59 +26,54 @@ import org.openecomp.sdc.be.config.BeEcompErrorManager; import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity; import org.openecomp.sdc.common.log.wrappers.Logger; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.ObjectInput; -import java.io.ObjectInputStream; -import java.io.ObjectOutput; -import java.io.ObjectOutputStream; +import java.io.*; public class SerializationUtils { - private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); + private static Logger log = Logger.getLogger(SerializationUtils.class.getName()); - private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); + private static FSTConfiguration conf = FSTConfiguration.createDefaultConfiguration(); - public static Either<byte[], Boolean> serialize(Object object) { + public static Either<byte[], Boolean> serialize(Object object) { - try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { - out.writeObject(object); - return Either.left(bos.toByteArray()); - } catch (Exception e) { - log.debug("Failed to serialize object", e); - return Either.right(false); - } - } + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutput out = new ObjectOutputStream(bos)) { + out.writeObject(object); + return Either.left(bos.toByteArray()); + } catch (Exception e) { + log.debug("Failed to serialize object", e); + return Either.right(false); + } + } - public static Either<Object, Boolean> deserialize(byte[] bytes) { + public static Either<Object, Boolean> deserialize(byte[] bytes) { - try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { - return Either.left(in.readObject()); - } catch (Exception e) { - log.debug("Failed to deserialize object", e); - return Either.right(false); - } - } + try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes); ObjectInput in = new ObjectInputStream(bis)) { + return Either.left(in.readObject()); + } catch (Exception e) { + log.debug("Failed to deserialize object", e); + return Either.right(false); + } + } - public static Either<byte[], Boolean> serializeExt(Object object) { - try { - byte[] value = conf.asByteArray(object); - return Either.left(value); - } catch (Exception e) { - return Either.right(false); - } - } + public static Either<byte[], Boolean> serializeExt(Object object) { + try { + byte[] value = conf.asByteArray(object); + return Either.left(value); + } catch (Exception e) { + return Either.right(false); + } + } - public static <T> Either<T, Boolean> deserializeExt(byte[] bytes, Class<T> clazz, String componentName) { - try { - Object object = conf.asObject(bytes); - T castObject = clazz.cast(object); - return Either.left(castObject); - } catch (Exception e) { - log.debug("Failed to deserialize object of type {} and uid {}", clazz, componentName, e); - BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); - return Either.right(false); - } - } + public static <T> Either<T, Boolean> deserializeExt(byte[] bytes, Class<T> clazz, String componentName) { + try { + Object object = conf.asObject(bytes); + T castObject = clazz.cast(object); + return Either.left(castObject); + } catch (Exception e) { + log.debug("Failed to deserialize object of type {} and uid {}",clazz,componentName, e); + BeEcompErrorManager.getInstance().logInternalUnexpectedError("DeserializeObjectFromCache", "Failed to deserialize object of type " + clazz, ErrorSeverity.WARNING); + return Either.right(false); + } + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java index 88f00f5ee4..2d07069388 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/StreamUtils.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. @@ -31,68 +31,69 @@ import java.util.stream.StreamSupport; /** * Utility Class For Actions On Streams - * + * * @author mshitrit + * */ public final class StreamUtils { - private StreamUtils() { - throw new UnsupportedOperationException(); - } - - /** - * Breaks the stream when the predicate is not met.<br> - * Does not evaluate elements after the stream breaks.<br> - * This method evaluates the stream.<br> - * - * @param stream - * @param predicate - * @return - */ - public static <T> Stream<T> takeWhilePlusOneNoEval(Stream<T> stream, Predicate<T> predicate) { - List<T> results = new ArrayList<>(); - Consumer<T> listAdder = results::add; - stream.map(e -> { - listAdder.accept(e); - return e; - }).filter(e -> !predicate.test(e)).findFirst(); - return results.stream(); - } - - public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); - } - - public static <T> Stream<T> takeWhilePlusOne(Stream<T> stream, Predicate<T> predicate) { - return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); - } - - private static <T> Spliterator<T> takeWhile(Spliterator<T> splitr, Predicate<T> predicate) { - return new MySplitIterator<>(splitr, predicate); - } - - public static class MySplitIterator<T> extends AbstractSpliterator<T> implements Spliterator<T> { - private boolean stillGoing = true; - private Spliterator<T> innerItr; - private Predicate<T> innerPred; - - private MySplitIterator(Spliterator<T> splitItr, Predicate<T> pred) { - super(splitItr.estimateSize(), 0); - innerItr = splitItr; - innerPred = pred; - } - - @Override - public boolean tryAdvance(Consumer<? super T> action) { - boolean canAdvance = true; - if (stillGoing) { - stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); - } else { - canAdvance = false; - } - return canAdvance; - } - - private Consumer<? super T> createConsumerWrapper(Consumer<? super T> action) { + private StreamUtils() { + throw new UnsupportedOperationException(); + } + + /** + * Breaks the stream when the predicate is not met.<br> + * Does not evaluate elements after the stream breaks.<br> + * This method evaluates the stream.<br> + * + * @param stream + * @param predicate + * @return + */ + public static <T> Stream<T> takeWhilePlusOneNoEval(Stream<T> stream, Predicate<T> predicate) { + List<T> results = new ArrayList<>(); + Consumer<T> listAdder = results::add; + stream.map(e -> { + listAdder.accept(e); + return e; + }).filter(e -> !predicate.test(e)).findFirst(); + return results.stream(); + } + + public static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<T> predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), predicate), false); + } + + public static <T> Stream<T> takeWhilePlusOne(Stream<T> stream, Predicate<T> predicate) { + return StreamSupport.stream(takeWhile(stream.spliterator(), new StopAfterFailPredicate<>(predicate)), false); + } + + private static <T> Spliterator<T> takeWhile(Spliterator<T> splitr, Predicate<T> predicate) { + return new MySplitIterator<>(splitr, predicate); + } + + public static class MySplitIterator<T> extends AbstractSpliterator<T> implements Spliterator<T> { + boolean stillGoing = true; + private Spliterator<T> innerItr; + private Predicate<T> innerPred; + + private MySplitIterator(Spliterator<T> splitItr, Predicate<T> pred) { + super(splitItr.estimateSize(), 0); + innerItr = splitItr; + innerPred = pred; + } + + @Override + public boolean tryAdvance(Consumer<? super T> action) { + boolean canAdvance = true; + if (stillGoing) { + stillGoing = innerItr.tryAdvance(createConsumerWrapper(action)); + } else { + canAdvance = false; + } + return canAdvance; + } + + private Consumer<? super T> createConsumerWrapper(Consumer<? super T> action) { return new Consumer<T>() { @Override @@ -104,31 +105,31 @@ public final class StreamUtils { } }; - } - - } - - public static class StopAfterFailPredicate<T> implements Predicate<T> { - private boolean hasNotFailed; - private Predicate<T> innerPredicate; - - private StopAfterFailPredicate(Predicate<T> pred) { - hasNotFailed = true; - innerPredicate = pred; - } - - @Override - public boolean test(T t) { - boolean isPassed; - if (hasNotFailed) { - isPassed = true; - hasNotFailed = innerPredicate.test(t); - } else { - isPassed = false; - } - return isPassed; - } - - } + } + + } + + public static class StopAfterFailPredicate<T> implements Predicate<T> { + boolean hasNotFailed; + Predicate<T> innerPredicate; + + private StopAfterFailPredicate(Predicate<T> pred) { + hasNotFailed = true; + innerPredicate = pred; + }; + + @Override + public boolean test(T t) { + boolean isPassed; + if (hasNotFailed) { + isPassed = true; + hasNotFailed = innerPredicate.test(t); + } else { + isPassed = false; + } + return isPassed; + } + + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java index dcba5711d1..e14c98ee8f 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ThreadLocalsHolder.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. @@ -20,39 +20,77 @@ package org.openecomp.sdc.common.util; +import org.openecomp.sdc.common.api.FilterDecisionEnum; +import org.openecomp.sdc.common.datastructure.UserContext; + public class ThreadLocalsHolder { - private static final ThreadLocal<String> UUID_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal<Long> REQUEST_START_TIME_THREAD_LOCAL = new ThreadLocal<>(); - private static final ThreadLocal<Boolean> IS_MDC_PROCESSED_THREAD_LOCAL = ThreadLocal.withInitial(() -> false); + private static final ThreadLocal<String> uuidThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal<Long> requestStartTimeThreadLocal = new ThreadLocal<>(); + private static final ThreadLocal<FilterDecisionEnum> apiType = new ThreadLocal<>(); + private static final ThreadLocal<Boolean> isMdcProcessedThreadLocal = new ThreadLocal<Boolean>() { + @Override + protected Boolean initialValue() { + return false; + } + }; - public static void setMdcProcessed(Boolean isMdcProcessed) { - IS_MDC_PROCESSED_THREAD_LOCAL.set(isMdcProcessed); - } - public static void setUuid(String uuid) { - UUID_THREAD_LOCAL.set(uuid); - } + private static final ThreadLocal<UserContext> userContextThreadLocal = new ThreadLocal<>(); - public static void setRequestStartTime(Long requestStartTime) { - REQUEST_START_TIME_THREAD_LOCAL.set(requestStartTime); - } + public static final UserContext getUserContext() {return userContextThreadLocal.get(); } - public static String getUuid() { - return UUID_THREAD_LOCAL.get(); - } + public static void setUserContext(UserContext userContext) {userContextThreadLocal.set(userContext); } - public static Long getRequestStartTime() { - return REQUEST_START_TIME_THREAD_LOCAL.get(); - } + public static void setMdcProcessed(Boolean isMdcProcessed) { + isMdcProcessedThreadLocal.set(isMdcProcessed); + } - public static Boolean isMdcProcessed() { - return IS_MDC_PROCESSED_THREAD_LOCAL.get(); - } + public static void setUuid(String uuid) { + uuidThreadLocal.set(uuid); + } + + public static void setRequestStartTime(Long requestStartTime) { + requestStartTimeThreadLocal.set(requestStartTime); + } - public static void cleanup() { - UUID_THREAD_LOCAL.remove(); - REQUEST_START_TIME_THREAD_LOCAL.remove(); - IS_MDC_PROCESSED_THREAD_LOCAL.remove(); + public static String getUuid() { + return uuidThreadLocal.get(); + } + + public static Long getRequestStartTime() { + return requestStartTimeThreadLocal.get(); + } + + public static Boolean isMdcProcessed() { + return isMdcProcessedThreadLocal.get(); + } + + public static void cleanup() { + uuidThreadLocal.remove(); + requestStartTimeThreadLocal.remove(); + isMdcProcessedThreadLocal.remove(); + userContextThreadLocal.remove(); + apiType.remove(); + } + + public static FilterDecisionEnum getApiType() { + return apiType.get(); + } + public static void setApiType(FilterDecisionEnum filterDecisionEnum) { + apiType.set(filterDecisionEnum); + } + + + public static boolean isInternalRequest() { + if (getApiType().equals(FilterDecisionEnum.INTERNAL)){ + return true; + } else return false; } + + public static boolean isExternalRequest() { + if (getApiType().equals(FilterDecisionEnum.EXTERNAL)){ + return true; + } else return false; + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java index 988f215a72..6183d42417 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/ValidationUtils.java @@ -21,365 +21,397 @@ package org.openecomp.sdc.common.util; import com.google.common.base.CharMatcher; +import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringEscapeUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.math.NumberUtils; import org.apache.commons.lang3.text.WordUtils; import org.apache.commons.validator.routines.UrlValidator; import org.jsoup.Jsoup; +import org.jsoup.helper.StringUtil; import org.jsoup.safety.Whitelist; -import java.util.Arrays; -import java.util.HashSet; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Set; +import java.util.*; import java.util.regex.Pattern; public class ValidationUtils { - public static final Integer COMPONENT_NAME_MAX_LENGTH = 1024; - public static final Pattern COMPONENT_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH - 1) + "}$"); - public static final Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; - public static final Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern - .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); - public static final Integer RSI_NAME_MAX_LENGTH = 1024; - public static final Pattern RSI_NAME_PATTERN = Pattern - .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); - public static final Integer COMMENT_MAX_LENGTH = 256; - - public static final Integer ICON_MAX_LENGTH = 25; - public static final Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); - public static final Integer PROJECT_CODE_MAX_LEGTH = 50; - public static final Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); - - public static final Integer CONNTACT_ID_MAX_LENGTH = 50; - public static final Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); - public static final Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); - public static final Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); - public static final Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+"); // ,#?&@$<>~^`\\[]{}|")(*! - - public static final Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); - public static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; - public static final Integer SERVICE_TYPE_MAX_LENGTH = 400; - public static final Integer SERVICE_ROLE_MAX_LENGTH = 400; - - public static final Integer TAG_MAX_LENGTH = 1024; - public static final Integer TAG_LIST_MAX_LENGTH = 1024; - public static final Integer VENDOR_NAME_MAX_LENGTH = 60; - public static final Pattern VENDOR_NAME_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer VENDOR_RELEASE_MAX_LENGTH = 25; - public static final Pattern VENDOR_RELEASE_PATTERN = Pattern - .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); - public static final Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; - - public static final Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+"); - - public static final Pattern DASH_PATTERN = Pattern.compile("[-]+"); - public static final Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); - public static final Pattern PLUS_PATTERN = Pattern.compile("[+]+"); - public static final Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); - public static final Pattern AMP_PATTERN = Pattern.compile("[&]+"); - public static final Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); - public static final Pattern APOST_PATTERN = Pattern.compile("[']+"); - public static final Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); - public static final Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); - public static final Pattern COLON_PATTERN = Pattern.compile("[:]+"); - public static final Pattern AT_PATTERN = Pattern.compile("[@]+"); - public static final Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); - public static final Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>( - Arrays.asList("of", "to", "for", "as", "a", "an", "the")); - - public static final Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); - public static final Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); - public static final Integer ARTIFACT_LABEL_LENGTH = 255; - public static final Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); - public static final Integer CATEGORY_LABEL_MIN_LENGTH = 3; - public static final Integer CATEGORY_LABEL_MAX_LENGTH = 25; - - public static final Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); - public static final Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); - public static final Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); - public static final Integer CONSUMER_NAME_MAX_LENGTH = 255; - // public static final Pattern CONSUMER_NAME_PATTERN = - // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + - // "}?$"); - public static final Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); - public static final Integer CONSUMER_SALT_LENGTH = 32; - public static final Integer CONSUMER_PASSWORD_LENGTH = 64; - public static final Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); - public static final Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); - public static final Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); - public static final Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); - public static final Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); - - public static final Integer ARTIFACT_NAME_LENGTH = 255; - public static final Integer API_URL_LENGTH = 100; - public static final Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; - - public static final Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; - public static final Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; - public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; - public static final Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH - 1) + "}$"); - - public static final Integer POLICY_MAX_LENGTH = 1024; - public static final Pattern POLICY_NAME_PATTERN = Pattern - .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH - 1) + "}$"); - - public static boolean validateArtifactLabel(String label) { - return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); - } - - public static boolean validateArtifactDisplayName(String displayName) { - return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); - } - - public static boolean validateCategoryDisplayNameFormat(String label) { - boolean res = true; - if (label != null) { - label = label.trim(); - res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); - } - return res; - } - - public static String normalizeCategoryName4Display(String str) { - if (str != null) { - str = str.trim(); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = AMP_PATTERN.matcher(str).replaceAll("&"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = DOT_PATTERN.matcher(str).replaceAll("."); - str = APOST_PATTERN.matcher(str).replaceAll("'"); - str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); - str = EQUAL_PATTERN.matcher(str).replaceAll("="); - str = COLON_PATTERN.matcher(str).replaceAll(":"); - str = AT_PATTERN.matcher(str).replaceAll("@"); - str = normaliseWhitespace(str); - str = AND_PATTERN.matcher(str).replaceAll(" & "); - - // Case normalizing - StringBuilder sb = new StringBuilder(); - String[] split = str.split(" "); - for (int i = 0; i < split.length; i++) { - String splitted = split[i]; - String lowerCase = splitted.toLowerCase(); - // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but - // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not - // lowercased because it's first word) - // Agreed with Ella, 26/11/15 - if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { - sb.append(lowerCase); - } else { - sb.append(WordUtils.capitalize(splitted)); - } - sb.append(" "); - } - str = sb.toString().trim(); - } - return str; - } - - public static String normalizeCategoryName4Uniqueness(String str) { - return str.toLowerCase(); - } - - public static boolean validateCategoryDisplayNameLength(String label) { - return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH - && label.length() <= CATEGORY_LABEL_MAX_LENGTH); - } - - public static boolean validateProductFullNameLength(String fullName) { - return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH - && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); - } - - public static boolean validateArtifactLabelLength(String label) { - return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; - } - - public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { - return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; - } - - public static boolean validateResourceInstanceName(String resourceInstanceName) { - return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); - } - - public static boolean validateUrlLength(String url) { - return url.length() <= API_URL_LENGTH; - } - - public static boolean validateArtifactNameLength(String artifactName) { - return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); - } - - public static boolean validateComponentNamePattern(String componentName) { - return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); - } - - public static boolean validateComponentNameLength(String componentName) { - return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; - } - - public static boolean validateIcon(String icon) { - return ICON_PATTERN.matcher(icon).matches(); - } - - public static boolean validateIconLength(String icon) { - return icon.length() <= ICON_MAX_LENGTH; - } - - public static boolean validateProjectCode(String projectCode) { - return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); - } - - public static boolean validateProjectCodeLegth(String projectCode) { - return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; - } - - public static boolean validateContactId(String contactId) { - return CONTACT_ID_PATTERN.matcher(contactId).matches(); - } - - public static boolean validateCost(String cost) { - return COST_PATTERN.matcher(cost).matches(); - } - - public static String removeHtmlTags(String str) { - return Jsoup.clean(str, Whitelist.none()); - } - - public static String removeAllTags(String htmlText) { - - return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); - } - - public static String normaliseWhitespace(String str) { - StringBuilder sb = new StringBuilder(str.length()); - appendNormalisedWhitespace(sb, str, false); - return sb.toString(); - } - - private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { - boolean lastWasWhite = false; - boolean reachedNonWhite = false; - - int len = string.length(); - int c; - for (int i = 0; i < len; i += Character.charCount(c)) { - c = string.codePointAt(i); - if (isWhitespace(c)) { - if ((stripLeading && !reachedNonWhite) || lastWasWhite) { - continue; - } - accum.append(' '); - lastWasWhite = true; - } else { - accum.appendCodePoint(c); - lastWasWhite = false; - reachedNonWhite = true; - } - } - } - - private static boolean isWhitespace(int c) { - return c == ' '; - } - - public static String stripOctets(String str) { - return OCTET_PATTERN.matcher(str).replaceAll(""); - } - - public static String removeNoneUtf8Chars(String input) { - return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); - } - - public static boolean validateIsEnglish(String input) { - return ENGLISH_PATTERN.matcher(input).matches(); - } - - public static boolean validateIsAscii(String input) { - - return CharMatcher.ASCII.matchesAllOf(input); - } - - public static String convertHtmlTagsToEntities(String input) { - return StringEscapeUtils.escapeHtml4(input); - } - - public static List<String> removeDuplicateFromList(List<String> list) { - Set<String> hs = new LinkedHashSet<>(list); - list.clear(); - list.addAll(hs); - return list; - - } - - public static boolean validateTagLength(String tag) { - if (tag != null) { - return tag.length() <= TAG_MAX_LENGTH; - } - return false; - } - - public static boolean validateTagListLength(int tagListLength) { - return tagListLength <= TAG_LIST_MAX_LENGTH; - } - - public static boolean validateDescriptionLength(String description) { - return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; - } - - public static boolean validateStringNotEmpty(String value) { - if ((value == null) || (value.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateListNotEmpty(List<?> list) { - if ((list == null) || (list.isEmpty())) { - return false; - } - return true; - } - - public static boolean validateVendorName(String vendorName) { - return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); - } - - public static boolean validateVendorNameLength(String vendorName) { - return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; - } - - public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { - return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; - } - - public static boolean validateVendorRelease(String vendorRelease) { - return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); - } - - public static boolean validateVendorReleaseLength(String vendorRelease) { - return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; - } - - public static boolean validateServiceTypeLength(String serviceType) { - return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; - } - - public static boolean validateServiceRoleLength(String serviceRole) { - return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; - } - - - public static boolean hasBeenCertified(String version) { - return NumberUtils.toDouble(version) >= 1; - } + public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024; + public final static Pattern COMPONENT_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$"); + public final static Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50; + public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern + .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$"); + public final static Integer RSI_NAME_MAX_LENGTH = 1024; + public final static Pattern RSI_NAME_PATTERN = Pattern + .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$"); + public final static Integer COMMENT_MAX_LENGTH = 256; + + public final static Integer ICON_MAX_LENGTH = 25; + public final static Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$"); + public final static Integer PROJECT_CODE_MAX_LEGTH = 50; + public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$"); + + // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9) + public final static Integer CONNTACT_ID_MAX_LENGTH = 50; + // public final static Pattern CONTACT_ID_PATTERN = Pattern +// .compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}"); + public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$"); + public final static Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}"); + public final static Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+"); + public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*! + + public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$"); + public final static Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$"); + public final static Pattern SERVICE_METADATA_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]{1,256}"); + public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024; + public final static Integer SERVICE_TYPE_MAX_LENGTH = 256; + public final static Integer SERVICE_ROLE_MAX_LENGTH = 256; + public final static Integer SERVICE_FUNCTION_MAX_LENGTH = 256; + public final static Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100; + + public final static Integer TAG_MAX_LENGTH = 1024; + public final static Integer TAG_LIST_MAX_LENGTH = 1024; + public final static Integer VENDOR_NAME_MAX_LENGTH = 60; + public final static Pattern VENDOR_NAME_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25; + public final static Pattern VENDOR_RELEASE_PATTERN = Pattern + .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$"); + public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65; + + public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+"); + + public final static Pattern DASH_PATTERN = Pattern.compile("[-]+"); + public final static Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+"); + public final static Pattern PLUS_PATTERN = Pattern.compile("[+]+"); + public final static Pattern SPACE_PATTERN = Pattern.compile("[ ]+"); + public final static Pattern AMP_PATTERN = Pattern.compile("[&]+"); + public final static Pattern DOT_PATTERN = Pattern.compile("[\\.]+"); + public final static Pattern APOST_PATTERN = Pattern.compile("[']+"); + public final static Pattern HASHTAG_PATTERN = Pattern.compile("[#]+"); + public final static Pattern EQUAL_PATTERN = Pattern.compile("[=]+"); + public final static Pattern COLON_PATTERN = Pattern.compile("[:]+"); + public final static Pattern AT_PATTERN = Pattern.compile("[@]+"); + public final static Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] "); + public final static Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>( + Arrays.asList("of", "to", "for", "as", "a", "an", "the")); + + public final static Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$"); + public final static Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$"); + public final static Integer ARTIFACT_LABEL_LENGTH = 255; + public final static Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$"); + public final static Integer CATEGORY_LABEL_MIN_LENGTH = 3; + public final static Integer CATEGORY_LABEL_MAX_LENGTH = 25; + + public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+"); + public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+"); + public final static Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+"); + public final static Integer CONSUMER_NAME_MAX_LENGTH = 255; + // public final static Pattern CONSUMER_NAME_PATTERN = + // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH + + // "}?$"); + public final static Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$"); + public final static Integer CONSUMER_SALT_LENGTH = 32; + public final static Integer CONSUMER_PASSWORD_LENGTH = 64; + public final static Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$"); + public final static Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$"); + public final static Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$"); + public final static Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$"); + public final static Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>"); + public final static Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$"); + + public final static Integer ARTIFACT_NAME_LENGTH = 255; + public final static Integer API_URL_LENGTH = 100; + public final static Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256; + + public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4; + public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100; + public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100; + public final static Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$"); + + public final static Integer POLICY_MAX_LENGTH = 1024; + public final static Pattern POLICY_NAME_PATTERN = Pattern + .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$"); + + public static boolean validateArtifactLabel(String label) { + return ARTIFACT_LABEL_PATTERN.matcher(label).matches(); + } + + public static boolean validateArtifactDisplayName(String displayName) { + return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches(); + } + + public static String cleanUpText(String text){ + text = removeNoneUtf8Chars(text); + text = normaliseWhitespace(text); + text = stripOctets(text); + text = removeHtmlTagsOnly(text); + return text; + } + + public static boolean validateTagPattern(String tag) { + return TAG_PATTERN.matcher(tag).matches(); + } + + public static boolean validateServiceMetadata(String metadataField) { + return SERVICE_METADATA_PATTERN.matcher(metadataField).matches(); + } + + public static boolean validateCommentPattern(String comment) { + return COMMENT_PATTERN.matcher(comment).matches(); + } + + public static boolean validateCategoryDisplayNameFormat(String label) { + boolean res = true; + if (label != null) { + label = label.trim(); + res = CATEGORY_LABEL_PATTERN.matcher(label).matches(); + } + return res; + } + + public static String normalizeCategoryName4Display(String str) { + if (str != null) { + str = str.trim(); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = AMP_PATTERN.matcher(str).replaceAll("&"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = DOT_PATTERN.matcher(str).replaceAll("."); + str = APOST_PATTERN.matcher(str).replaceAll("'"); + str = HASHTAG_PATTERN.matcher(str).replaceAll("#"); + str = EQUAL_PATTERN.matcher(str).replaceAll("="); + str = COLON_PATTERN.matcher(str).replaceAll(":"); + str = AT_PATTERN.matcher(str).replaceAll("@"); + str = normaliseWhitespace(str); + str = AND_PATTERN.matcher(str).replaceAll(" & "); + + // Case normalizing + StringBuilder sb = new StringBuilder(); + String[] split = str.split(" "); + for (int i = 0; i < split.length; i++) { + String splitted = split[i]; + String lowerCase = splitted.toLowerCase(); + // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but + // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not + // lowercased because it's first word) + // Agreed with Ella, 26/11/15 + if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) { + sb.append(lowerCase); + } else { + sb.append(WordUtils.capitalize(splitted)); + } + sb.append(" "); + } + str = sb.toString().trim(); + } + return str; + } + + public static String normalizeCategoryName4Uniqueness(String str) { + return str.toLowerCase(); + } + + public static boolean validateCategoryDisplayNameLength(String label) { + return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH + && label.length() <= CATEGORY_LABEL_MAX_LENGTH); + } + + public static boolean validateProductFullNameLength(String fullName) { + return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH + && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH); + } + + public static boolean validateArtifactLabelLength(String label) { + return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH; + } + + public static boolean validateResourceInstanceNameLength(String resourceInstanceName) { + return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH; + } + + public static boolean validateResourceInstanceName(String resourceInstanceName) { + return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches(); + } + + public static boolean validateUrlLength(String url) { + return url.length() <= API_URL_LENGTH; + } + + public static boolean validateArtifactNameLength(String artifactName) { + return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0); + } + + public static boolean validateComponentNamePattern(String componentName) { + return COMPONENT_NAME_PATTERN.matcher(componentName).matches(); + } + + public static boolean validateComponentNameLength(String componentName) { + return componentName.length() <= COMPONENT_NAME_MAX_LENGTH; + } + + public static boolean validateIcon(String icon) { + return ICON_PATTERN.matcher(icon).matches(); + } + + public static boolean validateIconLength(String icon) { + return icon.length() <= ICON_MAX_LENGTH; + } + + public static boolean validateProjectCode(String projectCode) { + return PROJECT_CODE_PATTERN.matcher(projectCode).matches(); + } + + public static boolean validateProjectCodeLegth(String projectCode) { + return projectCode.length() <= PROJECT_CODE_MAX_LEGTH; + } + + public static boolean validateContactId(String contactId) { + return CONTACT_ID_PATTERN.matcher(contactId).matches(); + } + + public static boolean validateCost(String cost) { + return COST_PATTERN.matcher(cost).matches(); + } + + public static String removeHtmlTags(String str) { + return Jsoup.clean(str, Whitelist.none()); + } + + public static String removeAllTags(String htmlText) { + + return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim(); + } + + public static String normaliseWhitespace(String str) { + StringBuilder sb = new StringBuilder(str.length()); + appendNormalisedWhitespace(sb, str, false); + return sb.toString(); + } + + private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) { + boolean lastWasWhite = false; + boolean reachedNonWhite = false; + + int len = string.length(); + int c; + for (int i = 0; i < len; i+= Character.charCount(c)) { + c = string.codePointAt(i); + if (isWhitespace(c)) { + if ((stripLeading && !reachedNonWhite) || lastWasWhite) + continue; + accum.append(' '); + lastWasWhite = true; + } + else { + accum.appendCodePoint(c); + lastWasWhite = false; + reachedNonWhite = true; + } + } + } + + private static boolean isWhitespace(int c){ + return c == ' '; + } + + public static String stripOctets(String str) { + return OCTET_PATTERN.matcher(str).replaceAll(""); + } + + public static String removeNoneUtf8Chars(String input) { + return NONE_UTF8_PATTERN.matcher(input).replaceAll(""); + } + + public static boolean validateIsEnglish(String input) { + return ENGLISH_PATTERN.matcher(input).matches(); + } + + public static boolean validateIsAscii(String input) { + + return CharMatcher.ASCII.matchesAllOf(input); + } + + public static String convertHtmlTagsToEntities(String input) { + return StringEscapeUtils.escapeHtml4(input); + } + + public static List<String> removeDuplicateFromList(List<String> list) { + Set<String> hs = new LinkedHashSet<>(list); + list.clear(); + list.addAll(hs); + return list; + + } + + public static boolean validateTagLength(String tag) { + if (tag != null) { + return tag.length() <= TAG_MAX_LENGTH; + } + return false; + } + + public static boolean validateTagListLength(int tagListLength) { + return tagListLength <= TAG_LIST_MAX_LENGTH; + } + + public static boolean validateDescriptionLength(String description) { + return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH; + } + + public static boolean validateStringNotEmpty(String value) { + if ((value == null) || (value.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateListNotEmpty(List<?> list) { + if ((list == null) || (list.isEmpty())) { + return false; + } + return true; + } + + public static boolean validateVendorName(String vendorName) { + return VENDOR_NAME_PATTERN.matcher(vendorName).matches(); + } + + public static boolean validateVendorNameLength(String vendorName) { + return vendorName.length() <= VENDOR_NAME_MAX_LENGTH; + } + + public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) { + return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH; + } + + public static boolean validateVendorRelease(String vendorRelease) { + return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches(); + } + + public static boolean validateVendorReleaseLength(String vendorRelease) { + return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH; + } + + public static boolean validateServiceTypeLength(String serviceType) { + return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH; + } + + public static boolean validateServiceRoleLength(String serviceRole) { + return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH; + } + + public static boolean validateServiceFunctionLength(String serviceFunction) { + return serviceFunction.length() <= SERVICE_FUNCTION_MAX_LENGTH; + } + + public static boolean validateServiceNamingPolicyLength(String namingPolicy) { + return namingPolicy.length() <= SERVICE_NAMING_POLICY_MAX_SIZE; + } + public static boolean hasBeenCertified(String version) { + return NumberUtils.toDouble(version) >= 1; + } public static String normaliseComponentName(String name) { String[] split = splitComponentName(name); @@ -389,7 +421,7 @@ public class ValidationUtils { } return sb.toString(); - } + } public static String normalizeComponentInstanceName(String name) { String[] split = splitComponentInstanceName(name); @@ -399,19 +431,19 @@ public class ValidationUtils { } return sb.toString(); - } + } - private static String[] splitComponentName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } - private static String[] splitComponentInstanceName(String name) { - String normalizedName = name.toLowerCase(); - normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } + private static String[] splitComponentInstanceName(String name) { + String normalizedName = name.toLowerCase(); + normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } public static String convertToSystemName(String name) { String[] split = splitComponentName(name); @@ -423,133 +455,137 @@ public class ValidationUtils { return sb.toString(); } - public static String normalizeFileName(String filename) { - // String[] split = filename.split(Pattern.quote(File.separator)); - // String name = ""; - // - // name = split[split.length - 1]; - return cleanFileName(filename); - - } - - private static String cleanFileName(String str) { - str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); - str = normaliseWhitespace(str); - str = SPACE_PATTERN.matcher(str).replaceAll("-"); - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = StringUtils.strip(str, "-_ ."); - - return str; - } - - public static boolean validateUrl(String url) { - - UrlValidator urlValidator = new UrlValidator(); - if (!urlValidator.isValid(url)) { - return false; - } - if (NONE_UTF8_PATTERN.matcher(url).find()) { - return false; - } - - if (URL_INVALIDE_PATTERN.matcher(url).find()) { - return false; - } - return true; - - } - - public static String cleanArtifactDisplayName(String strIn) { - String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = PLUS_PATTERN.matcher(str).replaceAll("+"); - str = normaliseWhitespace(str); - str = str.trim(); - // str = str.replaceAll(" ", ""); - - return str; - } - - public static String normalizeArtifactLabel(String strIn) { - - String str = DASH_PATTERN.matcher(strIn).replaceAll(""); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); - str = PLUS_PATTERN.matcher(str).replaceAll(""); - str = SPACE_PATTERN.matcher(str).replaceAll(""); - str = DOT_PATTERN.matcher(str).replaceAll(""); - str = str.toLowerCase(); - - return str; - } - - public static boolean validateAdditionalInformationKeyName(String str) { - return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); - } - - public static String normalizeAdditionalInformation(String str) { - if (str != null) { - str = DASH_PATTERN.matcher(str).replaceAll("-"); - str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); - str = normaliseWhitespace(str); - } - return str; - } - - public static boolean validateLength(String str, int length) { - if (str == null) { - return true; - } - return str.length() <= length; - } - - public static boolean validateConsumerName(String consumerName) { - return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); - } - - public static boolean isUTF8Str(String str) { - if (NONE_UTF8_PATTERN.matcher(str).find()) { - return false; - } - return true; - } - - public static boolean validateConsumerPassSalt(String consumerSalt) { - return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); - } - - public static boolean isFloatNumber(String number) { - return FLOAT_PATTERN.matcher(number).matches(); - } - - public static boolean validateCertifiedVersion(String version) { - return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); - } - - public static boolean validateMinorVersion(String version) { - return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); - } - - public static String normaliseProductName(String name) { - String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); - StringBuilder sb = new StringBuilder(); - for (String splitElement : split) { - sb.append(splitElement); - } - return sb.toString(); - - } - - private static String[] splitComponentName(Pattern pattern, String name) { - String normalizedName = name.toLowerCase(); - normalizedName = pattern.matcher(normalizedName).replaceAll(" "); - return normalizedName.split(" "); - } - - public static String removeHtmlTagsOnly(String htmlText) { - return HtmlCleaner.stripHtml(htmlText, false); - } - - public static boolean validateForwardingPathNamePattern(String forwardingPathName) { - return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); - } + public static String normalizeFileName(String filename) { + // String[] split = filename.split(Pattern.quote(File.separator)); + // String name = ""; + // + // name = split[split.length - 1]; + return cleanFileName(filename); + + } + + private static String cleanFileName(String str) { + str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll(""); + str = normaliseWhitespace(str); + str = SPACE_PATTERN.matcher(str).replaceAll("-"); + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = StringUtils.strip(str, "-_ ."); + + return str; + } + + public static boolean validateUrl(String url) { + + UrlValidator urlValidator = new UrlValidator(); + if (!urlValidator.isValid(url)) { + return false; + } + if (NONE_UTF8_PATTERN.matcher(url).find()) { + return false; + } + + if (URL_INVALIDE_PATTERN.matcher(url).find()) { + return false; + } + return true; + + } + + public static String cleanArtifactDisplayName(String strIn) { + String str = DASH_PATTERN.matcher(strIn).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = PLUS_PATTERN.matcher(str).replaceAll("+"); + str = normaliseWhitespace(str); + str = str.trim(); + // str = str.replaceAll(" ", ""); + + return str; + } + + public static String normalizeArtifactLabel(String strIn) { + + String str = DASH_PATTERN.matcher(strIn).replaceAll(""); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll(""); + str = PLUS_PATTERN.matcher(str).replaceAll(""); + str = SPACE_PATTERN.matcher(str).replaceAll(""); + str = DOT_PATTERN.matcher(str).replaceAll(""); + str = str.toLowerCase(); + + return str; + } + + public static boolean validateAdditionalInformationKeyName(String str) { + return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches(); + } + + public static String normalizeAdditionalInformation(String str) { + if (str != null) { + str = DASH_PATTERN.matcher(str).replaceAll("-"); + str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_"); + str = normaliseWhitespace(str); + } + return str; + } + + public static boolean validateLength(String str, int length) { + if (str == null) { + return true; + } + return str.length() <= length; + } + + public static boolean validateConsumerName(String consumerName) { + return CONSUMER_NAME_PATTERN.matcher(consumerName).matches(); + } + + public static boolean isUTF8Str(String str) { + if (NONE_UTF8_PATTERN.matcher(str).find()) { + return false; + } + return true; + } + + public static boolean validateConsumerPassSalt(String consumerSalt) { + return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches(); + } + + public static boolean isFloatNumber(String number) { + return FLOAT_PATTERN.matcher(number).matches(); + } + + public static boolean validateCertifiedVersion(String version) { + return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateMinorVersion(String version) { + return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches()); + } + + public static boolean validateCategoryIconNotEmpty(List<String> categoryIcons) { + return CollectionUtils.isEmpty(categoryIcons); + } + + public static String normaliseProductName(String name) { + String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name); + StringBuilder sb = new StringBuilder(); + for (String splitElement : split) { + sb.append(splitElement); + } + return sb.toString(); + + } + + private static String[] splitComponentName(Pattern pattern, String name) { + String normalizedName = name.toLowerCase(); + normalizedName = pattern.matcher(normalizedName).replaceAll(" "); + return normalizedName.split(" "); + } + + public static String removeHtmlTagsOnly(String htmlText) { + return HtmlCleaner.stripHtml(htmlText, false); + } + + public static boolean validateForwardingPathNamePattern(String forwardingPathName) { + return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches(); + } } diff --git a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java index 801b6c1aaa..b2435de12c 100644 --- a/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java +++ b/common-app-api/src/main/java/org/openecomp/sdc/common/util/YamlToObjectConverter.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -21,16 +21,7 @@ package org.openecomp.sdc.common.util; import org.apache.commons.codec.binary.Base64; -import org.openecomp.sdc.be.config.Configuration.ApplicationL1CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ApplicationL2CacheConfig; -import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig; -import org.openecomp.sdc.be.config.Configuration.BeMonitoringConfig; -import org.openecomp.sdc.be.config.Configuration.EcompPortalConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig; -import org.openecomp.sdc.be.config.Configuration.ElasticSearchConfig.IndicesTimeFrequencyEntry; -import org.openecomp.sdc.be.config.Configuration.OnboardingConfig; -import org.openecomp.sdc.be.config.Configuration.SwitchoverDetectorConfig; -import org.openecomp.sdc.be.config.Configuration.ToscaValidatorsConfig; +import org.openecomp.sdc.be.config.Configuration.*; import org.openecomp.sdc.be.config.DistributionEngineConfiguration; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.ComponentArtifactTypesConfig; import org.openecomp.sdc.be.config.DistributionEngineConfiguration.CreateTopicConfig; @@ -57,228 +48,222 @@ import java.util.Map; public class YamlToObjectConverter { - private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); + private static Logger log = Logger.getLogger(YamlToObjectConverter.class.getName()); - private static HashMap<String, Yaml> yamls = new HashMap<>(); + private static HashMap<String, Yaml> yamls = new HashMap<>(); - private static Yaml defaultYaml = new Yaml(); + private static Yaml defaultYaml = new Yaml(); - static { + static { - org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DistributionEngineConfiguration.class); - TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); - deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); - deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); - deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); - deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); - deConstructor.addTypeDescription(deDescription); - Yaml yaml = new Yaml(deConstructor); - yamls.put(DistributionEngineConfiguration.class.getName(), yaml); + org.yaml.snakeyaml.constructor.Constructor deConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DistributionEngineConfiguration.class); + TypeDescription deDescription = new TypeDescription(DistributionEngineConfiguration.class); + deDescription.putListPropertyType("distributionStatusTopic", DistributionStatusTopicConfig.class); + deDescription.putListPropertyType("distribNotifServiceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("distribNotifResourceArtifactTypes", ComponentArtifactTypesConfig.class); + deDescription.putListPropertyType("createTopic", CreateTopicConfig.class); + deDescription.putListPropertyType("distributionNotificationTopic", DistributionNotificationTopicConfig.class); + deConstructor.addTypeDescription(deDescription); + Yaml yaml = new Yaml(deConstructor); + yamls.put(DistributionEngineConfiguration.class.getName(), yaml); - // FE conf - org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.fe.config.Configuration.class); - TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); - feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); - feConfConstructor.addTypeDescription(feConfDescription); - yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); - - // BE conf - org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( - org.openecomp.sdc.be.config.Configuration.class); - TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); - beConfConstructor.addTypeDescription(beConfDescription); - - // systemMonitoring - beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - - // elasticSearch - beConfDescription.putListPropertyType("elasticSearch", ElasticSearchConfig.class); - TypeDescription esDescription = new TypeDescription(ElasticSearchConfig.class); - esDescription.putListPropertyType("indicesTimeFrequency", IndicesTimeFrequencyEntry.class); - beConfConstructor.addTypeDescription(esDescription); - - // resourceDeploymentArtifacts and serviceDeploymentArtifacts - beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, - ArtifactTypeConfig.class); - - // onboarding - beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); - - // ecompPortal - beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); - // switchoverDetector - beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); - - // ApplicationL1Cache - beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); - - // ApplicationL2Cache - beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); - - // tosca validators config - beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); - - yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); - - // HEAT deployment artifact - org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( - DeploymentArtifactHeatConfiguration.class); - PropertyUtils propertyUtils = new PropertyUtils(); - // Skip properties which are found in YAML but not found in POJO - propertyUtils.setSkipMissingProperties(true); - depArtHeatConstructor.setPropertyUtils(propertyUtils); - yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), - new Yaml(depArtHeatConstructor)); - - } - - private static <T> Yaml getYamlByClassName(Class<T> className) { - - Yaml yaml = yamls.get(className.getName()); - if (yaml == null) { - yaml = defaultYaml; - } - - return yaml; - } - - public <T> T convert(String dirPath, Class<T> className, String configFileName) { - - T config = null; - - try { - - String fullFileName = dirPath + File.separator + configFileName; - - config = convert(fullFileName, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", configFileName, e); - } - - return config; - } - - public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { - private HashMap<String, Class<?>> classMap = new HashMap<>(); - - public MyYamlConstructor(Class<? extends Object> theRoot) { - super(theRoot); - classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); - classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); - } - - /* - * This is a modified version of the Constructor. Rather than using a - * class loader to get external classes, they are already predefined - * above. This approach works similar to the typeTags structure in the - * original constructor, except that class information is pre-populated - * during initialization rather than runtime. - * - * @see - * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. - * snakeyaml.nodes.Node) - */ - protected Class<?> getClassForNode(Node node) { - String name = node.getTag().getClassName(); - Class<?> cl = classMap.get(name); - if (cl == null) { - throw new YAMLException("Class not found: " + name); - } else { - return cl; - } - } - } - - public <T> T convert(String fullFileName, Class<T> className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); - - InputStream in = null; - try { - - File f = new File(fullFileName); - if (!f.exists()) { - log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "The file {} cannot be found. Ignore reading configuration.", fullFileName); - return null; - } - in = Files.newInputStream(Paths.get(fullFileName)); - - config = yaml.loadAs(in, className); - - // System.out.println(config.toString()); - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file {} to object.", fullFileName, e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public <T> T convert(byte[] fileContents, Class<T> className) { - - T config = null; - - Yaml yaml = getYamlByClassName(className); + // FE conf + org.yaml.snakeyaml.constructor.Constructor feConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.fe.config.Configuration.class); + TypeDescription feConfDescription = new TypeDescription(org.openecomp.sdc.fe.config.Configuration.class); + feConfDescription.putListPropertyType("systemMonitoring", FeMonitoringConfig.class); + feConfConstructor.addTypeDescription(feConfDescription); + yamls.put(org.openecomp.sdc.fe.config.Configuration.class.getName(), new Yaml(feConfConstructor)); + + // BE conf + org.yaml.snakeyaml.constructor.Constructor beConfConstructor = new org.yaml.snakeyaml.constructor.Constructor( + org.openecomp.sdc.be.config.Configuration.class); + TypeDescription beConfDescription = new TypeDescription(org.openecomp.sdc.be.config.Configuration.class); + beConfConstructor.addTypeDescription(beConfDescription); + + // systemMonitoring + beConfDescription.putListPropertyType("systemMonitoring", BeMonitoringConfig.class); - InputStream in = null; - try { - - in = new ByteArrayInputStream(fileContents); - - config = yaml.loadAs(in, className); - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object", e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException e) { - log.debug("Failed to close input stream", e); - } - } - } - - return config; - } - - public boolean isValidYamlEncoded64(byte[] fileContents) { - log.trace("Received Base64 data - decoding before validating..."); - byte[] decodedFileContents = Base64.decodeBase64(fileContents); - - return isValidYaml(decodedFileContents); - } - - @SuppressWarnings("unchecked") - public boolean isValidYaml(byte[] fileContents) { - try { - - Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); - - for (Object o : mappedToscaTemplateIt) { - System.out.println("Loaded object type:" + o.getClass()); - Map<String, Object> map = (Map<String, Object>) o; - } - - } catch (Exception e) { - log.error(EcompLoggerErrorCode.UNKNOWN_ERROR, "", "", "Failed to convert yaml file to object - yaml is invalid", e); - return false; - } - return true; - } + // resourceDeploymentArtifacts and serviceDeploymentArtifacts + beConfDescription.putMapPropertyType("resourceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + beConfDescription.putMapPropertyType("serviceDeploymentArtifacts", String.class, + ArtifactTypeConfig.class); + + // onboarding + beConfDescription.putListPropertyType("onboarding", OnboardingConfig.class); + + // ecompPortal + beConfDescription.putListPropertyType("ecompPortal", EcompPortalConfig.class); + // switchoverDetector + beConfDescription.putListPropertyType("switchoverDetector", SwitchoverDetectorConfig.class); + + // ApplicationL1Cache + beConfDescription.putListPropertyType("applicationL1Cache", ApplicationL1CacheConfig.class); + + // ApplicationL2Cache + beConfDescription.putListPropertyType("applicationL2Cache", ApplicationL2CacheConfig.class); + + // tosca validators config + beConfDescription.putListPropertyType("toscaValidators", ToscaValidatorsConfig.class); + + yamls.put(org.openecomp.sdc.be.config.Configuration.class.getName(), new Yaml(beConfConstructor)); + + // HEAT deployment artifact + org.yaml.snakeyaml.constructor.Constructor depArtHeatConstructor = new org.yaml.snakeyaml.constructor.Constructor( + DeploymentArtifactHeatConfiguration.class); + PropertyUtils propertyUtils = new PropertyUtils(); + // Skip properties which are found in YAML but not found in POJO + propertyUtils.setSkipMissingProperties(true); + depArtHeatConstructor.setPropertyUtils(propertyUtils); + yamls.put(org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration.class.getName(), + new Yaml(depArtHeatConstructor)); + + } + + private static <T> Yaml getYamlByClassName(Class<T> className) { + + Yaml yaml = yamls.get(className.getName()); + if (yaml == null) { + yaml = defaultYaml; + } + + return yaml; + } + + public <T> T convert(String dirPath, Class<T> className, String configFileName) { + + T config = null; + + try { + + String fullFileName = dirPath + File.separator + configFileName; + + config = convert(fullFileName, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", configFileName,e); + } + + return config; + } + + public class MyYamlConstructor extends org.yaml.snakeyaml.constructor.Constructor { + private HashMap<String, Class<?>> classMap = new HashMap<>(); + + public MyYamlConstructor(Class<? extends Object> theRoot) { + super(theRoot); + classMap.put(DistributionEngineConfiguration.class.getName(), DistributionEngineConfiguration.class); + classMap.put(DistributionStatusTopicConfig.class.getName(), DistributionStatusTopicConfig.class); + } + + /* + * This is a modified version of the Constructor. Rather than using a + * class loader to get external classes, they are already predefined + * above. This approach works similar to the typeTags structure in the + * original constructor, except that class information is pre-populated + * during initialization rather than runtime. + * + * @see + * org.yaml.snakeyaml.constructor.Constructor#getClassForNode(org.yaml. + * snakeyaml.nodes.Node) + */ + protected Class<?> getClassForNode(Node node) { + String name = node.getTag().getClassName(); + Class<?> cl = classMap.get(name); + if (cl == null) + throw new YAMLException("Class not found: " + name); + else + return cl; + } + } + + public <T> T convert(String fullFileName, Class<T> className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + File f = new File(fullFileName); + if (!f.exists()) { + log.warn(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","The file {} cannot be found. Ignore reading configuration.",fullFileName); + return null; + } + in = Files.newInputStream(Paths.get(fullFileName)); + + config = yaml.loadAs(in, className); + + // System.out.println(config.toString()); + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file {} to object.", fullFileName, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public <T> T convert(byte[] fileContents, Class<T> className) { + + T config = null; + + Yaml yaml = getYamlByClassName(className); + + InputStream in = null; + try { + + in = new ByteArrayInputStream(fileContents); + + config = yaml.loadAs(in, className); + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object", e); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException e) { + log.debug("Failed to close input stream", e); + e.printStackTrace(); + } + } + } + + return config; + } + + public boolean isValidYamlEncoded64(byte[] fileContents) { + log.trace("Received Base64 data - decoding before validating..."); + byte[] decodedFileContents = Base64.decodeBase64(fileContents); + + return isValidYaml(decodedFileContents); + } + @SuppressWarnings("unchecked") + public boolean isValidYaml(byte[] fileContents) { + try { + + Iterable<Object> mappedToscaTemplateIt = defaultYaml.loadAll(new ByteArrayInputStream(fileContents)); + + for (Object o : mappedToscaTemplateIt) { + System.out.println("Loaded object type:" + o.getClass()); + Map<String, Object> map = (Map<String, Object>) o; + } + + } catch (Exception e) { + log.error(EcompLoggerErrorCode.UNKNOWN_ERROR,"","","Failed to convert yaml file to object - yaml is invalid", e); + return false; + } + return true; + } } |