2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.common.util;
23 import com.google.common.base.CharMatcher;
24 import org.apache.commons.collections.CollectionUtils;
25 import org.apache.commons.text.StringEscapeUtils;
26 import org.apache.commons.lang3.StringUtils;
27 import org.apache.commons.lang3.math.NumberUtils;
28 import org.apache.commons.text.WordUtils;
29 import org.apache.commons.validator.routines.UrlValidator;
30 import org.jsoup.Jsoup;
31 import org.jsoup.safety.Whitelist;
34 import java.util.regex.Pattern;
36 public class ValidationUtils {
38 private ValidationUtils() {
41 public static final Integer COMPONENT_NAME_MAX_LENGTH = 1024;
42 public static final Pattern COMPONENT_NAME_PATTERN = Pattern
43 .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$");
44 public static final Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50;
45 public static final Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern
46 .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$");
47 public static final Integer RSI_NAME_MAX_LENGTH = 1024;
48 public static final Pattern RSI_NAME_PATTERN = Pattern
49 .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$");
50 public static final Integer COMMENT_MAX_LENGTH = 256;
52 public static final Integer ICON_MAX_LENGTH = 25;
53 public static final Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$");
54 public static final Integer PROJECT_CODE_MAX_LEGTH = 50;
55 public static final Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$");
57 // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9)
58 public static final Integer CONNTACT_ID_MAX_LENGTH = 50;
60 public static final Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$");
61 public static final Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}");
62 public static final Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+");
63 public static final Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*!
65 public static final Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$");
66 public static final Pattern COMMENT_PATTERN = Pattern.compile("^[\\u0000-\\u00BF]{1,1024}$");
67 public static final Pattern SERVICE_METADATA_PATTERN = Pattern.compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]{1,256}");
68 public static final Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024;
69 public static final Integer SERVICE_TYPE_MAX_LENGTH = 256;
70 public static final Integer SERVICE_ROLE_MAX_LENGTH = 256;
71 public static final Integer SERVICE_FUNCTION_MAX_LENGTH = 256;
72 public static final Integer SERVICE_NAMING_POLICY_MAX_SIZE = 100;
74 public static final Integer TAG_MAX_LENGTH = 1024;
75 public static final Integer TAG_LIST_MAX_LENGTH = 1024;
76 public static final Integer VENDOR_NAME_MAX_LENGTH = 60;
77 public static final Pattern VENDOR_NAME_PATTERN = Pattern
78 .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
79 public static final Integer VENDOR_RELEASE_MAX_LENGTH = 25;
80 public static final Pattern VENDOR_RELEASE_PATTERN = Pattern
81 .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
82 public static final Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65;
84 public static final Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+");
86 public static final Pattern YANG_MODULE_3GPP_PATTERN = Pattern.compile("^(_3gpp).*$");
87 public static final Pattern DASH_PATTERN = Pattern.compile("[-]+");
88 public static final Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+");
89 public static final Pattern PLUS_PATTERN = Pattern.compile("[+]+");
90 public static final Pattern SPACE_PATTERN = Pattern.compile("[ ]+");
91 public static final Pattern AMP_PATTERN = Pattern.compile("[&]+");
92 public static final Pattern DOT_PATTERN = Pattern.compile("[\\.]+");
93 public static final Pattern APOST_PATTERN = Pattern.compile("[']+");
94 public static final Pattern HASHTAG_PATTERN = Pattern.compile("[#]+");
95 public static final Pattern EQUAL_PATTERN = Pattern.compile("[=]+");
96 public static final Pattern COLON_PATTERN = Pattern.compile("[:]+");
97 public static final Pattern AT_PATTERN = Pattern.compile("[@]+");
98 public static final Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] ");
99 private static final Set<String> CATEGORY_CONJUNCTIONS = new HashSet<>(
100 Arrays.asList("of", "to", "for", "as", "a", "an", "the"));
102 public static final Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$");
103 public static final Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-@+]+$");
104 public static final Integer ARTIFACT_LABEL_LENGTH = 255;
105 public static final Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
106 public static final Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
107 public static final Integer CATEGORY_LABEL_MIN_LENGTH = 3;
108 public static final Integer CATEGORY_LABEL_MAX_LENGTH = 25;
110 public static final Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+");
111 public static final Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+");
112 public static final Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+");
113 public static final Integer CONSUMER_NAME_MAX_LENGTH = 255;
115 public static final Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$");
116 public static final Integer CONSUMER_SALT_LENGTH = 32;
117 public static final Integer CONSUMER_PASSWORD_LENGTH = 64;
118 public static final Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$");
119 public static final Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$");
120 public static final Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$");
121 public static final Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$");
122 public static final Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>");
123 public static final Pattern TAG_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,1024}$");
125 public static final Integer ARTIFACT_NAME_LENGTH = 255;
126 public static final Integer API_URL_LENGTH = 100;
127 public static final Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256;
129 public static final Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4;
130 public static final Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100;
131 public static final Integer FORWARDING_PATH_NAME_MAX_LENGTH = 100;
132 public static final Pattern FORWARDING_PATH_NAME_PATTERN = Pattern.compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (FORWARDING_PATH_NAME_MAX_LENGTH-1) + "}$");
134 public static final Integer POLICY_MAX_LENGTH = 1024;
135 public static final Pattern POLICY_NAME_PATTERN = Pattern
136 .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (POLICY_MAX_LENGTH-1) + "}$");
138 public static boolean validateArtifactLabel(String label) {
139 return ARTIFACT_LABEL_PATTERN.matcher(label).matches();
142 public static boolean validateArtifactDisplayName(String displayName) {
143 return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches();
146 public static String cleanUpText(String text){
147 text = removeNoneUtf8Chars(text);
148 text = normaliseWhitespace(text);
149 text = stripOctets(text);
150 text = removeHtmlTagsOnly(text);
154 public static boolean validateTagPattern(String tag) {
155 return TAG_PATTERN.matcher(tag).matches();
158 public static boolean validateServiceMetadata(String metadataField) {
159 return SERVICE_METADATA_PATTERN.matcher(metadataField).matches();
162 public static boolean validateCommentPattern(String comment) {
163 return COMMENT_PATTERN.matcher(comment).matches();
166 public static boolean validateCategoryDisplayNameFormat(String label) {
169 label = label.trim();
170 res = CATEGORY_LABEL_PATTERN.matcher(label).matches();
175 public static String normalizeCategoryName4Display(String str) {
178 str = DASH_PATTERN.matcher(str).replaceAll("-");
179 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
180 str = AMP_PATTERN.matcher(str).replaceAll("&");
181 str = PLUS_PATTERN.matcher(str).replaceAll("+");
182 str = DOT_PATTERN.matcher(str).replaceAll(".");
183 str = APOST_PATTERN.matcher(str).replaceAll("'");
184 str = HASHTAG_PATTERN.matcher(str).replaceAll("#");
185 str = EQUAL_PATTERN.matcher(str).replaceAll("=");
186 str = COLON_PATTERN.matcher(str).replaceAll(":");
187 str = AT_PATTERN.matcher(str).replaceAll("@");
188 str = normaliseWhitespace(str);
189 str = AND_PATTERN.matcher(str).replaceAll(" & ");
192 StringBuilder sb = new StringBuilder();
193 String[] split = str.split(" ");
194 for (int i = 0; i < split.length; i++) {
195 String splitted = split[i];
196 String lowerCase = splitted.toLowerCase();
197 // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but
198 // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not
199 // lowercased because it's first word)
200 // Agreed with Ella, 26/11/15
201 if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) {
202 sb.append(lowerCase);
204 sb.append(WordUtils.capitalize(splitted));
208 str = sb.toString().trim();
213 public static String normalizeCategoryName4Uniqueness(String str) {
214 return str.toLowerCase();
217 public static boolean validateCategoryDisplayNameLength(String label) {
218 return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH
219 && label.length() <= CATEGORY_LABEL_MAX_LENGTH);
222 public static boolean validateProductFullNameLength(String fullName) {
223 return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH
224 && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH);
227 public static boolean validateArtifactLabelLength(String label) {
228 return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH;
231 public static boolean validateResourceInstanceNameLength(String resourceInstanceName) {
232 return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH;
235 public static boolean validateResourceInstanceName(String resourceInstanceName) {
236 return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches();
239 public static boolean validateUrlLength(String url) {
240 return url.length() <= API_URL_LENGTH;
243 public static boolean validateArtifactNameLength(String artifactName) {
244 return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0);
247 public static boolean validateComponentNamePattern(String componentName) {
248 return COMPONENT_NAME_PATTERN.matcher(componentName).matches();
251 public static boolean validateComponentNameLength(String componentName) {
252 return componentName.length() <= COMPONENT_NAME_MAX_LENGTH;
255 public static boolean validateIcon(String icon) {
256 return ICON_PATTERN.matcher(icon).matches();
259 public static boolean validateIconLength(String icon) {
260 return icon.length() <= ICON_MAX_LENGTH;
263 public static boolean validateProjectCode(String projectCode) {
264 return PROJECT_CODE_PATTERN.matcher(projectCode).matches();
267 public static boolean validateProjectCodeLegth(String projectCode) {
268 return projectCode.length() <= PROJECT_CODE_MAX_LEGTH;
271 public static boolean validateContactId(String contactId) {
272 return CONTACT_ID_PATTERN.matcher(contactId).matches();
275 public static boolean validateCost(String cost) {
276 return COST_PATTERN.matcher(cost).matches();
279 public static String removeHtmlTags(String str) {
280 return Jsoup.clean(str, Whitelist.none());
283 public static String removeAllTags(String htmlText) {
285 return TAGS_PATTERN.matcher(htmlText).replaceAll("").trim();
288 public static String normaliseWhitespace(String str) {
289 StringBuilder sb = new StringBuilder(str.length());
290 appendNormalisedWhitespace(sb, str, false);
291 return sb.toString();
294 private static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading) {
295 boolean lastWasWhite = false;
296 boolean reachedNonWhite = false;
298 int len = string.length();
300 for (int i = 0; i < len; i+= Character.charCount(c)) {
301 c = string.codePointAt(i);
302 if (isWhitespace(c)) {
303 if ((stripLeading && !reachedNonWhite) || lastWasWhite)
309 accum.appendCodePoint(c);
310 lastWasWhite = false;
311 reachedNonWhite = true;
316 private static boolean isWhitespace(int c){
320 public static String stripOctets(String str) {
321 return OCTET_PATTERN.matcher(str).replaceAll("");
324 public static String removeNoneUtf8Chars(String input) {
325 return NONE_UTF8_PATTERN.matcher(input).replaceAll("");
328 public static boolean validateIsEnglish(String input) {
329 return ENGLISH_PATTERN.matcher(input).matches();
332 public static boolean validateIsAscii(String input) {
334 return CharMatcher.ASCII.matchesAllOf(input);
337 public static String convertHtmlTagsToEntities(String input) {
338 return StringEscapeUtils.escapeHtml4(input);
341 public static List<String> removeDuplicateFromList(List<String> list) {
342 Set<String> hs = new LinkedHashSet<>(list);
349 public static boolean validateTagLength(String tag) {
351 return tag.length() <= TAG_MAX_LENGTH;
356 public static boolean validateTagListLength(int tagListLength) {
357 return tagListLength <= TAG_LIST_MAX_LENGTH;
360 public static boolean validateDescriptionLength(String description) {
361 return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH;
364 public static boolean validateStringNotEmpty(String value) {
365 if ((value == null) || (value.isEmpty())) {
371 public static boolean validateListNotEmpty(List<?> list) {
372 if ((list == null) || (list.isEmpty())) {
378 public static boolean validateVendorName(String vendorName) {
379 return VENDOR_NAME_PATTERN.matcher(vendorName).matches();
382 public static boolean validateVendorNameLength(String vendorName) {
383 return vendorName.length() <= VENDOR_NAME_MAX_LENGTH;
386 public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) {
387 return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH;
390 public static boolean validateVendorRelease(String vendorRelease) {
391 return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches();
394 public static boolean validateVendorReleaseLength(String vendorRelease) {
395 return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH;
398 public static boolean validateServiceTypeLength(String serviceType) {
399 return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH;
402 public static boolean validateServiceRoleLength(String serviceRole) {
403 return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH;
406 public static boolean validateServiceFunctionLength(String serviceFunction) {
407 return serviceFunction.length() <= SERVICE_FUNCTION_MAX_LENGTH;
410 public static boolean validateServiceNamingPolicyLength(String namingPolicy) {
411 return namingPolicy.length() <= SERVICE_NAMING_POLICY_MAX_SIZE;
413 public static boolean hasBeenCertified(String version) {
414 return NumberUtils.toDouble(version) >= 1;
417 public static String normaliseComponentName(String name) {
418 String[] split = splitComponentName(name);
419 StringBuilder sb = new StringBuilder();
420 for (String splitElement : split) {
421 sb.append(splitElement);
423 return sb.toString();
427 public static String normalizeComponentInstanceName(String name) {
428 String[] split = splitComponentInstanceName(name);
429 StringBuilder sb = new StringBuilder();
430 for (String splitElement : split) {
431 sb.append(splitElement);
433 return sb.toString();
437 private static String[] splitComponentName(String name) {
438 String normalizedName = name.toLowerCase();
439 normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
440 return normalizedName.split(" ");
443 private static String[] splitComponentInstanceName(String name) {
444 String normalizedName = name.toLowerCase();
445 normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
446 return normalizedName.split(" ");
449 public static String convertToSystemName(String name) {
450 String[] split = splitComponentName(name);
451 StringBuilder sb = new StringBuilder();
452 for (String splitElement : split) {
453 String capitalize = WordUtils.capitalize(splitElement);
454 sb.append(capitalize);
456 return sb.toString();
459 public static String normalizeFileName(String filename) {
460 return cleanFileName(filename);
464 private static String cleanFileName(String str) {
465 str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll("");
466 str = normaliseWhitespace(str);
467 str = SPACE_PATTERN.matcher(str).replaceAll("-");
468 str = DASH_PATTERN.matcher(str).replaceAll("-");
469 if (!YANG_MODULE_3GPP_PATTERN.matcher(str).matches())
470 str = StringUtils.strip(str, "-_ .");
475 public static boolean validateUrl(String url) {
477 UrlValidator urlValidator = new UrlValidator();
478 if (!urlValidator.isValid(url)) {
481 if (NONE_UTF8_PATTERN.matcher(url).find()) {
485 if (URL_INVALIDE_PATTERN.matcher(url).find()) {
492 public static String cleanArtifactDisplayName(String strIn) {
493 String str = DASH_PATTERN.matcher(strIn).replaceAll("-");
494 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
495 str = PLUS_PATTERN.matcher(str).replaceAll("+");
496 str = normaliseWhitespace(str);
502 public static String normalizeArtifactLabel(String strIn) {
504 String str = DASH_PATTERN.matcher(strIn).replaceAll("");
505 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("");
506 str = PLUS_PATTERN.matcher(str).replaceAll("");
507 str = SPACE_PATTERN.matcher(str).replaceAll("");
508 str = DOT_PATTERN.matcher(str).replaceAll("");
509 str = str.toLowerCase();
514 public static boolean validateAdditionalInformationKeyName(String str) {
515 return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches();
518 public static String normalizeAdditionalInformation(String str) {
520 str = DASH_PATTERN.matcher(str).replaceAll("-");
521 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
522 str = normaliseWhitespace(str);
527 public static boolean validateLength(String str, int length) {
531 return str.length() <= length;
534 public static boolean validateConsumerName(String consumerName) {
535 return CONSUMER_NAME_PATTERN.matcher(consumerName).matches();
538 public static boolean isUTF8Str(String str) {
539 if (NONE_UTF8_PATTERN.matcher(str).find()) {
545 public static boolean validateConsumerPassSalt(String consumerSalt) {
546 return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches();
549 public static boolean isFloatNumber(String number) {
550 return FLOAT_PATTERN.matcher(number).matches();
553 public static boolean validateCertifiedVersion(String version) {
554 return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches());
557 public static boolean validateMinorVersion(String version) {
558 return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches());
561 public static boolean validateCategoryIconNotEmpty(List<String> categoryIcons) {
562 return CollectionUtils.isEmpty(categoryIcons);
565 public static String normaliseProductName(String name) {
566 String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name);
567 StringBuilder sb = new StringBuilder();
568 for (String splitElement : split) {
569 sb.append(splitElement);
571 return sb.toString();
575 private static String[] splitComponentName(Pattern pattern, String name) {
576 String normalizedName = name.toLowerCase();
577 normalizedName = pattern.matcher(normalizedName).replaceAll(" ");
578 return normalizedName.split(" ");
581 public static String removeHtmlTagsOnly(String htmlText) {
582 return HtmlCleaner.stripHtml(htmlText, false);
585 public static boolean validateForwardingPathNamePattern(String forwardingPathName) {
586 return FORWARDING_PATH_NAME_PATTERN.matcher(forwardingPathName).matches();