0bcdf8ebbffb5f7e6743cd64e4a256970a751344
[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 java.lang.reflect.Array;
20 import java.lang.reflect.InvocationTargetException;
21 import java.util.ArrayList;
22 import java.util.Collection;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Set;
29 import java.util.UUID;
30
31 import org.apache.commons.collections4.MapUtils;
32 import org.apache.commons.lang3.ArrayUtils;
33 import org.apache.commons.lang3.StringUtils;
34 import org.openecomp.core.utilities.exception.NewInstanceRuntimeException;
35
36 /**
37  * This class provides auxiliary static methods.
38  */
39 public class CommonMethods {
40
41     private static final char[] CHARS = new char[] {
42             '0', '1', '2', '3', '4', '5', '6', '7',
43             '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
44     };
45
46     /**
47      * Private default constructor to prevent instantiation of the class objects.
48      */
49     private CommonMethods() {
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      * or one 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(final Class<T> cls) {
166         try {
167             return cls.getDeclaredConstructor().newInstance();
168         } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException ex) {
169             throw new NewInstanceRuntimeException(String.format("Could not create instance for '%s'", cls.getName())
170                 , ex);
171         }
172     }
173
174     /**
175      * Print stack trace string.
176      *
177      * @return the string
178      */
179     public static String printStackTrace() {
180         StringBuilder sb = new StringBuilder();
181         StackTraceElement[] trace = Thread.currentThread().getStackTrace();
182         for (StackTraceElement traceElement : trace) {
183             sb.append("\t  ").append(traceElement);
184             sb.append(System.lineSeparator());
185         }
186         return sb.toString();
187     }
188
189     /**
190      * Converts array of strings to comma-separated string.
191      *
192      * @param arr array of strings
193      * @return the string
194      */
195     public static String arrayToCommaSeparatedString(String[] arr) {
196         return arrayToSeparatedString(arr, ',');
197     }
198
199     /**
200      * Collection to comma separated string string.
201      *
202      * @param elementCollection the element collection
203      * @return the string
204      */
205     public static String collectionToCommaSeparatedString(Collection<String> elementCollection) {
206         return String.join(",", elementCollection);
207     }
208
209     /**
210      * Converts array of strings to string separated with specified character.
211      *
212      * @param arr       array of strings
213      * @param separator the separator
214      * @return the string
215      */
216     public static String arrayToSeparatedString(String[] arr, char separator) {
217         return String.join(Character.toString(separator), arr);
218     }
219
220     /**
221      * Converts array of strings to string separated with specified character.
222      *
223      * @param list      array of strings
224      * @param separator the separator
225      * @return the string
226      */
227     public static String listToSeparatedString(List<String> list, char separator) {
228         return String.join(Character.toString(separator), list);
229     }
230
231     /**
232      * Duplicate string with delimiter string.
233      *
234      * @param arg                  the arg
235      * @param separator            the separator
236      * @param numberOfDuplications the number of duplications
237      * @return the string
238      */
239     public static String duplicateStringWithDelimiter(String arg, char separator,
240                                                       int numberOfDuplications) {
241         StringBuilder sb = new StringBuilder();
242
243         for (int i = 0; i < numberOfDuplications; i++) {
244             if (i > 0) {
245                 sb.append(separator);
246             }
247             sb.append(arg);
248         }
249         return sb.toString();
250     }
251
252     /**
253      * To single element set set.
254      *
255      * @param <T>     the class of the objects in the set
256      * @param element the single element to be contained in the returned Set
257      * @return an immutable set containing only the specified object. The returned set is
258      * serializable.
259      */
260     public static <T> Set<T> toSingleElementSet(T element) {
261         return Collections.singleton(element);
262
263     }
264
265     /**
266      * Merge lists of map list.
267      *
268      * @param <T>    the type parameter
269      * @param <S>    the type parameter
270      * @param target the target
271      * @param source the source
272      * @return the list
273      */
274     public static <T, S> List<Map<T, S>> mergeListsOfMap(List<Map<T, S>> target,
275                                                          List<Map<T, S>> source) {
276         List<Map<T, S>> retList = new ArrayList<>();
277         if (Objects.nonNull(target)) {
278             retList.addAll(target);
279         }
280
281         if (Objects.nonNull(source)) {
282             for (Map<T, S> sourceMap : source) {
283                 for (Map.Entry<T, S> entry : sourceMap.entrySet()) {
284                     mergeEntryInList(entry.getKey(), entry.getValue(), retList);
285                 }
286             }
287         }
288         return retList;
289     }
290
291     /**
292      * Merge lists list.
293      *
294      * @param <T>    the type parameter
295      * @param target the target
296      * @param source the source
297      * @return the list
298      */
299     public static <T> List<T> mergeLists(List<T> target, List<T> source) {
300         List<T> retList = new ArrayList<>();
301
302         if (Objects.nonNull(source)) {
303             retList.addAll(source);
304         }
305         if (Objects.nonNull(target)) {
306             retList.addAll(target);
307         }
308
309         return retList;
310     }
311
312     /**
313      * Merge entry in list.
314      *
315      * @param <T>    the type parameter
316      * @param <S>    the type parameter
317      * @param key    the key
318      * @param value  the value
319      * @param target the target
320      */
321     public static <T, S> void mergeEntryInList(T key, S value, List<Map<T, S>> target) {
322         boolean found = false;
323         for (Map<T, S> map : target) {
324             if (map.containsKey(key)) {
325                 map.put(key, value);
326                 found = true;
327             }
328         }
329
330         if (!found) {
331             Map<T, S> newMap = new HashMap<>();
332             newMap.put(key, value);
333             target.add(newMap);
334         }
335     }
336
337
338     /**
339      * Merge maps map.
340      *
341      * @param <T>       the type parameter
342      * @param <S>       the type parameter
343      * @param firstMap  the firstMap
344      * @param secondMap the secondMap
345      * @return the map
346      * Second Map is overridden data from the first map
347      */
348     public static <T, S> Map<T, S> mergeMaps(Map<T, S> firstMap, Map<T, S> secondMap) {
349         Map<T, S> retMap = new HashMap<>();
350         if (MapUtils.isNotEmpty(firstMap)) {
351             retMap.putAll(firstMap);
352         }
353         if (MapUtils.isNotEmpty(secondMap)) {
354             retMap.putAll(secondMap);
355         }
356         return retMap;
357     }
358
359 }
360