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