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;
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;
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;
42 import java.util.UUID;
45 * This class provides auxiliary static methods.
47 public class CommonMethods {
48 //private static final Logger logger = LoggerFactory.getLogger(CommonMethods.class);
50 private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
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'
58 * Private default constructor to prevent instantiation of the class objects.
60 private CommonMethods() {
64 * Serializes an object instance into byte array.
66 * @param object An instance to be serialized.
67 * @return Java array of bytes.
68 * @see #deserializeObject(byte[]) #deserializeObject(byte[])
70 public static byte[] serializeObject(Serializable object) {
71 ByteArrayOutputStream byteArray = new ByteArrayOutputStream(2048);
73 ObjectOutputStream ds = new ObjectOutputStream(byteArray);
74 ds.writeObject(object);
76 } catch (IOException e0) {
77 throw new RuntimeException(e0);
80 return byteArray.toByteArray();
84 * Deserializes an object instance.
86 * @param bytes Java array of bytes.
87 * @return Deserialized instance of an object.
88 * @see #serializeObject(Serializable) #serializeObject(Serializable)
90 public static Serializable deserializeObject(byte[] bytes) {
91 Serializable obj = null;
93 ObjectInputStream stream = new ObjectInputStream(new ByteArrayInputStream(bytes));
94 obj = (Serializable) stream.readObject();
96 } catch (IOException | ClassNotFoundException e0) {
97 throw new RuntimeException(e0);
101 } // deserializeObject
104 * Encodes binary byte stream to ASCII format.
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[])
110 public static byte[] encode(byte[] binary) {
111 return Base64.encodeBase64(binary);
115 * Decodes ASCII byte stream into binary format.
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[])
121 public static byte[] decode(byte[] ascii) {
122 return Base64.decodeBase64(ascii);
126 * Checks whether the given <tt>Object</tt> is empty.
128 * @param obj Object to be checked.
129 * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
131 public static boolean isEmpty(Object obj) {
136 * Checks whether the given <tt>Object</tt> is empty.
138 * @param byteArray Object to be checked.
139 * @return <tt>true</tt> - if the Object is null, <tt>false</tt> otherwise.
141 public static boolean isEmpty(byte[] byteArray) {
142 return (byteArray == null || byteArray.length == 0);
146 * Checks whether the given <tt>String</tt> is empty.
148 * @param str String object to be checked.
149 * @return <tt>true</tt> - if the String is null or empty, <tt>false</tt> - otherwise.
151 public static boolean isEmpty(String str) {
152 return str == null || str.length() == 0;
156 * Checks whether the given Java array is empty.
158 * @param array Java array to be checked.
159 * @return <tt>true</tt> - if the array is null or empty, <tt>false</tt> - otherwise.
161 public static boolean isEmpty(Object[] array) {
162 return array == null || array.length == 0;
166 * Checks whether the given collection is empty.
168 * @param collection A collection to be checked.
169 * @return <tt>true</tt> - if the collection is null or empty, <tt>false</tt> - otherwise.
171 public static boolean isEmpty(Collection<?> collection) {
172 return collection == null || collection.isEmpty();
176 * Checks whether the given map is empty.
178 * @param map A map to be checked.
179 * @return <tt>true</tt> - if the map is null or empty, <tt>false</tt> - otherwise.
181 public static boolean isEmpty(Map<?, ?> map) {
182 return map == null || map.isEmpty();
186 * Converts the array with Long elements to the array with long (primitive type).
188 * @param array input array with Long elements.
189 * @return array with the same elements converted to the long type (primitive).
191 public static long[] toPrimitive(Long[] array) {
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;
204 * Converts a collection to Java array.
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.
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;
219 * Gets an universally unique identifier (UUID).
221 * @return String representation of generated UUID.
223 public static String nextUuId() {
224 UUID uuid = UUID.randomUUID();
226 StringBuilder buff = new StringBuilder(32);
227 long2string(uuid.getMostSignificantBits(), buff);
228 long2string(uuid.getLeastSignificantBits(), buff);
230 return buff.toString();
233 private static void long2string(long lng, StringBuilder buff) {
234 for (int i = 0; i < 16; i++) {
235 long nextByte = lng & 0xF000000000000000L;
237 boolean isNegative = nextByte < 0;
238 nextByte = rightShift(nextByte, 60);
244 buff.append(CHARS[(int) nextByte]);
248 private static long rightShift(long lng, int num) {
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
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.
265 @SuppressWarnings("unchecked")
266 public static <T> T[] concat(T[] left, T[] right) {
271 } else if (isEmpty(right)) {
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);
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.
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.
297 @SuppressWarnings("unchecked")
298 public static <B, D> D cast(B b0, Class<D> cls) {
301 if (!cls.isInstance(b0)) {
302 throw new ClassCastException(String
303 .format("Failed to cast from '%s' to '%s'", b0.getClass().getName(), cls.getName()));
313 * New instance object.
315 * @param classname the classname
318 public static Object newInstance(String classname) {
319 return newInstance(classname, Object.class);
325 * @param <T> the type parameter
326 * @param classname the classname
330 @SuppressWarnings("unchecked")
331 public static <T> T newInstance(String classname, Class<T> cls) {
333 if (isEmpty(classname)) {
334 throw new IllegalArgumentException();
338 throw new IllegalArgumentException();
342 Class<?> temp = Class.forName(classname);
344 if (!cls.isAssignableFrom(temp)) {
345 throw new ClassCastException(
346 String.format("Failed to cast from '%s' to '%s'", classname, cls.getName()));
349 Class<? extends T> impl = (Class<? extends T>) temp;
351 return newInstance(impl);
352 } catch (ClassNotFoundException e0) {
353 throw new IllegalArgumentException(e0);
360 * @param <T> the type parameter
364 public static <T> T newInstance(Class<T> cls) {
366 return cls.newInstance();
367 } catch (InstantiationException e0) {
368 throw new RuntimeException(e0);
369 } catch (IllegalAccessException e0) {
370 throw new RuntimeException(e0);
375 * Gets resources path.
377 * @param resourceName the resource name
378 * @return the resources path
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);
392 * @return the stack trace
394 public static String getStackTrace(Throwable t0) {
398 StringWriter sw = new StringWriter();
399 t0.printStackTrace(new PrintWriter(sw));
400 return sw.toString();
404 * Print stack trace string.
408 public static String printStackTrace() {
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());
416 String str = sw.toString();
419 } catch (IOException e0) {
420 System.err.println(e0);
427 * Is equal object boolean.
429 * @param obj1 the obj 1
430 * @param obj2 the obj 2
431 * @return the boolean
433 public static boolean isEqualObject(Object obj1, Object obj2) {
434 boolean isEqualValue = false;
435 if (obj1 == null && obj2 == null) {
439 if (!isEqualValue && obj1 != null && obj2 != null && obj1.equals(obj2)) {
446 * Converts array of strings to comma-separated string.
448 * @param arr array of strings
451 public static String arrayToCommaSeparatedString(String[] arr) {
452 return arrayToSeparatedString(arr, ',');
456 * Collection to comma separated string string.
458 * @param elementCollection the element collection
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, ',');
468 * Converts array of strings to string separated with specified character.
470 * @param arr array of strings
471 * @param separator the separator
474 public static String arrayToSeparatedString(String[] arr, char separator) {
475 return listToSeparatedString(Arrays.asList(arr), separator);
479 * Converts array of strings to string separated with specified character.
481 * @param list array of strings
482 * @param separator the separator
485 public static String listToSeparatedString(List<String> list, char separator) {
488 StringBuilder sb = new StringBuilder();
489 int sz = list.size();
490 for (int i = 0; i < sz; i++) {
492 sb.append(separator);
494 sb.append(list.get(i));
502 * Duplicate string with delimiter string.
505 * @param separator the separator
506 * @param numberOfDuplications the number of duplications
509 public static String duplicateStringWithDelimiter(String arg, char separator,
510 int numberOfDuplications) {
512 StringBuilder sb = new StringBuilder();
514 for (int i = 0; i < numberOfDuplications; i++) {
516 sb.append(separator);
525 * Bytes to hex string.
527 * @param bytes the bytes
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;
535 hexChars[x0] = hexArray[v0 >>> 4];
536 hexChars[x0 + 1] = hexArray[v0 & 0x0F];
538 return new String(hexChars);
542 * To single element set set.
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.
548 public static <T> Set<T> toSingleElementSet(T element) {
549 return Collections.singleton(element);