-
Notifications
You must be signed in to change notification settings - Fork 623
Expand file tree
/
Copy pathClickHouseUtils.java
More file actions
1649 lines (1488 loc) · 59 KB
/
ClickHouseUtils.java
File metadata and controls
1649 lines (1488 loc) · 59 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
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
package com.clickhouse.data;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystems;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileAttribute;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ServiceLoader;
import java.util.Set;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.function.UnaryOperator;
public final class ClickHouseUtils {
private static final boolean IS_UNIX;
private static final boolean IS_WINDOWS;
private static final String HOME_DIR;
static {
final String osName = System.getProperty("os.name", "");
// https://github.com/apache/commons-lang/blob/5a3904c8678574a4ddb8502ebbc606be1091fb3f/src/main/java/org/apache/commons/lang3/SystemUtils.java#L1370
IS_UNIX = osName.startsWith("AIX") || osName.startsWith("HP-UX") || osName.startsWith("OS/400")
|| osName.startsWith("Irix") || osName.startsWith("Linux") || osName.startsWith("LINUX")
|| osName.startsWith("Mac OS X") || osName.startsWith("Solaris") || osName.startsWith("SunOS")
|| osName.startsWith("FreeBSD") || osName.startsWith("OpenBSD") || osName.startsWith("NetBSD");
IS_WINDOWS = osName.toLowerCase(Locale.ROOT).contains("windows");
HOME_DIR = IS_WINDOWS
? Paths.get(System.getenv("APPDATA"), "clickhouse").toFile().getAbsolutePath()
: Paths.get(System.getProperty("user.home"), ".clickhouse").toFile().getAbsolutePath();
}
/**
* Default charset.
*/
public static final String DEFAULT_CHARSET = StandardCharsets.UTF_8.name();
public static final int MIN_CORE_THREADS = 4;
public static final CompletableFuture<Void> NULL_FUTURE = CompletableFuture.completedFuture(null);
public static final Supplier<?> NULL_SUPPLIER = () -> null;
public static final String VARIABLE_PREFIX = "{{";
public static final String VARIABLE_SUFFIX = "}}";
/**
* Parses a boolean value from string. Accepts "true"/"false" and "1"/"0".
*
* @param value string value
* @return parsed boolean, or {@code false} if value is null or unrecognized
*/
public static boolean parseBoolean(String value) {
if (value == null) {
return false;
}
if ("1".equals(value)) {
return true;
}
if ("0".equals(value)) {
return false;
}
return Boolean.parseBoolean(value);
}
private static <T> T findFirstService(Class<? extends T> serviceInterface) {
ClickHouseChecker.nonNull(serviceInterface, "serviceInterface");
T service = null;
for (T s : ServiceLoader.load(serviceInterface, ClickHouseUtils.class.getClassLoader())) {
if (s != null) {
service = s;
break;
}
}
return service;
}
public static String applyVariables(String template, UnaryOperator<String> applyFunc) {
if (template == null) {
template = "";
}
if (applyFunc == null) {
return template;
}
StringBuilder sb = new StringBuilder();
for (int i = 0, len = template.length(); i < len; i++) {
int index = template.indexOf(VARIABLE_PREFIX, i);
if (index != -1) {
sb.append(template.substring(i, index));
i = index;
index = template.indexOf(VARIABLE_SUFFIX, i);
if (index != -1) {
String variable = template.substring(i + VARIABLE_PREFIX.length(), index).trim();
String value = applyFunc.apply(variable);
if (value == null) {
i += VARIABLE_PREFIX.length() - 1;
sb.append(VARIABLE_PREFIX);
} else {
i = index + VARIABLE_SUFFIX.length() - 1;
sb.append(value);
}
} else {
sb.append(template.substring(i));
break;
}
} else {
sb.append(template.substring(i));
break;
}
}
return sb.toString();
}
public static String applyVariables(String template, Map<String, String> variables) {
return applyVariables(template, variables == null || variables.isEmpty() ? null : variables::get);
}
/**
* Creates a temporary file. Same as {@code createTempFile(null, null, true)}.
*
* @return non-null temporary file
* @throws IOException when failed to create the temporary file
*/
public static File createTempFile() throws IOException {
return createTempFile(null, null, true);
}
/**
* Creates a temporary file with given prefix and suffix. Same as
* {@code createTempFile(prefix, suffix, true)}.
*
* @param prefix prefix, could be null
* @param suffix suffix, could be null
* @return non-null temporary file
* @throws IOException when failed to create the temporary file
*/
public static File createTempFile(String prefix, String suffix) throws IOException {
return createTempFile(prefix, suffix, true);
}
/**
* Creates a temporary file with the given prefix and suffix. The file has only
* read and write access granted to the owner.
*
* @param prefix prefix, null or empty string is taken as {@code "ch"}
* @param suffix suffix, null or empty string is taken as {@code ".data"}
* @param deleteOnExit whether the file be deleted on exit
* @return non-null temporary file
* @throws IOException when failed to create the temporary file
*/
public static File createTempFile(String prefix, String suffix, boolean deleteOnExit) throws IOException {
if (prefix == null || prefix.isEmpty()) {
prefix = "ch";
}
if (suffix == null || suffix.isEmpty()) {
suffix = ".data";
}
final File f;
if (IS_UNIX) {
FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions
.asFileAttribute(PosixFilePermissions.fromString("rw-------"));
f = Files.createTempFile(prefix, suffix, attr).toFile();
} else {
f = Files.createTempFile(prefix, suffix).toFile(); // NOSONAR
f.setReadable(true, true); // NOSONAR
f.setWritable(true, true); // NOSONAR
f.setExecutable(false, false); // NOSONAR
}
if (deleteOnExit) {
f.deleteOnExit();
}
return f;
}
/**
* Decode given string using {@link URLDecoder} and
* {@link StandardCharsets#UTF_8}.
*
* @param encodedString encoded string
* @return non-null decoded string
*/
public static String decode(String encodedString) {
if (ClickHouseChecker.isNullOrEmpty(encodedString)) {
return "";
}
try {
return URLDecoder.decode(encodedString, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
return encodedString;
}
}
/**
* Encode given string using {@link URLEncoder} and
* {@link StandardCharsets#UTF_8}.
*
* @param str string to encode
* @return non-null encoded string
*/
public static String encode(String str) {
if (ClickHouseChecker.isNullOrEmpty(str)) {
return "";
}
try {
return URLEncoder.encode(str, DEFAULT_CHARSET);
} catch (UnsupportedEncodingException e) {
return str;
}
}
/**
* Extracts parameters, usually key-value pairs, from the given query string.
*
* @param query non-empty query string
* @param params mutable map for extracted parameters, a new {@link HashMap}
* will be created when it's null
* @return map with extracted parameters, usually same as {@code params}
*/
public static Map<String, String> extractParameters(String query, Map<String, String> params) {
if (params == null) {
params = new HashMap<>();
}
if (ClickHouseChecker.isNullOrEmpty(query)) {
return params;
}
int len = query.length();
for (int i = 0; i < len; i++) {
int index = query.indexOf('&', i);
if (index == i) {
continue;
}
String param;
if (index < 0) {
param = query.substring(i);
i = len;
} else {
param = query.substring(i, index);
i = index;
}
index = param.indexOf('=');
String key;
String value;
if (index < 0) {
key = decode(param);
if (key.charAt(0) == '!') {
key = key.substring(1);
value = Boolean.FALSE.toString();
} else {
value = Boolean.TRUE.toString();
}
} else {
key = decode(param.substring(0, index));
value = decode(param.substring(index + 1));
}
// any multi-value option? cluster?
if (!ClickHouseChecker.isNullOrEmpty(value)) {
params.put(key, value);
}
}
return params;
}
public static <T> T newInstance(String className, Class<T> returnType, Class<?> callerClass) {
if (className == null || className.isEmpty() || returnType == null) {
throw new IllegalArgumentException("Non-empty class name and return type are required");
} else if (callerClass == null) {
callerClass = returnType;
}
try {
Class<?> clazz = Class.forName(className, false, callerClass.getClassLoader());
if (!returnType.isAssignableFrom(clazz)) {
throw new IllegalArgumentException(
format("Invalid %s class type. Input class should be a superclass of %s.", className,
returnType));
}
return returnType.cast(clazz.getConstructor().newInstance());
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException(format("Class %s is not found in the classpath.", className));
} catch (IllegalAccessException | NoSuchMethodException e) {
throw new IllegalArgumentException(
format("Class %s does not have a public constructor without any argument.", className));
} catch (InstantiationException | InvocationTargetException e) {
throw new IllegalArgumentException(format("Error while creating an %s class instance.", className), e);
}
}
/**
* Gets absolute and normalized path to the given file.
*
* @param file non-empty file
* @return non-null absolute and normalized path to the file
*/
public static Path getFile(String file) {
if (file == null || file.isEmpty()) {
throw new IllegalArgumentException("Non-empty file is required");
} else if (file.startsWith("~/")) {
return Paths.get(System.getProperty("user.home"), file.substring(2)).normalize();
}
return Paths.get(file).toAbsolutePath().normalize();
}
/**
* Finds files according to the given pattern and path.
*
* @param pattern non-empty pattern may or may have syntax prefix as in
* {@link java.nio.file.FileSystem#getPathMatcher(String)},
* defaults to {@code glob} syntax
* @param paths path to search, defaults to current work directory
* @return non-null list of normalized absolute paths matching the pattern
* @throws IOException when failed to find files
*/
public static List<Path> findFiles(String pattern, String... paths) throws IOException {
if (pattern == null || pattern.isEmpty()) {
throw new IllegalArgumentException("Non-empty pattern is required");
} else if (pattern.startsWith("~/")) {
return Collections
.singletonList(Paths.get(System.getProperty("user.home"), pattern.substring(2)).normalize());
}
if (!pattern.startsWith("glob:") && !pattern.startsWith("regex:")) {
if (IS_WINDOWS) {
final String reservedCharsWindows = "<>:\"|?*";
pattern.chars().anyMatch(
value -> {
if (value < ' ' || reservedCharsWindows.indexOf(value) != -1) {
throw new IllegalArgumentException(String.format("File path contains reserved character <%s>", value));
}
return false;
}
);
}
Path path = Paths.get(pattern);
if (path.isAbsolute()) {
return Collections.singletonList(path);
} else {
pattern = "glob:" + pattern;
}
}
final Path searchPath;
if (paths == null || paths.length == 0) {
searchPath = Paths.get("");
} else {
String root = paths[0];
Path rootPath = root.startsWith("~/")
? Paths.get(System.getProperty("user.home"), root.substring(2)).normalize()
: Paths.get(root);
searchPath = paths.length < 2 ? rootPath
: Paths.get(rootPath.toFile().getAbsolutePath(), Arrays.copyOfRange(paths, 1, paths.length))
.normalize();
}
final List<Path> files = new ArrayList<>();
final PathMatcher matcher = FileSystems.getDefault().getPathMatcher(pattern);
Files.walkFileTree(searchPath, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
if (matcher.matches(path)) {
files.add(path.normalize());
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc)
throws IOException {
return FileVisitResult.CONTINUE;
}
});
return files;
}
public static String toJavaByteArrayExpression(byte[] bytes) {
if (bytes == null) {
return "null";
}
int len = bytes.length;
if (len == 0) {
return "{}";
}
String prefix = "(byte)0x";
StringBuilder builder = new StringBuilder(10 * len).append('{');
for (int i = 0; i < len; i++) {
builder.append(prefix).append(String.format("%02X", 0xFF & bytes[i])).append(',');
}
builder.setCharAt(builder.length() - 1, '}');
return builder.toString();
}
public static ExecutorService newThreadPool(Object owner, int maxThreads, int maxRequests) {
return newThreadPool(owner, maxThreads, 0, maxRequests, 0L, true);
}
public static ExecutorService newThreadPool(Object owner, int coreThreads, int maxThreads, int maxRequests,
long keepAliveTimeoutMs, boolean allowCoreThreadTimeout) {
final BlockingQueue<Runnable> queue;
if (coreThreads < MIN_CORE_THREADS) {
coreThreads = MIN_CORE_THREADS;
}
if (maxRequests > 0) {
queue = new ArrayBlockingQueue<>(maxRequests);
if (maxThreads <= coreThreads) {
maxThreads = coreThreads * 2;
}
} else {
queue = new LinkedBlockingQueue<>();
if (maxThreads != coreThreads) {
maxThreads = coreThreads;
}
}
if (keepAliveTimeoutMs <= 0L) {
keepAliveTimeoutMs = allowCoreThreadTimeout ? 1000L : 0L;
}
ThreadPoolExecutor pool = new ThreadPoolExecutor(coreThreads, maxThreads, keepAliveTimeoutMs,
TimeUnit.MILLISECONDS, queue, new ClickHouseThreadFactory(owner), new ThreadPoolExecutor.AbortPolicy());
if (allowCoreThreadTimeout) {
pool.allowCoreThreadTimeOut(true);
}
return pool;
}
public static boolean isCloseBracket(char ch) {
return ch == ')' || ch == ']' || ch == '}';
}
public static boolean isOpenBracket(char ch) {
return ch == '(' || ch == '[' || ch == '{';
}
public static boolean isQuote(char ch) {
return ch == '\'' || ch == '`' || ch == '"';
}
public static boolean isSeparator(char ch) {
return ch == ',' || ch == ';';
}
/**
* Escape quotes in given string.
*
* @param str string
* @param quote quote to escape
* @return escaped string
*/
public static String escape(String str, char quote) {
if (str == null) {
return str;
}
int len = str.length();
StringBuilder sb = new StringBuilder(len + 10);
for (int i = 0; i < len; i++) {
char ch = str.charAt(i);
if (ch == quote || ch == '\\') {
sb.append('\\');
}
sb.append(ch);
}
return sb.toString();
}
/**
* Unescape quoted string.
*
* @param str quoted string
* @return unescaped string
*/
public static String unescape(String str) {
if (ClickHouseChecker.isNullOrEmpty(str)) {
return str;
}
int len = str.length();
char quote = str.charAt(0);
if (!isQuote(quote) || quote != str.charAt(len - 1)) { // not a quoted string
return str;
}
StringBuilder sb = new StringBuilder(len = len - 1);
for (int i = 1; i < len; i++) {
char ch = str.charAt(i);
if (++i >= len) {
sb.append(ch);
} else {
char nextChar = str.charAt(i);
if (ch == '\\' || (ch == quote && nextChar == quote)) {
sb.append(nextChar);
} else {
sb.append(ch);
i--;
}
}
}
return sb.toString();
}
/**
* Wrapper of {@code String.format(Locale.ROOT, ...)}.
*
* @param template string to format
* @param args arguments used in substitution
* @return formatted string
*/
public static String format(String template, Object... args) {
return String.format(Locale.ROOT, template, args);
}
/**
* Normalizes given directory by appending back slash if it does exist.
*
* @param dir original directory
* @return normalized directory
*/
public static String normalizeDirectory(String dir) {
if (dir == null || dir.isEmpty()) {
return "./";
}
return dir.charAt(dir.length() - 1) == '/' ? dir : dir.concat("/");
}
private static int readJsonArray(String json, List<Object> array, int startIndex, int len) {
StringBuilder builder = new StringBuilder();
// skip the first bracket
for (int i = startIndex + 1; i < len; i++) {
char ch = json.charAt(i);
if (Character.isWhitespace(ch) || ch == ',' || ch == ':') {
continue;
} else if (ch == '"') {
i = readUnescapedJsonString(json, builder, i, len) - 1;
array.add(builder.toString());
builder.setLength(0);
} else if (ch == '-' || (ch >= '0' && ch <= '9')) {
List<Object> list = new ArrayList<>(1);
i = readJsonNumber(json, list, i, len) - 1;
array.add(list.get(0));
builder.setLength(0);
} else if (ch == '{') {
Map<String, Object> map = new LinkedHashMap<>();
i = readJsonObject(json, map, i, len) - 1;
array.add(map);
} else if (ch == '[') {
List<Object> list = new LinkedList<>();
i = readJsonArray(json, list, i, len) - 1;
array.add(list.toArray(new Object[0]));
} else if (ch == ']') {
return i + 1;
} else {
List<Object> list = new ArrayList<>(1);
i = readJsonConstants(json, list, i, len) - 1;
array.add(list.get(0));
}
}
return len;
}
private static int readJsonConstants(String json, List<Object> value, int startIndex, int len) {
String c = "null";
if (json.indexOf(c, startIndex) == startIndex) {
value.add(null);
} else if (json.indexOf(c = "false", startIndex) == startIndex) {
value.add(Boolean.FALSE);
} else if (json.indexOf(c = "true", startIndex) == startIndex) {
value.add(Boolean.TRUE);
} else {
throw new IllegalArgumentException(format("Expect one of 'null', 'false', 'true' but we got '%s'",
json.substring(startIndex, Math.min(startIndex + 5, len))));
}
return startIndex + c.length();
}
private static int readJsonNumber(String json, List<Object> value, int startIndex, int len) {
int endIndex = len;
StringBuilder builder = new StringBuilder().append(json.charAt(startIndex));
boolean hasDot = false;
boolean hasExp = false;
// add first digit
for (int i = startIndex + 1; i < len; i++) {
char n = json.charAt(i);
if (n >= '0' && n <= '9') {
builder.append(n);
} else if (!hasDot && n == '.') {
hasDot = true;
builder.append(n);
} else if (!hasExp && (n == 'e' || n == 'E')) {
hasDot = true;
hasExp = true;
builder.append(n);
if (i + 1 < len) {
char next = json.charAt(i + 1);
if (next == '+' || next == '-') {
builder.append(next);
i++;
}
}
boolean hasNum = false;
for (int j = i + 1; j < len; j++) {
char next = json.charAt(j);
if (next >= '0' && next <= '9') {
hasNum = true;
builder.append(next);
} else {
if (!hasNum) {
throw new IllegalArgumentException("Expect number after exponent at " + i);
}
endIndex = j + 1;
break;
}
}
break;
} else {
endIndex = i;
break;
}
}
if (hasDot) {
if (hasExp || builder.length() >= 21) {
value.add(new BigDecimal(builder.toString()));
} else if (builder.length() >= 11) {
value.add(Double.parseDouble(builder.toString()));
} else {
value.add(Float.parseFloat(builder.toString()));
}
} else {
if (hasExp || builder.length() >= 19) {
value.add(new BigInteger(builder.toString()));
} else if (builder.length() >= 10) {
value.add(Long.parseLong(builder.toString()));
} else {
value.add(Integer.parseInt(builder.toString()));
}
}
return endIndex;
}
private static int readJsonObject(String json, Map<String, Object> object, int startIndex, int len) {
StringBuilder builder = new StringBuilder();
String key = null;
// skip the first bracket
for (int i = startIndex + 1; i < len; i++) {
char ch = json.charAt(i);
if (Character.isWhitespace(ch) || ch == ',' || ch == ':') {
continue;
} else if (ch == '"') {
i = readUnescapedJsonString(json, builder, i, len) - 1;
if (key != null) {
object.put(key, builder.toString());
key = null;
} else {
key = builder.toString();
}
builder.setLength(0);
} else if (ch == '-' || (ch >= '0' && ch <= '9')) {
if (key == null) {
throw new IllegalArgumentException("Key is not available");
}
List<Object> list = new ArrayList<>(1);
i = readJsonNumber(json, list, i, len) - 1;
object.put(key, list.get(0));
key = null;
builder.setLength(0);
} else if (ch == '{') {
if (key == null) {
throw new IllegalArgumentException("Key is not available");
}
Map<String, Object> map = new LinkedHashMap<>();
i = readJsonObject(json, map, i, len) - 1;
object.put(key, map);
key = null;
builder.setLength(0);
} else if (ch == '[') {
if (key == null) {
throw new IllegalArgumentException("Key is not available");
}
List<Object> list = new LinkedList<>();
i = readJsonArray(json, list, i, len) - 1;
key = null;
object.put(key, list.toArray(new Object[0]));
} else if (ch == '}') {
return i + 1;
} else {
if (key == null) {
throw new IllegalArgumentException("Key is not available");
}
List<Object> list = new ArrayList<>(1);
i = readJsonConstants(json, list, i, len) - 1;
object.put(key, list.get(0));
key = null;
}
}
return len;
}
private static int readUnescapedJsonString(String json, StringBuilder builder, int startIndex, int len) {
// skip the first double quote
for (int i = startIndex + 1; i < len; i++) {
char c = json.charAt(i);
if (c == '\\') {
if (++i < len) {
builder.append(json.charAt(i));
}
} else if (c == '"') {
return i + 1;
} else {
builder.append(c);
}
}
return len;
}
/**
* Removes specific character from the given string.
*
* @param str string to remove character from
* @param ch specific character to be removed from the string
* @param more more characters to be removed
* @return non-null string without the specific character
*/
public static String remove(String str, char ch, char... more) {
if (str == null || str.isEmpty()) {
return "";
}
int l = more == null ? 0 : more.length;
if (l == 0 && str.indexOf(ch) == -1) {
return str;
}
// deduped array
char[] chars = new char[1 + l];
chars[0] = ch;
int p = 1;
for (int i = 0; i < l; i++) {
char c = more[i];
boolean skip = false;
for (int j = 0, k = i + 1; j < k; j++) {
if (chars[j] == c) {
skip = true;
break;
}
}
if (!skip) {
chars[p++] = c;
}
}
int len = str.length();
StringBuilder builder = new StringBuilder(len);
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
boolean skip = false;
for (int j = 0; j < p; j++) {
if (chars[j] == c) {
skip = true;
break;
}
}
if (!skip) {
builder.append(c);
}
}
return builder.toString();
}
/**
* Simple and un-protected JSON parser.
*
* @param json non-empty JSON string
* @return object array, Boolean, Number, null, String, or Map
* @throws IllegalArgumentException when JSON string is null or empty
*/
public static Object parseJson(String json) {
if (json == null || json.isEmpty()) {
throw new IllegalArgumentException("Non-empty JSON string is required");
}
boolean hasValue = false;
Object value = null;
StringBuilder builder = new StringBuilder();
for (int i = 0, len = json.length(); i < len; i++) {
char ch = json.charAt(i);
if (Character.isWhitespace(ch)) {
continue;
} else if (ch == '{') {
// read object
Map<String, Object> map = new LinkedHashMap<>();
i = readJsonObject(json, map, i, len) - 1;
hasValue = true;
value = map;
} else if (ch == '[') {
// read array
List<Object> list = new LinkedList<>();
i = readJsonArray(json, list, i, len) - 1;
hasValue = true;
value = list.toArray(new Object[0]);
} else if (ch == '"') {
// read string
i = readUnescapedJsonString(json, builder, i, len) - 1;
hasValue = true;
value = builder.toString();
} else if (ch == '-' || (ch >= '0' && ch <= '9')) {
// read number
List<Object> list = new ArrayList<>(1);
i = readJsonNumber(json, list, i, len) - 1;
hasValue = true;
value = list.get(0);
} else {
List<Object> list = new ArrayList<>(1);
i = readJsonConstants(json, list, i, len) - 1;
hasValue = true;
value = list.get(0);
}
break;
}
if (!hasValue) {
throw new IllegalArgumentException("No value extracted from given JSON string");
}
return value;
}
public static char getCloseBracket(char openBracket) {
char closeBracket;
if (openBracket == '(') {
closeBracket = ')';
} else if (openBracket == '[') {
closeBracket = ']';
} else if (openBracket == '{') {
closeBracket = '}';
} else {
throw new IllegalArgumentException("Unsupported bracket: " + openBracket);
}
return closeBracket;
}
public static <T> T getService(Class<? extends T> serviceInterface) {
return getService(serviceInterface, null);
}
/**
* Load service according to given interface using
* {@link java.util.ServiceLoader}, fallback to given default service or
* supplier function if not found.
*
* @param <T> type of service
* @param serviceInterface non-null service interface
* @param defaultService optionally default service
* @return non-null service
*/
public static <T> T getService(Class<? extends T> serviceInterface, T defaultService) {
T service = defaultService;
Exception error = null;
// load custom implementation if any
try {
T s = findFirstService(serviceInterface);
if (s != null) {
service = s;
}
} catch (Exception t) {
error = t;
}
if (service == null) {
throw new IllegalStateException(String.format("Failed to get service %s", serviceInterface.getName()),
error);
}
return service;
}
public static <T> T getService(Class<? extends T> serviceInterface, Supplier<T> supplier) {
T service = null;
Exception error = null;
// load custom implementation if any
try {
service = findFirstService(serviceInterface);
} catch (Exception t) {
error = t;
}
// and then try supplier function if no luck
if (service == null && supplier != null) {
try {
service = supplier.get();
} catch (Exception t) {
// override the error
error = t;
}
}
if (service == null) {
throw new IllegalStateException(String.format("Failed to get service %s", serviceInterface.getName()),
error);
}
return service;
}
/**
* Search file in current directory, home directory, and then classpath, Get
* input stream to read the given file.
*
* @param file path to the file
* @return input stream
* @throws FileNotFoundException when the file does not exists
*/
public static InputStream getFileInputStream(String file) throws FileNotFoundException {
Path path = Paths.get(ClickHouseChecker.nonBlank(file, "file"));
StringBuilder builder = new StringBuilder();
InputStream in = null;
if (Files.exists(path)) {
builder.append(',').append(file);
in = new FileInputStream(path.toFile());
} else if (!path.isAbsolute()) {
path = Paths.get(HOME_DIR, file);
if (Files.exists(path)) {
builder.append(',').append(path.toString());