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