KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > roller > ui > rendering > velocity > deprecated > OldUtilities


1 /*
2  * Licensed to the Apache Software Foundation (ASF) under one or more
3  * contributor license agreements. The ASF licenses this file to You
4  * under the Apache License, Version 2.0 (the "License"); you may not
5  * use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License. For additional information regarding
15  * copyright in this work, please see the NOTICE file in the top level
16  * directory of this distribution.
17  */

18 package org.apache.roller.ui.rendering.velocity.deprecated;
19
20 import java.io.IOException JavaDoc;
21 import java.io.UnsupportedEncodingException JavaDoc;
22 import java.net.URLDecoder JavaDoc;
23 import java.net.URLEncoder JavaDoc;
24 import java.text.SimpleDateFormat JavaDoc;
25 import java.util.Date JavaDoc;
26 import java.util.regex.Matcher JavaDoc;
27 import java.util.regex.Pattern JavaDoc;
28 import org.apache.commons.lang.StringEscapeUtils;
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.commons.logging.Log;
31 import org.apache.commons.logging.LogFactory;
32 import org.apache.roller.util.DateUtil;
33 import org.apache.roller.util.RegexUtil;
34 import org.apache.roller.util.Utilities;
35
36
37 /**
38  * Utility methods needed by old Roller 2.X macros/templates.
39  * Deprecated because they are either redundant or unnecesary.
40  */

41 public class OldUtilities {
42     
43     /** The <code>Log</code> instance for this class. */
44     private static Log mLogger = LogFactory.getLog(OldUtilities.class);
45     
46     private static Pattern JavaDoc mLinkPattern =
47             Pattern.compile("<a HREF=.*?>", Pattern.CASE_INSENSITIVE);
48     private static final Pattern JavaDoc OPENING_B_TAG_PATTERN =
49             Pattern.compile("&lt;b&gt;", Pattern.CASE_INSENSITIVE);
50     private static final Pattern JavaDoc CLOSING_B_TAG_PATTERN =
51             Pattern.compile("&lt;/b&gt;", Pattern.CASE_INSENSITIVE);
52     private static final Pattern JavaDoc OPENING_I_TAG_PATTERN =
53             Pattern.compile("&lt;i&gt;", Pattern.CASE_INSENSITIVE);
54     private static final Pattern JavaDoc CLOSING_I_TAG_PATTERN =
55             Pattern.compile("&lt;/i&gt;", Pattern.CASE_INSENSITIVE);
56     private static final Pattern JavaDoc OPENING_BLOCKQUOTE_TAG_PATTERN =
57             Pattern.compile("&lt;blockquote&gt;", Pattern.CASE_INSENSITIVE);
58     private static final Pattern JavaDoc CLOSING_BLOCKQUOTE_TAG_PATTERN =
59             Pattern.compile("&lt;/blockquote&gt;", Pattern.CASE_INSENSITIVE);
60     private static final Pattern JavaDoc BR_TAG_PATTERN =
61             Pattern.compile("&lt;br */*&gt;", Pattern.CASE_INSENSITIVE);
62     private static final Pattern JavaDoc OPENING_P_TAG_PATTERN =
63             Pattern.compile("&lt;p&gt;", Pattern.CASE_INSENSITIVE);
64     private static final Pattern JavaDoc CLOSING_P_TAG_PATTERN =
65             Pattern.compile("&lt;/p&gt;", Pattern.CASE_INSENSITIVE);
66     private static final Pattern JavaDoc OPENING_PRE_TAG_PATTERN =
67             Pattern.compile("&lt;pre&gt;", Pattern.CASE_INSENSITIVE);
68     private static final Pattern JavaDoc CLOSING_PRE_TAG_PATTERN =
69             Pattern.compile("&lt;/pre&gt;", Pattern.CASE_INSENSITIVE);
70     private static final Pattern JavaDoc OPENING_UL_TAG_PATTERN =
71             Pattern.compile("&lt;ul&gt;", Pattern.CASE_INSENSITIVE);
72     private static final Pattern JavaDoc CLOSING_UL_TAG_PATTERN =
73             Pattern.compile("&lt;/ul&gt;", Pattern.CASE_INSENSITIVE);
74     private static final Pattern JavaDoc OPENING_OL_TAG_PATTERN =
75             Pattern.compile("&lt;ol&gt;", Pattern.CASE_INSENSITIVE);
76     private static final Pattern JavaDoc CLOSING_OL_TAG_PATTERN =
77             Pattern.compile("&lt;/ol&gt;", Pattern.CASE_INSENSITIVE);
78     private static final Pattern JavaDoc OPENING_LI_TAG_PATTERN =
79             Pattern.compile("&lt;li&gt;", Pattern.CASE_INSENSITIVE);
80     private static final Pattern JavaDoc CLOSING_LI_TAG_PATTERN =
81             Pattern.compile("&lt;/li&gt;", Pattern.CASE_INSENSITIVE);
82     private static final Pattern JavaDoc CLOSING_A_TAG_PATTERN =
83             Pattern.compile("&lt;/a&gt;", Pattern.CASE_INSENSITIVE);
84     private static final Pattern JavaDoc OPENING_A_TAG_PATTERN =
85             Pattern.compile("&lt;a HREF=.*?&gt;", Pattern.CASE_INSENSITIVE);
86     private static final Pattern JavaDoc QUOTE_PATTERN =
87             Pattern.compile("&quot;", Pattern.CASE_INSENSITIVE);
88             
89     public static boolean isEmpty(String JavaDoc str) {
90         if (str == null) return true;
91         return "".equals(str.trim());
92     }
93     
94     public static boolean isNotEmpty(String JavaDoc str) {
95         return !isEmpty(str);
96     }
97     
98     public static String JavaDoc[] split(String JavaDoc str1, String JavaDoc str2) {
99         return StringUtils.split(str1, str2);
100     }
101     
102     public static String JavaDoc replace(String JavaDoc src, String JavaDoc target, String JavaDoc rWith) {
103         return StringUtils.replace(src, target, rWith);
104     }
105     
106     public static String JavaDoc replace(String JavaDoc src, String JavaDoc target, String JavaDoc rWith, int maxCount) {
107         return StringUtils.replace(src, target, rWith, maxCount);
108     }
109     
110     public static boolean equals(String JavaDoc str1, String JavaDoc str2) {
111         return StringUtils.equals(str1, str2);
112     }
113     
114     public static boolean isAlphanumeric(String JavaDoc str) {
115         return StringUtils.isAlphanumeric(str);
116     }
117     
118     public static String JavaDoc[] stripAll(String JavaDoc[] strs) {
119         return StringUtils.stripAll(strs);
120     }
121     
122     public static String JavaDoc left(String JavaDoc str, int length) {
123         return StringUtils.left(str, length);
124     }
125     
126     public static String JavaDoc escapeHTML(String JavaDoc str) {
127         return StringEscapeUtils.escapeHtml(str);
128     }
129     
130     public static String JavaDoc unescapeHTML(String JavaDoc str) {
131         return StringEscapeUtils.unescapeHtml(str);
132     }
133                
134     /**
135      * Remove occurences of html, defined as any text
136      * between the characters "&lt;" and "&gt;". Replace
137      * any HTML tags with a space.
138      */

139     public static String JavaDoc removeHTML(String JavaDoc str) {
140         return removeHTML(str, true);
141     }
142     
143     /**
144      * Remove occurences of html, defined as any text
145      * between the characters "&lt;" and "&gt;".
146      * Optionally replace HTML tags with a space.
147      */

148     public static String JavaDoc removeHTML(String JavaDoc str, boolean addSpace) {
149         return Utilities.removeHTML(str, addSpace);
150     }
151         
152     /**
153      * Autoformat.
154      */

155     public static String JavaDoc autoformat(String JavaDoc s) {
156         String JavaDoc ret = StringUtils.replace(s, "\n", "<br />");
157         return ret;
158     }
159     
160     /**
161      * Return date for current time.
162      */

163     public static Date JavaDoc getNow() {
164         return new Date JavaDoc();
165     }
166     
167     /**
168      * Format date using SimpleDateFormat format string.
169      */

170     public static String JavaDoc formatDate(Date JavaDoc d, String JavaDoc fmt) {
171         SimpleDateFormat JavaDoc format = new SimpleDateFormat JavaDoc(fmt);
172         return format.format(d);
173     }
174     
175     /**
176      * Format date in ISO-8601 format.
177      */

178     public static String JavaDoc formatIso8601Date(Date JavaDoc d) {
179         return DateUtil.formatIso8601(d);
180     }
181     
182     /**
183      * Format date in ISO-8601 format.
184      */

185     public static String JavaDoc formatIso8601Day(Date JavaDoc d) {
186         return DateUtil.formatIso8601Day(d);
187     }
188     
189     /**
190      * Return a date in RFC-822 format.
191      */

192     public static String JavaDoc formatRfc822Date(Date JavaDoc date) {
193         return DateUtil.formatRfc822(date);
194     }
195     
196     /**
197      * Return a date in RFC-822 format.
198      */

199     public static String JavaDoc format8charsDate(Date JavaDoc date) {
200         return DateUtil.format8chars(date);
201     }
202     
203     /**
204      * Strips HTML and truncates.
205      */

206     public static String JavaDoc truncate(
207             String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
208         // strip markup from the string
209
String JavaDoc str2 = removeHTML(str, false);
210         
211         // quickly adjust the upper if it is set lower than 'lower'
212
if (upper < lower) {
213             upper = lower;
214         }
215         
216         // now determine if the string fits within the upper limit
217
// if it does, go straight to return, do not pass 'go' and collect $200
218
if(str2.length() > upper) {
219             // the magic location int
220
int loc;
221             
222             // first we determine where the next space appears after lower
223
loc = str2.lastIndexOf(' ', upper);
224             
225             // now we'll see if the location is greater than the lower limit
226
if(loc >= lower) {
227                 // yes it was, so we'll cut it off here
228
str2 = str2.substring(0, loc);
229             } else {
230                 // no it wasnt, so we'll cut it off at the upper limit
231
str2 = str2.substring(0, upper);
232                 loc = upper;
233             }
234             
235             // the string was truncated, so we append the appendToEnd String
236
str2 = str2 + appendToEnd;
237         }
238         
239         return str2;
240     }
241     
242     public static String JavaDoc truncateNicely(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
243         return Utilities.truncateNicely(str, lower, upper, appendToEnd);
244     }
245     
246     public static String JavaDoc truncateText(String JavaDoc str, int lower, int upper, String JavaDoc appendToEnd) {
247         // strip markup from the string
248
String JavaDoc str2 = removeHTML(str, false);
249         boolean diff = (str2.length() < str.length());
250         
251         // quickly adjust the upper if it is set lower than 'lower'
252
if(upper < lower) {
253             upper = lower;
254         }
255         
256         // now determine if the string fits within the upper limit
257
// if it does, go straight to return, do not pass 'go' and collect $200
258
if(str2.length() > upper) {
259             // the magic location int
260
int loc;
261             
262             // first we determine where the next space appears after lower
263
loc = str2.lastIndexOf(' ', upper);
264             
265             // now we'll see if the location is greater than the lower limit
266
if(loc >= lower) {
267                 // yes it was, so we'll cut it off here
268
str2 = str2.substring(0, loc);
269             } else {
270                 // no it wasnt, so we'll cut it off at the upper limit
271
str2 = str2.substring(0, upper);
272                 loc = upper;
273             }
274             // the string was truncated, so we append the appendToEnd String
275
str = str2 + appendToEnd;
276         }
277         return str;
278     }
279     
280     public static String JavaDoc hexEncode(String JavaDoc str) {
281         if (StringUtils.isEmpty(str)) return str;
282         
283         return RegexUtil.encode(str);
284     }
285     
286     public static String JavaDoc encodeEmail(String JavaDoc str) {
287         return str!=null ? RegexUtil.encodeEmail(str) : null;
288     }
289     
290     /**
291      * URL encoding.
292      * @param s a string to be URL-encoded
293      * @return URL encoding of s using character encoding UTF-8; null if s is null.
294      */

295     public static final String JavaDoc encode(String JavaDoc s) {
296         try {
297             if (s != null)
298                 return URLEncoder.encode(s, "UTF-8");
299             else
300                 return s;
301         } catch (UnsupportedEncodingException JavaDoc e) {
302             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
303
return s;
304         }
305     }
306     
307     /**
308      * URL decoding.
309      * @param s a URL-encoded string to be URL-decoded
310      * @return URL decoded value of s using character encoding UTF-8; null if s is null.
311      */

312     public static final String JavaDoc decode(String JavaDoc s) {
313         try {
314             if (s != null)
315                 return URLDecoder.decode(s, "UTF-8");
316             else
317                 return s;
318         } catch (UnsupportedEncodingException JavaDoc e) {
319             // Java Spec requires UTF-8 be in all Java environments, so this should not happen
320
return s;
321         }
322     }
323         
324     /**
325      * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML.
326      */

327     public static String JavaDoc addNofollow(String JavaDoc html) {
328         if (html == null || html.length() == 0) {
329             return html;
330         }
331         Matcher JavaDoc m = mLinkPattern.matcher(html);
332         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
333         while (m.find()) {
334             int start = m.start();
335             int end = m.end();
336             String JavaDoc link = html.substring(start, end);
337             buf.append(html.substring(0, start));
338             if (link.indexOf("rel=\"nofollow\"") == -1) {
339                 buf.append(
340                         link.substring(0, link.length() - 1) + " rel=\"nofollow\">");
341             } else {
342                 buf.append(link);
343             }
344             html = html.substring(end, html.length());
345             m = mLinkPattern.matcher(html);
346         }
347         buf.append(html);
348         return buf.toString();
349     }
350     
351     /**
352      * Transforms the given String into a subset of HTML displayable on a web
353      * page. The subset includes &lt;b&gt;, &lt;i&gt;, &lt;p&gt;, &lt;br&gt;,
354      * &lt;pre&gt; and &lt;a href&gt; (and their corresponding end tags).
355      *
356      * @param s the String to transform
357      * @return the transformed String
358      */

359     public static String JavaDoc transformToHTMLSubset(String JavaDoc s) {
360         
361         if (s == null) {
362             return null;
363         }
364         
365         s = replace(s, OPENING_B_TAG_PATTERN, "<b>");
366         s = replace(s, CLOSING_B_TAG_PATTERN, "</b>");
367         s = replace(s, OPENING_I_TAG_PATTERN, "<i>");
368         s = replace(s, CLOSING_I_TAG_PATTERN, "</i>");
369         s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>");
370         s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>");
371         s = replace(s, BR_TAG_PATTERN, "<br />");
372         s = replace(s, OPENING_P_TAG_PATTERN, "<p>");
373         s = replace(s, CLOSING_P_TAG_PATTERN, "</p>");
374         s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>");
375         s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>");
376         s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>");
377         s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>");
378         s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>");
379         s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>");
380         s = replace(s, OPENING_LI_TAG_PATTERN, "<li>");
381         s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>");
382         s = replace(s, QUOTE_PATTERN, "\"");
383         
384         // HTTP links
385
s = replace(s, CLOSING_A_TAG_PATTERN, "</a>");
386         Matcher JavaDoc m = OPENING_A_TAG_PATTERN.matcher(s);
387         while (m.find()) {
388             int start = m.start();
389             int end = m.end();
390             String JavaDoc link = s.substring(start, end);
391             link = "<" + link.substring(4, link.length() - 4) + ">";
392             s = s.substring(0, start) + link + s.substring(end, s.length());
393             m = OPENING_A_TAG_PATTERN.matcher(s);
394         }
395         
396         // escaped angle brackets
397
s = s.replaceAll("&amp;lt;", "&lt;");
398         s = s.replaceAll("&amp;gt;", "&gt;");
399         s = s.replaceAll("&amp;#", "&#");
400         
401         return s;
402     }
403     
404     private static String JavaDoc replace(String JavaDoc string, Pattern JavaDoc pattern, String JavaDoc replacement) {
405         Matcher JavaDoc m = pattern.matcher(string);
406         return m.replaceAll(replacement);
407     }
408     
409     /**
410      * Convert a byte array into a Base64 string (as used in mime formats)
411      */

412     public static String JavaDoc toBase64(byte[] aValue) {
413         
414         final String JavaDoc m_strBase64Chars =
415                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
416         
417         int byte1;
418         int byte2;
419         int byte3;
420         int iByteLen = aValue.length;
421         StringBuffer JavaDoc tt = new StringBuffer JavaDoc();
422         
423         for (int i = 0; i < iByteLen; i += 3) {
424             boolean bByte2 = (i + 1) < iByteLen;
425             boolean bByte3 = (i + 2) < iByteLen;
426             byte1 = aValue[i] & 0xFF;
427             byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
428             byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
429             
430             tt.append(m_strBase64Chars.charAt(byte1 / 4));
431             tt.append(m_strBase64Chars.charAt((byte2 / 16) + ((byte1 & 0x3) * 16)));
432             tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64) + ((byte2 & 0xF) * 4)) : '='));
433             tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F) : '='));
434         }
435         
436         return tt.toString();
437     }
438     
439     
440     //------------------------------------------------------------------------
441
/**
442      * Escape, but do not replace HTML.
443      * @param escapeAmpersand Optionally escape
444      * ampersands (&amp;).
445      */

446     public static String JavaDoc escapeHTML(String JavaDoc s, boolean escapeAmpersand) {
447         return Utilities.escapeHTML(s, escapeAmpersand);
448     }
449                 
450     //------------------------------------------------------------------------
451
/**
452      * Replace occurrences of str1 in string str with str2
453      */

454     public static String JavaDoc stringReplace(String JavaDoc str, String JavaDoc str1, String JavaDoc str2) {
455         String JavaDoc ret = StringUtils.replace(str,str1,str2);
456         return ret;
457     }
458     
459     //------------------------------------------------------------------------
460
/**
461      * Replace occurrences of str1 in string str with str2
462      * @param str String to operate on
463      * @param str1 String to be replaced
464      * @param str2 String to be used as replacement
465      * @param maxCount Number of times to replace, 0 for all
466      */

467     public static String JavaDoc stringReplace(
468             String JavaDoc str,
469             String JavaDoc str1,
470             String JavaDoc str2,
471             int maxCount) {
472         String JavaDoc ret = StringUtils.replace(str,str1,str2,maxCount);
473         return ret;
474     }
475         
476
477     
478     /**
479      * Encode a string using Base64 encoding. Used when storing passwords
480      * as cookies.
481      *
482      * This is weak encoding in that anyone can use the decodeString
483      * routine to reverse the encoding.
484      *
485      * @param str
486      * @return String
487      * @throws IOException
488      */

489     public static String JavaDoc encodeString(String JavaDoc str) throws IOException JavaDoc {
490         sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
491         String JavaDoc encodedStr = encoder.encodeBuffer(str.getBytes());
492         
493         return (encodedStr.trim());
494     }
495     
496     /**
497      * Decode a string using Base64 encoding.
498      *
499      * @param str
500      * @return String
501      * @throws IOException
502      */

503     public static String JavaDoc decodeString(String JavaDoc str) throws IOException JavaDoc {
504         sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
505         String JavaDoc value = new String JavaDoc(dec.decodeBuffer(str));
506         
507         return (value);
508     }
509                
510     /**
511      * @param str
512      * @return
513      */

514     private static String JavaDoc stripLineBreaks(String JavaDoc str) {
515         // TODO: use a string buffer, ignore case !
516
str = str.replaceAll("<br>", "");
517         str = str.replaceAll("<br/>", "");
518         str = str.replaceAll("<br />", "");
519         str = str.replaceAll("<p></p>", "");
520         str = str.replaceAll("<p/>","");
521         str = str.replaceAll("<p />","");
522         return str;
523     }
524     
525     /**
526      * Need need to get rid of any user-visible HTML tags once all text has been
527      * removed such as &lt;BR&gt;. This sounds like a better approach than removing
528      * all HTML tags and taking the chance to leave some tags un-closed.
529      *
530      * WARNING: this method has serious performance problems a
531      *
532      * @author Alexis Moussine-Pouchkine <alexis.moussine-pouchkine@france.sun.com>
533      * @author Lance Lavandowska
534      * @param str the String object to modify
535      * @return the new String object without the HTML "visible" tags
536      */

537     private static String JavaDoc removeVisibleHTMLTags(String JavaDoc str) {
538         str = stripLineBreaks(str);
539         StringBuffer JavaDoc result = new StringBuffer JavaDoc(str);
540         StringBuffer JavaDoc lcresult = new StringBuffer JavaDoc(str.toLowerCase());
541         
542         // <img should take care of smileys
543
String JavaDoc[] visibleTags = {"<img"}; // are there others to add?
544
int stringIndex;
545         for ( int j = 0 ; j < visibleTags.length ; j++ ) {
546             while ( (stringIndex = lcresult.indexOf(visibleTags[j])) != -1 ) {
547                 if ( visibleTags[j].endsWith(">") ) {
548                     result.delete(stringIndex, stringIndex+visibleTags[j].length() );
549                     lcresult.delete(stringIndex, stringIndex+visibleTags[j].length() );
550                 } else {
551                     // need to delete everything up until next closing '>', for <img for instance
552
int endIndex = result.indexOf(">", stringIndex);
553                     if (endIndex > -1) {
554                         // only delete it if we find the end! If we don't the HTML may be messed up, but we
555
// can't safely delete anything.
556
result.delete(stringIndex, endIndex + 1 );
557                         lcresult.delete(stringIndex, endIndex + 1 );
558                     }
559                 }
560             }
561         }
562         
563         // TODO: This code is buggy by nature. It doesn't deal with nesting of tags properly.
564
// remove certain elements with open & close tags
565
String JavaDoc[] openCloseTags = {"li", "a", "div", "h1", "h2", "h3", "h4"}; // more ?
566
for (int j = 0; j < openCloseTags.length; j++) {
567             // could this be better done with a regular expression?
568
String JavaDoc closeTag = "</"+openCloseTags[j]+">";
569             int lastStringIndex = 0;
570             while ( (stringIndex = lcresult.indexOf( "<"+openCloseTags[j], lastStringIndex)) > -1) {
571                 lastStringIndex = stringIndex;
572                 // Try to find the matching closing tag (ignores possible nesting!)
573
int endIndex = lcresult.indexOf(closeTag, stringIndex);
574                 if (endIndex > -1) {
575                     // If we found it delete it.
576
result.delete(stringIndex, endIndex+closeTag.length());
577                     lcresult.delete(stringIndex, endIndex+closeTag.length());
578                 } else {
579                     // Try to see if it is a self-closed empty content tag, i.e. closed with />.
580
endIndex = lcresult.indexOf(">", stringIndex);
581                     int nextStart = lcresult.indexOf("<", stringIndex+1);
582                     if (endIndex > stringIndex && lcresult.charAt(endIndex-1) == '/' && (endIndex < nextStart || nextStart == -1)) {
583                         // Looks like it, so remove it.
584
result.delete(stringIndex, endIndex + 1);
585                         lcresult.delete(stringIndex, endIndex + 1);
586                         
587                     }
588                 }
589             }
590         }
591         
592         return result.toString();
593     }
594     
595     
596     /**
597      * Converts a character to HTML or XML entity.
598      *
599      * @param ch The character to convert.
600      * @param xml Convert the character to XML if set to true.
601      * @author Erik C. Thauvin
602      *
603      * @return The converted string.
604      */

605     public static final String JavaDoc charToHTML(char ch, boolean xml) {
606         int c;
607         
608         // Convert left bracket
609
if (ch == '<') {
610             return ("&lt;");
611         }
612         
613         // Convert left bracket
614
else if (ch == '>') {
615             return ("&gt;");
616         }
617         
618         // Convert ampersand
619
else if (ch == '&') {
620             return ("&amp;");
621         }
622         
623         // Commented out to eliminate redundant numeric character codes (ROL-507)
624
// High-ASCII character
625
//else if (ch >= 128)
626
//{
627
//c = ch;
628
//return ("&#" + c + ';');
629
//}
630

631         // Convert double quote
632
else if (xml && (ch == '"')) {
633             return ("&quot;");
634         }
635         
636         // Convert single quote
637
else if (xml && (ch == '\'')) {
638             return ("&#39;");
639         }
640         
641         // No conversion
642
else {
643             // Return character as string
644
return (String.valueOf(ch));
645         }
646     }
647     
648     /**
649      * Converts a text string to HTML or XML entities.
650      *
651      * @author Erik C. Thauvin
652      * @param text The string to convert.
653      * @param xml Convert the string to XML if set to true.
654      *
655      * @return The converted string.
656      */

657     public static final String JavaDoc textToHTML(String JavaDoc text, boolean xml) {
658         if (text == null) return "null";
659         final StringBuffer JavaDoc html = new StringBuffer JavaDoc();
660         
661         // Loop thru each characters of the text
662
for (int i = 0; i < text.length(); i++) {
663             // Convert character to HTML/XML
664
html.append(charToHTML(text.charAt(i), xml));
665         }
666         
667         // Return HTML/XML string
668
return html.toString();
669     }
670     
671     /**
672      * Converts a text string to HTML or XML entities.
673      *
674      * @param text The string to convert.
675      * @author Erik C. Thauvin
676      * @return The converted string.
677      */

678     public static final String JavaDoc textToHTML(String JavaDoc text) {
679         return textToHTML(text, false);
680     }
681     
682     /**
683      * Converts a text string to XML entities.
684      *
685      * @param text The string to convert.
686      * @author Erik C. Thauvin
687      * @return The converted string.
688      */

689     public static final String JavaDoc textToXML(String JavaDoc text) {
690         return textToHTML(text, true);
691     }
692     
693     /**
694      * Converts a text string to HTML or XML entities.
695      * @param text The string to convert.
696      * @return The converted string.
697      */

698     public static final String JavaDoc textToCDATA(String JavaDoc text) {
699         if (text == null) return "null";
700         final StringBuffer JavaDoc html = new StringBuffer JavaDoc();
701         
702         // Loop thru each characters of the text
703
for (int i = 0; i < text.length(); i++) {
704             // Convert character to HTML/XML
705
html.append(charToCDATA(text.charAt(i)));
706         }
707         
708         // Return HTML/XML string
709
return html.toString();
710     }
711     
712     /**
713      * Converts a character to CDATA character.
714      * @param ch The character to convert.
715      * @return The converted string.
716      */

717     public static final String JavaDoc charToCDATA(char ch) {
718         int c;
719         
720         if (ch >= 128) {
721             c = ch;
722             
723             return ("&#" + c + ';');
724         }
725         
726         // No conversion
727
else {
728             // Return character as string
729
return (String.valueOf(ch));
730         }
731     }
732     
733 }
734
Popular Tags