[SDC-29] Amdocs OnBoard 1707 initial commit.
[sdc.git] / openecomp-be / lib / openecomp-core-lib / openecomp-utilities-lib / src / main / java / org / openecomp / core / utilities / CommonMethods.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.core.utilities;
22
23 import org.apache.commons.codec.binary.Base64;
24 import org.apache.commons.collections4.MapUtils;
25
26 import java.io.ByteArrayInputStream;
27 import java.io.ByteArrayOutputStream;
28 import java.io.IOException;
29 import java.io.ObjectInputStream;
30 import java.io.ObjectOutputStream;
31 import java.io.PrintWriter;
32 import java.io.Serializable;
33 import java.io.StringWriter;
34 import java.lang.reflect.Array;
35 import java.net.URL;
36 import java.util.ArrayList;
37 import java.util.Arrays;
38 import java.util.Collection;
39 import java.util.Collections;
40 import java.util.HashMap;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Objects;
44 import java.util.Set;
45 import java.util.UUID;
46
47 /**
48  * This class provides auxiliary static methods.
49  */
50 public class CommonMethods {
51
52   private static final char[] CHARS = new char[]{
53       '0', '1', '2', '3', '4', '5', '6', '7',
54       '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
55   };
56   private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
57
58   /**
59    * Private default constructor to prevent instantiation of the class objects.
60    */
61   private CommonMethods() {
62   }
63
64   /**
65    * Serializes an object instance into byte array.
66    *
67    * @param object An instance to be serialized.
68    * @return Java array of bytes.
69    * @see #deserializeObject(byte[]) #deserializeObject(byte[])
70    */
71   public static byte[] serializeObject(Serializable object) {
72     ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048);
73     try {
74       ObjectOutputStream ds = new ObjectOutputStream(byteArray);
75       ds.writeObject(object);
76       ds.close();
77     } catch (IOException exception) {
78       throw new RuntimeException(exception);
79     }
80
81     return byteArray.toByteArray();
82   } // serializeObject
83
84   /**
85    * Deserializes an object instance.
86    *
87    * @param bytes Java array of bytes.
88    * @return Deserialized instance of an object.
89    * @see #serializeObject(Serializable) #serializeObject(Serializable)
90    */
91   public static Serializable deserializeObject(byte[] bytes) {
92     Serializable obj = null;
93     try {
94       ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes));
95       obj = (Serializable) stream.readObject();
96       stream.close();
97     } catch (IOException | ClassNotFoundException exception) {
98       throw new RuntimeException(exception);
99     }
100
101     return obj;
102   } // deserializeObject
103
104   /**
105    * Encodes binary byte stream to ASCII format.
106    *
107    * @param binary An Java array of bytes in binary format.
108    * @return An Java array of bytes encoded in ASCII format.
109    * @see #decode(byte[]) #decode(byte[])
110    */
111   public static byte[] encode(byte[] binary) {
112     return Base64.encodeBase64(binary);
113   }
114
115   /**
116    * Decodes ASCII byte stream into binary format.
117    *
118    * @param ascii An Java array of bytes in ASCII format.
119    * @return An Java array of bytes encoded in binary format.
120    * @see #encode(byte[]) #encode(byte[])
121    */
122   public static byte[] decode(byte[] ascii) {
123     return Base64.decodeBase64(ascii);
124   }
125
126   /**
127    * Checks whether the given <tt>Object</tt> is empty.
128    *
129    * @param obj Object to be checked.
130    * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
131    */
132   public static boolean isEmpty(Object obj) {
133     return obj == null;
134   }
135
136   /**
137    * Checks whether the given <tt>Object</tt> is empty.
138    *
139    * @param byteArray Object to be checked.
140    * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
141    */
142   public static boolean isEmpty(byte[] byteArray) {
143     return (byteArray == null || byteArray.length == 0);
144   }
145
146   /**
147    * Checks whether the given <tt>String</tt> is empty.
148    *
149    * @param str String object to be checked.
150    * @return <tt>true</tt> - if the String is null or empty, <tt>false</tt> - otherwise.
151    */
152   public static boolean isEmpty(String str) {
153     return str == null || str.length() == 0;
154   }
155
156   /**
157    * Checks whether the given Java array is empty.
158    *
159    * @param array Java array to be checked.
160    * @return <tt>true</tt> - if the array is null or empty, <tt>false</tt> - otherwise.
161    */
162   public static boolean isEmpty(Object[] array) {
163     return array == null || array.length == 0;
164   }
165
166   /**
167    * Checks whether the given collection is empty.
168    *
169    * @param collection A collection to be checked.
170    * @return <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - otherwise.
171    */
172   public static boolean isEmpty(Collection<?> collection) {
173     return collection == null || collection.isEmpty();
174   }
175
176   /**
177    * Checks whether the given map is empty.
178    *
179    * @param map A map to be checked.
180    * @return <tt>true</tt> - if the map is null or empty, <tt>false</tt> - otherwise.
181    */
182   public static boolean isEmpty(Map<?, ?> map) {
183     return map == null || map.isEmpty();
184   }
185
186   /**
187    * Converts the array with Long elements to the array with long (primitive type).
188    *
189    * @param array input array with Long elements
190    * @return array with the same elements converted to the long type (primitive)
191    */
192   public static long[] toPrimitive(Long[] array) {
193     if (array == null) {
194       return null;
195     }
196
197     long[] result = new long[array.length];
198     for (int i = 0; i < array.length; i++) {
199       result[i] = array[i] != null ? array[i] : 0L;
200     }
201     return result;
202   }
203
204   /**
205    * Converts a collection to Java array.
206    *
207    * @param <T>  Java type of the collection element.
208    * @param col  Collection to be converted to array
209    * @param type Java type of collection/array element
210    * @return An Java array of collection elements, or empty array if collection is null or empty.
211    */
212   @SuppressWarnings("unchecked")
213   public static <T> T[] toArray(Collection<? extends T> col, Class<T> type) {
214     int length = isEmpty(col) ? 0 : col.size();
215     T[] array = (T[]) Array.newInstance(type, length);
216     return col != null ? col.toArray(array) : array;
217   }
218
219   /**
220    * Gets an universally unique identifier (UUID).
221    *
222    * @return String representation of generated UUID.
223    */
224   public static String nextUuId() {
225     UUID uuid = UUID.randomUUID();
226
227     StringBuilder buff = new StringBuilder(32);
228     long2string(uuid.getMostSignificantBits(), buff);
229     long2string(uuid.getLeastSignificantBits(), buff);
230
231     return buff.toString();
232   }
233
234   private static void long2string(long lng, StringBuilder buff) {
235     for (int i = 0; i < 16; i++) {
236       long nextByte = lng & 0xF000000000000000L;
237       lng <<= 4;
238       boolean isNegative = nextByte < 0;
239       nextByte = rightShift(nextByte, 60);
240
241       if (isNegative) {
242         nextByte |= 0x08;
243       }
244
245       buff.append(CHARS[(int) nextByte]);
246     }
247   }
248
249   private static long rightShift(long lng, int num) {
250     return lng >>> num;
251   }
252
253   /**
254    * Concatenates two Java arrays. The method allocates a new array and copies
255    * all elements to it or returns one of input arrays if another one is
256    * empty.
257    *
258    * @param <T>   the type parameter
259    * @param left  Elements of this array will be copied to positions from 0 to <tt>left.length -
260    *              1</tt> in the target array.
261    * @param right Elements of this array will be copied to positions from <tt>left.length</tt> to
262    *              <tt>left.length + right.length</tt>
263    * @return A newly allocate Java array that accommodates elements of source (left/right) arrays
264     orone of source arrays if another is empty, <tt>null</tt> - otherwise.
265    */
266   @SuppressWarnings("unchecked")
267   public static <T> T[] concat(T[] left, T[] right) {
268     T[] res = null;
269
270     if (isEmpty(left)) {
271       res = right;
272     } else if (isEmpty(right)) {
273       res = left;
274     } else {
275       res = (T[]) Array.newInstance(left[0].getClass(), left.length + right.length);
276       System.arraycopy(left, 0, res, 0, left.length);
277       System.arraycopy(right, 0, res, left.length, right.length);
278     }
279
280     return res;
281   } // concat
282
283   /**
284    * Casts an object to the class or interface represented by the specified
285    * <tt>Class</tt> object. The method logic is similar to Java method
286    * <tt>Class.cast(Object)</tt> with the only difference that unlike Java's
287    * version the type name of the current object instance is specified in the
288    * error message if casting fails to simplify error tracking.
289    *
290    * @param <B> the type parameter
291    * @param <D> the type parameter
292    * @param b1  An object instance to be casted to the specified Java type.
293    * @param cls Target Java type.
294    * @return Object instance safely casted to the requested Java type.
295    * @throws ClassCastException In case which is the given object is not instance of the specified
296    *                            Java type.
297    */
298   @SuppressWarnings("unchecked")
299   public static <B, D> D cast(B b1, Class<D> cls) {
300     D d1 = null;
301     if (b1 != null) {
302       if (!cls.isInstance(b1)) {
303         throw new ClassCastException(String
304             .format("Failed to cast from '%s' to '%s'", b1.getClass().getName(), cls.getName()));
305       } else {
306         d1 = (D) b1;
307       }
308     }
309
310     return d1;
311   } // cast
312
313   /**
314    * New instance object.
315    *
316    * @param classname the classname
317    * @return the object
318    */
319   public static Object newInstance(String classname) {
320     return newInstance(classname, Object.class);
321   }
322
323   /**
324    * New instance t.
325    *
326    * @param <T>       the type parameter
327    * @param classname the classname
328    * @param cls       the cls
329    * @return the t
330    */
331   @SuppressWarnings("unchecked")
332   public static <T> T newInstance(String classname, Class<T> cls) {
333
334     if (isEmpty(classname)) {
335       throw new IllegalArgumentException();
336     }
337
338     if (cls == null) {
339       throw new IllegalArgumentException();
340     }
341
342     try {
343       Class<?> temp = Class.forName(classname);
344
345       if (!cls.isAssignableFrom(temp)) {
346         throw new ClassCastException(
347             String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
348       }
349
350       Class<? extends T> impl = (Class<? extends T>) temp;
351
352       return newInstance(impl);
353     } catch (ClassNotFoundException exception) {
354       throw new IllegalArgumentException(exception);
355     }
356   }
357
358   /**
359    * New instance t.
360    *
361    * @param <T> the type parameter
362    * @param cls the cls
363    * @return the t
364    */
365   public static <T> T newInstance(Class<T> cls) {
366     try {
367       return cls.newInstance();
368     } catch (InstantiationException exception) {
369       throw new RuntimeException(exception);
370     } catch (IllegalAccessException exception) {
371       throw new RuntimeException(exception);
372     }
373   }
374
375   /**
376    * Gets resources path.
377    *
378    * @param resourceName the resource name
379    * @return the resources path
380    */
381   public static String getResourcesPath(String resourceName) {
382     URL resourceUrl = CommonMethods.class.getClassLoader().getResource(resourceName);
383     String resourcePath = resourceUrl.getPath();
384     String dirPath = resourcePath.substring(0, resourcePath.lastIndexOf("/") + 1);
385
386     return dirPath;
387   }
388
389   /**
390    * Gets stack trace.
391    *
392    * @param throwable the throwable
393    * @return the stack trace
394    */
395   public static String getStackTrace(Throwable throwable) {
396     if (null == throwable) {
397       return "";
398     }
399     StringWriter sw = new StringWriter();
400     throwable.printStackTrace(new PrintWriter(sw));
401     return sw.toString();
402   }
403
404   /**
405    * Print stack trace string.
406    *
407    * @return the string
408    */
409   public static String printStackTrace() {
410
411     StringWriter sw = new StringWriter();
412     StackTraceElement[] trace = Thread.currentThread().getStackTrace();
413     for (StackTraceElement traceElement : trace) {
414       sw.write("\t  " + traceElement);
415       sw.write(System.lineSeparator());
416     }
417     String str = sw.toString();
418     try {
419       sw.close();
420     } catch (IOException exception) {
421       System.err.println(exception);
422     }
423     return str;
424
425   }
426
427   /**
428    * Is equal object boolean.
429    *
430    * @param obj1 the obj 1
431    * @param obj2 the obj 2
432    * @return the boolean
433    */
434   public static boolean isEqualObject(Object obj1, Object obj2) {
435     boolean isEqualValue = false;
436     if (obj1 == null && obj2 == null) {
437       isEqualValue = true;
438     }
439
440     if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) {
441       isEqualValue = true;
442     }
443     return isEqualValue;
444   }
445
446   /**
447    * Converts array of strings to comma-separated string.
448    *
449    * @param arr array of strings
450    * @return the string
451    */
452   public static String arrayToCommaSeparatedString(String[] arr) {
453     return arrayToSeparatedString(arr, ',');
454   }
455
456   /**
457    * Collection to comma separated string string.
458    *
459    * @param elementCollection the element collection
460    * @return the string
461    */
462   public static String collectionToCommaSeparatedString(Collection<String> elementCollection) {
463     List<String> list = new ArrayList<>();
464     elementCollection.stream().forEach(element -> list.add(element));
465     return listToSeparatedString(list, ',');
466   }
467
468   /**
469    * Converts array of strings to string separated with specified character.
470    *
471    * @param arr       array of strings
472    * @param separator the separator
473    * @return the string
474    */
475   public static String arrayToSeparatedString(String[] arr, char separator) {
476     return listToSeparatedString(Arrays.asList(arr), separator);
477   }
478
479   /**
480    * Converts array of strings to string separated with specified character.
481    *
482    * @param list      array of strings
483    * @param separator the separator
484    * @return the string
485    */
486   public static String listToSeparatedString(List<String> list, char separator) {
487     String res = null;
488     if (null != list) {
489       StringBuilder sb = new StringBuilder();
490       int sz = list.size();
491       for (int i = 0; i < sz; i++) {
492         if (i > 0) {
493           sb.append(separator);
494         }
495         sb.append(list.get(i));
496       }
497       res = sb.toString();
498     }
499     return res;
500   }
501
502   /**
503    * Duplicate string with delimiter string.
504    *
505    * @param arg                  the arg
506    * @param separator            the separator
507    * @param numberOfDuplications the number of duplications
508    * @return the string
509    */
510   public static String duplicateStringWithDelimiter(String arg, char separator,
511                                                     int numberOfDuplications) {
512     String res = null;
513     StringBuilder sb = new StringBuilder();
514
515     for (int i = 0; i < numberOfDuplications; i++) {
516       if (i > 0) {
517         sb.append(separator);
518       }
519       sb.append(arg);
520     }
521     res = sb.toString();
522     return res;
523   }
524
525   /**
526    * Bytes to hex string.
527    *
528    * @param bytes the bytes
529    * @return the string
530    */
531   public static String bytesToHex(byte[] bytes) {
532     char[] hexChars = new char[bytes.length * 2];
533     for (int j = 0; j < bytes.length; j++) {
534       int var = bytes[j] & 0xFF;
535       int x1 = j << 1;
536       hexChars[x1] = hexArray[var >>> 4];
537       hexChars[x1 + 1] = hexArray[var & 0x0F];
538     }
539     return new String(hexChars);
540   }
541
542   /**
543    * To single element set set.
544    *
545    * @param <T>     the class of the objects in the set
546    * @param element the single element to be contained in the returned Set
547    * @return an immutable set containing only the specified object. The returned set is
548     serializable.
549    */
550   public static <T> Set<T> toSingleElementSet(T element) {
551     return Collections.singleton(element);
552
553   }
554
555   /**
556    * Merge lists of map list.
557    *
558    * @param <T>    the type parameter
559    * @param <S>    the type parameter
560    * @param target the target
561    * @param source the source
562    * @return the list
563    */
564   public static <T, S> List<Map<T, S>> mergeListsOfMap(List<Map<T, S>> target,
565                                                        List<Map<T, S>> source) {
566     List<Map<T, S>> retList = new ArrayList<>();
567     if (Objects.nonNull(target)) {
568       retList.addAll(target);
569     }
570
571     if (Objects.nonNull(source)) {
572       for (Map<T, S> sourceMap : source) {
573         for (Map.Entry<T, S> entry : sourceMap.entrySet()) {
574           mergeEntryInList(entry.getKey(), entry.getValue(), retList);
575         }
576       }
577     }
578     return retList;
579   }
580
581   /**
582    * Merge lists list.
583    *
584    * @param <T>    the type parameter
585    * @param target the target
586    * @param source the source
587    * @return the list
588    */
589   public static <T> List<T> mergeLists(List<T> target, List<T> source) {
590     List<T> retList = new ArrayList<>();
591
592     if (Objects.nonNull(source)) {
593       retList.addAll(source);
594     }
595     if (Objects.nonNull(target)) {
596       retList.addAll(target);
597     }
598
599     return retList;
600   }
601
602   /**
603    * Merge entry in list.
604    *
605    * @param <T>    the type parameter
606    * @param <S>    the type parameter
607    * @param key    the key
608    * @param value  the value
609    * @param target the target
610    */
611   public static <T, S> void mergeEntryInList(T key, S value, List<Map<T, S>> target) {
612     boolean found = false;
613     for (Map<T, S> map : target) {
614       if (map.containsKey(key)) {
615         map.put(key, value);
616         found = true;
617       }
618     }
619
620     if (!found) {
621       Map<T, S> newMap = new HashMap<>();
622       newMap.put(key, value);
623       target.add(newMap);
624     }
625   }
626
627
628   /**
629    * Merge maps map.
630    *
631    * @param <T>    the type parameter
632    * @param <S>    the type parameter
633    * @param target the target
634    * @param source the source
635    * @return the map
636    */
637   public static <T, S> Map<T, S> mergeMaps(Map<T, S> target, Map<T, S> source) {
638     Map<T, S> retMap = new HashMap<>();
639     if (MapUtils.isNotEmpty(source)) {
640       retMap.putAll(source);
641     }
642     if (MapUtils.isNotEmpty(target)) {
643       retMap.putAll(target);
644     }
645     return retMap;
646   }
647
648 }
649