1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.argeo.jcr.fs;
18
19 import java.io.ByteArrayOutputStream;
20 import java.io.UnsupportedEncodingException;
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
23 import java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.Properties;
26
27
28
29
30
31 class Text {
32
33
34
35
36 private Text() {
37 }
38
39
40
41
42 public static final char[] hexTable = "0123456789abcdef".toCharArray();
43
44
45
46
47
48
49
50
51
52
53 public static String md5(String data, String enc) throws UnsupportedEncodingException {
54 try {
55 return digest("MD5", data.getBytes(enc));
56 } catch (NoSuchAlgorithmException e) {
57 throw new InternalError("MD5 digest not available???");
58 }
59 }
60
61
62
63
64
65
66
67
68 public static String md5(String data) {
69 try {
70 return md5(data, "utf-8");
71 } catch (UnsupportedEncodingException e) {
72 throw new InternalError("UTF8 digest not available???");
73 }
74 }
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93 public static String digest(String algorithm, String data, String enc)
94 throws NoSuchAlgorithmException, UnsupportedEncodingException {
95
96 return digest(algorithm, data.getBytes(enc));
97 }
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112 public static String digest(String algorithm, byte[] data) throws NoSuchAlgorithmException {
113
114 MessageDigest md = MessageDigest.getInstance(algorithm);
115 byte[] digest = md.digest(data);
116 StringBuilder res = new StringBuilder(digest.length * 2);
117 for (byte b : digest) {
118 res.append(hexTable[(b >> 4) & 15]);
119 res.append(hexTable[b & 15]);
120 }
121 return res.toString();
122 }
123
124
125
126
127
128
129
130
131
132
133
134
135 public static String[] explode(String str, int ch) {
136 return explode(str, ch, false);
137 }
138
139
140
141
142
143
144
145
146
147
148
149
150
151 public static String[] explode(String str, int ch, boolean respectEmpty) {
152 if (str == null || str.length() == 0) {
153 return new String[0];
154 }
155
156 ArrayList<String> strings = new ArrayList<String>();
157 int pos;
158 int lastpos = 0;
159
160
161 while ((pos = str.indexOf(ch, lastpos)) >= 0) {
162 if (pos - lastpos > 0 || respectEmpty) {
163 strings.add(str.substring(lastpos, pos));
164 }
165 lastpos = pos + 1;
166 }
167
168 if (lastpos < str.length()) {
169 strings.add(str.substring(lastpos));
170 } else if (respectEmpty && lastpos == str.length()) {
171 strings.add("");
172 }
173
174
175 return strings.toArray(new String[strings.size()]);
176 }
177
178
179
180
181
182
183
184
185
186 public static String implode(String[] arr, String delim) {
187 StringBuilder buf = new StringBuilder();
188 for (int i = 0; i < arr.length; i++) {
189 if (i > 0) {
190 buf.append(delim);
191 }
192 buf.append(arr[i]);
193 }
194 return buf.toString();
195 }
196
197
198
199
200
201
202
203
204
205
206
207
208 public static String replace(String text, String oldString, String newString) {
209 if (text == null || oldString == null || newString == null) {
210 throw new IllegalArgumentException("null argument");
211 }
212 int pos = text.indexOf(oldString);
213 if (pos == -1) {
214 return text;
215 }
216 int lastPos = 0;
217 StringBuilder sb = new StringBuilder(text.length());
218 while (pos != -1) {
219 sb.append(text.substring(lastPos, pos));
220 sb.append(newString);
221 lastPos = pos + oldString.length();
222 pos = text.indexOf(oldString, lastPos);
223 }
224 if (lastPos < text.length()) {
225 sb.append(text.substring(lastPos));
226 }
227 return sb.toString();
228 }
229
230
231
232
233
234
235
236
237
238 public static String encodeIllegalXMLCharacters(String text) {
239 return encodeMarkupCharacters(text, false);
240 }
241
242
243
244
245
246
247
248
249
250 public static String encodeIllegalHTMLCharacters(String text) {
251 return encodeMarkupCharacters(text, true);
252 }
253
254 private static String encodeMarkupCharacters(String text, boolean isHtml) {
255 if (text == null) {
256 throw new IllegalArgumentException("null argument");
257 }
258 StringBuilder buf = null;
259 int length = text.length();
260 int pos = 0;
261 for (int i = 0; i < length; i++) {
262 int ch = text.charAt(i);
263 switch (ch) {
264 case '<':
265 case '>':
266 case '&':
267 case '"':
268 case '\'':
269 if (buf == null) {
270 buf = new StringBuilder();
271 }
272 if (i > 0) {
273 buf.append(text.substring(pos, i));
274 }
275 pos = i + 1;
276 break;
277 default:
278 continue;
279 }
280 if (ch == '<') {
281 buf.append("<");
282 } else if (ch == '>') {
283 buf.append(">");
284 } else if (ch == '&') {
285 buf.append("&");
286 } else if (ch == '"') {
287 buf.append(""");
288 } else if (ch == '\'') {
289 buf.append(isHtml ? "'" : "'");
290 }
291 }
292 if (buf == null) {
293 return text;
294 } else {
295 if (pos < length) {
296 buf.append(text.substring(pos));
297 }
298 return buf.toString();
299 }
300 }
301
302
303
304
305
306
307
308
309
310
311
312
313 public static BitSet URISave;
314
315
316
317
318 public static BitSet URISaveEx;
319
320 static {
321 URISave = new BitSet(256);
322 int i;
323 for (i = 'a'; i <= 'z'; i++) {
324 URISave.set(i);
325 }
326 for (i = 'A'; i <= 'Z'; i++) {
327 URISave.set(i);
328 }
329 for (i = '0'; i <= '9'; i++) {
330 URISave.set(i);
331 }
332 URISave.set('-');
333 URISave.set('_');
334 URISave.set('.');
335 URISave.set('!');
336 URISave.set('~');
337 URISave.set('*');
338 URISave.set('\'');
339 URISave.set('(');
340 URISave.set(')');
341
342 URISaveEx = (BitSet) URISave.clone();
343 URISaveEx.set('/');
344 }
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360 public static String escape(String string, char escape) {
361 return escape(string, escape, false);
362 }
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381 public static String escape(String string, char escape, boolean isPath) {
382 try {
383 BitSet validChars = isPath ? URISaveEx : URISave;
384 byte[] bytes = string.getBytes("utf-8");
385 StringBuilder out = new StringBuilder(bytes.length);
386 for (byte aByte : bytes) {
387 int c = aByte & 0xff;
388 if (validChars.get(c) && c != escape) {
389 out.append((char) c);
390 } else {
391 out.append(escape);
392 out.append(hexTable[(c >> 4) & 0x0f]);
393 out.append(hexTable[(c) & 0x0f]);
394 }
395 }
396 return out.toString();
397 } catch (UnsupportedEncodingException e) {
398 throw new InternalError(e.toString());
399 }
400 }
401
402
403
404
405
406
407
408
409
410
411
412
413 public static String escape(String string) {
414 return escape(string, '%');
415 }
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430 public static String escapePath(String path) {
431 return escape(path, '%', true);
432 }
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451 public static String unescape(String string, char escape) {
452 try {
453 byte[] utf8 = string.getBytes("utf-8");
454
455
456 if ((utf8.length >= 1 && utf8[utf8.length - 1] == escape)
457 || (utf8.length >= 2 && utf8[utf8.length - 2] == escape)) {
458 throw new IllegalArgumentException("Premature end of escape sequence at end of input");
459 }
460
461 ByteArrayOutputStream out = new ByteArrayOutputStream(utf8.length);
462 for (int k = 0; k < utf8.length; k++) {
463 byte b = utf8[k];
464 if (b == escape) {
465 out.write((decodeDigit(utf8[++k]) << 4) + decodeDigit(utf8[++k]));
466 } else {
467 out.write(b);
468 }
469 }
470
471 return new String(out.toByteArray(), "utf-8");
472 } catch (UnsupportedEncodingException e) {
473 throw new InternalError(e.toString());
474 }
475 }
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493 public static String unescape(String string) {
494 return unescape(string, '%');
495 }
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517 public static String escapeIllegalJcrChars(String name) {
518 return escapeIllegalChars(name, "%/:[]*|\t\r\n");
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 public static String escapeIllegalJcr10Chars(String name) {
544 return escapeIllegalChars(name, "%/:[]*'\"|\t\r\n");
545 }
546
547 private static String escapeIllegalChars(String name, String illegal) {
548 StringBuilder buffer = new StringBuilder(name.length() * 2);
549 for (int i = 0; i < name.length(); i++) {
550 char ch = name.charAt(i);
551 if (illegal.indexOf(ch) != -1 || (ch == '.' && name.length() < 3)
552 || (ch == ' ' && (i == 0 || i == name.length() - 1))) {
553 buffer.append('%');
554 buffer.append(Character.toUpperCase(Character.forDigit(ch / 16, 16)));
555 buffer.append(Character.toUpperCase(Character.forDigit(ch % 16, 16)));
556 } else {
557 buffer.append(ch);
558 }
559 }
560 return buffer.toString();
561 }
562
563
564
565
566
567
568
569
570
571
572
573
574 public static String escapeIllegalXpathSearchChars(String s) {
575 StringBuilder sb = new StringBuilder();
576 sb.append(s.substring(0, (s.length() - 1)));
577 char c = s.charAt(s.length() - 1);
578
579 if (c == '!' || c == '(' || c == ':' || c == '^' || c == '[' || c == ']' || c == '{' || c == '}' || c == '?') {
580 sb.append('\\');
581 }
582 sb.append(c);
583 return sb.toString();
584 }
585
586
587
588
589
590
591
592
593
594
595
596
597 public static String unescapeIllegalJcrChars(String name) {
598 StringBuilder buffer = new StringBuilder(name.length());
599 int i = name.indexOf('%');
600 while (i > -1 && i + 2 < name.length()) {
601 buffer.append(name.toCharArray(), 0, i);
602 int a = Character.digit(name.charAt(i + 1), 16);
603 int b = Character.digit(name.charAt(i + 2), 16);
604 if (a > -1 && b > -1) {
605 buffer.append((char) (a * 16 + b));
606 name = name.substring(i + 3);
607 } else {
608 buffer.append('%');
609 name = name.substring(i + 1);
610 }
611 i = name.indexOf('%');
612 }
613 buffer.append(name);
614 return buffer.toString();
615 }
616
617
618
619
620
621
622
623
624
625
626 public static String getName(String path) {
627 return getName(path, '/');
628 }
629
630
631
632
633
634
635
636
637
638
639
640
641
642 public static String getName(String path, char delim) {
643 return path == null ? null : path.substring(path.lastIndexOf(delim) + 1);
644 }
645
646
647
648
649
650
651
652 public static String getName(String path, boolean ignoreTrailingSlash) {
653 if (ignoreTrailingSlash && path != null && path.endsWith("/") && path.length() > 1) {
654 path = path.substring(0, path.length() - 1);
655 }
656 return getName(path);
657 }
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675 public static String getNamespacePrefix(String qname) {
676 int pos = qname.indexOf(':');
677 return pos >= 0 ? qname.substring(0, pos) : "";
678 }
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695 public static String getLocalName(String qname) {
696 int pos = qname.indexOf(':');
697 return pos >= 0 ? qname.substring(pos + 1) : qname;
698 }
699
700
701
702
703
704
705
706
707
708
709 public static boolean isSibling(String p1, String p2) {
710 int pos1 = p1.lastIndexOf('/');
711 int pos2 = p2.lastIndexOf('/');
712 return (pos1 == pos2 && pos1 >= 0 && p1.regionMatches(0, p2, 0, pos1));
713 }
714
715
716
717
718
719
720
721
722
723
724
725
726 public static boolean isDescendant(String path, String descendant) {
727 String pattern = path.endsWith("/") ? path : path + "/";
728 return !pattern.equals(descendant) && descendant.startsWith(pattern);
729 }
730
731
732
733
734
735
736
737
738
739
740
741
742 public static boolean isDescendantOrEqual(String path, String descendant) {
743 if (path.equals(descendant)) {
744 return true;
745 } else {
746 String pattern = path.endsWith("/") ? path : path + "/";
747 return descendant.startsWith(pattern);
748 }
749 }
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764 public static String getRelativeParent(String path, int level) {
765 int idx = path.length();
766 while (level > 0) {
767 idx = path.lastIndexOf('/', idx - 1);
768 if (idx < 0) {
769 return "";
770 }
771 level--;
772 }
773 return (idx == 0) ? "/" : path.substring(0, idx);
774 }
775
776
777
778
779
780
781
782 public static String getRelativeParent(String path, int level, boolean ignoreTrailingSlash) {
783 if (ignoreTrailingSlash && path.endsWith("/") && path.length() > 1) {
784 path = path.substring(0, path.length() - 1);
785 }
786 return getRelativeParent(path, level);
787 }
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802 public static String getAbsoluteParent(String path, int level) {
803 int idx = 0;
804 int len = path.length();
805 while (level >= 0 && idx < len) {
806 idx = path.indexOf('/', idx + 1);
807 if (idx < 0) {
808 idx = len;
809 }
810 level--;
811 }
812 return level >= 0 ? "" : path.substring(0, idx);
813 }
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832 public static String replaceVariables(Properties variables, String value, boolean ignoreMissing)
833 throws IllegalArgumentException {
834 StringBuilder result = new StringBuilder();
835
836
837
838
839
840 int p = 0, q = value.indexOf("${");
841 while (q != -1) {
842 result.append(value.substring(p, q));
843 p = q;
844 q = value.indexOf("}", q + 2);
845 if (q != -1) {
846 String variable = value.substring(p + 2, q);
847 String replacement = variables.getProperty(variable);
848 if (replacement == null) {
849 if (ignoreMissing) {
850 replacement = "";
851 } else {
852 throw new IllegalArgumentException("Replacement not found for ${" + variable + "}.");
853 }
854 }
855 result.append(replacement);
856 p = q + 1;
857 q = value.indexOf("${", p);
858 }
859 }
860 result.append(value.substring(p, value.length()));
861
862 return result.toString();
863 }
864
865 private static byte decodeDigit(byte b) {
866 if (b >= 0x30 && b <= 0x39) {
867 return (byte) (b - 0x30);
868 } else if (b >= 0x41 && b <= 0x46) {
869 return (byte) (b - 0x37);
870 } else if (b >= 0x61 && b <= 0x66) {
871 return (byte) (b - 0x57);
872 } else {
873 throw new IllegalArgumentException("Escape sequence is not hexadecimal: " + (char) b);
874 }
875 }
876
877 }