5a4d3cbd0da1241c43df540b529082caecb64049
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.openecomp.core.utilities;
18
19 import org.apache.commons.collections4.MapUtils;
20 import org.apache.commons.lang3.ArrayUtils;
21 import org.apache.commons.lang3.StringUtils;
22 import java.util.*;
23
24 import java.lang.reflect.Array;
25
26 /**
27  * This class provides auxiliary static methods.
28  */
29 public class CommonMethods {
30
31   private static final char[] CHARS = new char[]{
32       '0', '1', '2', '3', '4', '5', '6', '7',
33       '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
34   };
35
36   /**
37    * Private default constructor to prevent instantiation of the class objects.
38    */
39   private CommonMethods() {
40   }
41
42   /**
43    * Checks whether the given collection is empty.
44    *
45    * @param collection A collection to be checked.
46    * @return <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - otherwise.
47    */
48   public static boolean isEmpty(Collection<?> collection) {
49     return collection == null || collection.isEmpty();
50   }
51
52   /**
53    * Gets an universally unique identifier (UUID).
54    *
55    * @return String representation of generated UUID.
56    */
57   public static String nextUuId() {
58     UUID uuid = UUID.randomUUID();
59
60     StringBuilder buff = new StringBuilder(32);
61     long2string(uuid.getMostSignificantBits(), buff);
62     long2string(uuid.getLeastSignificantBits(), buff);
63
64     return buff.toString();
65   }
66
67   private static void long2string(long lng, StringBuilder buff) {
68     long value = lng;
69     for (int i = 0; i < 16; i++) {
70       long nextByte = value & 0xF000000000000000L;
71       value <<= 4;
72       boolean isNegative = nextByte < 0;
73       nextByte = nextByte >>> 60;
74
75       if (isNegative) {
76         nextByte |= 0x08;
77       }
78
79       buff.append(CHARS[(int) nextByte]);
80     }
81   }
82
83   /**
84    * Concatenates two Java arrays. The method allocates a new array and copies
85    * all elements to it or returns one of input arrays if another one is
86    * empty.
87    *
88    * @param <T>   the type parameter
89    * @param left  Elements of this array will be copied to positions from 0 to <tt>left.length -
90    *              1</tt> in the target array.
91    * @param right Elements of this array will be copied to positions from <tt>left.length</tt> to
92    *              <tt>left.length + right.length</tt>
93    * @return A newly allocate Java array that accommodates elements of source (left/right) arrays
94     orone of source arrays if another is empty, <tt>null</tt> - otherwise.
95    */
96   @SuppressWarnings("unchecked")
97   public static <T> T[] concat(T[] left, T[] right) {
98     T[] res;
99
100     if (ArrayUtils.isEmpty(left)) {
101       res = right;
102     } else if (ArrayUtils.isEmpty(right)) {
103       res = left;
104     } else {
105       res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length);
106       System.arraycopy(left, 0, res, 0, left.length);
107       System.arraycopy(right, 0, res, left.length, right.length);
108     }
109
110     return res;
111   } // concat
112
113   /**
114    * New instance object.
115    *
116    * @param classname the classname
117    * @return the object
118    */
119   public static Object newInstance(String classname) {
120     return newInstance(classname, Object.class);
121   }
122
123   /**
124    * New instance t.
125    *
126    * @param <T>       the type parameter
127    * @param classname the classname
128    * @param cls       the cls
129    * @return the t
130    */
131   @SuppressWarnings("unchecked")
132   public static <T> T newInstance(String classname, Class<T> cls) {
133
134     if (StringUtils.isEmpty(classname)) {
135       throw new IllegalArgumentException();
136     }
137
138     if (cls == null) {
139       throw new IllegalArgumentException();
140     }
141
142     try {
143       Class<?> temp = Class.forName(classname);
144
145       if (!cls.isAssignableFrom(temp)) {
146         throw new ClassCastException(
147             String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
148       }
149
150       Class<? extends T> impl = (Class<? extends T>) temp;
151
152       return newInstance(impl);
153     } catch (ClassNotFoundException exception) {
154       throw new IllegalArgumentException(exception);
155     }
156   }
157
158   /**
159    * New instance t.
160    *
161    * @param <T> the type parameter
162    * @param cls the cls
163    * @return the t
164    */
165   public static <T> T newInstance(Class<T> cls) {
166     try {
167       return cls.newInstance();
168     } catch (InstantiationException | IllegalAccessException exception) {
169       throw new RuntimeException(exception);
170     }
171   }
172
173   /**
174    * Print stack trace string.
175    *
176    * @return the string
177    */
178   public static String printStackTrace() {
179     StringBuilder sb = new StringBuilder();
180     StackTraceElement[] trace = Thread.currentThread().getStackTrace();
181     for (StackTraceElement traceElement : trace) {
182       sb.append("\t  ").append(traceElement);
183       sb.append(System.lineSeparator());
184     }
185     return sb.toString();
186   }
187
188   /**
189    * Converts array of strings to comma-separated string.
190    *
191    * @param arr array of strings
192    * @return the string
193    */
194   public static String arrayToCommaSeparatedString(String[] arr) {
195     return arrayToSeparatedString(arr, ',');
196   }
197
198   /**
199    * Collection to comma separated string string.
200    *
201    * @param elementCollection the element collection
202    * @return the string
203    */
204   public static String collectionToCommaSeparatedString(Collection<String> elementCollection) {
205     return String.join(",", elementCollection);
206   }
207
208   /**
209    * Converts array of strings to string separated with specified character.
210    *
211    * @param arr       array of strings
212    * @param separator the separator
213    * @return the string
214    */
215   public static String arrayToSeparatedString(String[] arr, char separator) {
216     return String.join(Character.toString(separator), arr);
217   }
218
219   /**
220    * Converts array of strings to string separated with specified character.
221    *
222    * @param list      array of strings
223    * @param separator the separator
224    * @return the string
225    */
226   public static String listToSeparatedString(List<String> list, char separator) {
227     return String.join(Character.toString(separator), list);
228   }
229
230   /**
231    * Duplicate string with delimiter string.
232    *
233    * @param arg                  the arg
234    * @param separator            the separator
235    * @param numberOfDuplications the number of duplications
236    * @return the string
237    */
238   public static String duplicateStringWithDelimiter(String arg, char separator,
239                                                     int numberOfDuplications) {
240     StringBuilder sb = new StringBuilder();
241
242     for (int i = 0; i < numberOfDuplications; i++) {
243       if (i > 0) {
244         sb.append(separator);
245       }
246       sb.append(arg);
247     }
248     return sb.toString();
249   }
250
251   /**
252    * To single element set set.
253    *
254    * @param <T>     the class of the objects in the set
255    * @param element the single element to be contained in the returned Set
256    * @return an immutable set containing only the specified object. The returned set is
257     serializable.
258    */
259   public static <T> Set<T> toSingleElementSet(T element) {
260     return Collections.singleton(element);
261
262   }
263
264   /**
265    * Merge lists of map list.
266    *
267    * @param <T>    the type parameter
268    * @param <S>    the type parameter
269    * @param target the target
270    * @param source the source
271    * @return the list
272    */
273   public static <T, S> List<Map<T, S>> mergeListsOfMap(List<Map<T, S>> target,
274                                                        List<Map<T, S>> source) {
275     List<Map<T, S>> retList = new ArrayList<>();
276     if (Objects.nonNull(target)) {
277       retList.addAll(target);
278     }
279
280     if (Objects.nonNull(source)) {
281       for (Map<T, S> sourceMap : source) {
282         for (Map.Entry<T, S> entry : sourceMap.entrySet()) {
283           mergeEntryInList(entry.getKey(), entry.getValue(), retList);
284         }
285       }
286     }
287     return retList;
288   }
289
290   /**
291    * Merge lists list.
292    *
293    * @param <T>    the type parameter
294    * @param target the target
295    * @param source the source
296    * @return the list
297    */
298   public static <T> List<T> mergeLists(List<T> target, List<T> source) {
299     List<T> retList = new ArrayList<>();
300
301     if (Objects.nonNull(source)) {
302       retList.addAll(source);
303     }
304     if (Objects.nonNull(target)) {
305       retList.addAll(target);
306     }
307
308     return retList;
309   }
310
311   /**
312    * Merge entry in list.
313    *
314    * @param <T>    the type parameter
315    * @param <S>    the type parameter
316    * @param key    the key
317    * @param value  the value
318    * @param target the target
319    */
320   public static <T, S> void mergeEntryInList(T key, S value, List<Map<T, S>> target) {
321     boolean found = false;
322     for (Map<T, S> map : target) {
323       if (map.containsKey(key)) {
324         map.put(key, value);
325         found = true;
326       }
327     }
328
329     if (!found) {
330       Map<T, S> newMap = new HashMap<>();
331       newMap.put(key, value);
332       target.add(newMap);
333     }
334   }
335
336
337   /**
338    * Merge maps map.
339    *
340    * @param <T>    the type parameter
341    * @param <S>    the type parameter
342    * @param firstMap the firstMap
343    * @param secondMap the secondMap
344    * @return the map
345    * Second Map is overridden data from the first map
346    */
347   public static <T, S> Map<T, S> mergeMaps(Map<T, S> firstMap, Map<T, S> secondMap) {
348     Map<T, S> retMap = new HashMap<>();
349     if (MapUtils.isNotEmpty(firstMap)) {
350       retMap.putAll(firstMap);
351     }
352     if (MapUtils.isNotEmpty(secondMap)) {
353       retMap.putAll(secondMap);
354     }
355     return retMap;
356   }
357
358 }
359