-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
Strings.java
1256 lines (1145 loc) · 47.4 KB
/
Strings.java
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright Debezium Authors.
*
* Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0
*/
package io.debezium.util;
import java.io.ByteArrayOutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import io.debezium.annotation.ThreadSafe;
import io.debezium.text.ParsingException;
import io.debezium.text.TokenStream;
import io.debezium.text.TokenStream.CharacterStream;
import io.debezium.text.TokenStream.Tokenizer;
import io.debezium.text.TokenStream.Tokens;
/**
* String-related utility methods.
*
* @author Randall Hauch
* @author Horia Chiorean
*/
@ThreadSafe
public final class Strings {
private static final Pattern TIME_PATTERN = Pattern.compile("([0-9]*):([0-9]*):([0-9]*)(\\.([0-9]*))?");
/**
* Generate the set of values that are included in the list.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @param trim specifies whether each input item is trimmed before being added to the returned collection
* @return the set of objects included in the list; never null
*/
private static <T> Set<T> setOf(String input, Function<String, String[]> splitter, Function<String, T> factory, boolean trim) {
if (input == null) {
return Collections.emptySet();
}
Set<T> matches = new HashSet<>();
for (String item : splitter.apply(input)) {
T obj = factory.apply(trim ? item.trim() : item);
if (obj != null) {
matches.add(obj);
}
}
return matches;
}
/**
* Generate the set of values that are included in the list.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOf(String input, Function<String, String[]> splitter, Function<String, T> factory) {
return setOf(input, splitter, factory, false);
}
/**
* Generate the set of values that are included in the list, with each element trimmed.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOfTrimmed(String input, Function<String, String[]> splitter, Function<String, T> factory) {
return setOf(input, splitter, factory, true);
}
/**
* Generate the list of values that are included in the list.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @param trim specifies whether each input item is trimmed before being added to the returned collection
* @return the list of objects included in the list; never null
*/
private static <T> List<T> listOf(String input, Function<String, String[]> splitter, Function<String, T> factory, boolean trim) {
if (input == null) {
return Collections.emptyList();
}
List<T> matches = new ArrayList<T>();
for (String item : splitter.apply(input)) {
T obj = factory.apply(trim ? item.trim() : item);
if (obj != null) {
matches.add(obj);
}
}
return matches;
}
/**
* Generate the list of values that are included in the list.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @return the list of objects included in the list; never null
*/
public static <T> List<T> listOf(String input, Function<String, String[]> splitter, Function<String, T> factory) {
return listOf(input, splitter, factory, false);
}
/**
* Generate the list of values that are included in the list, with each element trimmed.
*
* @param input the input string
* @param splitter the function that splits the input into multiple items; may not be null
* @param factory the factory for creating string items into filter matches; may not be null
* @return the list of objects included in the list; never null
*/
public static <T> List<T> listOfTrimmed(String input, Function<String, String[]> splitter, Function<String, T> factory) {
return listOf(input, splitter, factory, true);
}
/**
* Generate the set of values that are included in the list delimited by the given delimiter.
*
* @param input the input string
* @param delimiter the character used to delimit the items in the input
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOf(String input, char delimiter, Function<String, T> factory) {
return setOf(input, (str) -> str.split("[" + delimiter + "]"), factory);
}
/**
* Generate the set of values that are included in the list delimited by the given delimiter, with each element trimmed.
*
* @param input the input string
* @param delimiter the character used to delimit the items in the input
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOfTrimmed(String input, char delimiter, Function<String, T> factory) {
return setOfTrimmed(input, (str) -> str.split("[" + delimiter + "]"), factory);
}
/**
* Generate the set of values that are included in the list separated by commas.
*
* @param input the input string
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOf(String input, Function<String, T> factory) {
return setOf(input, ',', factory);
}
/**
* Generate the set of values that are included in the list separated by commas, with each element trimmed.
*
* @param input the input string
* @param factory the factory for creating string items into filter matches; may not be null
* @return the set of objects included in the list; never null
*/
public static <T> Set<T> setOfTrimmed(String input, Function<String, T> factory) {
return setOfTrimmed(input, ',', factory);
}
/**
* Generate the set of regular expression {@link Pattern}s that are specified in the string containing comma-separated
* regular expressions.
*
* @param input the input string with comma-separated regular expressions. Comma can be escaped with backslash.
* @return the set of regular expression {@link Pattern}s included within the given string; never null
* @throws PatternSyntaxException if the input includes an invalid regular expression
*/
public static Set<Pattern> setOfRegex(String input, int regexFlags) {
return setOf(input, RegExSplitter::split, (str) -> Pattern.compile(str, regexFlags));
}
/**
* Generate the set of regular expression {@link Pattern}s that are specified in the string containing comma-separated
* regular expressions.
*
* @param input the input string with comma-separated regular expressions. Comma can be escaped with backslash.
* @return the set of regular expression {@link Pattern}s included within the given string; never null
* @throws PatternSyntaxException if the input includes an invalid regular expression
*/
public static Set<Pattern> setOfRegex(String input) {
return setOf(input, RegExSplitter::split, Pattern::compile);
}
/**
* Generate the set of regular expression {@link Pattern}s that are specified in the string containing comma-separated
* regular expressions.
*
* @param input the input string with comma-separated regular expressions. Comma can be escaped with backslash.
* @param regexFlags the flags for {@link Pattern#compile(String, int) compiling regular expressions}
* @return the list of regular expression {@link Pattern}s included in the list; never null
* @throws PatternSyntaxException if the input includes an invalid regular expression
* @throws IllegalArgumentException if bit values other than those corresponding to the defined
* match flags are set in {@code regexFlags}
*/
public static List<Pattern> listOfRegex(String input, int regexFlags) {
return listOf(input, RegExSplitter::split, (str) -> Pattern.compile(str, regexFlags));
}
/**
* Represents a predicate (boolean-valued function) of one character argument.
*/
@FunctionalInterface
public interface CharacterPredicate {
/**
* Evaluates this predicate on the given character argument.
*
* @param c the input argument
* @return {@code true} if the input argument matches the predicate, or {@code false} otherwise
*/
boolean test(char c);
}
/**
* Split the supplied content into lines, returning each line as an element in the returned list.
*
* @param content the string content that is to be split
* @return the list of lines; never null but may be an empty (unmodifiable) list if the supplied content is null or empty
*/
public static List<String> splitLines(final String content) {
if (content == null || content.length() == 0) {
return Collections.emptyList();
}
String[] lines = content.split("[\\r]?\\n");
return Arrays.asList(lines);
}
/**
* Compare two {@link CharSequence} instances.
*
* @param str1 the first character sequence; may be null
* @param str2 the second character sequence; may be null
* @return a negative integer if the first sequence is less than the second, zero if the sequence are equivalent (including if
* both are null), or a positive integer if the first sequence is greater than the second
*/
public static int compareTo(CharSequence str1, CharSequence str2) {
if (str1 == str2) {
return 0;
}
if (str1 == null) {
return -1;
}
if (str2 == null) {
return 1;
}
return str1.toString().compareTo(str2.toString());
}
/**
* Check whether the two {@link String} instances are equal ignoring case.
*
* @param str1 the first character sequence; may be null
* @param str2 the second character sequence; may be null
* @return {@code true} if both are null or if the two strings are equal to each other ignoring case, or {@code false}
* otherwise
*/
public static boolean equalsIgnoreCase(String str1, String str2) {
if (str1 == str2) {
return true;
}
if (str1 == null) {
return str2 == null;
}
return str1.equalsIgnoreCase(str2);
}
/**
* Returns a new String composed of the supplied integer values joined together
* with a copy of the specified {@code delimiter}.
*
* @param delimiter the delimiter that separates each element
* @param values the values to join together.
* @return a new {@code String} that is composed of the {@code elements} separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements} is {@code null}
* @see java.lang.String#join
*/
public static String join(CharSequence delimiter, int[] values) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(values);
if (values.length == 0) {
return "";
}
if (values.length == 1) {
return Integer.toString(values[0]);
}
StringBuilder sb = new StringBuilder();
sb.append(values[0]);
for (int i = 1; i != values.length; ++i) {
sb.append(delimiter);
sb.append(values[i]);
}
return sb.toString();
}
/**
* Returns a new String composed of the supplied values joined together with a copy of the specified {@code delimiter}.
* All {@code null} values are simply ignored.
*
* @param delimiter the delimiter that separates each element
* @param values the values to join together.
* @return a new {@code String} that is composed of the {@code elements} separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements} is {@code null}
* @see java.lang.String#join
*/
public static <T> String join(CharSequence delimiter, Iterable<T> values) {
return join(delimiter, values, v -> {
return v != null ? v.toString() : null;
});
}
/**
* Returns a new String composed of the supplied values joined together with a copy of the specified {@code delimiter}.
*
* @param delimiter the delimiter that separates each element
* @param values the values to join together.
* @param conversion the function that converts the supplied values into strings, or returns {@code null} if the value
* is to be excluded
* @return a new {@code String} that is composed of the {@code elements} separated by the {@code delimiter}
*
* @throws NullPointerException If {@code delimiter} or {@code elements} is {@code null}
* @see java.lang.String#join
*/
public static <T> String join(CharSequence delimiter, Iterable<T> values, Function<T, String> conversion) {
Objects.requireNonNull(delimiter);
Objects.requireNonNull(values);
Iterator<T> iter = values.iterator();
if (!iter.hasNext()) {
return "";
}
StringBuilder sb = new StringBuilder();
String first = conversion.apply(iter.next());
boolean delimit = false;
if (first != null) {
sb.append(first);
delimit = true;
}
while (iter.hasNext()) {
String next = conversion.apply(iter.next());
if (next != null) {
if (delimit) {
sb.append(delimiter);
}
sb.append(next);
delimit = true;
}
}
return sb.toString();
}
/**
* Trim away any leading or trailing whitespace characters.
* <p>
* This is semantically equivalent to {@link String#trim()} but instead uses {@link #trim(String, CharacterPredicate)}.
*
* @param str the string to be trimmed; may not be null
* @return the trimmed string; never null
* @see #trim(String,CharacterPredicate)
*/
public static String trim(String str) {
return trim(str, c -> c <= ' '); // same logic as String.trim()
}
/**
* Trim away any leading or trailing characters that satisfy the supplied predicate
*
* @param str the string to be trimmed; may not be null
* @param predicate the predicate function; may not be null
* @return the trimmed string; never null
* @see #trim(String)
*/
public static String trim(String str, CharacterPredicate predicate) {
int len = str.length();
if (len == 0) {
return str;
}
int st = 0;
while ((st < len) && predicate.test(str.charAt(st))) {
st++;
}
while ((st < len) && predicate.test(str.charAt(len - 1))) {
len--;
}
return ((st > 0) || (len < str.length())) ? str.substring(st, len) : str;
}
/**
* Create a new string containing the specified character repeated a specific number of times.
*
* @param charToRepeat the character to repeat
* @param numberOfRepeats the number of times the character is to repeat in the result; must be greater than 0
* @return the resulting string
*/
public static String createString(final char charToRepeat,
int numberOfRepeats) {
assert numberOfRepeats >= 0;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < numberOfRepeats; ++i) {
sb.append(charToRepeat);
}
return sb.toString();
}
/**
* Pad the string with the specific character to ensure the string is at least the specified length.
*
* @param original the string to be padded; may not be null
* @param length the minimum desired length; must be positive
* @param padChar the character to use for padding, if the supplied string is not long enough
* @return the padded string of the desired length
* @see #justifyLeft(String, int, char)
*/
public static String pad(String original,
int length,
char padChar) {
if (original.length() >= length) {
return original;
}
StringBuilder sb = new StringBuilder(original);
while (sb.length() < length) {
sb.append(padChar);
}
return sb.toString();
}
/**
* Set the length of the string, padding with the supplied character if the supplied string is shorter than desired, or
* truncating the string if it is longer than desired. Unlike {@link #justifyLeft(String, int, char)}, this method does not
* remove leading and trailing whitespace.
*
* @param original the string for which the length is to be set; may not be null
* @param length the desired length; must be positive
* @param padChar the character to use for padding, if the supplied string is not long enough
* @return the string of the desired length
* @see #justifyLeft(String, int, char)
*/
public static String setLength(String original,
int length,
char padChar) {
return justifyLeft(original, length, padChar, false);
}
public enum Justify {
LEFT,
RIGHT,
CENTER;
}
/**
* Justify the contents of the string.
*
* @param justify the way in which the string is to be justified
* @param str the string to be right justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the right justified string
*/
public static String justify(Justify justify,
String str,
final int width,
char padWithChar) {
switch (justify) {
case LEFT:
return justifyLeft(str, width, padWithChar);
case RIGHT:
return justifyRight(str, width, padWithChar);
case CENTER:
return justifyCenter(str, width, padWithChar);
}
assert false;
return null;
}
/**
* Right justify the contents of the string, ensuring that the string ends at the last character. If the supplied string is
* longer than the desired width, the leading characters are removed so that the last character in the supplied string at the
* last position. If the supplied string is shorter than the desired width, the padding character is inserted one or more
* times such that the last character in the supplied string appears as the last character in the resulting string and that
* the length matches that specified.
*
* @param str the string to be right justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the right justified string
*/
public static String justifyRight(String str,
final int width,
char padWithChar) {
assert width > 0;
// Trim the leading and trailing whitespace ...
str = str != null ? str.trim() : "";
final int length = str.length();
int addChars = width - length;
if (addChars < 0) {
// truncate the first characters, keep the last
return str.subSequence(length - width, length).toString();
}
// Prepend the whitespace ...
final StringBuilder sb = new StringBuilder();
while (addChars > 0) {
sb.append(padWithChar);
--addChars;
}
// Write the content ...
sb.append(str);
return sb.toString();
}
/**
* Left justify the contents of the string, ensuring that the supplied string begins at the first character and that the
* resulting string is of the desired length. If the supplied string is longer than the desired width, it is truncated to the
* specified length. If the supplied string is shorter than the desired width, the padding character is added to the end of
* the string one or more times such that the length is that specified. All leading and trailing whitespace is removed.
*
* @param str the string to be left justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the left justified string
* @see #setLength(String, int, char)
*/
public static String justifyLeft(String str,
final int width,
char padWithChar) {
return justifyLeft(str, width, padWithChar, true);
}
protected static String justifyLeft(String str,
final int width,
char padWithChar,
boolean trimWhitespace) {
// Trim the leading and trailing whitespace ...
str = str != null ? (trimWhitespace ? str.trim() : str) : "";
int addChars = width - str.length();
if (addChars < 0) {
// truncate
return str.subSequence(0, width).toString();
}
// Write the content ...
final StringBuilder sb = new StringBuilder();
sb.append(str);
// Append the whitespace ...
while (addChars > 0) {
sb.append(padWithChar);
--addChars;
}
return sb.toString();
}
/**
* Center the contents of the string. If the supplied string is longer than the desired width, it is truncated to the
* specified length. If the supplied string is shorter than the desired width, padding characters are added to the beginning
* and end of the string such that the length is that specified; one additional padding character is prepended if required.
* All leading and trailing whitespace is removed before centering.
*
* @param str the string to be left justified; if null, an empty string is used
* @param width the desired width of the string; must be positive
* @param padWithChar the character to use for padding, if needed
* @return the left justified string
* @see #setLength(String, int, char)
*/
public static String justifyCenter(String str,
final int width,
char padWithChar) {
// Trim the leading and trailing whitespace ...
str = str != null ? str.trim() : "";
int addChars = width - str.length();
if (addChars < 0) {
// truncate
return str.subSequence(0, width).toString();
}
// Write the content ...
int prependNumber = addChars / 2;
int appendNumber = prependNumber;
if ((prependNumber + appendNumber) != addChars) {
++prependNumber;
}
final StringBuilder sb = new StringBuilder();
// Prepend the pad character(s) ...
while (prependNumber > 0) {
sb.append(padWithChar);
--prependNumber;
}
// Add the actual content
sb.append(str);
// Append the pad character(s) ...
while (appendNumber > 0) {
sb.append(padWithChar);
--appendNumber;
}
return sb.toString();
}
/**
* Get the stack trace of the supplied exception.
*
* @param throwable the exception for which the stack trace is to be returned
* @return the stack trace, or null if the supplied exception is null
*/
public static String getStackTrace(Throwable throwable) {
if (throwable == null) {
return null;
}
final ByteArrayOutputStream bas = new ByteArrayOutputStream();
final PrintWriter pw = new PrintWriter(bas);
throwable.printStackTrace(pw);
pw.close();
return bas.toString();
}
/**
* Parse the supplied string as a number.
*
* @param value the string representation of a integer value
* @return the number, or {@code null} if the value is not a number
*/
public static Number asNumber(String value) {
return asNumber(value, null);
}
/**
* Parse the supplied string as a number.
*
* @param value the string representation of a integer value
* @param defaultValueProvider the function that returns a value to be used when the string value is null or cannot be parsed
* as a number; may be null if no default value is to be used
* @return the number, or {@code null} if the value is not a number and no default value is supplied
*/
public static Number asNumber(String value, Supplier<Number> defaultValueProvider) {
if (value != null) {
try {
return Short.valueOf(value);
}
catch (NumberFormatException e1) {
try {
return Integer.valueOf(value);
}
catch (NumberFormatException e2) {
try {
return Long.valueOf(value);
}
catch (NumberFormatException e3) {
try {
return Float.valueOf(value);
}
catch (NumberFormatException e4) {
try {
return Double.valueOf(value);
}
catch (NumberFormatException e5) {
try {
return new BigInteger(value);
}
catch (NumberFormatException e6) {
try {
return new BigDecimal(value);
}
catch (NumberFormatException e7) {
}
}
}
}
}
}
}
}
return defaultValueProvider != null ? defaultValueProvider.get() : null;
}
/**
* Parse the supplied string as a integer value.
*
* @param value the string representation of a integer value
* @param defaultValue the value to return if the string value is null or cannot be parsed as an int
* @return the int value
*/
public static int asInt(String value, int defaultValue) {
if (value != null) {
try {
return Integer.parseInt(value);
}
catch (NumberFormatException e) {
}
}
return defaultValue;
}
/**
* Parse the supplied string as a long value.
*
* @param value the string representation of a long value
* @param defaultValue the value to return if the string value is null or cannot be parsed as a long
* @return the long value
*/
public static long asLong(String value, long defaultValue) {
if (value != null) {
try {
return Long.parseLong(value);
}
catch (NumberFormatException e) {
}
}
return defaultValue;
}
/**
* Parse the supplied string as a double value.
*
* @param value the string representation of a double value
* @param defaultValue the value to return if the string value is null or cannot be parsed as a double
* @return the double value
*/
public static double asDouble(String value, double defaultValue) {
if (value != null) {
try {
return Double.parseDouble(value);
}
catch (NumberFormatException e) {
}
}
return defaultValue;
}
/**
* Parse the supplied string as a boolean value.
*
* @param value the string representation of a boolean value
* @param defaultValue the value to return if the string value is null or cannot be parsed as a boolean
* @return the boolean value
*/
public static boolean asBoolean(String value, boolean defaultValue) {
if (value != null) {
try {
return Boolean.parseBoolean(value);
}
catch (NumberFormatException e) {
}
}
return defaultValue;
}
/**
* Converts the given string (in the format 00:00:00(.0*)) into a {@link Duration}.
*
* @return the given value as {@code Duration} or {@code null} if {@code null} was passed.
*/
public static Duration asDuration(String timeString) {
if (timeString == null) {
return null;
}
Matcher matcher = TIME_PATTERN.matcher(timeString);
if (!matcher.matches()) {
throw new RuntimeException("Unexpected format for TIME column: " + timeString);
}
long hours = Long.parseLong(matcher.group(1));
long minutes = Long.parseLong(matcher.group(2));
long seconds = Long.parseLong(matcher.group(3));
long nanoSeconds = 0;
String microSecondsString = matcher.group(5);
if (microSecondsString != null) {
nanoSeconds = Long.parseLong(Strings.justifyLeft(microSecondsString, 9, '0'));
}
if (hours >= 0) {
return Duration.ofHours(hours)
.plusMinutes(minutes)
.plusSeconds(seconds)
.plusNanos(nanoSeconds);
}
else {
return Duration.ofHours(hours)
.minusMinutes(minutes)
.minusSeconds(seconds)
.minusNanos(nanoSeconds);
}
}
/**
* For the given duration in milliseconds, obtain a readable representation of the form {@code HHH:MM:SS.mmm}, where
* <dl>
* <dt>HHH</dt>
* <dd>is the number of hours written in at least 2 digits (e.g., "03")</dd>
* <dt>MM</dt>
* <dd>is the number of minutes written in 2 digits (e.g., "05")</dd>
* <dt>SS</dt>
* <dd>is the number of seconds written in 2 digits (e.g., "09")</dd>
* <dt>mmm</dt>
* <dd>is the fractional part of seconds, written with 1-3 digits (any trailing zeros are dropped)</dd>
* </dl>
*
* @param durationInMillis the duration in milliseconds
* @return the readable duration.
*/
public static String duration(long durationInMillis) {
long seconds = durationInMillis / 1000;
long s = seconds % 60;
long m = (seconds / 60) % 60;
long h = (seconds / (60 * 60));
long q = durationInMillis % 1000;
StringBuilder result = new StringBuilder(15);
if (h < 10) {
result.append("0");
}
result.append(h).append(":");
if (m < 10) {
result.append("0");
}
result.append(m).append(":");
if (s < 10) {
result.append("0");
}
result.append(s).append(".");
if (q == 0) {
result.append("0");
return result.toString();
}
else if (q < 10) {
result.append("00");
}
else if (q < 100) {
result.append("0");
}
result.append(q);
int length = result.length();
if (result.charAt(length - 1) == '0') {
if (result.charAt(length - 2) == '0') {
return result.substring(0, length - 2);
}
else {
return result.substring(0, length - 1);
}
}
else {
return result.toString();
}
}
/**
* Obtain a function that will replace variables in the supplied value with values from the supplied lookup function.
* <p>
* Variables may appear anywhere within a string value, and multiple variables can be used within the same value. Variables
* take the form:
*
* <pre>
* variable := '${' variableNames [ ':' defaultValue ] '}'
* variableNames := variableName [ ',' variableNames ]
* variableName := // any characters except ',' and ':' and '}'
* defaultValue := // any characters except '}'
* </pre>
*
* Note that <i>variableName</i> is the name used to look up a the property.
* </p>
* Notice that the syntax supports multiple <i>variables</i>. The logic will process the <i>variables</i> from let to right,
* until an existing property is found. And at that point, it will stop and will not attempt to find values for the other
* <i>variables</i>.
* <p>
*
* @param replacementsByVariableName the function used to find the replacements for variable names; may not be null
* @return the function that will replace variables in supplied strings; never null
*/
public static Function<String, String> replaceVariablesWith(Function<String, String> replacementsByVariableName) {
return (value) -> {
return replaceVariables(value, replacementsByVariableName);
};
}
private static final String CURLY_PREFIX = "${";
private static final String CURLY_SUFFIX = "}";
private static final String VAR_DELIM = ",";
private static final String DEFAULT_DELIM = ":";
/**
* Look in the supplied value for variables and replace them with values from the supplied lookup function.
* <p>
* Variables may appear anywhere within a string value, and multiple variables can be used within the same value. Variables
* take the form:
*
* <pre>
* variable := '${' variableNames [ ':' defaultValue ] '}'
* variableNames := variableName [ ',' variableNames ]
* variableName := // any characters except ',' and ':' and '}'
* defaultValue := // any characters except '}'
* </pre>
*
* Note that <i>variableName</i> is the name used to look up a the property.
* </p>
* Notice that the syntax supports multiple <i>variables</i>. The logic will process the <i>variables</i> from let to right,
* until an existing property is found. And at that point, it will stop and will not attempt to find values for the other
* <i>variables</i>.
* <p>
*
* @param value the content in which the variables are to be found and replaced; may not be null
* @param replacementsByVariableName the function used to find the replacements for variable names; may not be null
* @return the function that will replace variables in supplied strings; never null
*/
public static String replaceVariables(String value, Function<String, String> replacementsByVariableName) {
if (value == null || value.trim().length() == 0) {
return value;
}
StringBuilder sb = new StringBuilder(value);
// Get the index of the first constant, if any
int startName = sb.indexOf(CURLY_PREFIX);
if (startName == -1) {
return value;
}
// process as many different variable groupings that are defined, where one group will resolve to one property
// substitution
while (startName != -1) {
String defaultValue = null;
int endName = sb.indexOf(CURLY_SUFFIX, startName);
if (endName == -1) {
// if no suffix can be found, then this variable was probably defined incorrectly
// but return what there is at this point
return sb.toString();
}
String varString = sb.substring(startName + 2, endName);
if (varString.indexOf(DEFAULT_DELIM) > -1) {
List<String> defaults = split(varString, DEFAULT_DELIM);
// get the property(s) variables that are defined left of the default delimiter.
varString = defaults.get(0);
// if the default is defined, then capture in case none of the other properties are found
if (defaults.size() == 2) {
defaultValue = defaults.get(1);
}
}
String constValue = null;
// split the property(s) based VAR_DELIM, when multiple property options are defined
List<String> vars = split(varString, VAR_DELIM);
for (final String var : vars) {
constValue = replacementsByVariableName.apply(var);
// the first found property is the value to be substituted
if (constValue != null) {
break;
}
}
// if no property is found to substitute, then use the default value, if defined
if (constValue == null && defaultValue != null) {
constValue = defaultValue;
}
if (constValue != null) {