1 55 package org.lateralnz.common.util; 56 57 import java.io.ByteArrayInputStream ; 58 import java.io.ByteArrayOutputStream ; 59 import java.io.BufferedReader ; 60 import java.io.File ; 61 import java.io.FileReader ; 62 import java.io.IOException ; 63 import java.io.Reader ; 64 import java.security.MessageDigest ; 65 import java.text.MessageFormat ; 66 import java.util.ArrayList ; 67 import java.util.HashMap ; 68 import java.util.Iterator ; 69 import java.util.List ; 70 import java.util.Map ; 71 import java.util.StringTokenizer ; 72 import java.util.zip.GZIPInputStream ; 73 import java.util.zip.GZIPOutputStream ; 74 75 import java.util.regex.Matcher ; 76 import java.util.regex.Pattern ; 77 import java.util.regex.PatternSyntaxException ; 78 79 84 public final class StringUtils implements Constants { 85 private static MessageDigest md5 = null; 86 private static MessageDigest sha = null; 87 88 private static HashMap patternCache = new HashMap (); 89 90 private static final String MD5 = "MD5"; 91 private static final String SHA = "SHA"; 92 93 private static final char[] hexChars = new char[] {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}; 94 95 private static final String [][] HTML_PATTERNS = { 96 { "&", "&"}, 97 { "<", "<" }, 98 { ">", ">" }, 99 { "\\ \\; ", " " }, 100 { "'", "'" }, 101 { "\"", """ }, 102 { "\n", "<br />" }, 103 { "\n ", "<br /> " } 104 }; 105 106 private static final String [][] ESCAPES = { { "\n", "\\n" }, 107 { "\r", "\\r" }, 108 { "\"", "\\\"" }, 109 { "\t", "\\t" } }; 110 111 private static final String [][] REV_ESCAPES = { { "\\n", "\n" }, 112 { "\\r", "\r" }, 113 { "\\\"", "\"" }, 114 { "\\t", "\t" }, 115 { "\\'", "'" }}; 116 117 private static final String AMP_HASH = "&#"; 118 119 private static Pattern [] strpatterns = new Pattern [HTML_PATTERNS.length]; 120 121 static { 122 try { 123 for (int i = 0; i < HTML_PATTERNS.length; i++) { 124 strpatterns[i] = getPattern(HTML_PATTERNS[i][0]); 125 } 126 127 } 128 catch (PatternSyntaxException pse) { 129 pse.printStackTrace(); 130 } 131 } 132 133 136 public static final int countOccurrences(String s, char c) { 137 int total = 0; 138 for (int i = 0; i < s.length(); i++) { 139 if (s.charAt(i) == c) { 140 total++; 141 } 142 } 143 return total; 144 } 145 146 public static final int countOccurrences(StringBuffer sb, char c) { 147 int total = 0; 148 for (int i = 0; i < sb.length(); i++) { 149 if (sb.charAt(i) == c) { 150 total++; 151 } 152 } 153 return total; 154 } 155 156 public static final String degzip(byte[] b) throws IOException { 157 GZIPInputStream gis = null; 158 try { 159 gis = new GZIPInputStream (new ByteArrayInputStream (b)); 160 161 int offset = 0; 162 int len = 1024; 163 int read; 164 int total = 0; 165 byte[] buf = new byte[len]; 166 while ((read = gis.read(buf, offset, len)) != -1) { 167 total += read; 168 if (read < len) { 169 break; 170 } 171 else { 172 byte[] tmp = new byte[buf.length + len]; 173 System.arraycopy(buf, 0, tmp, 0, buf.length); 174 offset = buf.length; 175 buf = tmp; 176 } 177 } 178 179 return new String (buf, 0, total); 180 } 181 finally { 182 IOUtils.close(gis); 183 } 184 } 185 186 189 public static final String escape(String s) { 190 StringBuffer sb = new StringBuffer (s); 191 for (int i = 0; i < ESCAPES.length; i++) { 192 replace(sb, ESCAPES[i][0], ESCAPES[i][1]); 193 } 194 195 return sb.toString(); 196 197 } 198 199 202 public static final List findRegex(String s, String pattern) { 203 ArrayList rtn = new ArrayList (); 204 Pattern p = getPattern(pattern); 205 Matcher matcher = p.matcher(s); 206 while (matcher.find()) { 207 int groups = matcher.groupCount(); 208 for (int i = 1; i <= groups; i++) { 209 rtn.add(matcher.group(i)); 210 } 211 } 212 213 return rtn; 214 } 215 216 220 public static final String format(String pattern, Object [] arguments) { 221 if (isEmpty(pattern)) { 222 return EMPTY; 223 } 224 else { 225 return MessageFormat.format(pattern, arguments); 226 } 227 } 228 229 233 public static final String format(String pattern, String argument) { 234 return format(pattern, new Object []{ argument }); 235 } 236 237 public static final String fromArray(String [] s, String delim) { 238 if (s == null || s.length < 1) { 239 return EMPTY; 240 } 241 else { 242 return fromArray(s, delim, 0, s.length); 243 } 244 } 245 246 254 public static final String fromArray(String [] s, String delim, int start, int len) { 255 StringBuffer sb = new StringBuffer (); 256 if (s != null && start < s.length && len > 0) { 257 for (int i = 0, j = start; i < len && j < s.length; i++, j++) { 258 sb.append(s[j]); 259 if (j < s.length-1 && i < len-1) { 260 sb.append(delim); 261 } 262 } 263 } 264 return sb.toString(); 265 } 266 267 270 public static final String fromList(List l, String delim) { 271 StringBuffer sb = new StringBuffer (); 272 Iterator iter = l.iterator(); 273 while (iter.hasNext()) { 274 sb.append(iter.next()); 275 if (iter.hasNext()) { 276 sb.append(delim); 277 } 278 } 279 return sb.toString(); 280 } 281 282 289 public static final String fromMap(Map map, char delim) { 290 StringBuffer sb = new StringBuffer (); 291 Iterator iter = map.keySet().iterator(); 292 while (iter.hasNext()) { 293 String key = (String )iter.next(); 294 String value = (String )map.get(key); 295 if (sb.length() > 0) { 296 sb.append(delim); 297 } 298 sb.append(key).append(EQUALS).append(value); 299 } 300 return sb.toString(); 301 } 302 303 310 public static final String getFromDelimitedString(String s, String delim, int index) { 311 String rtn = null; 312 StringTokenizer st = new StringTokenizer (s, delim); 313 int counter = 0; 314 while (st.hasMoreTokens() && counter <= index) { 315 if (counter == index) { 316 rtn = st.nextToken(); 317 } 318 else { 319 st.nextToken(); 320 } 321 counter++; 322 } 323 324 return rtn; 325 } 326 327 public static final Pattern getPattern(String pattern) throws PatternSyntaxException { 328 if (patternCache.containsKey(pattern)) { 329 return (Pattern )patternCache.get(pattern); 330 } 331 else { 332 Pattern pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL); 333 patternCache.put(pattern, pat); 334 return pat; 335 } 336 } 337 338 341 public static String getRandomString(int len) { 342 char[] stringchars = new char[len]; 343 for (int i = 0; i < len; i++) { 344 int index = (int)((Math.random() * 25 + 65) + 0.5); 345 if (Math.random() > 0.5) { 346 index += 32; 347 } 348 stringchars[i] = (char)index; 349 } 350 return new String (stringchars); 351 } 352 353 358 public static final String getTagValue(String s, String tagStart, String tagEnd) { 359 if (isEmpty(s)) { 360 return EMPTY; 361 } 362 else { 363 int start = s.indexOf(tagStart); 364 if (start < 0) { 365 return EMPTY; 366 } 367 else { 368 start += tagStart.length(); 369 } 370 371 int end = -1; 372 if (!StringUtils.isEmpty(tagEnd)) { 373 end = s.indexOf(tagEnd, start); 374 } 375 376 if (end >= 0) { 377 return s.substring(start, end); 378 } 379 else { 380 return s.substring(start); 381 } 382 } 383 } 384 385 public static final byte[] gzip(String s) throws IOException { 386 ByteArrayOutputStream baos; 387 GZIPOutputStream gos = null; 388 try { 389 baos = new ByteArrayOutputStream (); 390 gos = new GZIPOutputStream (baos); 391 byte[] b = s.getBytes(); 392 gos.write(b, 0, b.length); 393 gos.finish(); 394 return baos.toByteArray(); 395 } 396 finally { 397 IOUtils.close(gos); 398 } 399 } 400 401 404 public static final boolean isEmpty(String s) { 405 if (s == null || s.equals(EMPTY)) { 406 return true; 407 } 408 else { 409 return false; 410 } 411 } 412 413 416 public static final boolean isEmpty(Object o) { 417 if (o == null || (o instanceof String && o.equals(EMPTY))) { 418 return true; 419 } 420 else { 421 return false; 422 } 423 } 424 425 428 public static final boolean isEqual(String s1, String s2) { 429 if ((isEmpty(s1) && !isEmpty(s2)) || (!isEmpty(s1) && isEmpty(s2))) { 430 return false; 431 } 432 else if (isEmpty(s1) && isEmpty(s2)) { 433 return true; 434 } 435 else { 436 return s1.equals(s2); 437 } 438 } 439 440 443 public static final boolean isNumeric(String s) { 444 if (isEmpty(s)) { 445 return false; 446 } 447 448 for (int i = 0; i < s.length(); i++) { 449 if (!Character.isDigit(s.charAt(i))) { 450 return false; 451 } 452 } 453 454 return true; 455 } 456 457 462 public static final String isNull(String s, String replacement) { 463 return (s == null ? replacement : s); 464 } 465 466 467 471 public static final String lpad(String text, char pad, int length) { 472 return pad(text, pad, length, true); 473 } 474 475 480 public static final boolean matches(String s, String pattern) throws PatternSyntaxException { 481 Pattern p = getPattern(pattern); 482 483 Matcher matcher = p.matcher(s); 484 485 return matcher.matches(); 486 } 487 488 491 private static final String pad(String text, char pad, int length, boolean left) { 492 int textlen = text.length(); 493 if (textlen > length) { 494 return text; 495 } 496 497 StringBuffer sb; 498 if (left) { 499 sb = new StringBuffer (); 500 } 501 else { 502 sb = new StringBuffer (text); 503 } 504 505 int len = length - textlen; 506 for (int i = 0; i < len; i++) { 507 sb.append(pad); 508 } 509 510 if (left) { 511 sb.append(text); 512 } 513 514 return sb.toString(); 515 } 516 517 520 public static final String readFromFile(String filename) { 521 File f = new File (filename); 522 523 if (f.exists() && f.canRead()) { 524 FileReader fr = null; 525 try { 526 fr = new FileReader (f); 527 return readFrom(fr); 528 } 529 catch (Exception e) { 530 e.printStackTrace(); 531 } 532 finally { 533 IOUtils.close(fr); 534 } 535 } 536 else { 537 System.err.println(filename + " does not exist or is not readable"); 538 } 539 540 541 return EMPTY; 542 } 543 544 547 public static final String readFrom(Reader r) { 548 try { 549 StringBuffer sb = new StringBuffer (); 550 BufferedReader in = new BufferedReader (r); 551 char[] array = new char[2048]; 552 int num; 553 while ((num = in.read(array)) != -1) { 554 sb.append(array, 0, num); 555 } 556 in.close(); 557 558 return sb.toString(); 559 } 560 catch (Exception e) { } 561 562 return EMPTY; 563 } 564 565 568 public static final String readFrom(Reader r, int size) { 569 try { 570 StringBuffer sb = new StringBuffer (); 571 BufferedReader in = new BufferedReader (r); 572 char[] array = new char[size]; 573 in.read(array); 574 String rtn = new String (array); 575 return rtn; 576 } 577 catch (Exception e) { 578 e.printStackTrace(); 579 return EMPTY; 580 } 581 } 582 583 593 public static final String remove(String s, String chars) { 594 if (s == null) { 595 return EMPTY; 596 } 597 else { 598 StringBuffer sb = new StringBuffer (); 599 for (int i = 0; i < s.length(); i++) { 600 char c = s.charAt(i); 601 if (chars.indexOf(c) < 0) { 602 sb.append(c); 603 } 604 } 605 return sb.toString(); 606 } 607 } 608 609 613 public static final void replace(StringBuffer sb, String oldstr, String newstr) { 614 if (sb.length() == 0 || isEmpty(oldstr)) { 615 return; 616 } 617 else if (newstr == null) { 618 newstr = EMPTY; 619 } 620 int len = oldstr.length(); 621 int nlen = newstr.length(); 622 int start = 0; 623 int occ = 0; 624 while (occ != -1) { 625 occ = sb.indexOf(oldstr, start); 626 if (occ != -1) { 627 sb.replace(occ, occ + len, newstr); 628 start = occ + nlen; 629 } 630 } 631 } 632 633 639 public static final String replace(String s, String oldstr, String newstr) { 640 if (isEmpty(s)) { 641 return s; 642 } 643 StringBuffer sb = new StringBuffer (s); 644 645 replace(sb, oldstr, newstr); 646 647 return sb.toString(); 648 } 649 650 651 public static final String replaceChars(String s, String chars, char newChar) { 652 StringBuffer sb = new StringBuffer (); 653 for (int i = 0; i < s.length(); i++) { 654 char c = s.charAt(i); 655 if (chars.indexOf(c) >= 0) { 656 sb.append(newChar); 657 } 658 else { 659 sb.append(c); 660 } 661 } 662 return sb.toString(); 663 } 664 665 674 public static final String replaceTag(String s, String tagStart, String tagEnd, String replace) { 675 if (s.length() == 0 || isEmpty(tagStart) || isEmpty(tagEnd)) { 676 return EMPTY; 677 } 678 else if (replace == null) { 679 replace = EMPTY; 680 } 681 StringBuffer sb = new StringBuffer (s); 682 int nlen = replace.length(); 683 int elen = tagEnd.length(); 684 int start = 0; 685 int occ = 0; 686 while (occ != -1) { 687 occ = sb.indexOf(tagStart, start); 688 if (occ != -1) { 689 int occend = sb.indexOf(tagEnd, occ) + elen; 690 sb.replace(occ, occend, replace); 691 start = occ + nlen; 692 } 693 } 694 return sb.toString(); 695 } 696 697 701 public static final String rpad(String text, char pad, int length) { 702 return pad(text, pad, length, false); 703 } 704 705 710 public static final List splitRegex(String s, String pattern) throws PatternSyntaxException { 711 713 String [] tmp = s.split(pattern); 714 List l = java.util.Arrays.asList(tmp); 715 716 return new ArrayList (l); 717 } 718 719 724 public static final String strip(String s, String chars) { 725 StringBuffer sb = new StringBuffer (); 726 for (int i = 0; i < s.length(); i++) { 727 char c = s.charAt(i); 728 if (chars.indexOf(c) < 0) { 729 sb.append(c); 730 } 731 } 732 733 return sb.toString(); 734 } 735 736 739 public static final String stripLTSpaces(String s) { 740 Pattern lpattern = getPattern("^\\s+"); 741 Pattern rpattern = getPattern("\\s+$"); 742 743 Matcher matcher = lpattern.matcher(s); 744 s = matcher.replaceAll(EMPTY); 745 matcher = rpattern.matcher(s); 746 String rtn = matcher.replaceAll(EMPTY); 747 return rtn; 748 } 749 750 755 public static final String [] toArray(String s, String delim) { 756 return toArray(s, delim, false); 757 } 758 759 765 public static final String [] toArray(String s, String delim, boolean returnDelims) { 766 StringTokenizer st = new StringTokenizer (s, delim, returnDelims); 767 String [] rtn = new String [st.countTokens()]; 768 for (int i = 0; i < rtn.length; i++) { 769 rtn[i] = st.nextToken(); 770 } 771 772 st = null; 773 return rtn; 774 } 775 776 780 public static final String toDirectory(String filename) { 781 if (isEmpty(filename)) { 782 return EMPTY; 783 } 784 else if (filename.endsWith(FILE_SEPARATOR)) { 785 return filename; 786 } 787 else { 788 return filename + FILE_SEPARATOR; 789 } 790 } 791 792 public static final String toHex(byte b) { 793 int i = b & 0xff; 794 int h0 = i & 0xf; 795 int h1 = (i >>> 4) & 0xf; 796 797 char[] c = new char[2]; 798 c[0] = hexChars[h1]; 799 c[1] = hexChars[h0]; 800 801 return new String (c); 802 } 803 804 public static final String toHex(byte[] b) { 805 StringBuffer sb = new StringBuffer (); 806 for (int i = 0; i < b.length; i++) { 807 sb.append(toHex(b[i])); 808 } 809 return sb.toString(); 810 } 811 812 815 public static final String toHTML(String s) { 816 return toHTML(s, true); 817 } 818 819 823 public static final String toHTML(String s, boolean includeBR) { 824 Matcher matcher; 825 int end = strpatterns.length-2; 826 if (includeBR) { 827 end = strpatterns.length; 828 } 829 830 for (int i = 0; i < end; i++) { 831 matcher = strpatterns[i].matcher(s); 832 s = matcher.replaceAll(HTML_PATTERNS[i][1]); 833 } 834 835 return s; 836 } 837 838 842 public static final List toList(String s, String delim, List list) { 843 if (isEmpty(s)) { 844 s = EMPTY; 845 } 846 StringTokenizer st = new StringTokenizer (s, delim); 847 while (st.hasMoreTokens()) { 848 list.add(st.nextToken()); 849 } 850 851 st = null; 852 return list; 853 } 854 855 858 public static final List toList(String s, String delim) { 859 ArrayList list = new ArrayList (); 860 return toList(s, delim, list); 861 } 862 863 868 public static final Map toMap(String s, String delim) { 869 HashMap hm = new HashMap (); 870 871 toMap(hm, s, delim); 872 873 return hm; 874 } 875 876 880 public static final void toMap(Map m, String s, String delim) { 881 if (!isEmpty(s)) { 882 StringTokenizer st = new StringTokenizer (s, delim); 883 while (st.hasMoreTokens()) { 884 String token = st.nextToken(); 885 int pos = token.indexOf(EQUALS); 886 if (pos >= 0) { 887 String key = token.substring(0, pos); 888 String val; 889 if (pos < token.length()-1) { 890 val = token.substring(pos+1); 891 } 892 else { 893 val = EMPTY; 894 } 895 m.put(key, val); 896 } 897 else { 898 m.put(s, EMPTY); 899 } 900 } 901 } 902 } 903 904 908 public static final String unescape(String s) { 909 StringBuffer sb = new StringBuffer (s); 910 for (int i = 0; i < REV_ESCAPES.length; i++) { 911 replace(sb, REV_ESCAPES[i][0], REV_ESCAPES[i][1]); 912 } 913 914 return sb.toString(); 915 916 } 917 918 921 public static final String unencode(String s) throws NumberFormatException { 922 StringBuffer sb = new StringBuffer (s); 923 int pos = 0; 924 int endpos; 925 String tmp; 926 while ((pos = sb.indexOf(AMP_HASH, pos)) >= 0) { 927 endpos = sb.indexOf(SEMICOLON, pos); 928 if (endpos >= 0) { 929 tmp = sb.substring(pos+2, endpos); 930 int i = Integer.parseInt(tmp); 931 sb.replace(pos, endpos+1, EMPTY + (char)i); 932 } 933 pos++; 934 } 935 return sb.toString(); 936 } 937 938 private static final String toDigest(String s, MessageDigest md) throws Exception { 939 md.update(s.getBytes()); 940 941 StringBuffer sb = new StringBuffer (); 942 byte[] b = md.digest(); 943 for (int i = 0; i < b.length; i++) { 944 sb.append(toHex(b[i])); 945 } 946 947 return sb.toString(); 948 963 } 964 965 968 public static final String toMD5Digest(String s) throws Exception { 969 if (md5 == null) { 970 synchronized (StringUtils.class) { 971 if (md5 == null) { 972 md5 = MessageDigest.getInstance(MD5); 973 } 974 } 975 } 976 977 MessageDigest md5c = (MessageDigest )md5.clone(); 978 979 return toDigest(s, md5c); 980 } 981 982 public static final String toSHADigest(String s) throws Exception { 983 if (sha == null) { 984 synchronized (StringUtils.class) { 985 if (sha == null) { 986 sha = MessageDigest.getInstance(SHA); 987 } 988 } 989 } 990 991 MessageDigest shac = (MessageDigest )sha.clone(); 992 993 return toDigest(s, shac); 994 995 } 996 997 }
| Popular Tags
|