Catalog alignment
[sdc.git] / common-app-api / src / main / java / org / openecomp / sdc / common / util / GeneralUtility.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 org.apache.commons.codec.binary.Base64;
24 import org.apache.commons.io.FileUtils;
25 import org.onap.logging.ref.slf4j.ONAPLogConstants;
26 import org.openecomp.sdc.common.api.Constants;
27 import org.openecomp.sdc.common.log.api.ILogConfiguration;
28 import org.slf4j.MDC;
29
30 import java.io.File;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.HashMap;
34 import java.util.List;
35 import java.util.Map;
36 import java.util.regex.Pattern;
37
38 public class GeneralUtility {
39
40         public static boolean generateTextFile(String fileName, String fileData) {
41                 boolean isSuccessfull = true;
42                 try {
43                         FileUtils.writeStringToFile(new File(fileName), fileData);
44                 } catch (IOException e) {
45                         isSuccessfull = false;
46                 }
47                 return isSuccessfull;
48         }
49         
50         /**
51          * Use with care, usage is not advised!!!
52          * The method only checks if String does not contain special characters + length divided by 4 with no remainder.
53          * The methods contained in other common libraries do the same.
54          */
55         public static boolean isBase64Encoded(byte[] data) {
56                 return Base64.isBase64(data);
57         }
58         
59         /**
60          *Use with care, usage is not advised!!!
61          * The method only checks if String does not contain special characters + length divided by 4 with no remainder.
62          * The methods contained in other common libraries do the same.
63          */
64         public static boolean isBase64Encoded(String str) {
65                 boolean isEncoded = false;
66                 try {
67                         // checks if the string was properly padded to the
68                         isEncoded = ((str.length() % 4 == 0) && (Pattern.matches("\\A[a-zA-Z0-9/+]+={0,2}\\z", str)));
69                         if (isEncoded) {
70                                 // If no exception is caught, then it is possibly a base64
71                                 // encoded string
72                                 byte[] data = Base64.decodeBase64(str);
73                         }
74
75                 } catch (Exception e) {
76                         // If exception is caught, then it is not a base64 encoded string
77                         isEncoded = false;
78                 }
79                 return isEncoded;
80         }
81
82         /**
83          * Checks whether the passed string exceeds a limit of number of characters.
84          * 
85          * @param str
86          * @param limit
87          * @return the result of comparison, or false if str is null.
88          */
89         public static boolean isExceedingLimit(String str, int limit) {
90                 if (str == null) {
91                         return false;
92                 }
93                 return str.length() > limit;
94         }
95
96         /**
97          * 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
98          * 3+1+3+1+5=13
99          *
100          * @param strList
101          * @param limit
102          * @param delimiterLength
103          *            - 0 if there is no delimeter.
104          * @return the result of comparison, or false if strList is null.
105          */
106         public static boolean isExceedingLimit(List<String> strList, int limit, int delimiterLength) {
107                 if (strList == null || strList.isEmpty()) {
108                         return false;
109                 }
110                 int sum = 0;
111                 int size = strList.size();
112                 for (int i = 0; i < size - 1; i++) {
113                         String str = strList.get(i);
114                         if (str != null) {
115                                 sum += str.length();
116                         }
117                         sum += delimiterLength;
118                 }
119                 String str = strList.get(size - 1);
120                 if (str != null) {
121                         sum += str.length();
122                 }
123                 return sum > limit;
124         }
125
126         /**
127          * 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.
128          * 
129          * @param fileName
130          * @return extension
131          */
132         public static String getFilenameExtension(String fileName) {
133                 String res = Constants.EMPTY_STRING;
134                 if (fileName != null) {
135                         int indexOf = fileName.lastIndexOf('.');
136                         if (indexOf != -1 && indexOf < (fileName.length() - 1)) {
137                                 res = fileName.substring(indexOf + 1);
138                         }
139                 }
140                 return res;
141         }
142
143         public static String calculateMD5Base64EncodedByByteArray(byte[] payload) {
144                 String decodedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(payload);
145                 byte[] encodeMd5 = Base64.encodeBase64(decodedMd5.getBytes());
146                 return new String(encodeMd5);
147
148         }
149
150         /**
151          * 
152          * @param data
153          * @return
154          */
155         public static String calculateMD5Base64EncodedByString(String data) {
156                 String calculatedMd5 = org.apache.commons.codec.digest.DigestUtils.md5Hex(data);
157
158                 // encode base-64 result
159                 byte[] encodeBase64 = Base64.encodeBase64(calculatedMd5.getBytes());
160                 return new String(encodeBase64);
161         }
162         
163         
164         /**
165          * 
166          * @param String
167          * @return String is null or Empty
168          */
169         public static boolean isEmptyString(String str) {
170         return str == null || str.trim().isEmpty();
171     }
172
173         public static String getEcompRequestId() {
174                 return MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
175         }
176
177
178
179
180         public static <T extends ICategorizedElement> Map<String,Map<String,List<T>>> getCategorizedComponents(List<T> components) {
181
182                 Map<String, Map<String, List<T>>> categorizedMap = new HashMap<>();
183                 components.forEach(component -> categorizeComponent(component, categorizedMap));
184                 return categorizedMap;
185         }
186
187         private static <T extends ICategorizedElement> void categorizeComponent(T component, Map<String, Map<String, List<T>>> categorizedMap) {
188                 if(component.getComponentTypeAsString().equals("SERVICE")){
189                         categorizeService(component, categorizedMap);
190                 }else if(component.getComponentTypeAsString().equals("RESOURCE")){
191                         categorizeResource(component, categorizedMap);
192                 }
193         }
194
195         private static <T extends ICategorizedElement> void categorizeResource(T component, Map<String, Map<String, List<T>>> categorizedMap) {
196                 String category = component.getCategoryName();
197                 String subCategory = component.getSubcategoryName();
198                 putComponentToMap(component, categorizedMap, category, subCategory);
199         }
200
201         private static <T extends ICategorizedElement> void categorizeService(T component, Map<String, Map<String, List<T>>> categorizedMap) {
202                 String category = "Generic";
203                 String subCategory = "Generic";
204                 putComponentToMap(component, categorizedMap, category, subCategory);
205         }
206
207         private static <T extends ICategorizedElement> void putComponentToMap(T component, Map<String, Map<String, List<T>>> categorizedMap,
208                                                                                                                                                   String category, String subCategory) {
209
210                 Map<String, List<T>> categoryMap = categorizedMap.computeIfAbsent(category, k -> new HashMap<>());
211                 List<T> subCategoryList = categoryMap.computeIfAbsent(subCategory, k -> new ArrayList<>());
212                 subCategoryList.add(component);
213         }
214
215 }