-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathStringUtils.java
More file actions
474 lines (393 loc) · 12.6 KB
/
StringUtils.java
File metadata and controls
474 lines (393 loc) · 12.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
package javasabr.rlib.common.util;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;
import java.util.regex.Pattern;
import org.jspecify.annotations.NullMarked;
import org.jspecify.annotations.Nullable;
/**
* The class with utility methods for working with strings.
*
* @author JavaSaBr
*/
@NullMarked
public class StringUtils {
public static final String EMPTY = "";
private static final Pattern EMAIL_PATTERN = Pattern.compile(
"^[_\\p{L}0-9-]+(\\.[_\\p{L}0-9-]+)*@[\\p{L}0-9]+" + "(\\.[\\p{L}0-9]+)*(\\.[\\p{L}]{2,})$",
Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);
private static final ThreadLocal<MessageDigest> LOCAL_HASH_MD = ThreadLocal.withInitial(StringUtils::getHashMD5);
/**
* Return an empty string if the received string is null.
*
* @param string the string.
* @return an empty string if the received string is null.
*/
public static String emptyIfNull(@Nullable String string) {
return string == null ? EMPTY : string;
}
/**
* Return the another string if the received string is empty or null.
*
* @param string the string.
* @param another the another string.
* @return the another string if the received string is empty or null.
*/
public static String ifEmpty(@Nullable String string, String another) {
return isEmpty(string) ? another : string;
}
/**
* Return the another string if the received string is blank or null.
*
* @param string the string.
* @param another the another string.
* @return the another string if the received string is blank or null.
*/
public static String ifBlank(@Nullable String string, String another) {
return isBlank(string) ? another : string;
}
/**
* Check a string email.
*
* @param email the string email.
* @return true if the email is correct.
*/
public static boolean isValidEmail(String email) {
var matcher = EMAIL_PATTERN.matcher(email);
return matcher.matches();
}
/**
* Simple check of the string value about does it look like an email.
*
* @param value the string value.
* @return true if it looks like an email.
*/
public static boolean isEmail(String value) {
var lastDotIndex = value.lastIndexOf('.');
var lastSignIndex = value.lastIndexOf('@');
return lastSignIndex > 1 && lastDotIndex > lastSignIndex && lastDotIndex < value.length() - 1;
}
/**
* Compare two strings.
*
* @param first the first string.
* @param second the second string.
* @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1.
*/
public static int compare(@Nullable String first, @Nullable String second) {
if (first == null) {
return 1;
} else if (second == null) {
return -1;
}
return first.compareTo(second);
}
/**
* Compare two strings with ignoring case.
*
* @param first the first string.
* @param second the second string.
* @return 1 if the first string is null or is greater then second, 0 if the first string is the same or -1.
*/
public static int compareIgnoreCase(@Nullable String first, @Nullable String second) {
if (first == null) {
return 1;
} else if (second == null) {
return -1;
}
return first.compareToIgnoreCase(second);
}
/**
* Compare two strings.
*
* @param first the first string.
* @param second the second string.
* @return true if these strings are equal.
*/
public static boolean equals(@Nullable String first, @Nullable String second) {
return !(first == null || second == null) && first.equals(second);
}
/**
* Compare two strings with ignoring case.
*
* @param first the first string.
* @param second the second string.
* @return true if these strings are equal.
*/
public static boolean equalsIgnoreCase(@Nullable String first, @Nullable String second) {
return !(first == null || second == null) && first.equalsIgnoreCase(second);
}
/**
* Print stack trace of an exception to a string.
*
* @param throwable the exception.
* @return the stack trace.
*/
public static String toString(Throwable throwable) {
return toString(throwable, 6);
}
/**
* Print stack trace of an exception to a string.
*
* @param throwable the exception.
* @param deepLevel the max level of deep.
* @return the stack trace.
*/
public static String toString(Throwable throwable, int deepLevel) {
var writer = new StringWriter();
var printWriter = new PrintWriter(writer);
throwable.printStackTrace(printWriter);
var stackTrace = new StringBuilder(writer.toString());
int level = 0;
for (var cause = throwable.getCause(); cause != null && level < deepLevel; cause = cause.getCause(), level++) {
writer = new StringWriter();
printWriter = new PrintWriter(writer);
cause.printStackTrace(printWriter);
stackTrace.append("\n caused by ");
stackTrace.append(writer.toString());
}
return stackTrace.toString();
}
/**
* Generate a random string using Aa-Zz characters.
*
* @param length the length of result string.
* @return the new string.
*/
public static String generate(int length) {
return generate(length, length);
}
/**
* Generate a random string using Aa-Zz characters.
*
* @param minLength the min length of result string.
* @param maxLength the max length of result string.
* @return the new string.
*/
public static String generate(int minLength, int maxLength) {
var localRandom = ThreadLocalRandom.current();
var length = minLength == maxLength ? maxLength : localRandom.nextInt(minLength, maxLength);
var array = new char[length];
var min = Math.min('a', 'A');
var max = Math.max('z', 'z');
for (int i = 0; i < length; i++) {
array[i] = (char) localRandom.nextInt(min, max);
}
return String.valueOf(array);
}
/**
* @return the md5 message digest.
*/
private static MessageDigest getHashMD5() {
try {
return MessageDigest.getInstance("MD5");
} catch (final NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
/**
* Returns true if the string is empty or null.
*
* @param string the string.
* @return true if the string is null or empty.
*/
public static boolean isEmpty(@Nullable String string) {
return string == null || string.isEmpty();
}
/**
* Returns true if the string is blank or null.
*
* @param string the string.
* @return true if the string is null or blank.
*/
public static boolean isBlank(@Nullable String string) {
return string == null || string.isBlank();
}
/**
* Returns true if the string isn't empty.
*
* @param string the string.
* @return true if the string isn't empty.
*/
public static boolean isNotEmpty(@Nullable String string) {
return !isEmpty(string);
}
/**
* Returns true if the string isn't blank.
*
* @param string the string.
* @return true if the string isn't blank.
*/
public static boolean isNotBlank(@Nullable String string) {
return !isBlank(string);
}
/**
* Gets the length of the string.
*
* @param string the string.
* @return length or 0 if a string is null or empty.
*/
public static int length(@Nullable String string) {
return string == null ? 0 : string.length();
}
/**
* Encode the string to hash MD5.
*
* @param string a string.
* @return the encoded string.
*/
public static String toMD5(String string) {
final MessageDigest hashMD5 = LOCAL_HASH_MD.get();
hashMD5.update(string.getBytes(), 0, string.length());
return new BigInteger(1, hashMD5.digest()).toString(16);
}
/**
* Present the byte array as a hex string.
*
* @param array the byte array.
* @return the hex string.
* @since 9.0.3
*/
public static String bytesToHexString(byte[] array) {
var builder = new StringBuilder(array.length * 2);
for (var value : array) {
var element = Integer.toHexString(value & 0xFF);
if (element.length() == 1) {
element = "0" + element;
}
builder.append(element);
}
return builder.toString();
}
/**
* Parse the hex string to a byte array.
*
* @param string the hex string.
* @return the byte array.
* @since 9.0.3
*/
public static byte[] hexStringToBytes(String string) {
var array = string.toCharArray();
var result = new byte[string.length() / 2];
for (int i = 0, g = 0, length = array.length - 1; i < length; i += 2) {
var element = String.valueOf(array, i, 2);
result[g++] = (byte) Integer.parseInt(element, 16);
}
return result;
}
/**
* Convert the string from HEX to a plain string.
*
* @param string the HEX string.
* @return the plain string.
* @since 9.0.3
*/
public static String fromHex(String string) {
var array = string.toCharArray();
var builder = new StringBuilder(string.length() / 4);
for (int i = 0, length = array.length - 3; i < length; i += 4) {
var element = String.valueOf(array, i, 4);
builder.append((char) Integer.parseInt(element, 16));
}
return builder.toString();
}
/**
* Convert the plain string to a HEX string.
*
* @param string the plain string.
* @return the hex string.
* @since 9.0.3
*/
public static String toHex(String string) {
var builder = new StringBuilder(string.length() * 2);
for (int i = 0, length = string.length(); i < length; i++) {
var charAt = string.charAt(i);
var element = Integer.toHexString(charAt);
if (element.length() == 1) {
element = "000" + element;
} else if (element.length() == 2) {
element = "00" + element;
} else if (element.length() == 3) {
element = "0" + element;
}
builder.append(element);
}
return builder.toString();
}
/**
* Replace the variable in the string.
*
* @param string the source string.
* @param firstName the variable's name.
* @param firstVal the variable's value.
* @return result string.
*/
public static String replace(String string, String firstName, String firstVal) {
var capacity = string.length();
capacity = capacity - firstName.length() + firstVal.length();
capacity = Math.max(capacity, string.length());
var builder = new StringBuilder(capacity);
builder.append(string);
replace(builder, firstName, firstVal);
return builder.toString();
}
/**
* Replace the variables in the string.
*
* @param string the source string.
* @param firstName the first variable's name.
* @param firstVal the first variable's value.
* @param secondName the second variable's name.
* @param secondVal the second variable's value.
* @return result string.
*/
public static String replace(
String string,
String firstName,
String firstVal,
String secondName,
String secondVal) {
var capacity = string.length();
capacity = capacity - firstName.length() + firstVal.length();
capacity = capacity - secondName.length() + secondVal.length();
capacity = Math.max(capacity, string.length());
var builder = new StringBuilder(capacity);
builder.append(string);
replace(builder, firstName, firstVal);
replace(builder, secondName, secondVal);
return builder.toString();
}
/**
* Replace the variables in the string.
*
* @param string the source string.
* @param params the variable's parameters, name -> val, name -> val.
* @return result string.
* @throws IllegalArgumentException if params count < 2 or % 2 != 0
*/
public static String replace(String string, String... params) {
if (params.length < 2 || params.length % 2 != 0) {
throw new IllegalArgumentException("Wrong params count.");
}
var capacity = string.length();
for (int i = 0; i < params.length - 1; i += 2) {
capacity = capacity - params[i].length() + params[i + 1].length();
}
capacity = Math.max(capacity, string.length());
var builder = new StringBuilder(capacity);
builder.append(string);
for (var i = 0; i < params.length - 1; i += 2) {
replace(builder, params[i], params[i + 1]);
}
return builder.toString();
}
private static void replace(StringBuilder builder, String name, String value) {
for (int index = builder.indexOf(name), count = 0;
index != -1 && count < 100; index = builder.indexOf(name), count++) {
builder.replace(index, index + name.length(), value);
}
}
}