KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > lateralnz > common > util > StringUtils


1 /* ====================================================================
2  * The LateralNZ Software License, Version 1.0
3  *
4  * Copyright (c) 2003 LateralNZ. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  *
10  * 1. Redistributions of source code must retain the above copyright
11  * notice, this list of conditions and the following disclaimer.
12  *
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in
15  * the documentation and/or other materials provided with the
16  * distribution.
17  *
18  * 3. The end-user documentation included with the redistribution,
19  * if any, must include the following acknowledgment:
20  * "This product includes software developed by
21  * LateralNZ (http://www.lateralnz.org/) and other third parties."
22  * Alternately, this acknowledgment may appear in the software itself,
23  * if and wherever such third-party acknowledgments normally appear.
24  *
25  * 4. The names "LateralNZ" must not be used to endorse or promote
26  * products derived from this software without prior written
27  * permission. For written permission, please
28  * contact oss@lateralnz.org.
29  *
30  * 5. Products derived from this software may not be called "Panther",
31  * or "Lateral" or "LateralNZ", nor may "PANTHER" or "LATERAL" or
32  * "LATERALNZ" appear in their name, without prior written
33  * permission of LateralNZ.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many
50  * individuals on behalf of LateralNZ. For more
51  * information on Lateral, please see http://www.lateralnz.com/ or
52  * http://www.lateralnz.org
53  *
54  */

55 package org.lateralnz.common.util;
56
57 import java.io.ByteArrayInputStream JavaDoc;
58 import java.io.ByteArrayOutputStream JavaDoc;
59 import java.io.BufferedReader JavaDoc;
60 import java.io.File JavaDoc;
61 import java.io.FileReader JavaDoc;
62 import java.io.IOException JavaDoc;
63 import java.io.Reader JavaDoc;
64 import java.security.MessageDigest JavaDoc;
65 import java.text.MessageFormat JavaDoc;
66 import java.util.ArrayList JavaDoc;
67 import java.util.HashMap JavaDoc;
68 import java.util.Iterator JavaDoc;
69 import java.util.List JavaDoc;
70 import java.util.Map JavaDoc;
71 import java.util.StringTokenizer JavaDoc;
72 import java.util.zip.GZIPInputStream JavaDoc;
73 import java.util.zip.GZIPOutputStream JavaDoc;
74
75 import java.util.regex.Matcher JavaDoc;
76 import java.util.regex.Pattern JavaDoc;
77 import java.util.regex.PatternSyntaxException JavaDoc;
78
79 /**
80  * common string utility functions
81  *
82  * @author J R Briggs
83  */

84 public final class StringUtils implements Constants {
85   private static MessageDigest JavaDoc md5 = null;
86   private static MessageDigest JavaDoc sha = null;
87   
88   private static HashMap JavaDoc patternCache = new HashMap JavaDoc();
89   
90   private static final String JavaDoc MD5 = "MD5";
91   private static final String JavaDoc 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 JavaDoc[][] HTML_PATTERNS = {
96   { "&", "&"},
97   { "<", "&lt;" },
98   { ">", "&gt;" },
99   { "\\&nbsp\\; ", "&nbsp;&nbsp;" },
100   { "'", "&#39;" },
101   { "\"", "&#34;" },
102   { "\n", "<br />" },
103   { "\n ", "<br />&nbsp;" }
104   };
105   
106   private static final String JavaDoc[][] ESCAPES = { { "\n", "\\n" },
107   { "\r", "\\r" },
108   { "\"", "\\\"" },
109   { "\t", "\\t" } };
110   
111   private static final String JavaDoc[][] REV_ESCAPES = { { "\\n", "\n" },
112   { "\\r", "\r" },
113   { "\\\"", "\"" },
114   { "\\t", "\t" },
115   { "\\'", "'" }};
116   
117   private static final String JavaDoc AMP_HASH = "&#";
118   
119   private static Pattern JavaDoc[] strpatterns = new Pattern JavaDoc[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 JavaDoc pse) {
129       pse.printStackTrace();
130     }
131   }
132
133  /**
134   * count the occurrences of a character in a string
135   */

136   public static final int countOccurrences(String JavaDoc 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 JavaDoc 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 JavaDoc degzip(byte[] b) throws IOException JavaDoc {
157     GZIPInputStream JavaDoc gis = null;
158     try {
159       gis = new GZIPInputStream JavaDoc(new ByteArrayInputStream JavaDoc(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 JavaDoc(buf, 0, total);
180     }
181     finally {
182       IOUtils.close(gis);
183     }
184   }
185   
186  /**
187   * escape a string
188   */

189   public static final String JavaDoc escape(String JavaDoc s) {
190     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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  /**
200   * return a list of regular expression groups given a string and a regex grouping pattern
201   */

202   public static final List JavaDoc findRegex(String JavaDoc s, String JavaDoc pattern) {
203     ArrayList JavaDoc rtn = new ArrayList JavaDoc();
204     Pattern JavaDoc p = getPattern(pattern);
205     Matcher JavaDoc 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  /**
217   * a quick and dirty wrapper over MessageFormat.format, so we don't need
218   * to import it into JSPs as well as org.lateralnz.util.*
219   */

220   public static final String JavaDoc format(String JavaDoc pattern, Object JavaDoc[] arguments) {
221     if (isEmpty(pattern)) {
222       return EMPTY;
223     }
224     else {
225       return MessageFormat.format(pattern, arguments);
226     }
227   }
228   
229  /**
230   * a wrapper for MessageFormat.format that takes a single argument
231   * rather than an array
232   */

233   public static final String JavaDoc format(String JavaDoc pattern, String JavaDoc argument) {
234     return format(pattern, new Object JavaDoc[]{ argument });
235   }
236   
237   public static final String JavaDoc fromArray(String JavaDoc[] s, String JavaDoc 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   /**
247    * turn an array of strings into a single delimited string
248    * @param s the array of strings to use
249    * @param delim the delimiter to use between each value
250    * @param start the start position of the array
251    * @param len the number of elements to use from the array
252    * @returns a delimited string
253    */

254   public static final String JavaDoc fromArray(String JavaDoc[] s, String JavaDoc delim, int start, int len) {
255     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
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  /**
268   * turn a list of strings into a single delimited string
269   */

270   public static final String JavaDoc fromList(List JavaDoc l, String JavaDoc delim) {
271     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
272     Iterator JavaDoc 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   /**
283    * create a string based upon the contents of a map. The string will be constructed
284    * as key=value[DELIM]key=value[DELIM]..., where [DELIM] is specified in the call to
285    * this method. For example:
286    * fromMap(m, ',')
287    * would return: key1=value1,key2=value2,key3=value3,etc
288    */

289   public static final String JavaDoc fromMap(Map JavaDoc map, char delim) {
290     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
291     Iterator JavaDoc iter = map.keySet().iterator();
292     while (iter.hasNext()) {
293       String JavaDoc key = (String JavaDoc)iter.next();
294       String JavaDoc value = (String JavaDoc)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   /**
304    * parse a delimited string returning the element at the specified index
305    * @param s the string to parse
306    * @param delim the delimiters
307    * @param index the index value to return
308    * @returns a string value
309    */

310   public static final String JavaDoc getFromDelimitedString(String JavaDoc s, String JavaDoc delim, int index) {
311     String JavaDoc rtn = null;
312     StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(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 JavaDoc getPattern(String JavaDoc pattern) throws PatternSyntaxException JavaDoc {
328     if (patternCache.containsKey(pattern)) {
329       return (Pattern JavaDoc)patternCache.get(pattern);
330     }
331     else {
332       Pattern JavaDoc pat = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
333       patternCache.put(pattern, pat);
334       return pat;
335     }
336   }
337   
338   /**
339    * create a random string of a specified length
340    */

341   public static String JavaDoc 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 JavaDoc(stringchars);
351   }
352   
353  /**
354   * given a string and the start and end of a tag return the contents of the tag.
355   * For example, given the string: "hello this &lt;!-- is a test --&gt;" and a tag start
356   * of "&lt;!--" and a tag end of "--&gt;", this method should return " is a test "
357   */

358   public static final String JavaDoc getTagValue(String JavaDoc s, String JavaDoc tagStart, String JavaDoc 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 JavaDoc s) throws IOException JavaDoc {
386     ByteArrayOutputStream JavaDoc baos;
387     GZIPOutputStream JavaDoc gos = null;
388     try {
389       baos = new ByteArrayOutputStream JavaDoc();
390       gos = new GZIPOutputStream JavaDoc(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   /**
402    * return true if a string is null or empty (in other words equals(\"\"))
403    */

404   public static final boolean isEmpty(String JavaDoc s) {
405     if (s == null || s.equals(EMPTY)) {
406       return true;
407     }
408     else {
409       return false;
410     }
411   }
412   
413   /**
414    * return true if an object is null, or it is a string and empty
415    */

416   public static final boolean isEmpty(Object JavaDoc o) {
417     if (o == null || (o instanceof String JavaDoc && o.equals(EMPTY))) {
418       return true;
419     }
420     else {
421       return false;
422     }
423   }
424   
425  /**
426   * check for equality between two strings, taking nulls into account
427   */

428   public static final boolean isEqual(String JavaDoc s1, String JavaDoc 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   /**
441    * Check if a string is numeric (digit chars only)
442    */

443   public static final boolean isNumeric(String JavaDoc 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   /**
458    * if a string is null, then return the specified replacement
459    * @param s the string to check for null
460    * @param replacement the string to return if s is null
461    */

462   public static final String JavaDoc isNull(String JavaDoc s, String JavaDoc replacement) {
463     return (s == null ? replacement : s);
464   }
465   
466   
467   /**
468    * left pad a string with a certain character so that it equals the specified
469    * length
470    */

471   public static final String JavaDoc lpad(String JavaDoc text, char pad, int length) {
472     return pad(text, pad, length, true);
473   }
474   
475   /**
476    * return true if a particular string matches the regular expression
477    * @param s the string to check
478    * @param pattern the regular expression to look for
479    */

480   public static final boolean matches(String JavaDoc s, String JavaDoc pattern) throws PatternSyntaxException JavaDoc {
481     Pattern JavaDoc p = getPattern(pattern);
482     
483     Matcher JavaDoc matcher = p.matcher(s);
484     
485     return matcher.matches();
486   }
487   
488  /**
489   * actual padding method
490   */

491   private static final String JavaDoc pad(String JavaDoc text, char pad, int length, boolean left) {
492     int textlen = text.length();
493     if (textlen > length) {
494       return text;
495     }
496     
497     StringBuffer JavaDoc sb;
498     if (left) {
499       sb = new StringBuffer JavaDoc();
500     }
501     else {
502       sb = new StringBuffer JavaDoc(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   /**
518    * read the contents of a file and return as a string
519    */

520   public static final String JavaDoc readFromFile(String JavaDoc filename) {
521     File JavaDoc f = new File JavaDoc(filename);
522     
523     if (f.exists() && f.canRead()) {
524       FileReader JavaDoc fr = null;
525       try {
526         fr = new FileReader JavaDoc(f);
527         return readFrom(fr);
528       }
529       catch (Exception JavaDoc 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  /**
545   * read the contents of the specified reader
546   */

547   public static final String JavaDoc readFrom(Reader JavaDoc r) {
548     try {
549       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
550       BufferedReader JavaDoc in = new BufferedReader JavaDoc(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 JavaDoc e) { }
561     
562     return EMPTY;
563   }
564   
565  /**
566   * read the contents of the specified reader up to the specified size
567   */

568   public static final String JavaDoc readFrom(Reader JavaDoc r, int size) {
569     try {
570       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
571       BufferedReader JavaDoc in = new BufferedReader JavaDoc(r);
572       char[] array = new char[size];
573       in.read(array);
574       String JavaDoc rtn = new String JavaDoc(array);
575       return rtn;
576     }
577     catch (Exception JavaDoc e) {
578       e.printStackTrace();
579       return EMPTY;
580     }
581   }
582   
583   /**
584    * remove all occurences of a list of characters from a string. for example:
585    * <pre>
586    * remove("This is a test", " ");
587    * </pre>
588    * should return "Thisisatest".
589    * @param s the string to remove characters from
590    * @param chars the list of characters to remove
591    * @returns a new string with chars removed
592    */

593   public static final String JavaDoc remove(String JavaDoc s, String JavaDoc chars) {
594     if (s == null) {
595       return EMPTY;
596     }
597     else {
598       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
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   /**
610    * replace all references of a string in a stringbuffer with the contents
611    * of a replacement string
612    */

613   public static final void replace(StringBuffer JavaDoc sb, String JavaDoc oldstr, String JavaDoc 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   /**
634    * replace all occurrences of a string with the contents of another string
635    * @param s the string to search
636    * @param oldstr the string pattern to look for
637    * @param newstr the string pattern to replace with
638    */

639   public static final String JavaDoc replace(String JavaDoc s, String JavaDoc oldstr, String JavaDoc newstr) {
640     if (isEmpty(s)) {
641       return s;
642     }
643     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(s);
644     
645     replace(sb, oldstr, newstr);
646     
647     return sb.toString();
648   }
649   
650   
651   public static final String JavaDoc replaceChars(String JavaDoc s, String JavaDoc chars, char newChar) {
652     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
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   /**
666    * replace all references to a 'tag' within a string. A tag is a section of text
667    * defined with a start string and and end string.
668    * For example:
669    * <pre>
670    * replaceTag("this is a test <!-- this is a test --> blah blah", "<!--", "-->", "");
671    * </pre>
672    * Would be expected to return "this is a test blah blah"
673    */

674   public static final String JavaDoc replaceTag(String JavaDoc s, String JavaDoc tagStart, String JavaDoc tagEnd, String JavaDoc 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 JavaDoc sb = new StringBuffer JavaDoc(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   /**
698    * right pad a string with a character so that the length is the same as that
699    * specified by the length param
700    */

701   public static final String JavaDoc rpad(String JavaDoc text, char pad, int length) {
702     return pad(text, pad, length, false);
703   }
704   
705   /**
706    * split a string based upon a regular expression pattern
707    * For example: splitRegex("a,b,c,d,e", ",")
708    * would return a list containing a, b, c, d, and e as the elements
709    */

710   public static final List JavaDoc splitRegex(String JavaDoc s, String JavaDoc pattern) throws PatternSyntaxException JavaDoc {
711 // Pattern p = getPattern(pattern);
712

713     String JavaDoc[] tmp = s.split(pattern);
714     List JavaDoc l = java.util.Arrays.asList(tmp);
715     
716     return new ArrayList JavaDoc(l);
717   }
718   
719   /**
720    * strip all occurrences of characters in a string from a specified string
721    * @param s the string to search
722    * @param chars a string of characters to remove from s
723    */

724   public static final String JavaDoc strip(String JavaDoc s, String JavaDoc chars) {
725     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
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   /**
737    * strip leading a trailing spaces from a string based upon line delimiters
738    */

739   public static final String JavaDoc stripLTSpaces(String JavaDoc s) {
740     Pattern JavaDoc lpattern = getPattern("^\\s+");
741     Pattern JavaDoc rpattern = getPattern("\\s+$");
742     
743     Matcher JavaDoc matcher = lpattern.matcher(s);
744     s = matcher.replaceAll(EMPTY);
745     matcher = rpattern.matcher(s);
746     String JavaDoc rtn = matcher.replaceAll(EMPTY);
747     return rtn;
748   }
749   
750   /**
751    * turn a string into an array of strings (delimiters are not returned as part of the array)
752    * @param s the string to convert
753    * @param delim the delimiters to use in conversion
754    */

755   public static final String JavaDoc[] toArray(String JavaDoc s, String JavaDoc delim) {
756     return toArray(s, delim, false);
757   }
758   
759   /**
760    * turn a string into a string array based upon a delimiter
761    * @param s the string to convert
762    * @param delim the delimiters to use in conversion
763    * @param returnDelimiters if true, then delimiters are included in the array
764    */

765   public static final String JavaDoc[] toArray(String JavaDoc s, String JavaDoc delim, boolean returnDelims) {
766     StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, delim, returnDelims);
767     String JavaDoc[] rtn = new String JavaDoc[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  /**
777   * makes sure that a directory filename ends with the file separator.
778   * eg: /usr/local/lib becomes /usr/local/lib/
779   */

780   public static final String JavaDoc toDirectory(String JavaDoc 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 JavaDoc 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 JavaDoc(c);
802   }
803   
804   public static final String JavaDoc toHex(byte[] b) {
805     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
806     for (int i = 0; i < b.length; i++) {
807       sb.append(toHex(b[i]));
808     }
809     return sb.toString();
810   }
811   
812   /**
813    * convert a string into an 'HTML-ready' string, handling special characters and newlines
814    */

815   public static final String JavaDoc toHTML(String JavaDoc s) {
816     return toHTML(s, true);
817   }
818   
819   /**
820    * convert a string into an 'HTML-ready' string, handling special characters.
821    * This will convert newlines to html breaks if specified
822    */

823   public static final String JavaDoc toHTML(String JavaDoc s, boolean includeBR) {
824     Matcher JavaDoc 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   /**
839    * chop a string up into tokens based upon the delimiter and add
840    * the tokens to a list
841    */

842   public static final List JavaDoc toList(String JavaDoc s, String JavaDoc delim, List JavaDoc list) {
843     if (isEmpty(s)) {
844       s = EMPTY;
845     }
846     StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, delim);
847     while (st.hasMoreTokens()) {
848       list.add(st.nextToken());
849     }
850     
851     st = null;
852     return list;
853   }
854   
855   /**
856    * turn a string into a list based upon a delimiter
857    */

858   public static final List JavaDoc toList(String JavaDoc s, String JavaDoc delim) {
859     ArrayList JavaDoc list = new ArrayList JavaDoc();
860     return toList(s, delim, list);
861   }
862   
863   /**
864    * turn a string into a map of param=value objects based upon a delimiter.
865    * The string should be something like: "a=100,b=hello,c=a203" where the delimiter
866    * is obviously ","
867    */

868   public static final Map JavaDoc toMap(String JavaDoc s, String JavaDoc delim) {
869     HashMap JavaDoc hm = new HashMap JavaDoc();
870     
871     toMap(hm, s, delim);
872     
873     return hm;
874   }
875   
876   /**
877    * turn a string into a map of param=value objects based upon a delimiter and
878    * using the specified map object for the result
879    */

880   public static final void toMap(Map JavaDoc m, String JavaDoc s, String JavaDoc delim) {
881     if (!isEmpty(s)) {
882       StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(s, delim);
883       while (st.hasMoreTokens()) {
884         String JavaDoc token = st.nextToken();
885         int pos = token.indexOf(EQUALS);
886         if (pos >= 0) {
887           String JavaDoc key = token.substring(0, pos);
888           String JavaDoc 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   /**
905    * take a string that contains escaped values \\n \\t \\r and returns it with
906    * the actual escape codes (\n, \t, \r)
907    */

908   public static final String JavaDoc unescape(String JavaDoc s) {
909     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(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   /**
919    * unencode a string containing html escape codes (in the form &amp;#...;)
920    */

921   public static final String JavaDoc unencode(String JavaDoc s) throws NumberFormatException JavaDoc {
922     StringBuffer JavaDoc sb = new StringBuffer JavaDoc(s);
923     int pos = 0;
924     int endpos;
925     String JavaDoc 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 JavaDoc toDigest(String JavaDoc s, MessageDigest JavaDoc md) throws Exception JavaDoc {
939     md.update(s.getBytes());
940     
941     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
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     /*
949     StringReader sr = new StringReader(new String(md.digest()));
950     int c;
951     StringBuffer sb = new StringBuffer();
952     while ((c = sr.read()) != -1) {
953       String hexString = Integer.toHexString(c);
954       if ( hexString.length() == 1 ) {
955         sb.append(ZERO).append(hexString);
956       }
957       else {
958         sb.append(hexString);
959       }
960     }
961     
962     return sb.toString();*/

963   }
964   
965   /**
966    * return an MD5 digest of a specified string
967    */

968   public static final String JavaDoc toMD5Digest(String JavaDoc s) throws Exception JavaDoc {
969     if (md5 == null) {
970       synchronized (StringUtils.class) {
971         if (md5 == null) {
972           md5 = MessageDigest.getInstance(MD5);
973         }
974       }
975     }
976     
977     MessageDigest JavaDoc md5c = (MessageDigest JavaDoc)md5.clone();
978     
979     return toDigest(s, md5c);
980   }
981
982   public static final String JavaDoc toSHADigest(String JavaDoc s) throws Exception JavaDoc {
983     if (sha == null) {
984       synchronized (StringUtils.class) {
985         if (sha == null) {
986           sha = MessageDigest.getInstance(SHA);
987         }
988       }
989     }
990     
991     MessageDigest JavaDoc shac = (MessageDigest JavaDoc)sha.clone();
992     
993     return toDigest(s, shac);
994     
995   }
996  
997 }
Popular Tags