1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.nuiton.util;
24
25 import org.apache.commons.lang3.SystemUtils;
26
27 import java.awt.Color;
28 import java.lang.reflect.Field;
29 import java.security.MessageDigest;
30 import java.security.NoSuchAlgorithmException;
31 import java.text.DateFormat;
32 import java.text.MessageFormat;
33 import java.text.ParseException;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.Date;
37 import java.util.List;
38 import java.util.Locale;
39
40
41
42
43
44
45
46
47
48
49
50
51 public class StringUtil {
52
53 public static final String[] EMPTY_STRING_ARRAY = new String[0];
54
55
56 protected StringUtil() {
57 }
58
59
60
61
62
63
64
65
66 public static boolean isEmail(String str) {
67 return str.matches("^[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+((\\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)?)+@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-]*[a-zA-Z0-9])?$");
68 }
69
70
71
72
73
74
75
76
77 public static String escapeCsvValue(String value, String csvSeparator) {
78
79 boolean valueNeedQuotes =
80 value.contains("\n")
81 || value.contains("\t")
82 || value.contains(",")
83 || value.contains(";")
84 || value.contains("\"")
85 || value.contains(csvSeparator);
86
87 if (valueNeedQuotes) {
88
89 value = value.replaceAll("\"", "\"\"");
90 value = "\"" + value + "\"";
91 }
92 return value;
93 }
94
95
96
97
98
99
100
101
102 public interface ToString<O> {
103
104
105
106
107
108
109
110 String toString(O o);
111 }
112
113
114
115
116
117
118
119
120 public static class ToCSV<O> implements StringUtil.ToString<O> {
121
122 protected String csvSeparator;
123
124 public ToCSV(String csvSeparator) {
125 this.csvSeparator = csvSeparator;
126 }
127
128 @Override
129 public String toString(O o) {
130 String value = getStringValue(o);
131 return escapeCsvValue(value, csvSeparator);
132 }
133
134
135
136
137
138
139
140
141 public String getStringValue(O o) {
142 return o.toString();
143 }
144 }
145
146
147
148
149
150
151
152
153
154
155
156
157 public static String join(Iterable<?> iterable, String separator,
158 boolean trim) {
159 String result = join(iterable, null, separator, trim);
160 return result;
161 }
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180 public static <O> String join(Iterable<O> iterable, ToString<O> ts,
181 String separator, boolean trim) throws NullPointerException {
182 if (iterable == null) {
183 throw new NullPointerException("null iterable can't be used" +
184 " to join the elements with " + separator);
185 }
186
187 if (!iterable.iterator().hasNext()) {
188 return "";
189 }
190 StringBuilder builder = new StringBuilder();
191 for (O o : iterable) {
192
193 if (o == null) {
194 continue;
195 }
196 String str;
197
198 if (ts != null) {
199 str = ts.toString(o);
200
201 } else {
202 str = o.toString();
203 }
204
205 if (trim) {
206 str = str.trim();
207 }
208 builder.append(separator).append(str);
209 }
210
211 String result = builder.substring(separator.length());
212 return result;
213 }
214
215
216
217
218
219
220
221
222
223
224
225 public static String substring(String s, int begin) {
226 String result = substring(s, begin, s.length());
227 return result;
228 }
229
230
231
232
233
234
235
236
237
238
239
240
241 public static String substring(String s, int begin, int end) {
242 if (begin < 0) {
243 begin = s.length() + begin;
244 }
245 if (end < 0) {
246 end = s.length() + end;
247 }
248 if (end < begin) {
249 end = begin;
250 }
251
252 String result;
253 result = s.substring(begin, end);
254 return result;
255 }
256
257 private static final Character[] openingChars = {'(', '{', '['};
258
259 private static final Character[] closingChars = {')', '}', ']'};
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275 public static String[] split(String args, String separator) {
276 return split(openingChars, closingChars, args, separator);
277 }
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292 public static String[] split(String stringList) {
293 String[] result;
294 result = split(stringList, ",");
295 return result;
296 }
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316 public static String[] split(Character[] openingChars,
317 Character[] closingChars,
318 String args, String separator) {
319 if (args == null) {
320 return EMPTY_STRING_ARRAY;
321 }
322
323 List<String> result = new ArrayList<String>();
324
325 int start = 0;
326 int end;
327 StringBuilder op = new StringBuilder();
328 char last = '\0';
329
330 List<Character> opening = Arrays.asList(openingChars);
331
332 List<Character> closing = Arrays.asList(closingChars);
333
334 for (int i = 0; i < args.length(); i++) {
335 char c = args.charAt(i);
336 if (c == '\\') {
337
338 i++;
339 } else if (last != '"' && last != '\'') {
340 if (opening.contains(c)) {
341 op.append(c);
342 } else if (closing.contains(c)) {
343 op.deleteCharAt(op.length() - 1);
344 } else if (c == '"' || c == '\'') {
345
346 last = c;
347 } else if (op.length() == 0 &&
348 args.regionMatches(i, separator, 0,
349 separator.length())) {
350
351 end = i;
352
353 i += separator.length() - 1;
354
355 String a = args.substring(start, end);
356 result.add(a);
357
358 start = end + separator.length();
359 }
360 } else if (c == last) {
361
362 last = '\0';
363 }
364 }
365
366 if (start < args.length()) {
367 String a = args.substring(start, args.length());
368 result.add(a);
369 }
370
371 return result.toArray(new String[result.size()]);
372 }
373
374 public static boolean toBoolean(String s) {
375 return "true".equalsIgnoreCase(s);
376 }
377
378 public static byte toByte(String s) {
379 return Byte.parseByte(s);
380 }
381
382 public static double toDouble(String s) {
383 return Double.parseDouble(s);
384 }
385
386 public static float toFloat(String s) {
387 return Float.parseFloat(s);
388 }
389
390 public static long toLong(String s) {
391 return Long.parseLong(s);
392 }
393
394 public static short toShort(String s) {
395 return Short.parseShort(s);
396 }
397
398 public static int toInt(String s) {
399 return Integer.parseInt(s);
400 }
401
402 public static char toChar(String s) {
403
404 return s.charAt(0);
405 }
406
407 public static boolean[] toArrayBoolean(String... s) {
408 boolean[] result = new boolean[s.length];
409 for (int i = 0; i < result.length; i++) {
410 result[i] = toBoolean(s[i]);
411 }
412 return result;
413 }
414
415 public static byte[] toArrayByte(String... s) {
416 byte[] result = new byte[s.length];
417 for (int i = 0; i < result.length; i++) {
418 result[i] = toByte(s[i]);
419 }
420 return result;
421 }
422
423 public static double[] toArrayDouble(String... s) {
424 double[] result = new double[s.length];
425 for (int i = 0; i < result.length; i++) {
426 result[i] = toDouble(s[i]);
427 }
428 return result;
429 }
430
431 public static float[] toArrayFloat(String... s) {
432 float[] result = new float[s.length];
433 for (int i = 0; i < result.length; i++) {
434 result[i] = toFloat(s[i]);
435 }
436 return result;
437 }
438
439 public static long[] toArrayLong(String... s) {
440 long[] result = new long[s.length];
441 for (int i = 0; i < result.length; i++) {
442 result[i] = toLong(s[i]);
443 }
444 return result;
445 }
446
447 public static short[] toArrayShort(String... s) {
448 short[] result = new short[s.length];
449 for (int i = 0; i < result.length; i++) {
450 result[i] = toShort(s[i]);
451 }
452 return result;
453 }
454
455 public static int[] toArrayInt(String... s) {
456 int[] result = new int[s.length];
457 for (int i = 0; i < result.length; i++) {
458 result[i] = toInt(s[i]);
459 }
460 return result;
461 }
462
463 public static char[] toArrayChar(String... s) {
464 char[] result = new char[s.length];
465 for (int i = 0; i < result.length; i++) {
466 result[i] = toChar(s[i]);
467 }
468
469 return result;
470 }
471
472 private static final char[] HEX_CHARS = {'0', '1', '2', '3',
473 '4', '5', '6', '7',
474 '8', '9', 'a', 'b',
475 'c', 'd', 'e', 'f',};
476
477
478
479
480
481
482
483
484 public static String asHex(byte hash[]) {
485 char buf[] = new char[hash.length * 2];
486 for (int i = 0, x = 0; i < hash.length; i++) {
487 buf[x++] = HEX_CHARS[hash[i] >>> 4 & 0xf];
488 buf[x++] = HEX_CHARS[hash[i] & 0xf];
489 }
490 return new String(buf);
491 }
492
493
494
495
496
497
498
499
500
501
502
503
504 public static Color toColor(String s) throws StringUtilException {
505 try {
506 if (s.startsWith("#")) {
507
508 String hr = s.substring(1, 3);
509 String hg = s.substring(3, 5);
510 String hb = s.substring(5, 7);
511
512
513 int r = Integer.parseInt(hr, 16);
514 int g = Integer.parseInt(hg, 16);
515 int b = Integer.parseInt(hb, 16);
516
517 if (s.length() == 9) {
518
519 String ha = s.substring(7, 9);
520 int a = Integer.parseInt(ha, 16);
521 return new Color(r, g, b, a);
522 } else {
523 return new Color(r, g, b);
524 }
525 } else {
526 Field f;
527 f = Color.class.getField(s);
528 return (Color) f.get(Color.class);
529 }
530 } catch (NumberFormatException e) {
531 throw new StringUtilException(
532 "Error during conversion from string to color", e);
533 } catch (SecurityException e) {
534 throw new StringUtilException(
535 "Error during conversion from string to color", e);
536 } catch (NoSuchFieldException e) {
537 throw new StringUtilException(
538 "Error during conversion from string to color", e);
539 } catch (IllegalArgumentException e) {
540 throw new StringUtilException(
541 "Error during conversion from string to color", e);
542 } catch (IllegalAccessException e) {
543 throw new StringUtilException(
544 "Error during conversion from string to color", e);
545 }
546 }
547
548 public static Date toDate(String s) throws ParseException {
549 return DateFormat.getDateInstance().parse(s);
550 }
551
552 static final protected double[] timeFactors = {1000000, 1000, 60, 60, 24};
553
554 static final protected String[] timeUnites = {"ns", "ms", "s", "m", "h",
555 "d"};
556
557
558
559
560
561
562
563
564 public static String convertTime(long value) {
565 return convert(value, timeFactors, timeUnites);
566 }
567
568
569
570
571
572
573
574
575
576 public static String convertTime(long value, long value2) {
577 return convertTime(value2 - value);
578 }
579
580 static final protected double[] memoryFactors = {1024, 1024, 1024, 1024};
581
582 static final protected String[] memoryUnites = {"o", "Ko", "Mo", "Go",
583 "To"};
584
585
586
587
588
589
590
591
592 public static String convertMemory(long value) {
593 return convert(value, memoryFactors, memoryUnites);
594 }
595
596
597
598
599
600
601
602
603
604
605
606 public static String convert(long value, double[] factors, String[] unites) {
607 long sign = value == 0 ? 1 : value / Math.abs(value);
608 int i = 0;
609 double tmp = Math.abs(value);
610 while (i < factors.length && i < unites.length && tmp > factors[i]) {
611 tmp = tmp / factors[i++];
612 }
613
614 tmp *= sign;
615 String result;
616 result = MessageFormat.format("{0,number,0.###}{1}", tmp,
617 unites[i]);
618 return result;
619 }
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635 public static boolean checkEnclosure(String txt, char opener, char closer) {
636 if (txt.indexOf(opener) == -1 && txt.indexOf(closer) == -1) {
637
638 return true;
639 }
640 List<Integer> opens = new ArrayList<Integer>();
641 for (int i = 0; i < txt.length(); i++) {
642 char c = txt.charAt(i);
643 if (c == opener) {
644
645 opens.add(i);
646 continue;
647 }
648 if (c == closer) {
649 if (opens.isEmpty()) {
650
651 return false;
652 }
653
654 opens.remove(opens.size() - 1);
655 }
656 }
657 return opens.isEmpty();
658 }
659
660
661
662
663
664
665
666
667
668
669 public static String convertToConstantName(String name) {
670 StringBuilder sb = new StringBuilder();
671 char lastChar = 0;
672 for (int i = 0, j = name.length(); i < j; i++) {
673 char c = name.charAt(i);
674 if (Character.isDigit(c)) {
675 sb.append(c);
676 lastChar = c;
677 continue;
678 }
679 if (!Character.isLetter(c)) {
680 if (lastChar != '_') {
681 sb.append('_');
682 }
683 lastChar = '_';
684 continue;
685 }
686 if (Character.isUpperCase(c)) {
687 if (!Character.isUpperCase(lastChar) && lastChar != '_') {
688 sb.append('_');
689 }
690 sb.append(c);
691 } else {
692 sb.append(Character.toUpperCase(c));
693 }
694 lastChar = c;
695 }
696 String result = sb.toString();
697
698 while (!result.isEmpty() && result.endsWith("_")) {
699 result = result.substring(0, result.length() - 1);
700 }
701
702 while (!result.isEmpty() && result.startsWith("_")) {
703 result = result.substring(1);
704 }
705 return result;
706 }
707
708
709
710
711
712
713
714
715 public static String encodeMD5(String toEncode) {
716
717 byte[] uniqueKey = toEncode.getBytes();
718 byte[] hash;
719
720 hash = MD5InputStream.getMD5Digest().digest(uniqueKey);
721
722
723 StringBuilder hashString = new StringBuilder();
724 for (byte aHash : hash) {
725 String hex = Integer.toHexString(aHash);
726 if (hex.length() == 1) {
727 hashString.append("0");
728 hashString.append(hex.charAt(hex.length() - 1));
729 } else {
730 hashString.append(hex.substring(hex.length() - 2));
731 }
732 }
733 return hashString.toString();
734 }
735
736
737
738
739
740
741
742
743 public static String encodeSHA1(String toEncode) {
744 String result;
745
746 try {
747 MessageDigest sha1Md = MessageDigest.getInstance("SHA-1");
748
749 byte[] digest = sha1Md.digest(toEncode.getBytes());
750 result = asHex(digest);
751 } catch (NoSuchAlgorithmException ex) {
752 throw new IllegalStateException("Can't find SHA-1 message digest algorithm", ex);
753 }
754
755 return result;
756 }
757
758
759
760
761
762 public static String getFileSeparatorRegex() {
763 String result;
764 if(SystemUtils.IS_OS_WINDOWS) {
765 result = "\\\\";
766 } else {
767 result = "/";
768 }
769 return result;
770 }
771 }