-
Notifications
You must be signed in to change notification settings - Fork 153
/
Utilities.java
1865 lines (1628 loc) · 53.5 KB
/
Utilities.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
package org.hl7.fhir.utilities;
import static org.apache.commons.lang3.StringUtils.isBlank;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/*
Copyright (c) 2011+, HL7, Inc.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of HL7 nor the names of its contributors may be used to
endorse or promote products derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
import org.apache.commons.io.FileUtils;
import org.hl7.fhir.exceptions.FHIRException;
import org.hl7.fhir.utilities.FileNotifier.FileNotifier2;
import javax.annotation.Nullable;
public class Utilities {
private static final String UUID_REGEX = "[0-9a-f]{8}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{4}\\-[0-9a-f]{12}";
private static final String OID_REGEX = "[0-2](\\.(0|[1-9][0-9]*))+";
static final String C_TEMP_DIR = "c:\\temp";
/**
* Returns the plural form of the word in the string.
* <p>
* Examples:
*
* <pre>
* inflector.pluralize("post") #=> "posts"
* inflector.pluralize("octopus") #=> "octopi"
* inflector.pluralize("sheep") #=> "sheep"
* inflector.pluralize("words") #=> "words"
* inflector.pluralize("the blue mailman") #=> "the blue mailmen"
* inflector.pluralize("CamelOctopus") #=> "CamelOctopi"
* </pre>
* <p>
* <p>
* <p>
* Note that if the {@link Object#toString()} is called on the supplied object, so this method works for non-strings, too.
*
* @param word the word that is to be pluralized.
* @return the pluralized form of the word, or the word itself if it could not be pluralized
* @see Inflector#singularize(Object)
*/
public static String pluralizeMe(String word) {
Inflector inf = new Inflector();
return inf.pluralize(word);
}
public static String pluralize(String word, int count) {
if (count == 1)
return word;
Inflector inf = new Inflector();
return inf.pluralize(word);
}
public static boolean isInteger(String string) {
if (isBlank(string)) {
return false;
}
String value = string.startsWith("-") ? string.substring(1) : string;
for (char next : value.toCharArray()) {
if (!Character.isDigit(next)) {
return false;
}
}
// check bounds -2,147,483,648..2,147,483,647
if (value.length() > 10)
return false;
if (string.startsWith("-")) {
if (value.length() == 10 && string.compareTo("2147483648") > 0)
return false;
} else {
if (value.length() == 10 && string.compareTo("2147483647") > 0)
return false;
}
return true;
}
public static boolean isLong(String string) {
if (isBlank(string)) {
return false;
}
String value = string.startsWith("-") ? string.substring(1) : string;
for (char next : value.toCharArray()) {
if (!Character.isDigit(next)) {
return false;
}
}
// check bounds -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807
if (value.length() > 20)
return false;
if (string.startsWith("-")) {
if (value.length() == 20 && string.compareTo("9223372036854775808") > 0)
return false;
} else {
if (value.length() == 20 && string.compareTo("9223372036854775807") > 0)
return false;
}
return true;
}
public static boolean isHex(String string) {
try {
int i = Integer.parseInt(string, 16);
return i != i + 1;
} catch (Exception e) {
return false;
}
}
public enum DecimalStatus {
BLANK, SYNTAX, RANGE, OK
}
public static boolean isDecimal(String value, boolean allowExponent, boolean allowLeadingZero) {
DecimalStatus ds = checkDecimal(value, allowExponent, true);
return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE;
}
public static boolean isDecimal(String value, boolean allowExponent) {
DecimalStatus ds = checkDecimal(value, allowExponent, false);
return ds == DecimalStatus.OK || ds == DecimalStatus.RANGE;
}
public static DecimalStatus checkDecimal(String value, boolean allowExponent, boolean allowLeadingZero) {
if (isBlank(value)) {
return DecimalStatus.BLANK;
}
// check for leading zeros
if (!allowLeadingZero) {
if (value.startsWith("0") && !"0".equals(value) && !value.startsWith("0."))
return DecimalStatus.SYNTAX;
if (value.startsWith("-0") && !"-0".equals(value) && !value.startsWith("-0."))
return DecimalStatus.SYNTAX;
if (value.startsWith("+0") && !"+0".equals(value) && !value.startsWith("+0."))
return DecimalStatus.SYNTAX;
}
// check for trailing dot
if (value.endsWith(".")) {
return DecimalStatus.SYNTAX;
}
boolean havePeriod = false;
boolean haveExponent = false;
boolean haveSign = false;
boolean haveDigits = false;
int preDecLength = 0;
int postDecLength = 0;
int exponentLength = 0;
int length = 0;
for (char next : value.toCharArray()) {
if (next == '.') {
if (!haveDigits || havePeriod || haveExponent)
return DecimalStatus.SYNTAX;
havePeriod = true;
preDecLength = length;
length = 0;
} else if (next == '-' || next == '+') {
if (haveDigits || haveSign)
return DecimalStatus.SYNTAX;
haveSign = true;
} else if (next == 'e' || next == 'E') {
if (!haveDigits || haveExponent || !allowExponent)
return DecimalStatus.SYNTAX;
haveExponent = true;
haveSign = false;
haveDigits = false;
if (havePeriod)
postDecLength = length;
else
preDecLength = length;
length = 0;
} else if (!Character.isDigit(next)) {
return DecimalStatus.SYNTAX;
} else {
haveDigits = true;
length++;
}
}
if (haveExponent && !haveDigits)
return DecimalStatus.SYNTAX;
if (haveExponent)
exponentLength = length;
else if (havePeriod)
postDecLength = length;
else
preDecLength = length;
// now, bounds checking - these are arbitrary
if (exponentLength > 4)
return DecimalStatus.RANGE;
if (preDecLength + postDecLength > 18)
return DecimalStatus.RANGE;
return DecimalStatus.OK;
}
public static String camelCase(String value) {
return new Inflector().camelCase(value.trim().replace(" ", "_"), false);
}
public static String upperCamelCase(String value) {
return new Inflector().upperCamelCase(value.trim().replace(" ", "_"));
}
public static String escapeXml(String doco) {
if (doco == null)
return "";
StringBuilder b = new StringBuilder();
for (char c : doco.toCharArray()) {
if (c == '<')
b.append("<");
else if (c == '>')
b.append(">");
else if (c == '&')
b.append("&");
else if (c == '"')
b.append(""");
else
b.append(c);
}
return b.toString();
}
public static String titleize(String s) {
StringBuilder b = new StringBuilder();
boolean up = true;
for (char c : s.toCharArray()) {
if (up)
b.append(Character.toUpperCase(c));
else
b.append(c);
up = c == ' ';
}
return b.toString();
}
public static String capitalize(String s) {
if (s == null) return null;
if (s.length() == 0) return s;
if (s.length() == 1) return s.toUpperCase();
return s.substring(0, 1).toUpperCase() + s.substring(1);
}
public static void copyDirectory(String sourceFolder, String destFolder, FileNotifier notifier) throws IOException, FHIRException {
CSFile src = new CSFile(sourceFolder);
if (!src.exists())
throw new FHIRException("Folder " + sourceFolder + " not found");
createDirectory(destFolder);
String[] files = src.list();
for (String f : files) {
if (new CSFile(sourceFolder + File.separator + f).isDirectory()) {
if (!f.startsWith(".")) { // ignore .git files...
copyDirectory(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier);
}
} else {
if (notifier != null)
notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f);
copyFile(new CSFile(sourceFolder + File.separator + f), new CSFile(destFolder + File.separator + f));
}
}
}
public static void copyDirectory2(String sourceFolder, String destFolder, FileNotifier2 notifier) throws IOException, FHIRException {
CSFile src = new CSFile(sourceFolder);
if (!src.exists())
throw new FHIRException("Folder " + sourceFolder + " not found");
createDirectory(destFolder);
String[] files = src.list();
for (String f : files) {
if (new CSFile(sourceFolder + File.separator + f).isDirectory()) {
if (!f.startsWith(".")) { // ignore .git files...
boolean doCopy = notifier != null ? notifier.copyFolder(sourceFolder + File.separator + f, destFolder + File.separator + f) : true;
if (doCopy) {
copyDirectory2(sourceFolder + File.separator + f, destFolder + File.separator + f, notifier);
}
}
} else {
boolean doCopy = notifier != null ? notifier.copyFile(sourceFolder + File.separator + f, destFolder + File.separator + f) : true;
if (doCopy) {
copyFile(new CSFile(sourceFolder + File.separator + f), new CSFile(destFolder + File.separator + f));
}
}
}
}
public static void copyFile(String source, String dest) throws IOException {
copyFile(new File(source), new File(dest));
}
public static void copyFile(File sourceFile, File destFile) throws IOException {
if (!destFile.exists()) {
if (!new CSFile(destFile.getParent()).exists()) {
createDirectory(destFile.getParent());
}
destFile.createNewFile();
}
FileInputStream source = null;
FileOutputStream destination = null;
try {
source = new FileInputStream(sourceFile);
destination = new FileOutputStream(destFile);
destination.getChannel().transferFrom(source.getChannel(), 0, source.getChannel().size());
} finally {
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
}
}
public static boolean checkFolder(String dir, List<String> errors)
throws IOException {
if (!new CSFile(dir).exists()) {
errors.add("Unable to find directory " + dir);
return false;
} else {
return true;
}
}
public static boolean checkFile(String purpose, String dir, String file, List<String> errors)
throws IOException {
if (!new CSFile(dir + file).exists()) {
if (errors != null)
errors.add("Unable to find " + purpose + " file " + file + " in " + dir);
return false;
} else {
return true;
}
}
public static String asCSV(List<String> strings) {
StringBuilder s = new StringBuilder();
boolean first = true;
for (String n : strings) {
if (!first)
s.append(",");
s.append(n);
first = false;
}
return s.toString();
}
public static String asHtmlBr(String prefix, List<String> strings) {
StringBuilder s = new StringBuilder();
boolean first = true;
for (String n : strings) {
if (!first)
s.append("<br/>");
s.append(prefix);
s.append(n);
first = false;
}
return s.toString();
}
public static void clearDirectory(String folder, String... exemptions) throws IOException {
File dir = new File(folder);
if (dir.exists()) {
if (exemptions.length == 0)
FileUtils.cleanDirectory(dir);
else {
String[] files = new CSFile(folder).list();
if (files != null) {
for (String f : files) {
if (!existsInList(f, exemptions)) {
File fh = new CSFile(folder + File.separatorChar + f);
if (fh.isDirectory())
clearDirectory(fh.getAbsolutePath());
fh.delete();
}
}
}
}
}
}
public static File createDirectory(String path) throws IOException {
new CSFile(path).mkdirs();
return new File(path);
}
public static String changeFileExt(String name, String ext) {
if (name.lastIndexOf('.') > -1)
return name.substring(0, name.lastIndexOf('.')) + ext;
else
return name + ext;
}
public static String cleanupTextString(String contents) {
if (contents == null || contents.trim().equals(""))
return null;
else
return contents.trim();
}
public static boolean noString(String v) {
return v == null || v.equals("");
}
public static void bytesToFile(byte[] content, String filename) throws IOException {
FileOutputStream out = new FileOutputStream(filename);
out.write(content);
out.close();
}
public static String appendSlash(String definitions) {
return definitions.endsWith(File.separator) ? definitions : definitions + File.separator;
}
public static String appendForwardSlash(String definitions) {
if (definitions == null) {
return "/";
}
return definitions.endsWith("/") ? definitions : definitions + "/";
}
public static String fileTitle(String file) {
if (file == null)
return null;
String s = new File(file).getName();
return s.indexOf(".") == -1 ? s : s.substring(0, s.indexOf("."));
}
public static String systemEol() {
return System.getProperty("line.separator");
}
public static String normaliseEolns(String value) {
return value.replace("\r\n", "\r").replace("\n", "\r").replace("\r", "\r\n");
}
public static String unescapeXml(String xml) throws FHIRException {
if (xml == null)
return null;
StringBuilder b = new StringBuilder();
int i = 0;
while (i < xml.length()) {
if (xml.charAt(i) == '&') {
StringBuilder e = new StringBuilder();
i++;
while (xml.charAt(i) != ';') {
e.append(xml.charAt(i));
i++;
}
if (e.toString().equals("lt"))
b.append("<");
else if (e.toString().equals("gt"))
b.append(">");
else if (e.toString().equals("amp"))
b.append("&");
else if (e.toString().equals("quot"))
b.append("\"");
else if (e.toString().equals("mu"))
b.append((char) 956);
else
throw new FHIRException("unknown XML entity \"" + e.toString() + "\"");
} else
b.append(xml.charAt(i));
i++;
}
return b.toString();
}
public static String unescapeJson(String json) throws FHIRException {
if (json == null)
return null;
StringBuilder b = new StringBuilder();
int i = 0;
while (i < json.length()) {
if (json.charAt(i) == '\\') {
i++;
char ch = json.charAt(i);
switch (ch) {
case '"':
b.append('b');
break;
case '\\':
b.append('\\');
break;
case '/':
b.append('/');
break;
case 'b':
b.append('\b');
break;
case 'f':
b.append('\f');
break;
case 'n':
b.append('\n');
break;
case 'r':
b.append('\r');
break;
case 't':
b.append('\t');
break;
case 'u':
String hex = json.substring(i + 1, i + 5);
b.append((char) Integer.parseInt(hex, 16));
break;
default:
throw new FHIRException("Unknown JSON escape \\" + ch);
}
} else
b.append(json.charAt(i));
i++;
}
return b.toString();
}
public static boolean isPlural(String word) {
word = word.toLowerCase();
if ("restricts".equals(word) || "contains".equals(word) || "data".equals(word) || "specimen".equals(word) || "replaces".equals(word) || "addresses".equals(word)
|| "supplementalData".equals(word) || "instantiates".equals(word) || "imports".equals(word))
return false;
Inflector inf = new Inflector();
return !inf.singularize(word).equals(word);
}
public static String padRight(String src, char c, int len) {
StringBuilder s = new StringBuilder();
s.append(src);
for (int i = 0; i < len - src.length(); i++)
s.append(c);
return s.toString();
}
public static String padLeft(String src, char c, int len) {
StringBuilder s = new StringBuilder();
for (int i = 0; i < len - src.length(); i++)
s.append(c);
s.append(src);
return s.toString();
}
public static String path(String... args) throws IOException {
StringBuilder s = new StringBuilder();
boolean d = false;
boolean first = true;
for (String arg : args) {
if (first && arg == null)
continue;
first = false;
if (!d)
d = !noString(arg);
else if (!s.toString().endsWith(File.separator))
s.append(File.separator);
String a = arg;
if (s.length() == 0) {
if ("[tmp]".equals(a)) {
if (hasCTempDir()) {
a = C_TEMP_DIR;
} else if (ToolGlobalSettings.hasTempPath()) {
a = ToolGlobalSettings.getTempPath();
} else {
a = System.getProperty("java.io.tmpdir");
}
} else if ("[user]".equals(a)) {
a = System.getProperty("user.home");
} else if (a.startsWith("[") && a.endsWith("]")) {
String ev = System.getenv(a.replace("[", "").replace("]", ""));
if (ev != null) {
a = ev;
} else {
a = "null";
}
}
}
a = a.replace("\\", File.separator);
a = a.replace("/", File.separator);
if (s.length() > 0 && a.startsWith(File.separator))
a = a.substring(File.separator.length());
while (a.startsWith(".." + File.separator)) {
if (s.length() == 0) {
s = new StringBuilder(Paths.get(".").toAbsolutePath().normalize().toString());
} else {
String p = s.toString().substring(0, s.length() - 1);
if (!p.contains(File.separator)) {
s = new StringBuilder();
} else {
s = new StringBuilder(p.substring(0, p.lastIndexOf(File.separator)) + File.separator);
}
}
a = a.substring(3);
}
if ("..".equals(a)) {
int i = s.substring(0, s.length() - 1).lastIndexOf(File.separator);
s = new StringBuilder(s.substring(0, i + 1));
} else
s.append(a);
}
return s.toString();
}
private static boolean hasCTempDir() {
if (!System.getProperty("os.name").toLowerCase().contains("win")) {
return false;
}
File tmp = new File(C_TEMP_DIR);
return tmp.exists() && tmp.isDirectory() && tmp.canWrite();
}
public static String pathURL(String... args) {
StringBuilder s = new StringBuilder();
boolean d = false;
for (String arg : args) {
if (arg != null) {
if (!d)
d = !noString(arg);
else if (s.toString() != null && !s.toString().endsWith("/") && !arg.startsWith("/"))
s.append("/");
s.append(arg);
}
}
return s.toString();
}
public static String nmtokenize(String cs) {
if (cs == null)
return "";
StringBuilder s = new StringBuilder();
for (int i = 0; i < cs.length(); i++) {
char c = cs.charAt(i);
if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-' || c == '_')
s.append(c);
else if (c != ' ')
s.append("." + Integer.toString(c));
}
return s.toString();
}
public static boolean isToken(String tail) {
if (tail == null || tail.length() == 0)
return false;
boolean result = isAlphabetic(tail.charAt(0));
for (int i = 1; i < tail.length(); i++) {
result = result && (isAlphabetic(tail.charAt(i)) || isDigit(tail.charAt(i)) || (tail.charAt(i) == '_') || (tail.charAt(i) == '[') || (tail.charAt(i) == ']'));
}
return result;
}
public static boolean isTokenChar(char ch) {
return isAlphabetic(ch) || (ch == '_');
}
public static boolean isDigit(char c) {
return (c >= '0') && (c <= '9');
}
public static boolean isAlphabetic(char c) {
return ((c >= 'a') && (c <= 'z')) || ((c >= 'A') && (c <= 'Z'));
}
public static String getDirectoryForFile(String filepath) {
File f = new File(filepath);
return f.getParent();
}
public static String appendPeriod(String s) {
if (Utilities.noString(s))
return s;
s = s.trim();
if (s.endsWith(".") || s.endsWith("?"))
return s;
return s + ".";
}
public static String removePeriod(String s) {
if (Utilities.noString(s))
return s;
if (s.endsWith("."))
return s.substring(0, s.length() - 1);
return s;
}
public static String stripBOM(String string) {
return string.replace("\uFEFF", "");
}
public static String oidTail(String id) {
if (id == null || !id.contains("."))
return id;
return id.substring(id.lastIndexOf(".") + 1);
}
public static String oidRoot(String id) {
if (id == null || !id.contains("."))
return id;
return id.substring(0, id.indexOf("."));
}
public static String escapeJava(String doco) {
if (doco == null)
return "";
StringBuilder b = new StringBuilder();
for (char c : doco.toCharArray()) {
if (c == '\r')
b.append("\\r");
else if (c == '\n')
b.append("\\n");
else if (c == '"')
b.append("\\\"");
else if (c == '\\')
b.append("\\\\");
else
b.append(c);
}
return b.toString();
}
public static String[] splitByCamelCase(String name) {
List<String> parts = new ArrayList<String>();
StringBuilder b = new StringBuilder();
for (int i = 0; i < name.length(); i++) {
if (i > 0 && Character.isUpperCase(name.charAt(i))) {
parts.add(b.toString());
b = new StringBuilder();
}
b.append(Character.toLowerCase(name.charAt(i)));
}
parts.add(b.toString());
return parts.toArray(new String[]{});
}
public static String encodeUri(String v) {
return v.replace(" ", "%20").replace("?", "%3F").replace("=", "%3D").replace("|", "%7C");
}
public static String normalize(String s) {
if (noString(s))
return null;
StringBuilder b = new StringBuilder();
boolean isWhitespace = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c)) {
b.append(Character.toLowerCase(c));
isWhitespace = false;
} else if (!isWhitespace) {
b.append(' ');
isWhitespace = true;
}
}
return b.toString().trim();
}
public static String normalizeSameCase(String s) {
if (noString(s))
return null;
StringBuilder b = new StringBuilder();
boolean isWhitespace = false;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isWhitespace(c)) {
b.append(c);
isWhitespace = false;
} else if (!isWhitespace) {
b.append(' ');
isWhitespace = true;
}
}
return b.toString().trim();
}
public static void copyFileToDirectory(File source, File destDir) throws IOException {
copyFile(source, new File(path(destDir.getAbsolutePath(), source.getName())));
}
public static boolean isWhitespace(String s) {
boolean ok = true;
for (int i = 0; i < s.length(); i++)
ok = ok && Character.isWhitespace(s.charAt(i));
return ok;
}
public static String URLEncode(String string) {
try {
return URLEncoder.encode(string, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e.getMessage());
}
}
public static String URLDecode(String ref) {
try {
return URLDecoder.decode(ref, "UTF-8");
} catch (UnsupportedEncodingException e) {
throw new Error(e.getMessage());
}
}
public static boolean charInSet(char value, char... array) {
for (int i : array)
if (value == i)
return true;
return false;
}
public static boolean charInRange(char ch, char a, char z) {
return ch >= a && ch <= z;
}
public static boolean existsInList(String value, List<String> array) {
if (value == null)
return false;
for (String s : array)
if (value.equals(s))
return true;
return false;
}
public static boolean existsInList(String value, String... array) {
if (value == null)
return false;
for (String s : array)
if (value.equals(s))
return true;
return false;
}
public static boolean existsInList(int value, int... array) {
for (int i : array)
if (value == i)
return true;
return false;
}
public static boolean existsInListNC(String value, String... array) {
for (String s : array)
if (value.equalsIgnoreCase(s))
return true;
return false;
}
public static String stringJoin(String sep, String... array) {
CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(sep);
for (String s : array)
if (!noString(s))
b.append(s);
return b.toString();
}
public static String getFileNameForName(String name) {
return name.toLowerCase();
}
public static void deleteTempFiles() throws IOException {
File file = createTempFile("test", "test");
String folder = getDirectoryForFile(file.getAbsolutePath());
String[] list = new File(folder).list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("ohfu-");
}
});
if (list != null) {
for (String n : list) {
new File(path(folder, n)).delete();
}
}
}
public static File createTempFile(String prefix, String suffix) throws IOException {
// this allows use to eaily identify all our dtemp files and delete them, since delete on Exit doesn't really work.
File file = File.createTempFile("ohfu-" + prefix, suffix);
file.deleteOnExit();
return file;
}
public static boolean isAsciiChar(char ch) {
return ch >= ' ' && ch <= '~';
}
public static String makeUuidLC() {
return UUID.randomUUID().toString().toLowerCase();
}
public static String makeUuidUrn() {
return "urn:uuid:" + UUID.randomUUID().toString().toLowerCase();
}
public static boolean isURL(String s) {
boolean ok = s.matches("^http(s{0,1})://[a-zA-Z0-9_/\\-\\.]+\\.([A-Za-z/]{2,5})[a-zA-Z0-9_/\\&\\?\\=\\-\\.\\~\\%]*");
return ok;
}
public static String escapeJson(String value) {
if (value == null)
return "";
StringBuilder b = new StringBuilder();
for (char c : value.toCharArray()) {
if (c == '\r')
b.append("\\r");
else if (c == '\n')
b.append("\\n");
else if (c == '\t')
b.append("\\t");