2 * ============LICENSE_START=======================================================
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.core.utilities;
23 import org.apache.commons.codec.binary.Base64;
24 import org.apache.commons.collections4.MapUtils;
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;
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;
43 import java.util.Objects;
45 import java.util.UUID;
48 * This class provides auxiliary static methods.
50 public class CommonMethods {
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'
56 private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
59 * Private default constructor to prevent instantiation of the class objects.
61 private CommonMethods() {
65 * Serializes an object instance into byte array.
67 * @param object An instance to be serialized.
68 * @return Java array of bytes.
69 * @see #deserializeObject(byte[]) #deserializeObject(byte[])
71 public static byte[] serializeObject(Serializable object) {
72 ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048);
74 ObjectOutputStream ds = new ObjectOutputStream(byteArray);
75 ds.writeObject(object);
77 } catch (IOException exception) {
78 throw new RuntimeException(exception);
81 return byteArray.toByteArray();
85 * Deserializes an object instance.
87 * @param bytes Java array of bytes.
88 * @return Deserialized instance of an object.
89 * @see #serializeObject(Serializable) #serializeObject(Serializable)
91 public static Serializable deserializeObject(byte[] bytes) {
92 Serializable obj = null;
94 ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes));
95 obj = (Serializable) stream.readObject();
97 } catch (IOException | ClassNotFoundException exception) {
98 throw new RuntimeException(exception);
102 } // deserializeObject
105 * Encodes binary byte stream to ASCII format.
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[])
111 public static byte[] encode(byte[] binary) {
112 return Base64.encodeBase64(binary);
116 * Decodes ASCII byte stream into binary format.
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[])
122 public static byte[] decode(byte[] ascii) {
123 return Base64.decodeBase64(ascii);
127 * Checks whether the given <tt>Object</tt> is empty.
129 * @param obj Object to be checked.
130 * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
132 public static boolean isEmpty(Object obj) {
137 * Checks whether the given <tt>Object</tt> is empty.
139 * @param byteArray Object to be checked.
140 * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
142 public static boolean isEmpty(byte[] byteArray) {
143 return (byteArray == null || byteArray.length == 0);
147 * Checks whether the given <tt>String</tt> is empty.
149 * @param str String object to be checked.
150 * @return <tt>true</tt> - if the String is null or empty, <tt>false</tt> - otherwise.
152 public static boolean isEmpty(String str) {
153 return str == null || str.length() == 0;
157 * Checks whether the given Java array is empty.
159 * @param array Java array to be checked.
160 * @return <tt>true</tt> - if the array is null or empty, <tt>false</tt> - otherwise.
162 public static boolean isEmpty(Object[] array) {
163 return array == null || array.length == 0;
167 * Checks whether the given collection is empty.
169 * @param collection A collection to be checked.
170 * @return <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - otherwise.
172 public static boolean isEmpty(Collection<?> collection) {
173 return collection == null || collection.isEmpty();
177 * Checks whether the given map is empty.
179 * @param map A map to be checked.
180 * @return <tt>true</tt> - if the map is null or empty, <tt>false</tt> - otherwise.
182 public static boolean isEmpty(Map<?, ?> map) {
183 return map == null || map.isEmpty();
187 * Converts the array with Long elements to the array with long (primitive type).
189 * @param array input array with Long elements
190 * @return array with the same elements converted to the long type (primitive)
192 public static long[] toPrimitive(Long[] array) {
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;
205 * Converts a collection to Java array.
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.
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;
220 * Gets an universally unique identifier (UUID).
222 * @return String representation of generated UUID.
224 public static String nextUuId() {
225 UUID uuid = UUID.randomUUID();
227 StringBuilder buff = new StringBuilder(32);
228 long2string(uuid.getMostSignificantBits(), buff);
229 long2string(uuid.getLeastSignificantBits(), buff);
231 return buff.toString();
234 private static void long2string(long lng, StringBuilder buff) {
235 for (int i = 0; i < 16; i++) {
236 long nextByte = lng & 0xF000000000000000L;
238 boolean isNegative = nextByte < 0;
239 nextByte = rightShift(nextByte, 60);
245 buff.append(CHARS[(int) nextByte]);
249 private static long rightShift(long lng, int num) {
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
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.
266 @SuppressWarnings("unchecked")
267 public static <T> T[] concat(T[] left, T[] right) {
272 } else if (isEmpty(right)) {
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);
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.
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
298 @SuppressWarnings("unchecked")
299 public static <B, D> D cast(B b1, Class<D> cls) {
302 if (!cls.isInstance(b1)) {
303 throw new ClassCastException(String
304 .format("Failed to cast from '%s' to '%s'", b1.getClass().getName(), cls.getName()));
314 * New instance object.
316 * @param classname the classname
319 public static Object newInstance(String classname) {
320 return newInstance(classname, Object.class);
326 * @param <T> the type parameter
327 * @param classname the classname
331 @SuppressWarnings("unchecked")
332 public static <T> T newInstance(String classname, Class<T> cls) {
334 if (isEmpty(classname)) {
335 throw new IllegalArgumentException();
339 throw new IllegalArgumentException();
343 Class<?> temp = Class.forName(classname);
345 if (!cls.isAssignableFrom(temp)) {
346 throw new ClassCastException(
347 String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
350 Class<? extends T> impl = (Class<? extends T>) temp;
352 return newInstance(impl);
353 } catch (ClassNotFoundException exception) {
354 throw new IllegalArgumentException(exception);
361 * @param <T> the type parameter
365 public static <T> T newInstance(Class<T> cls) {
367 return cls.newInstance();
368 } catch (InstantiationException exception) {
369 throw new RuntimeException(exception);
370 } catch (IllegalAccessException exception) {
371 throw new RuntimeException(exception);
376 * Gets resources path.
378 * @param resourceName the resource name
379 * @return the resources path
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);
392 * @param throwable the throwable
393 * @return the stack trace
395 public static String getStackTrace(Throwable throwable) {
396 if (null == throwable) {
399 StringWriter sw = new StringWriter();
400 throwable.printStackTrace(new PrintWriter(sw));
401 return sw.toString();
405 * Print stack trace string.
409 public static String printStackTrace() {
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());
417 String str = sw.toString();
420 } catch (IOException exception) {
421 System.err.println(exception);
428 * Is equal object boolean.
430 * @param obj1 the obj 1
431 * @param obj2 the obj 2
432 * @return the boolean
434 public static boolean isEqualObject(Object obj1, Object obj2) {
435 boolean isEqualValue = false;
436 if (obj1 == null && obj2 == null) {
440 if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) {
447 * Converts array of strings to comma-separated string.
449 * @param arr array of strings
452 public static String arrayToCommaSeparatedString(String[] arr) {
453 return arrayToSeparatedString(arr, ',');
457 * Collection to comma separated string string.
459 * @param elementCollection the element collection
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, ',');
469 * Converts array of strings to string separated with specified character.
471 * @param arr array of strings
472 * @param separator the separator
475 public static String arrayToSeparatedString(String[] arr, char separator) {
476 return listToSeparatedString(Arrays.asList(arr), separator);
480 * Converts array of strings to string separated with specified character.
482 * @param list array of strings
483 * @param separator the separator
486 public static String listToSeparatedString(List<String> list, char separator) {
489 StringBuilder sb = new StringBuilder();
490 int sz = list.size();
491 for (int i = 0; i < sz; i++) {
493 sb.append(separator);
495 sb.append(list.get(i));
503 * Duplicate string with delimiter string.
506 * @param separator the separator
507 * @param numberOfDuplications the number of duplications
510 public static String duplicateStringWithDelimiter(String arg, char separator,
511 int numberOfDuplications) {
513 StringBuilder sb = new StringBuilder();
515 for (int i = 0; i < numberOfDuplications; i++) {
517 sb.append(separator);
526 * Bytes to hex string.
528 * @param bytes the bytes
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;
536 hexChars[x1] = hexArray[var >>> 4];
537 hexChars[x1 + 1] = hexArray[var & 0x0F];
539 return new String(hexChars);
543 * To single element set set.
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
550 public static <T> Set<T> toSingleElementSet(T element) {
551 return Collections.singleton(element);
556 * Merge lists of map list.
558 * @param <T> the type parameter
559 * @param <S> the type parameter
560 * @param target the target
561 * @param source the source
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);
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);
584 * @param <T> the type parameter
585 * @param target the target
586 * @param source the source
589 public static <T> List<T> mergeLists(List<T> target, List<T> source) {
590 List<T> retList = new ArrayList<>();
592 if (Objects.nonNull(source)) {
593 retList.addAll(source);
595 if (Objects.nonNull(target)) {
596 retList.addAll(target);
603 * Merge entry in list.
605 * @param <T> the type parameter
606 * @param <S> the type parameter
608 * @param value the value
609 * @param target the target
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)) {
621 Map<T, S> newMap = new HashMap<>();
622 newMap.put(key, value);
631 * @param <T> the type parameter
632 * @param <S> the type parameter
633 * @param target the target
634 * @param source the source
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);
642 if (MapUtils.isNotEmpty(target)) {
643 retMap.putAll(target);