1 /*
2 * This file is part of Waarp Project (named also Waarp or GG).
3 *
4 * Copyright (c) 2019, Waarp SAS, and individual contributors by the @author
5 * tags. See the COPYRIGHT.txt in the distribution for a full listing of
6 * individual contributors.
7 *
8 * All Waarp Project is free software: you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * Waarp is distributed in the hope that it will be useful, but WITHOUT ANY
14 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License along with
18 * Waarp . If not, see <http://www.gnu.org/licenses/>.
19 */
20 package org.waarp.common.utility;
21
22 /**
23 * String utils
24 */
25 public final class StringUtils {
26 /**
27 * Random Generator
28 */
29 public static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current();
30
31 public static final String LINE_SEP;
32
33 static {
34 LINE_SEP = SystemPropertyUtil.get("line.separator");
35 }
36
37 private StringUtils() {
38 // empty
39 }
40
41 /**
42 * @param length the length of rray
43 *
44 * @return a byte array with random values
45 */
46 public static byte[] getRandom(final int length) {
47 if (length <= 0) {
48 return SingletonUtils.getSingletonByteArray();
49 }
50 final byte[] result = new byte[length];
51 for (int i = 0; i < result.length; i++) {
52 result[i] = (byte) (RANDOM.nextInt(95) + 32);
53 }
54 return result;
55 }
56
57 /**
58 * Revert Arrays.toString for bytes
59 *
60 * @param bytesString the string to transform
61 *
62 * @return the array of bytes
63 *
64 * @throws IllegalArgumentException if bytesString is null or empty
65 */
66 public static byte[] getBytesFromArraysToString(final String bytesString) {
67 ParametersChecker.checkParameter("Should not be null or empty",
68 bytesString);
69 final String[] strings =
70 bytesString.replace("[", "").replace("]", "").split(", ");
71 final byte[] result = new byte[strings.length];
72 try {
73 for (int i = 0; i < result.length; i++) {
74 result[i] = (byte) (Integer.parseInt(strings[i]) & 0xFF);
75 }
76 } catch (final NumberFormatException e) {
77 throw new IllegalArgumentException(e);
78 }
79 return result;
80 }
81
82 /**
83 * @param object to get its class name
84 *
85 * @return the short name of the Class of this object
86 */
87 public static String getClassName(final Object object) {
88 final Class<?> clasz = object.getClass();
89 String name = clasz.getSimpleName();
90 if (ParametersChecker.isNotEmpty(name)) {
91 return name;
92 } else {
93 name = clasz.getName();
94 final int pos = name.lastIndexOf('.');
95 if (pos < 0) {
96 return name;
97 }
98 return name.substring(pos + 1);
99 }
100 }
101
102 }
103