[SDC] rebase 1710 code
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / util / ValidationUtils.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.common.util;
22
23 import java.util.Arrays;
24 import java.util.HashSet;
25 import java.util.LinkedHashSet;
26 import java.util.List;
27 import java.util.Set;
28 import java.util.regex.Pattern;
29
30 import org.apache.commons.lang3.StringEscapeUtils;
31 import org.apache.commons.lang3.StringUtils;
32 import org.apache.commons.lang3.math.NumberUtils;
33 import org.apache.commons.lang3.text.WordUtils;
34 import org.apache.commons.validator.routines.UrlValidator;
35 import org.jsoup.Jsoup;
36 import org.jsoup.helper.StringUtil;
37 import org.jsoup.safety.Whitelist;
38
39 import com.google.common.base.CharMatcher;
40
41 public class ValidationUtils {
42         public final static Integer COMPONENT_NAME_MAX_LENGTH = 1024;
43         public final static Pattern COMPONENT_NAME_PATTERN = Pattern
44                         .compile("^[\\w][\\w \\.\\-\\_\\:\\+]{0," + (COMPONENT_NAME_MAX_LENGTH-1) + "}$");
45         public final static Integer ADDITIONAL_INFORMATION_KEY_MAX_LENGTH = 50;
46         public final static Pattern ADDITIONAL_INFORMATION_KEY_PATTERN = Pattern
47                         .compile("^[\\w\\s\\.\\-\\_]{1," + COMPONENT_NAME_MAX_LENGTH + "}$");
48         public final static Integer RSI_NAME_MAX_LENGTH = 1024;
49         public final static Pattern RSI_NAME_PATTERN = Pattern
50                         .compile("^[\\w \\s\\.\\-\\_\\:\\+]{1," + RSI_NAME_MAX_LENGTH + "}$");
51         public final static Integer COMMENT_MAX_LENGTH = 256;
52
53         public final static Integer ICON_MAX_LENGTH = 25;
54         public final static Pattern ICON_PATTERN = Pattern.compile("^[\\w\\-]{1," + ICON_MAX_LENGTH + "}$");
55         public final static Integer PROJECT_CODE_MAX_LEGTH = 50;
56         public final static Pattern PROJECT_CODE_PATTERN = Pattern.compile("^[\\s\\w_.-]{5,50}$");
57
58         // USER_ID format : aannnX (where a=a-z or A-Z, n=0-9, and X=a-z,A-Z, or 0-9)
59         public final static Integer CONNTACT_ID_MAX_LENGTH = 50;
60 //      public final static Pattern CONTACT_ID_PATTERN = Pattern
61 //                      .compile("[mM]{1}[0-9]{5}|[a-zA-Z]{2}[0-9]{4}|[a-zA-Z]{2}[0-9]{3}[a-zA-Z]{1}");
62         public final static Pattern CONTACT_ID_PATTERN = Pattern.compile("^[\\s\\w_.-]{1,50}$");
63         public final static Pattern OCTET_PATTERN = Pattern.compile("%[a-fA-F0-9]{2}");
64         public final static Pattern NONE_UTF8_PATTERN = Pattern.compile("[^\\x00-\\x7F]+");
65         public final static Pattern URL_INVALIDE_PATTERN = Pattern.compile("[,#?&@$<>~^`\\\\\\[\\]{}|\")(*!+=;%]+");// ,#?&@$<>~^`\\[]{}|")(*!
66
67         public final static Pattern ENGLISH_PATTERN = Pattern.compile("^[\\p{Graph}\\x20]+$");
68         public final static Integer COMPONENT_DESCRIPTION_MAX_LENGTH = 1024;
69         public final static Integer SERVICE_TYPE_MAX_LENGTH = 400;
70         public final static Integer SERVICE_ROLE_MAX_LENGTH = 400;
71
72         public final static Integer TAG_MAX_LENGTH = 1024;
73         public final static Integer TAG_LIST_MAX_LENGTH = 1024;
74         public final static Integer VENDOR_NAME_MAX_LENGTH = 60;
75         public final static Pattern VENDOR_NAME_PATTERN = Pattern
76                         .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
77         public final static Integer VENDOR_RELEASE_MAX_LENGTH = 25;
78         public final static Pattern VENDOR_RELEASE_PATTERN = Pattern
79                         .compile("^[\\x20-\\x21\\x23-\\x29\\x2B-\\x2E\\x30-\\x39\\x3B\\x3D\\x40-\\x5B\\x5D-\\x7B\\x7D-\\xFF]+$");
80         public final static Integer RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH = 65;
81
82         public final static Pattern CLEAN_FILENAME_PATTERN = Pattern.compile("[\\x00-\\x1f\\x80-\\x9f\\x5c/<?>\\*:|\"/]+");
83
84         public final static Pattern DASH_PATTERN = Pattern.compile("[-]+");
85         public final static Pattern UNDERSCORE_PATTERN = Pattern.compile("[_]+");
86         public final static Pattern PLUS_PATTERN = Pattern.compile("[+]+");
87         public final static Pattern SPACE_PATTERN = Pattern.compile("[ ]+");
88         public final static Pattern AMP_PATTERN = Pattern.compile("[&]+");
89         public final static Pattern DOT_PATTERN = Pattern.compile("[\\.]+");
90         public final static Pattern APOST_PATTERN = Pattern.compile("[']+");
91         public final static Pattern HASHTAG_PATTERN = Pattern.compile("[#]+");
92         public final static Pattern EQUAL_PATTERN = Pattern.compile("[=]+");
93         public final static Pattern COLON_PATTERN = Pattern.compile("[:]+");
94         public final static Pattern AT_PATTERN = Pattern.compile("[@]+");
95         public final static Pattern AND_PATTERN = Pattern.compile(" [aA][Nn][Dd] ");
96         public final static Set<String> CATEGORY_CONJUNCTIONS = new HashSet<String>(
97                         Arrays.asList("of", "to", "for", "as", "a", "an", "the"));
98
99         public final static Pattern COST_PATTERN = Pattern.compile("^[0-9]{1,5}\\.[0-9]{1,3}$");
100         public final static Pattern ARTIFACT_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9 \\-+]+$");
101         public final static Integer ARTIFACT_LABEL_LENGTH = 255;
102         public final static Pattern ARTIFACT_DISPLAY_NAME_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
103         public final static Pattern CATEGORY_LABEL_PATTERN = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9 &\\.'#=:@_\\-+]+$");
104         public final static Integer CATEGORY_LABEL_MIN_LENGTH = 4;
105         public final static Integer CATEGORY_LABEL_MAX_LENGTH = 25;
106
107         public final static Pattern COMPONENT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_]+");
108         public final static Pattern COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-]+");
109         public final static Pattern PRODUCT_NAME_DELIMETER_PATTERN = Pattern.compile("[\\.\\-\\_&=#@':\\[\\]\\+]+");
110         public final static Integer CONSUMER_NAME_MAX_LENGTH = 255;
111         // public final static Pattern CONSUMER_NAME_PATTERN =
112         // Pattern.compile("^[\\w]{1}?[\\w\\.\\-]{0," + CONSUMER_NAME_MAX_LENGTH +
113         // "}?$");
114         public final static Pattern CONSUMER_NAME_PATTERN = Pattern.compile("^[\\w]+[\\w\\.\\-]*$");
115         public final static Integer CONSUMER_SALT_LENGTH = 32;
116         public final static Integer CONSUMER_PASSWORD_LENGTH = 64;
117         public final static Pattern CONSUMER_PASS_SALT_PATTERN = Pattern.compile("^[a-z0-9]+$");
118         public final static Pattern FLOAT_PATTERN = Pattern.compile("^[\\d]+[\\.]{1}[\\d]+$");
119         public final static Pattern CERTIFIED_VERSION_PATTERN = Pattern.compile("^[1-9][0-9]*\\.0$");
120         public final static Pattern MINOR_VERSION_PATTERN = Pattern.compile("^0\\.[1-9][0-9]*$");
121         public final static Pattern TAGS_PATTERN = Pattern.compile("<[^><]*>");
122
123         public final static Integer ARTIFACT_NAME_LENGTH = 255;
124         public final static Integer API_URL_LENGTH = 100;
125         public final static Integer ARTIFACT_DESCRIPTION_MAX_LENGTH = 256;
126
127         public final static Integer PRODUCT_FULL_NAME_MIN_LENGTH = 4;
128         public final static Integer PRODUCT_FULL_NAME_MAX_LENGTH = 100;
129
130         public static boolean validateArtifactLabel(String label) {
131                 return ARTIFACT_LABEL_PATTERN.matcher(label).matches();
132         }
133         
134         public static boolean validateArtifactDisplayName(String displayName) {
135                 return ARTIFACT_DISPLAY_NAME_PATTERN.matcher(displayName).matches();
136         }
137
138         public static boolean validateCategoryDisplayNameFormat(String label) {
139                 boolean res = true;
140                 if (label != null) {
141                         label = label.trim();
142                         res = CATEGORY_LABEL_PATTERN.matcher(label).matches();
143                 }
144                 return res;
145         }
146
147         public static String normalizeCategoryName4Display(String str) {
148                 if (str != null) {
149                         str = str.trim();
150                         str = DASH_PATTERN.matcher(str).replaceAll("-");
151                         str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
152                         str = AMP_PATTERN.matcher(str).replaceAll("&");
153                         str = PLUS_PATTERN.matcher(str).replaceAll("+");
154                         str = DOT_PATTERN.matcher(str).replaceAll(".");
155                         str = APOST_PATTERN.matcher(str).replaceAll("'");
156                         str = HASHTAG_PATTERN.matcher(str).replaceAll("#");
157                         str = EQUAL_PATTERN.matcher(str).replaceAll("=");
158                         str = COLON_PATTERN.matcher(str).replaceAll(":");
159                         str = AT_PATTERN.matcher(str).replaceAll("@");
160                         str = normaliseWhitespace(str);
161                         str = AND_PATTERN.matcher(str).replaceAll(" & ");
162
163                         // Case normalizing
164                         StringBuilder sb = new StringBuilder();
165                         String[] split = str.split(" ");
166                         for (int i = 0; i < split.length; i++) {
167                                 String splitted = split[i];
168                                 String lowerCase = splitted.toLowerCase();
169                                 // BANK OF AMERICA --> BANK of AMERICA ("of" is lowercased), but
170                                 // OF BANK OF AMERICA --> OF BANK of AMERICA (first "OF" is not
171                                 // lowercased because it's first word)
172                                 // Agreed with Ella, 26/11/15
173                                 if ((i > 0) && CATEGORY_CONJUNCTIONS.contains(lowerCase)) {
174                                         sb.append(lowerCase);
175                                 } else {
176                                         sb.append(WordUtils.capitalize(splitted));
177                                 }
178                                 sb.append(" ");
179                         }
180                         str = sb.toString().trim();
181                 }
182                 return str;
183         }
184
185         public static String normalizeCategoryName4Uniqueness(String str) {
186                 return str.toLowerCase();
187         }
188
189         public static boolean validateCategoryDisplayNameLength(String label) {
190                 return (label != null && label.length() >= CATEGORY_LABEL_MIN_LENGTH
191                                 && label.length() <= CATEGORY_LABEL_MAX_LENGTH);
192         }
193
194         public static boolean validateProductFullNameLength(String fullName) {
195                 return (fullName != null && fullName.length() >= PRODUCT_FULL_NAME_MIN_LENGTH
196                                 && fullName.length() <= PRODUCT_FULL_NAME_MAX_LENGTH);
197         }
198
199         public static boolean validateArtifactLabelLength(String label) {
200                 return label.length() > 0 && label.length() <= ARTIFACT_LABEL_LENGTH;
201         }
202
203         public static boolean validateResourceInstanceNameLength(String resourceInstanceName) {
204                 return resourceInstanceName.length() <= RSI_NAME_MAX_LENGTH;
205         }
206
207         public static boolean validateResourceInstanceName(String resourceInstanceName) {
208                 return RSI_NAME_PATTERN.matcher(resourceInstanceName).matches();
209         }
210
211         public static boolean validateUrlLength(String url) {
212                 return url.length() <= API_URL_LENGTH;
213         }
214
215         public static boolean validateArtifactNameLength(String artifactName) {
216                 return (artifactName.length() <= ARTIFACT_NAME_LENGTH && artifactName.length() > 0);
217         }
218
219         public static boolean validateComponentNamePattern(String componentName) {
220                 return COMPONENT_NAME_PATTERN.matcher(componentName).matches();
221         }
222
223         public static boolean validateComponentNameLength(String componentName) {
224                 return componentName.length() <= COMPONENT_NAME_MAX_LENGTH;
225         }
226
227         public static boolean validateIcon(String icon) {
228                 return ICON_PATTERN.matcher(icon).matches();
229         }
230
231         public static boolean validateIconLength(String icon) {
232                 return icon.length() <= ICON_MAX_LENGTH;
233         }
234
235         public static boolean validateProjectCode(String projectCode) {
236                 return PROJECT_CODE_PATTERN.matcher(projectCode).matches();
237         }
238
239         public static boolean validateProjectCodeLegth(String projectCode) {
240                 return projectCode.length() <= PROJECT_CODE_MAX_LEGTH;
241         }
242
243         public static boolean validateContactId(String contactId) {
244                 return CONTACT_ID_PATTERN.matcher(contactId).matches();
245         }
246
247         public static boolean validateCost(String cost) {
248                 return COST_PATTERN.matcher(cost).matches();
249         }
250
251         public static String removeHtmlTags(String str) {
252                 return Jsoup.clean(str, Whitelist.none());
253         }
254
255         public static String removeAllTags(String htmlText) {
256
257                 String stripped = TAGS_PATTERN.matcher(htmlText).replaceAll("").trim();
258                 return stripped;
259         }
260
261         public static String normaliseWhitespace(String str) {
262                 return StringUtil.normaliseWhitespace(str);
263         }
264
265         public static String stripOctets(String str) {
266                 return OCTET_PATTERN.matcher(str).replaceAll("");
267         }
268
269         public static String removeNoneUtf8Chars(String input) {
270                 return NONE_UTF8_PATTERN.matcher(input).replaceAll("");
271         }
272
273         public static boolean validateIsEnglish(String input) {
274                 return ENGLISH_PATTERN.matcher(input).matches();
275         }
276
277         public static boolean validateIsAscii(String input) {
278
279                 boolean isAscii = CharMatcher.ASCII.matchesAllOf(input);
280
281                 return isAscii;
282         }
283
284         public static String convertHtmlTagsToEntities(String input) {
285                 return StringEscapeUtils.escapeHtml4(input);
286         }
287
288         public static List<String> removeDuplicateFromList(List<String> list) {
289                 Set<String> hs = new LinkedHashSet<>(list);
290                 list.clear();
291                 list.addAll(hs);
292                 return list;
293
294         }
295
296         public static boolean validateTagLength(String tag) {
297                 if (tag != null) {
298                         return tag.length() <= TAG_MAX_LENGTH;
299                 }
300                 return false;
301         }
302
303         public static boolean validateTagListLength(int tagListLength) {
304                 return tagListLength <= TAG_LIST_MAX_LENGTH;
305         }
306
307         public static boolean validateDescriptionLength(String description) {
308                 return description.length() <= COMPONENT_DESCRIPTION_MAX_LENGTH;
309         }
310
311         public static boolean validateStringNotEmpty(String value) {
312                 if ((value == null) || (value.isEmpty())) {
313                         return false;
314                 }
315                 return true;
316         }
317
318         public static boolean validateListNotEmpty(List<?> list) {
319                 if ((list == null) || (list.isEmpty())) {
320                         return false;
321                 }
322                 return true;
323         }
324
325         public static boolean validateVendorName(String vendorName) {
326                 return VENDOR_NAME_PATTERN.matcher(vendorName).matches();
327         }
328
329         public static boolean validateVendorNameLength(String vendorName) {
330                 return vendorName.length() <= VENDOR_NAME_MAX_LENGTH;
331         }
332
333         public static boolean validateResourceVendorModelNumberLength(String resourceVendorModelNumber) {
334                 return resourceVendorModelNumber.length() <= RESOURCE_VENDOR_MODEL_NUMBER_MAX_LENGTH;
335         }
336         
337         public static boolean validateVendorRelease(String vendorRelease) {
338                 return VENDOR_RELEASE_PATTERN.matcher(vendorRelease).matches();
339         }
340
341         public static boolean validateVendorReleaseLength(String vendorRelease) {
342                 return vendorRelease.length() <= VENDOR_RELEASE_MAX_LENGTH;
343         }
344         
345         public static boolean validateServiceTypeLength(String serviceType) {
346                 return serviceType.length() <= SERVICE_TYPE_MAX_LENGTH;
347         }
348         
349         public static boolean validateServiceRoleLength(String serviceRole) {
350                 return serviceRole.length() <= SERVICE_ROLE_MAX_LENGTH;
351         }
352
353
354
355         public static boolean hasBeenCertified(String version) {
356                 return NumberUtils.toDouble(version) >= 1;
357         }
358
359         public static String normaliseComponentName(String name) {
360                 String[] split = splitComponentName(name);
361                 StringBuffer sb = new StringBuffer();
362                 for (String splitElement : split) {
363                         sb.append(splitElement);
364                 }
365                 return sb.toString();
366
367         }
368
369         public static String normalizeComponentInstanceName(String name) {
370                 String[] split = splitComponentInctanceName(name);
371                 StringBuffer sb = new StringBuffer();
372                 for (String splitElement : split) {
373                         sb.append(splitElement);
374                 }
375                 return sb.toString();
376
377         }
378
379         private static String[] splitComponentName(String name) {
380                 String normalizedName = name.toLowerCase();
381                 normalizedName = COMPONENT_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
382                 String[] split = normalizedName.split(" ");
383                 return split;
384         }
385
386         private static String[] splitComponentInctanceName(String name) {
387                 String normalizedName = name.toLowerCase();
388                 normalizedName = COMPONENT_INCTANCE_NAME_DELIMETER_PATTERN.matcher(normalizedName).replaceAll(" ");
389                 String[] split = normalizedName.split(" ");
390                 return split;
391         }
392
393         public static String convertToSystemName(String name) {
394                 String[] split = splitComponentName(name);
395                 StringBuffer sb = new StringBuffer();
396                 for (String splitElement : split) {
397                         String capitalize = WordUtils.capitalize(splitElement);
398                         sb.append(capitalize);
399                 }
400                 return sb.toString();
401         }
402
403         public static String normalizeFileName(String filename) {
404                 // String[] split = filename.split(Pattern.quote(File.separator));
405                 // String name = "";
406                 //
407                 // name = split[split.length - 1];
408                 return cleanFileName(filename);
409
410         }
411
412         private static String cleanFileName(String str) {
413                 str = CLEAN_FILENAME_PATTERN.matcher(str).replaceAll("");
414                 str = normaliseWhitespace(str);
415                 str = SPACE_PATTERN.matcher(str).replaceAll("-");
416                 str = DASH_PATTERN.matcher(str).replaceAll("-");
417                 str = StringUtils.strip(str, "-_ .");
418
419                 return str;
420         }
421
422         public static boolean validateUrl(String url) {
423
424                 UrlValidator urlValidator = new UrlValidator();
425                 if (!urlValidator.isValid(url)) {
426                         return false;
427                 }
428                 if (NONE_UTF8_PATTERN.matcher(url).find()) {
429                         return false;
430                 }
431
432                 if (URL_INVALIDE_PATTERN.matcher(url).find()) {
433                         return false;
434                 }
435                 return true;
436
437         }
438
439         public static String cleanArtifactDisplayName(String strIn) {
440                 String str = DASH_PATTERN.matcher(strIn).replaceAll("-");
441                 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
442                 str = PLUS_PATTERN.matcher(str).replaceAll("+");
443                 str = normaliseWhitespace(str);
444                 str = str.trim();
445                 // str = str.replaceAll(" ", "");
446
447                 return str;
448         }
449
450         public static String normalizeArtifactLabel(String strIn) {
451
452                 String str = DASH_PATTERN.matcher(strIn).replaceAll("");
453                 str = UNDERSCORE_PATTERN.matcher(str).replaceAll("");
454                 str = PLUS_PATTERN.matcher(str).replaceAll("");
455                 str = SPACE_PATTERN.matcher(str).replaceAll("");
456                 str = DOT_PATTERN.matcher(str).replaceAll("");
457                 str = str.toLowerCase();
458
459                 return str;
460         }
461
462         public static boolean validateAdditionalInformationKeyName(String str) {
463                 return ADDITIONAL_INFORMATION_KEY_PATTERN.matcher(str).matches();
464         }
465
466         public static String normalizeAdditionalInformation(String str) {
467                 if (str != null) {
468                         str = DASH_PATTERN.matcher(str).replaceAll("-");
469                         str = UNDERSCORE_PATTERN.matcher(str).replaceAll("_");
470                         str = normaliseWhitespace(str);
471                 }
472                 return str;
473         }
474
475         public static boolean validateLength(String str, int length) {
476                 if (str == null) {
477                         return true;
478                 }
479                 return str.length() <= length;
480         }
481
482         public static boolean validateConsumerName(String consumerName) {
483                 return CONSUMER_NAME_PATTERN.matcher(consumerName).matches();
484         }
485
486         public static boolean isUTF8Str(String str) {
487                 if (NONE_UTF8_PATTERN.matcher(str).find()) {
488                         return false;
489                 }
490                 return true;
491         }
492
493         public static boolean validateConsumerPassSalt(String consumerSalt) {
494                 return CONSUMER_PASS_SALT_PATTERN.matcher(consumerSalt).matches();
495         }
496
497         public static boolean isFloatNumber(String number) {
498                 return FLOAT_PATTERN.matcher(number).matches();
499         }
500
501         public static boolean validateCertifiedVersion(String version) {
502                 return (version != null && CERTIFIED_VERSION_PATTERN.matcher(version).matches());
503         }
504
505         public static boolean validateMinorVersion(String version) {
506                 return (version != null && MINOR_VERSION_PATTERN.matcher(version).matches());
507         }
508
509         public static String normaliseProductName(String name) {
510                 String[] split = splitComponentName(PRODUCT_NAME_DELIMETER_PATTERN, name);
511                 StringBuffer sb = new StringBuffer();
512                 for (String splitElement : split) {
513                         sb.append(splitElement);
514                 }
515                 return sb.toString();
516
517         }
518
519         private static String[] splitComponentName(Pattern pattern, String name) {
520                 String normalizedName = name.toLowerCase();
521                 normalizedName = pattern.matcher(normalizedName).replaceAll(" ");
522                 String[] split = normalizedName.split(" ");
523                 return split;
524         }
525
526         public static String removeHtmlTagsOnly(String htmlText) {
527                 String stripped = HtmlCleaner.stripHtml(htmlText, false);
528                 return stripped;
529         }
530         
531 }