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