KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > util > Utilities


1 package org.apache.roller.util;
2
3 import java.io.BufferedInputStream JavaDoc;
4 import java.io.BufferedOutputStream JavaDoc;
5 import java.io.File JavaDoc;
6 import java.io.FileInputStream JavaDoc;
7 import java.io.FileOutputStream JavaDoc;
8 import java.io.IOException JavaDoc;
9 import java.io.InputStream JavaDoc;
10 import java.io.OutputStream JavaDoc;
11 import java.io.UnsupportedEncodingException JavaDoc;
12 import java.net.URLDecoder JavaDoc;
13 import java.net.URLEncoder JavaDoc;
14 import java.security.MessageDigest JavaDoc;
15 import java.util.NoSuchElementException JavaDoc;
16 import java.util.StringTokenizer JavaDoc;
17
18 import org.apache.commons.lang.StringEscapeUtils;
19 import org.apache.commons.lang.StringUtils;
20 import org.apache.commons.logging.Log;
21 import org.apache.commons.logging.LogFactory;
22
23 import sun.misc.BASE64Decoder;
24 import sun.misc.BASE64Encoder;
25
26 /**
27  * General purpose utilities, not for use in templates.
28  */

29 public class Utilities {
30     /** The <code>Log</code> instance for this class. */
31     private static Log mLogger = LogFactory.getLog(Utilities.class);
32       
33     //------------------------------------------------------------------------
34
/** Strip jsessionid off of a URL */
35     public static String JavaDoc stripJsessionId( String JavaDoc url ) {
36         // Strip off jsessionid found in referer URL
37
int startPos = url.indexOf(";jsessionid=");
38         if ( startPos != -1 ) {
39             int endPos = url.indexOf("?",startPos);
40             if ( endPos == -1 ) {
41                 url = url.substring(0,startPos);
42             } else {
43                 url = url.substring(0,startPos)
44                 + url.substring(endPos,url.length());
45             }
46         }
47         return url;
48     }
49     
50     //------------------------------------------------------------------------
51
/**
52      * Escape, but do not replace HTML.
53      * The default behaviour is to escape ampersands.
54      */

55     public static String JavaDoc escapeHTML(String JavaDoc s) {
56         return escapeHTML(s, true);
57     }
58     
59     //------------------------------------------------------------------------
60
/**
61      * Escape, but do not replace HTML.
62      * @param escapeAmpersand Optionally escape
63      * ampersands (&amp;).
64      */

65     public static String JavaDoc escapeHTML(String JavaDoc s, boolean escapeAmpersand) {
66         // got to do amp's first so we don't double escape
67
if (escapeAmpersand) {
68             s = StringUtils.replace(s, "&", "&amp;");
69         }
70         s = StringUtils.replace(s, "&nbsp;", " ");
71         s = StringUtils.replace(s, "\"", "&quot;");
72         s = StringUtils.replace(s, "<", "&lt;");
73         s = StringUtils.replace(s, ">", "&gt;");
74         return s;
75     }
76      
77     public static String JavaDoc unescapeHTML(String JavaDoc str) {
78         return StringEscapeUtils.unescapeHtml(str);
79     }
80     
81     //------------------------------------------------------------------------
82
/**
83      * Remove occurences of html, defined as any text
84      * between the characters "&lt;" and "&gt;". Replace
85      * any HTML tags with a space.
86      */

87     public static String JavaDoc removeHTML(String JavaDoc str) {
88         return removeHTML(str, true);
89     }
90     
91     /**
92      * Remove occurences of html, defined as any text
93      * between the characters "&lt;" and "&gt;".
94      * Optionally replace HTML tags with a space.
95      *
96      * @param str
97      * @param addSpace
98      * @return
99      */

100     public static String JavaDoc removeHTML(String JavaDoc str, boolean addSpace) {
101         if (str == null) return "";
102         StringBuffer JavaDoc ret = new StringBuffer JavaDoc(str.length());
103         int start = 0;
104         int beginTag = str.indexOf("<");
105         int endTag = 0;
106         if (beginTag == -1)
107             return str;
108         
109         while (beginTag >= start) {
110             if (beginTag > 0) {
111                 ret.append(str.substring(start, beginTag));
112                 
113                 // replace each tag with a space (looks better)
114
if (addSpace) ret.append(" ");
115             }
116             endTag = str.indexOf(">", beginTag);
117             
118             // if endTag found move "cursor" forward
119
if (endTag > -1) {
120                 start = endTag + 1;
121                 beginTag = str.indexOf("<", start);
122             }
123             // if no endTag found, get rest of str and break
124
else {
125                 ret.append(str.substring(beginTag));
126                 break;
127             }
128         }
129         // append everything after the last endTag
130
if (endTag > -1 && endTag + 1 < str.length()) {
131             ret.append(str.substring(endTag + 1));
132         }
133         return ret.toString().trim();
134     }
135     
136     //------------------------------------------------------------------------
137
/** Run both removeHTML and escapeHTML on a string.
138      * @param s String to be run through removeHTML and escapeHTML.
139      * @return String with HTML removed and HTML special characters escaped.
140      */

141     public static String JavaDoc removeAndEscapeHTML( String JavaDoc s ) {
142         if ( s==null ) return "";
143         else return Utilities.escapeHTML( Utilities.removeHTML(s) );
144     }
145     
146     //------------------------------------------------------------------------
147
/**
148      * Autoformat.
149      */

150     public static String JavaDoc autoformat(String JavaDoc s) {
151         String JavaDoc ret = StringUtils.replace(s, "\n", "<br />");
152         return ret;
153     }
154         
155     //------------------------------------------------------------------------
156
/**
157      * Replaces occurences of non-alphanumeric characters with an underscore.
158      */

159     public static String JavaDoc replaceNonAlphanumeric(String JavaDoc str) {
160         return replaceNonAlphanumeric(str, '_');
161     }
162     
163     //------------------------------------------------------------------------
164
/**
165      * Replaces occurences of non-alphanumeric characters with a
166      * supplied char.
167      */

168     public static String JavaDoc replaceNonAlphanumeric(String JavaDoc str, char subst) {
169         StringBuffer JavaDoc ret = new StringBuffer JavaDoc(str.length());
170         char[] testChars = str.toCharArray();
171         for (int i = 0; i < testChars.length; i++) {
172             if (Character.isLetterOrDigit(testChars[i])) {
173                 ret.append(testChars[i]);
174             } else {
175                 ret.append( subst );
176             }
177         }
178         return ret.toString();
179     }
180     
181     //------------------------------------------------------------------------
182
/**
183      * Remove occurences of non-alphanumeric characters.
184      */

185     public static String JavaDoc removeNonAlphanumeric(String JavaDoc str) {
186         StringBuffer JavaDoc ret = new StringBuffer JavaDoc(str.length());
187         char[] testChars = str.toCharArray();
188         for (int i = 0; i < testChars.length; i++) {
189             // MR: Allow periods in page links
190
if (Character.isLetterOrDigit(testChars[i]) ||
191                     testChars[i] == '.') {
192                 ret.append(testChars[i]);
193             }
194         }
195         return ret.toString();
196     }
197     
198     //------------------------------------------------------------------------
199
/**
200      * @param stringArray
201      * @param delim
202      * @return
203      */

204     public static String JavaDoc stringArrayToString(String JavaDoc[] stringArray, String JavaDoc delim) {
205         String JavaDoc ret = "";
206         for (int i = 0; i < stringArray.length; i++) {
207             if (ret.length() > 0)
208                 ret = ret + delim + stringArray[i];
209             else
210                 ret = stringArray[i];
211         }
212         return ret;
213     }
214     
215     //--------------------------------------------------------------------------
216
/** Convert string to string array. */
217     public static String JavaDoc[] stringToStringArray(String JavaDoc instr, String JavaDoc delim)
218     throws NoSuchElementException JavaDoc, NumberFormatException JavaDoc {
219         StringTokenizer JavaDoc toker = new StringTokenizer JavaDoc(instr, delim);
220         String JavaDoc stringArray[] = new String JavaDoc[toker.countTokens()];
221         int i = 0;
222         
223         while (toker.hasMoreTokens()) {
224             stringArray[i++] = toker.nextToken();
225         }
226         return stringArray;
227     }
228     
229     //--------------------------------------------------------------------------
230
/** Convert string to integer array. */
231     public static int[] stringToIntArray(String JavaDoc instr, String JavaDoc delim)
232     throws NoSuchElementException JavaDoc, NumberFormatException JavaDoc {
233         StringTokenizer JavaDoc toker = new StringTokenizer JavaDoc(instr, delim);
234         int intArray[] = new int[toker.countTokens()];
235         int i = 0;
236         
237         while (toker.hasMoreTokens()) {
238             String JavaDoc sInt = toker.nextToken();
239             int nInt = Integer.parseInt(sInt);
240             intArray[i++] = new Integer JavaDoc(nInt).intValue();
241         }
242         return intArray;
243     }
244     
245     //-------------------------------------------------------------------
246
/** Convert integer array to a string. */
247     public static String JavaDoc intArrayToString(int[] intArray) {
248         String JavaDoc ret = "";
249         for (int i = 0; i < intArray.length; i++) {
250             if (ret.length() > 0)
251                 ret = ret + "," + Integer.toString(intArray[i]);
252             else
253                 ret = Integer.toString(intArray[i]);
254         }
255         return ret;
256     }
257     
258     //------------------------------------------------------------------------
259
public static void copyFile(File JavaDoc from, File JavaDoc to) throws IOException JavaDoc {
260         InputStream JavaDoc in = null;
261         OutputStream JavaDoc out = null;
262         
263         try {
264             in = new FileInputStream JavaDoc(from);
265         } catch (IOException JavaDoc ex) {
266             throw new IOException JavaDoc(
267                     "Utilities.copyFile: opening input stream '"
268                     + from.getPath()
269                     + "', "
270                     + ex.getMessage());
271         }
272         
273         try {
274             out = new FileOutputStream JavaDoc(to);
275         } catch (Exception JavaDoc ex) {
276             try {
277                 in.close();
278             } catch (IOException JavaDoc ex1) {
279             }
280             throw new IOException JavaDoc(
281                     "Utilities.copyFile: opening output stream '"
282                     + to.getPath()
283                     + "', "
284                     + ex.getMessage());
285         }
286         
287         copyInputToOutput(in, out, from.length());
288     }
289     
290     //------------------------------------------------------------------------
291
/**
292      * Utility method to copy an input stream to an output stream.
293      * Wraps both streams in buffers. Ensures right numbers of bytes copied.
294      */

295     public static void copyInputToOutput(
296             InputStream JavaDoc input,
297             OutputStream JavaDoc output,
298             long byteCount)
299             throws IOException JavaDoc {
300         int bytes;
301         long length;
302         
303         BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(input);
304         BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(output);
305         
306         byte[] buffer;
307         buffer = new byte[8192];
308         
309         for (length = byteCount; length > 0;) {
310             bytes = (int) (length > 8192 ? 8192 : length);
311             
312             try {
313                 bytes = in.read(buffer, 0, bytes);
314             } catch (IOException JavaDoc ex) {
315                 try {
316                     in.close();
317                     out.close();
318                 } catch (IOException JavaDoc ex1) {
319                 }
320                 throw new IOException JavaDoc(
321                         "Reading input stream, " + ex.getMessage());
322             }
323             
324             if (bytes < 0)
325                 break;
326             
327             length -= bytes;
328             
329             try {
330                 out.write(buffer, 0, bytes);
331             } catch (IOException JavaDoc ex) {
332                 try {
333                     in.close();
334                     out.close();
335                 } catch (IOException JavaDoc ex1) {
336                 }
337                 throw new IOException JavaDoc(
338                         "Writing output stream, " + ex.getMessage());
339             }
340         }
341         
342         try {
343             in.close();
344             out.close();
345         } catch (IOException JavaDoc ex) {
346             throw new IOException JavaDoc("Closing file streams, " + ex.getMessage());
347         }
348     }
349     
350     //------------------------------------------------------------------------
351
public static void copyInputToOutput(
352             InputStream JavaDoc input,
353             OutputStream JavaDoc output)
354             throws IOException JavaDoc {
355         BufferedInputStream JavaDoc in = new BufferedInputStream JavaDoc(input);
356         BufferedOutputStream JavaDoc out = new BufferedOutputStream JavaDoc(output);
357         byte buffer[] = new byte[8192];
358         for (int count = 0; count != -1;) {
359             count = in.read(buffer, 0, 8192);
360             if (count != -1)
361                 out.write(buffer, 0, count);
362         }
363         
364         try {
365             in.close();
366             out.close();
367         } catch (IOException JavaDoc ex) {
368             throw new IOException JavaDoc("Closing file streams, " + ex.getMessage());
369         }
370     }
371     
372     /**
373      * Encode a string using algorithm specified in web.xml and return the
374      * resulting encrypted password. If exception, the plain credentials
375      * string is returned
376      *
377      * @param password Password or other credentials to use in authenticating
378      * this username
379      * @param algorithm Algorithm used to do the digest
380      *
381      * @return encypted password based on the algorithm.
382      */

383     public static String JavaDoc encodePassword(String JavaDoc password, String JavaDoc algorithm) {
384         byte[] unencodedPassword = password.getBytes();
385         
386         MessageDigest JavaDoc md = null;
387         
388         try {
389             // first create an instance, given the provider
390
md = MessageDigest.getInstance(algorithm);
391         } catch (Exception JavaDoc e) {
392             mLogger.error("Exception: " + e);
393             return password;
394         }
395         
396         md.reset();
397         
398         // call the update method one or more times
399
// (useful when you don't know the size of your data, eg. stream)
400
md.update(unencodedPassword);
401         
402         // now calculate the hash
403
byte[] encodedPassword = md.digest();
404         
405         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
406         
407         for (int i = 0; i < encodedPassword.length; i++) {
408             if ((encodedPassword[i] & 0xff) < 0x10) {
409                 buf.append("0");
410             }
411             
412             buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
413         }
414         
415         return buf.toString();
416     }
417     
418     /**
419      * Encode a string using Base64 encoding. Used when storing passwords
420      * as cookies.
421      *
422      * This is weak encoding in that anyone can use the decodeString
423      * routine to reverse the encoding.
424      *
425      * @param str
426      * @return String
427      * @throws IOException
428      */

429     public static String JavaDoc encodeString(String JavaDoc str) throws IOException JavaDoc {
430         BASE64Encoder encoder = new BASE64Encoder();
431         String JavaDoc encodedStr = encoder.encodeBuffer(str.getBytes());
432         
433         return (encodedStr.trim());
434     }
435     
436     /**
437      * Decode a string using Base64 encoding.
438      *
439      * @param str
440      * @return String
441      * @throws IOException
442      */

443     public static String JavaDoc decodeString(String JavaDoc str) throws IOException JavaDoc {
444         BASE64Decoder dec = new BASE64Decoder();
445         String JavaDoc value = new String JavaDoc(dec.decodeBuffer(str));
446         
447         return (value);
448     }
449     
450     /**
451      * Strips HTML and truncates.
452      */

453     public static String JavaDoc truncate(
454             String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
455         // strip markup from the string
456
String JavaDoc str2 = removeHTML(str, false);
457         
458         // quickly adjust the upper if it is set lower than 'lower'
459
if (upper < lower) {
460             upper = lower;
461         }
462         
463         // now determine if the string fits within the upper limit
464
// if it does, go straight to return, do not pass 'go' and collect $200
465
if(str2.length() > upper) {
466             // the magic location int
467
int loc;
468             
469             // first we determine where the next space appears after lower
470
loc = str2.lastIndexOf(' ', upper);
471             
472             // now we'll see if the location is greater than the lower limit
473
if(loc >= lower) {
474                 // yes it was, so we'll cut it off here
475
str2 = str2.substring(0, loc);
476             } else {
477                 // no it wasnt, so we'll cut it off at the upper limit
478
str2 = str2.substring(0, upper);
479                 loc = upper;
480             }
481             
482             // the string was truncated, so we append the appendToEnd String
483
str2 = str2 + appendToEnd;
484         }
485         
486         return str2;
487     }
488     
489     /**
490      * This method based on code from the String taglib at Apache Jakarta:
491      * http://cvs.apache.org/viewcvs/jakarta-taglibs/string/src/org/apache/taglibs/string/util/StringW.java?rev=1.16&content-type=text/vnd.viewcvs-markup
492      * Copyright (c) 1999 The Apache Software Foundation.
493      * Author: timster@mac.com
494      *
495      * @param str
496      * @param lower
497      * @param upper
498      * @param appendToEnd
499      * @return
500      */

501     public static String JavaDoc truncateNicely(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
502         // strip markup from the string
503
String JavaDoc str2 = removeHTML(str, false);
504         boolean diff = (str2.length() < str.length());
505         
506         // quickly adjust the upper if it is set lower than 'lower'
507
if(upper < lower) {
508             upper = lower;
509         }
510         
511         // now determine if the string fits within the upper limit
512
// if it does, go straight to return, do not pass 'go' and collect $200
513
if(str2.length() > upper) {
514             // the magic location int
515
int loc;
516             
517             // first we determine where the next space appears after lower
518
loc = str2.lastIndexOf(' ', upper);
519             
520             // now we'll see if the location is greater than the lower limit
521
if(loc >= lower) {
522                 // yes it was, so we'll cut it off here
523
str2 = str2.substring(0, loc);
524             } else {
525                 // no it wasnt, so we'll cut it off at the upper limit
526
str2 = str2.substring(0, upper);
527                 loc = upper;
528             }
529             
530             // HTML was removed from original str
531
if (diff) {
532                 
533                 // location of last space in truncated string
534
loc = str2.lastIndexOf(' ', loc);
535                 
536                 // get last "word" in truncated string (add 1 to loc to eliminate space
537
String JavaDoc str3 = str2.substring(loc+1);
538                 
539                 // find this fragment in original str, from 'loc' position
540
loc = str.indexOf(str3, loc) + str3.length();
541                 
542                 // get truncated string from original str, given new 'loc'
543
str2 = str.substring(0, loc);
544                 
545                 // get all the HTML from original str after loc
546
str3 = extractHTML(str.substring(loc));
547                 
548                 // remove any tags which generate visible HTML
549
// This call is unecessary, all HTML has already been stripped
550
//str3 = removeVisibleHTMLTags(str3);
551

552                 // append the appendToEnd String and
553
// add extracted HTML back onto truncated string
554
str = str2 + appendToEnd + str3;
555             } else {
556                 // the string was truncated, so we append the appendToEnd String
557
str = str2 + appendToEnd;
558             }
559             
560         }
561         
562         return str;
563     }
564     
565     public static String JavaDoc truncateText(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
566         // strip markup from the string
567
String JavaDoc str2 = removeHTML(str, false);
568         boolean diff = (str2.length() < str.length());
569         
570         // quickly adjust the upper if it is set lower than 'lower'
571
if(upper < lower) {
572             upper = lower;
573         }
574         
575         // now determine if the string fits within the upper limit
576
// if it does, go straight to return, do not pass 'go' and collect $200
577
if(str2.length() > upper) {
578             // the magic location int
579
int loc;
580             
581             // first we determine where the next space appears after lower
582
loc = str2.lastIndexOf(' ', upper);
583             
584             // now we'll see if the location is greater than the lower limit
585
if(loc >= lower) {
586                 // yes it was, so we'll cut it off here
587
str2 = str2.substring(0, loc);
588             } else {
589                 // no it wasnt, so we'll cut it off at the upper limit
590
str2 = str2.substring(0, upper);
591                 loc = upper;
592             }
593             // the string was truncated, so we append the appendToEnd String
594
str = str2 + appendToEnd;
595         }
596         return str;
597     }
598     
599     /**
600      * @param str
601      * @return
602      */

603     private static String JavaDoc stripLineBreaks(String JavaDoc str) {
604         // TODO: use a string buffer, ignore case !
605
str = str.replaceAll("<br>", "");
606         str = str.replaceAll("<br/>", "");
607         str = str.replaceAll("<br />", "");
608         str = str.replaceAll("<p></p>", "");
609         str = str.replaceAll("<p/>","");
610         str = str.replaceAll("<p />","");
611         return str;
612     }
613     
614     /**
615      * Need need to get rid of any user-visible HTML tags once all text has been
616      * removed such as &lt;BR&gt;. This sounds like a better approach than removing
617      * all HTML tags and taking the chance to leave some tags un-closed.
618      *
619      * WARNING: this method has serious performance problems a
620      *
621      * @author Alexis Moussine-Pouchkine <alexis.moussine-pouchkine@france.sun.com>
622      * @author Lance Lavandowska
623      * @param str the String object to modify
624      * @return the new String object without the HTML "visible" tags
625      */

626     private static String JavaDoc removeVisibleHTMLTags(String JavaDoc str) {
627         str = stripLineBreaks(str);
628         StringBuffer JavaDoc result = new StringBuffer JavaDoc(str);
629         StringBuffer JavaDoc lcresult = new StringBuffer JavaDoc(str.toLowerCase());
630         
631         // <img should take care of smileys
632
String JavaDoc[] visibleTags = {"<img"}; // are there others to add?
633
int stringIndex;
634         for ( int j = 0 ; j < visibleTags.length ; j++ ) {
635             while ( (stringIndex = lcresult.indexOf(visibleTags[j])) != -1 ) {
636                 if ( visibleTags[j].endsWith(">") ) {
637                     result.delete(stringIndex, stringIndex+visibleTags[j].length() );
638                     lcresult.delete(stringIndex, stringIndex+visibleTags[j].length() );
639                 } else {
640                     // need to delete everything up until next closing '>', for <img for instance
641
int endIndex = result.indexOf(">", stringIndex);
642                     if (endIndex > -1) {
643                         // only delete it if we find the end! If we don't the HTML may be messed up, but we
644
// can't safely delete anything.
645
result.delete(stringIndex, endIndex + 1 );
646                         lcresult.delete(stringIndex, endIndex + 1 );
647                     }
648                 }
649             }
650         }
651         
652         // TODO: This code is buggy by nature. It doesn't deal with nesting of tags properly.
653
// remove certain elements with open & close tags
654
String JavaDoc[] openCloseTags = {"li", "a", "div", "h1", "h2", "h3", "h4"}; // more ?
655
for (int j = 0; j < openCloseTags.length; j++) {
656             // could this be better done with a regular expression?
657
String JavaDoc closeTag = "</"+openCloseTags[j]+">";
658             int lastStringIndex = 0;
659             while ( (stringIndex = lcresult.indexOf( "<"+openCloseTags[j], lastStringIndex)) > -1) {
660                 lastStringIndex = stringIndex;
661                 // Try to find the matching closing tag (ignores possible nesting!)
662
int endIndex = lcresult.indexOf(closeTag, stringIndex);
663                 if (endIndex > -1) {
664                     // If we found it delete it.
665
result.delete(stringIndex, endIndex+closeTag.length());
666                     lcresult.delete(stringIndex, endIndex+closeTag.length());
667                 } else {
668                     // Try to see if it is a self-closed empty content tag, i.e. closed with />.
669
endIndex = lcresult.indexOf(">", stringIndex);
670                     int nextStart = lcresult.indexOf("<", stringIndex+1);
671                     if (endIndex > stringIndex && lcresult.charAt(endIndex-1) == '/' && (endIndex < nextStart || nextStart == -1)) {
672                         // Looks like it, so remove it.
673
result.delete(stringIndex, endIndex + 1);
674                         lcresult.delete(stringIndex, endIndex + 1);
675                         
676                     }
677                 }
678             }
679         }
680         
681         return result.toString();
682     }
683     
684     /**
685      * Extract (keep) JUST the HTML from the String.
686      * @param str
687      * @return
688      */

689     public static String JavaDoc extractHTML(String JavaDoc str) {
690         if (str == null) return "";
691         StringBuffer JavaDoc ret = new StringBuffer JavaDoc(str.length());
692         int start = 0;
693         int beginTag = str.indexOf("<");
694         int endTag = 0;
695         if (beginTag == -1)
696             return str;
697         
698         while (beginTag >= start) {
699             endTag = str.indexOf(">", beginTag);
700             
701             // if endTag found, keep tag
702
if (endTag > -1) {
703                 ret.append( str.substring(beginTag, endTag+1) );
704                 
705                 // move start forward and find another tag
706
start = endTag + 1;
707                 beginTag = str.indexOf("<", start);
708             }
709             // if no endTag found, break
710
else {
711                 break;
712             }
713         }
714         return ret.toString();
715     }
716     
717     
718     public static String JavaDoc hexEncode(String JavaDoc str) {
719         if (StringUtils.isEmpty(str)) return str;
720         
721         return RegexUtil.encode(str);
722     }
723     
724     public static String JavaDoc encodeEmail(String JavaDoc str) {
725         return str!=null ? RegexUtil.encodeEmail(str) : null;
726     }
727
728     /**
729      * URL encoding.
730      * @param s a string to be URL-encoded
731      * @return URL encoding of s using character encoding UTF-8; null if s is null.
732      */

733     public static final String JavaDoc encode(String JavaDoc s) {
734         try {
735             if (s != null)
736                 return URLEncoder.encode(s, "UTF-8");
737             else
738                 return s;
739         } catch (UnsupportedEncodingException JavaDoc e) {
740             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
741
return s;
742         }
743     }
744
745     /**
746      * URL decoding.
747      * @param s a URL-encoded string to be URL-decoded
748      * @return URL decoded value of s using character encoding UTF-8; null if s is null.
749      */

750     public static final String JavaDoc decode(String JavaDoc s) {
751         try {
752             if (s != null)
753                 return URLDecoder.decode(s, "UTF-8");
754             else
755                 return s;
756         } catch (UnsupportedEncodingException JavaDoc e) {
757             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
758
return s;
759         }
760     }
761
762     /**
763      * @param string
764      * @return
765      */

766     public static int stringToInt(String JavaDoc string) {
767         try {
768             return Integer.valueOf(string).intValue();
769         } catch (NumberFormatException JavaDoc e) {
770             mLogger.debug("Invalid Integer:" + string);
771         }
772         return 0;
773     }
774                     
775     /**
776      * Convert a byte array into a Base64 string (as used in mime formats)
777      */

778     public static String JavaDoc toBase64(byte[] aValue) {
779         
780         final String JavaDoc m_strBase64Chars =
781                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
782         
783         int byte1;
784         int byte2;
785         int byte3;
786         int iByteLen = aValue.length;
787         StringBuffer JavaDoc tt = new StringBuffer JavaDoc();
788         
789         for (int i = 0; i < iByteLen; i += 3) {
790             boolean bByte2 = (i + 1) < iByteLen;
791             boolean bByte3 = (i + 2) < iByteLen;
792             byte1 = aValue[i] & 0xFF;
793             byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
794             byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
795             
796             tt.append(m_strBase64Chars.charAt(byte1 / 4));
797             tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16)));
798             tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '='));
799             tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '='));
800         }
801         
802         return tt.toString();
803     }
804 }
805
Popular Tags