Source Code Cross Referenced for OldUtilities.java in  » Blogger-System » apache-roller-3.1 » org » apache » roller » ui » rendering » velocity » deprecated » Java Source Code / Java DocumentationJava Source Code and Java Documentation

Java Source Code / Java Documentation
1. 6.0 JDK Core
2. 6.0 JDK Modules
3. 6.0 JDK Modules com.sun
4. 6.0 JDK Modules com.sun.java
5. 6.0 JDK Modules sun
6. 6.0 JDK Platform
7. Ajax
8. Apache Harmony Java SE
9. Aspect oriented
10. Authentication Authorization
11. Blogger System
12. Build
13. Byte Code
14. Cache
15. Chart
16. Chat
17. Code Analyzer
18. Collaboration
19. Content Management System
20. Database Client
21. Database DBMS
22. Database JDBC Connection Pool
23. Database ORM
24. Development
25. EJB Server geronimo
26. EJB Server GlassFish
27. EJB Server JBoss 4.2.1
28. EJB Server resin 3.1.5
29. ERP CRM Financial
30. ESB
31. Forum
32. GIS
33. Graphic Library
34. Groupware
35. HTML Parser
36. IDE
37. IDE Eclipse
38. IDE Netbeans
39. Installer
40. Internationalization Localization
41. Inversion of Control
42. Issue Tracking
43. J2EE
44. JBoss
45. JMS
46. JMX
47. Library
48. Mail Clients
49. Net
50. Parser
51. PDF
52. Portal
53. Profiler
54. Project Management
55. Report
56. RSS RDF
57. Rule Engine
58. Science
59. Scripting
60. Search Engine
61. Security
62. Sevlet Container
63. Source Control
64. Swing Library
65. Template Engine
66. Test Coverage
67. Testing
68. UML
69. Web Crawler
70. Web Framework
71. Web Mail
72. Web Server
73. Web Services
74. Web Services apache cxf 2.0.1
75. Web Services AXIS2
76. Wiki Engine
77. Workflow Engines
78. XML
79. XML UI
Java
Java Tutorial
Java Open Source
Jar File Download
Java Articles
Java Products
Java by API
Photoshop Tutorials
Maya Tutorials
Flash Tutorials
3ds-Max Tutorials
Illustrator Tutorials
GIMP Tutorials
C# / C Sharp
C# / CSharp Tutorial
C# / CSharp Open Source
ASP.Net
ASP.NET Tutorial
JavaScript DHTML
JavaScript Tutorial
JavaScript Reference
HTML / CSS
HTML CSS Reference
C / ANSI-C
C Tutorial
C++
C++ Tutorial
Ruby
PHP
Python
Python Tutorial
Python Open Source
SQL Server / T-SQL
SQL Server / T-SQL Tutorial
Oracle PL / SQL
Oracle PL/SQL Tutorial
PostgreSQL
SQL / MySQL
MySQL Tutorial
VB.Net
VB.Net Tutorial
Flash / Flex / ActionScript
VBA / Excel / Access / Word
XML
XML Tutorial
Microsoft Office PowerPoint 2007 Tutorial
Microsoft Office Excel 2007 Tutorial
Microsoft Office Word 2007 Tutorial
Java Source Code / Java Documentation » Blogger System » apache roller 3.1 » org.apache.roller.ui.rendering.velocity.deprecated 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * Licensed to the Apache Software Foundation (ASF) under one or more
003:         *  contributor license agreements.  The ASF licenses this file to You
004:         * under the Apache License, Version 2.0 (the "License"); you may not
005:         * use this file except in compliance with the License.
006:         * You may obtain a copy of the License at
007:         *
008:         *     http://www.apache.org/licenses/LICENSE-2.0
009:         *
010:         * Unless required by applicable law or agreed to in writing, software
011:         * distributed under the License is distributed on an "AS IS" BASIS,
012:         * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013:         * See the License for the specific language governing permissions and
014:         * limitations under the License.  For additional information regarding
015:         * copyright in this work, please see the NOTICE file in the top level
016:         * directory of this distribution.
017:         */
018:        package org.apache.roller.ui.rendering.velocity.deprecated;
019:
020:        import java.io.IOException;
021:        import java.io.UnsupportedEncodingException;
022:        import java.net.URLDecoder;
023:        import java.net.URLEncoder;
024:        import java.text.SimpleDateFormat;
025:        import java.util.Date;
026:        import java.util.regex.Matcher;
027:        import java.util.regex.Pattern;
028:        import org.apache.commons.lang.StringEscapeUtils;
029:        import org.apache.commons.lang.StringUtils;
030:        import org.apache.commons.logging.Log;
031:        import org.apache.commons.logging.LogFactory;
032:        import org.apache.roller.util.DateUtil;
033:        import org.apache.roller.util.RegexUtil;
034:        import org.apache.roller.util.Utilities;
035:
036:        /**
037:         * Utility methods needed by old Roller 2.X macros/templates.
038:         * Deprecated because they are either redundant or unnecesary.
039:         */
040:        public class OldUtilities {
041:
042:            /** The <code>Log</code> instance for this class. */
043:            private static Log mLogger = LogFactory.getLog(OldUtilities.class);
044:
045:            private static Pattern mLinkPattern = Pattern.compile(
046:                    "<a href=.*?>", Pattern.CASE_INSENSITIVE);
047:            private static final Pattern OPENING_B_TAG_PATTERN = Pattern
048:                    .compile("&lt;b&gt;", Pattern.CASE_INSENSITIVE);
049:            private static final Pattern CLOSING_B_TAG_PATTERN = Pattern
050:                    .compile("&lt;/b&gt;", Pattern.CASE_INSENSITIVE);
051:            private static final Pattern OPENING_I_TAG_PATTERN = Pattern
052:                    .compile("&lt;i&gt;", Pattern.CASE_INSENSITIVE);
053:            private static final Pattern CLOSING_I_TAG_PATTERN = Pattern
054:                    .compile("&lt;/i&gt;", Pattern.CASE_INSENSITIVE);
055:            private static final Pattern OPENING_BLOCKQUOTE_TAG_PATTERN = Pattern
056:                    .compile("&lt;blockquote&gt;", Pattern.CASE_INSENSITIVE);
057:            private static final Pattern CLOSING_BLOCKQUOTE_TAG_PATTERN = Pattern
058:                    .compile("&lt;/blockquote&gt;", Pattern.CASE_INSENSITIVE);
059:            private static final Pattern BR_TAG_PATTERN = Pattern.compile(
060:                    "&lt;br */*&gt;", Pattern.CASE_INSENSITIVE);
061:            private static final Pattern OPENING_P_TAG_PATTERN = Pattern
062:                    .compile("&lt;p&gt;", Pattern.CASE_INSENSITIVE);
063:            private static final Pattern CLOSING_P_TAG_PATTERN = Pattern
064:                    .compile("&lt;/p&gt;", Pattern.CASE_INSENSITIVE);
065:            private static final Pattern OPENING_PRE_TAG_PATTERN = Pattern
066:                    .compile("&lt;pre&gt;", Pattern.CASE_INSENSITIVE);
067:            private static final Pattern CLOSING_PRE_TAG_PATTERN = Pattern
068:                    .compile("&lt;/pre&gt;", Pattern.CASE_INSENSITIVE);
069:            private static final Pattern OPENING_UL_TAG_PATTERN = Pattern
070:                    .compile("&lt;ul&gt;", Pattern.CASE_INSENSITIVE);
071:            private static final Pattern CLOSING_UL_TAG_PATTERN = Pattern
072:                    .compile("&lt;/ul&gt;", Pattern.CASE_INSENSITIVE);
073:            private static final Pattern OPENING_OL_TAG_PATTERN = Pattern
074:                    .compile("&lt;ol&gt;", Pattern.CASE_INSENSITIVE);
075:            private static final Pattern CLOSING_OL_TAG_PATTERN = Pattern
076:                    .compile("&lt;/ol&gt;", Pattern.CASE_INSENSITIVE);
077:            private static final Pattern OPENING_LI_TAG_PATTERN = Pattern
078:                    .compile("&lt;li&gt;", Pattern.CASE_INSENSITIVE);
079:            private static final Pattern CLOSING_LI_TAG_PATTERN = Pattern
080:                    .compile("&lt;/li&gt;", Pattern.CASE_INSENSITIVE);
081:            private static final Pattern CLOSING_A_TAG_PATTERN = Pattern
082:                    .compile("&lt;/a&gt;", Pattern.CASE_INSENSITIVE);
083:            private static final Pattern OPENING_A_TAG_PATTERN = Pattern
084:                    .compile("&lt;a href=.*?&gt;", Pattern.CASE_INSENSITIVE);
085:            private static final Pattern QUOTE_PATTERN = Pattern.compile(
086:                    "&quot;", Pattern.CASE_INSENSITIVE);
087:
088:            public static boolean isEmpty(String str) {
089:                if (str == null)
090:                    return true;
091:                return "".equals(str.trim());
092:            }
093:
094:            public static boolean isNotEmpty(String str) {
095:                return !isEmpty(str);
096:            }
097:
098:            public static String[] split(String str1, String str2) {
099:                return StringUtils.split(str1, str2);
100:            }
101:
102:            public static String replace(String src, String target, String rWith) {
103:                return StringUtils.replace(src, target, rWith);
104:            }
105:
106:            public static String replace(String src, String target,
107:                    String rWith, int maxCount) {
108:                return StringUtils.replace(src, target, rWith, maxCount);
109:            }
110:
111:            public static boolean equals(String str1, String str2) {
112:                return StringUtils.equals(str1, str2);
113:            }
114:
115:            public static boolean isAlphanumeric(String str) {
116:                return StringUtils.isAlphanumeric(str);
117:            }
118:
119:            public static String[] stripAll(String[] strs) {
120:                return StringUtils.stripAll(strs);
121:            }
122:
123:            public static String left(String str, int length) {
124:                return StringUtils.left(str, length);
125:            }
126:
127:            public static String escapeHTML(String str) {
128:                return StringEscapeUtils.escapeHtml(str);
129:            }
130:
131:            public static String unescapeHTML(String str) {
132:                return StringEscapeUtils.unescapeHtml(str);
133:            }
134:
135:            /**
136:             * Remove occurences of html, defined as any text
137:             * between the characters "&lt;" and "&gt;".  Replace
138:             * any HTML tags with a space.
139:             */
140:            public static String removeHTML(String str) {
141:                return removeHTML(str, true);
142:            }
143:
144:            /**
145:             * Remove occurences of html, defined as any text
146:             * between the characters "&lt;" and "&gt;".
147:             * Optionally replace HTML tags with a space.
148:             */
149:            public static String removeHTML(String str, boolean addSpace) {
150:                return Utilities.removeHTML(str, addSpace);
151:            }
152:
153:            /**
154:             * Autoformat.
155:             */
156:            public static String autoformat(String s) {
157:                String ret = StringUtils.replace(s, "\n", "<br />");
158:                return ret;
159:            }
160:
161:            /**
162:             * Return date for current time.
163:             */
164:            public static Date getNow() {
165:                return new Date();
166:            }
167:
168:            /**
169:             * Format date using SimpleDateFormat format string.
170:             */
171:            public static String formatDate(Date d, String fmt) {
172:                SimpleDateFormat format = new SimpleDateFormat(fmt);
173:                return format.format(d);
174:            }
175:
176:            /**
177:             * Format date in ISO-8601 format.
178:             */
179:            public static String formatIso8601Date(Date d) {
180:                return DateUtil.formatIso8601(d);
181:            }
182:
183:            /**
184:             * Format date in ISO-8601 format.
185:             */
186:            public static String formatIso8601Day(Date d) {
187:                return DateUtil.formatIso8601Day(d);
188:            }
189:
190:            /**
191:             * Return a date in RFC-822 format.
192:             */
193:            public static String formatRfc822Date(Date date) {
194:                return DateUtil.formatRfc822(date);
195:            }
196:
197:            /**
198:             * Return a date in RFC-822 format.
199:             */
200:            public static String format8charsDate(Date date) {
201:                return DateUtil.format8chars(date);
202:            }
203:
204:            /**
205:             * Strips HTML and truncates.
206:             */
207:            public static String truncate(String str, int lower, int upper,
208:                    String appendToEnd) {
209:                // strip markup from the string
210:                String str2 = removeHTML(str, false);
211:
212:                // quickly adjust the upper if it is set lower than 'lower'
213:                if (upper < lower) {
214:                    upper = lower;
215:                }
216:
217:                // now determine if the string fits within the upper limit
218:                // if it does, go straight to return, do not pass 'go' and collect $200
219:                if (str2.length() > upper) {
220:                    // the magic location int
221:                    int loc;
222:
223:                    // first we determine where the next space appears after lower
224:                    loc = str2.lastIndexOf(' ', upper);
225:
226:                    // now we'll see if the location is greater than the lower limit
227:                    if (loc >= lower) {
228:                        // yes it was, so we'll cut it off here
229:                        str2 = str2.substring(0, loc);
230:                    } else {
231:                        // no it wasnt, so we'll cut it off at the upper limit
232:                        str2 = str2.substring(0, upper);
233:                        loc = upper;
234:                    }
235:
236:                    // the string was truncated, so we append the appendToEnd String
237:                    str2 = str2 + appendToEnd;
238:                }
239:
240:                return str2;
241:            }
242:
243:            public static String truncateNicely(String str, int lower,
244:                    int upper, String appendToEnd) {
245:                return Utilities.truncateNicely(str, lower, upper, appendToEnd);
246:            }
247:
248:            public static String truncateText(String str, int lower, int upper,
249:                    String appendToEnd) {
250:                // strip markup from the string
251:                String str2 = removeHTML(str, false);
252:                boolean diff = (str2.length() < str.length());
253:
254:                // quickly adjust the upper if it is set lower than 'lower'
255:                if (upper < lower) {
256:                    upper = lower;
257:                }
258:
259:                // now determine if the string fits within the upper limit
260:                // if it does, go straight to return, do not pass 'go' and collect $200
261:                if (str2.length() > upper) {
262:                    // the magic location int
263:                    int loc;
264:
265:                    // first we determine where the next space appears after lower
266:                    loc = str2.lastIndexOf(' ', upper);
267:
268:                    // now we'll see if the location is greater than the lower limit
269:                    if (loc >= lower) {
270:                        // yes it was, so we'll cut it off here
271:                        str2 = str2.substring(0, loc);
272:                    } else {
273:                        // no it wasnt, so we'll cut it off at the upper limit
274:                        str2 = str2.substring(0, upper);
275:                        loc = upper;
276:                    }
277:                    // the string was truncated, so we append the appendToEnd String
278:                    str = str2 + appendToEnd;
279:                }
280:                return str;
281:            }
282:
283:            public static String hexEncode(String str) {
284:                if (StringUtils.isEmpty(str))
285:                    return str;
286:
287:                return RegexUtil.encode(str);
288:            }
289:
290:            public static String encodeEmail(String str) {
291:                return str != null ? RegexUtil.encodeEmail(str) : null;
292:            }
293:
294:            /**
295:             * URL encoding.
296:             * @param s a string to be URL-encoded
297:             * @return URL encoding of s using character encoding UTF-8; null if s is null.
298:             */
299:            public static final String encode(String s) {
300:                try {
301:                    if (s != null)
302:                        return URLEncoder.encode(s, "UTF-8");
303:                    else
304:                        return s;
305:                } catch (UnsupportedEncodingException e) {
306:                    // Java Spec requires UTF-8 be in all Java environments, so this should not happen
307:                    return s;
308:                }
309:            }
310:
311:            /**
312:             * URL decoding.
313:             * @param s a URL-encoded string to be URL-decoded
314:             * @return URL decoded value of s using character encoding UTF-8; null if s is null.
315:             */
316:            public static final String decode(String s) {
317:                try {
318:                    if (s != null)
319:                        return URLDecoder.decode(s, "UTF-8");
320:                    else
321:                        return s;
322:                } catch (UnsupportedEncodingException e) {
323:                    // Java Spec requires UTF-8 be in all Java environments, so this should not happen
324:                    return s;
325:                }
326:            }
327:
328:            /**
329:             * Code (stolen from Pebble) to add rel="nofollow" string to all links in HTML.
330:             */
331:            public static String addNofollow(String html) {
332:                if (html == null || html.length() == 0) {
333:                    return html;
334:                }
335:                Matcher m = mLinkPattern.matcher(html);
336:                StringBuffer buf = new StringBuffer();
337:                while (m.find()) {
338:                    int start = m.start();
339:                    int end = m.end();
340:                    String link = html.substring(start, end);
341:                    buf.append(html.substring(0, start));
342:                    if (link.indexOf("rel=\"nofollow\"") == -1) {
343:                        buf.append(link.substring(0, link.length() - 1)
344:                                + " rel=\"nofollow\">");
345:                    } else {
346:                        buf.append(link);
347:                    }
348:                    html = html.substring(end, html.length());
349:                    m = mLinkPattern.matcher(html);
350:                }
351:                buf.append(html);
352:                return buf.toString();
353:            }
354:
355:            /**
356:             * Transforms the given String into a subset of HTML displayable on a web
357:             * page. The subset includes &lt;b&gt;, &lt;i&gt;, &lt;p&gt;, &lt;br&gt;,
358:             * &lt;pre&gt; and &lt;a href&gt; (and their corresponding end tags).
359:             *
360:             * @param s   the String to transform
361:             * @return    the transformed String
362:             */
363:            public static String transformToHTMLSubset(String s) {
364:
365:                if (s == null) {
366:                    return null;
367:                }
368:
369:                s = replace(s, OPENING_B_TAG_PATTERN, "<b>");
370:                s = replace(s, CLOSING_B_TAG_PATTERN, "</b>");
371:                s = replace(s, OPENING_I_TAG_PATTERN, "<i>");
372:                s = replace(s, CLOSING_I_TAG_PATTERN, "</i>");
373:                s = replace(s, OPENING_BLOCKQUOTE_TAG_PATTERN, "<blockquote>");
374:                s = replace(s, CLOSING_BLOCKQUOTE_TAG_PATTERN, "</blockquote>");
375:                s = replace(s, BR_TAG_PATTERN, "<br />");
376:                s = replace(s, OPENING_P_TAG_PATTERN, "<p>");
377:                s = replace(s, CLOSING_P_TAG_PATTERN, "</p>");
378:                s = replace(s, OPENING_PRE_TAG_PATTERN, "<pre>");
379:                s = replace(s, CLOSING_PRE_TAG_PATTERN, "</pre>");
380:                s = replace(s, OPENING_UL_TAG_PATTERN, "<ul>");
381:                s = replace(s, CLOSING_UL_TAG_PATTERN, "</ul>");
382:                s = replace(s, OPENING_OL_TAG_PATTERN, "<ol>");
383:                s = replace(s, CLOSING_OL_TAG_PATTERN, "</ol>");
384:                s = replace(s, OPENING_LI_TAG_PATTERN, "<li>");
385:                s = replace(s, CLOSING_LI_TAG_PATTERN, "</li>");
386:                s = replace(s, QUOTE_PATTERN, "\"");
387:
388:                // HTTP links
389:                s = replace(s, CLOSING_A_TAG_PATTERN, "</a>");
390:                Matcher m = OPENING_A_TAG_PATTERN.matcher(s);
391:                while (m.find()) {
392:                    int start = m.start();
393:                    int end = m.end();
394:                    String link = s.substring(start, end);
395:                    link = "<" + link.substring(4, link.length() - 4) + ">";
396:                    s = s.substring(0, start) + link
397:                            + s.substring(end, s.length());
398:                    m = OPENING_A_TAG_PATTERN.matcher(s);
399:                }
400:
401:                // escaped angle brackets
402:                s = s.replaceAll("&amp;lt;", "&lt;");
403:                s = s.replaceAll("&amp;gt;", "&gt;");
404:                s = s.replaceAll("&amp;#", "&#");
405:
406:                return s;
407:            }
408:
409:            private static String replace(String string, Pattern pattern,
410:                    String replacement) {
411:                Matcher m = pattern.matcher(string);
412:                return m.replaceAll(replacement);
413:            }
414:
415:            /**
416:             * Convert a byte array into a Base64 string (as used in mime formats)
417:             */
418:            public static String toBase64(byte[] aValue) {
419:
420:                final String m_strBase64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
421:
422:                int byte1;
423:                int byte2;
424:                int byte3;
425:                int iByteLen = aValue.length;
426:                StringBuffer tt = new StringBuffer();
427:
428:                for (int i = 0; i < iByteLen; i += 3) {
429:                    boolean bByte2 = (i + 1) < iByteLen;
430:                    boolean bByte3 = (i + 2) < iByteLen;
431:                    byte1 = aValue[i] & 0xFF;
432:                    byte2 = (bByte2) ? (aValue[i + 1] & 0xFF) : 0;
433:                    byte3 = (bByte3) ? (aValue[i + 2] & 0xFF) : 0;
434:
435:                    tt.append(m_strBase64Chars.charAt(byte1 / 4));
436:                    tt.append(m_strBase64Chars.charAt((byte2 / 16)
437:                            + ((byte1 & 0x3) * 16)));
438:                    tt.append(((bByte2) ? m_strBase64Chars.charAt((byte3 / 64)
439:                            + ((byte2 & 0xF) * 4)) : '='));
440:                    tt.append(((bByte3) ? m_strBase64Chars.charAt(byte3 & 0x3F)
441:                            : '='));
442:                }
443:
444:                return tt.toString();
445:            }
446:
447:            //------------------------------------------------------------------------
448:            /**
449:             * Escape, but do not replace HTML.
450:             * @param escapeAmpersand Optionally escape
451:             * ampersands (&amp;).
452:             */
453:            public static String escapeHTML(String s, boolean escapeAmpersand) {
454:                return Utilities.escapeHTML(s, escapeAmpersand);
455:            }
456:
457:            //------------------------------------------------------------------------
458:            /**
459:             * Replace occurrences of str1 in string str with str2
460:             */
461:            public static String stringReplace(String str, String str1,
462:                    String str2) {
463:                String ret = StringUtils.replace(str, str1, str2);
464:                return ret;
465:            }
466:
467:            //------------------------------------------------------------------------
468:            /**
469:             * Replace occurrences of str1 in string str with str2
470:             * @param str String to operate on
471:             * @param str1 String to be replaced
472:             * @param str2 String to be used as replacement
473:             * @param maxCount Number of times to replace, 0 for all
474:             */
475:            public static String stringReplace(String str, String str1,
476:                    String str2, int maxCount) {
477:                String ret = StringUtils.replace(str, str1, str2, maxCount);
478:                return ret;
479:            }
480:
481:            /**
482:             * Encode a string using Base64 encoding. Used when storing passwords
483:             * as cookies.
484:             *
485:             * This is weak encoding in that anyone can use the decodeString
486:             * routine to reverse the encoding.
487:             *
488:             * @param str
489:             * @return String
490:             * @throws IOException
491:             */
492:            public static String encodeString(String str) throws IOException {
493:                sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
494:                String encodedStr = encoder.encodeBuffer(str.getBytes());
495:
496:                return (encodedStr.trim());
497:            }
498:
499:            /**
500:             * Decode a string using Base64 encoding.
501:             *
502:             * @param str
503:             * @return String
504:             * @throws IOException
505:             */
506:            public static String decodeString(String str) throws IOException {
507:                sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
508:                String value = new String(dec.decodeBuffer(str));
509:
510:                return (value);
511:            }
512:
513:            /**
514:             * @param str
515:             * @return
516:             */
517:            private static String stripLineBreaks(String str) {
518:                // TODO: use a string buffer, ignore case !
519:                str = str.replaceAll("<br>", "");
520:                str = str.replaceAll("<br/>", "");
521:                str = str.replaceAll("<br />", "");
522:                str = str.replaceAll("<p></p>", "");
523:                str = str.replaceAll("<p/>", "");
524:                str = str.replaceAll("<p />", "");
525:                return str;
526:            }
527:
528:            /**
529:             * Need need to get rid of any user-visible HTML tags once all text has been
530:             * removed such as &lt;BR&gt;. This sounds like a better approach than removing
531:             * all HTML tags and taking the chance to leave some tags un-closed.
532:             *
533:             * WARNING: this method has serious performance problems a
534:             *
535:             * @author Alexis Moussine-Pouchkine <alexis.moussine-pouchkine@france.sun.com>
536:             * @author Lance Lavandowska
537:             * @param str the String object to modify
538:             * @return the new String object without the HTML "visible" tags
539:             */
540:            private static String removeVisibleHTMLTags(String str) {
541:                str = stripLineBreaks(str);
542:                StringBuffer result = new StringBuffer(str);
543:                StringBuffer lcresult = new StringBuffer(str.toLowerCase());
544:
545:                // <img should take care of smileys
546:                String[] visibleTags = { "<img" }; // are there others to add?
547:                int stringIndex;
548:                for (int j = 0; j < visibleTags.length; j++) {
549:                    while ((stringIndex = lcresult.indexOf(visibleTags[j])) != -1) {
550:                        if (visibleTags[j].endsWith(">")) {
551:                            result.delete(stringIndex, stringIndex
552:                                    + visibleTags[j].length());
553:                            lcresult.delete(stringIndex, stringIndex
554:                                    + visibleTags[j].length());
555:                        } else {
556:                            // need to delete everything up until next closing '>', for <img for instance
557:                            int endIndex = result.indexOf(">", stringIndex);
558:                            if (endIndex > -1) {
559:                                // only delete it if we find the end!  If we don't the HTML may be messed up, but we
560:                                // can't safely delete anything.
561:                                result.delete(stringIndex, endIndex + 1);
562:                                lcresult.delete(stringIndex, endIndex + 1);
563:                            }
564:                        }
565:                    }
566:                }
567:
568:                // TODO:  This code is buggy by nature.  It doesn't deal with nesting of tags properly.
569:                // remove certain elements with open & close tags
570:                String[] openCloseTags = { "li", "a", "div", "h1", "h2", "h3",
571:                        "h4" }; // more ?
572:                for (int j = 0; j < openCloseTags.length; j++) {
573:                    // could this be better done with a regular expression?
574:                    String closeTag = "</" + openCloseTags[j] + ">";
575:                    int lastStringIndex = 0;
576:                    while ((stringIndex = lcresult.indexOf("<"
577:                            + openCloseTags[j], lastStringIndex)) > -1) {
578:                        lastStringIndex = stringIndex;
579:                        // Try to find the matching closing tag  (ignores possible nesting!)
580:                        int endIndex = lcresult.indexOf(closeTag, stringIndex);
581:                        if (endIndex > -1) {
582:                            // If we found it delete it.
583:                            result.delete(stringIndex, endIndex
584:                                    + closeTag.length());
585:                            lcresult.delete(stringIndex, endIndex
586:                                    + closeTag.length());
587:                        } else {
588:                            // Try to see if it is a self-closed empty content tag, i.e. closed with />.
589:                            endIndex = lcresult.indexOf(">", stringIndex);
590:                            int nextStart = lcresult.indexOf("<",
591:                                    stringIndex + 1);
592:                            if (endIndex > stringIndex
593:                                    && lcresult.charAt(endIndex - 1) == '/'
594:                                    && (endIndex < nextStart || nextStart == -1)) {
595:                                // Looks like it, so remove it.
596:                                result.delete(stringIndex, endIndex + 1);
597:                                lcresult.delete(stringIndex, endIndex + 1);
598:
599:                            }
600:                        }
601:                    }
602:                }
603:
604:                return result.toString();
605:            }
606:
607:            /**
608:             * Converts a character to HTML or XML entity.
609:             *
610:             * @param ch The character to convert.
611:             * @param xml Convert the character to XML if set to true.
612:             * @author Erik C. Thauvin
613:             *
614:             * @return The converted string.
615:             */
616:            public static final String charToHTML(char ch, boolean xml) {
617:                int c;
618:
619:                // Convert left bracket
620:                if (ch == '<') {
621:                    return ("&lt;");
622:                }
623:
624:                // Convert left bracket
625:                else if (ch == '>') {
626:                    return ("&gt;");
627:                }
628:
629:                // Convert ampersand
630:                else if (ch == '&') {
631:                    return ("&amp;");
632:                }
633:
634:                // Commented out to eliminate redundant numeric character codes (ROL-507)
635:                // High-ASCII character
636:                //else if (ch >= 128)
637:                //{
638:                //c = ch;
639:                //return ("&#" + c + ';');
640:                //}
641:
642:                // Convert double quote
643:                else if (xml && (ch == '"')) {
644:                    return ("&quot;");
645:                }
646:
647:                // Convert single quote
648:                else if (xml && (ch == '\'')) {
649:                    return ("&#39;");
650:                }
651:
652:                // No conversion
653:                else {
654:                    // Return character as string
655:                    return (String.valueOf(ch));
656:                }
657:            }
658:
659:            /**
660:             * Converts a text string to HTML or XML entities.
661:             *
662:             * @author Erik C. Thauvin
663:             * @param text The string to convert.
664:             * @param xml Convert the string to XML if set to true.
665:             *
666:             * @return The converted string.
667:             */
668:            public static final String textToHTML(String text, boolean xml) {
669:                if (text == null)
670:                    return "null";
671:                final StringBuffer html = new StringBuffer();
672:
673:                // Loop thru each characters of the text
674:                for (int i = 0; i < text.length(); i++) {
675:                    // Convert character to HTML/XML
676:                    html.append(charToHTML(text.charAt(i), xml));
677:                }
678:
679:                // Return HTML/XML string
680:                return html.toString();
681:            }
682:
683:            /**
684:             * Converts a text string to HTML or XML entities.
685:             *
686:             * @param text The string to convert.
687:             * @author Erik C. Thauvin
688:             * @return The converted string.
689:             */
690:            public static final String textToHTML(String text) {
691:                return textToHTML(text, false);
692:            }
693:
694:            /**
695:             * Converts a text string to XML entities.
696:             *
697:             * @param text The string to convert.
698:             * @author Erik C. Thauvin
699:             * @return The converted string.
700:             */
701:            public static final String textToXML(String text) {
702:                return textToHTML(text, true);
703:            }
704:
705:            /**
706:             * Converts a text string to HTML or XML entities.
707:             * @param text The string to convert.
708:             * @return The converted string.
709:             */
710:            public static final String textToCDATA(String text) {
711:                if (text == null)
712:                    return "null";
713:                final StringBuffer html = new StringBuffer();
714:
715:                // Loop thru each characters of the text
716:                for (int i = 0; i < text.length(); i++) {
717:                    // Convert character to HTML/XML
718:                    html.append(charToCDATA(text.charAt(i)));
719:                }
720:
721:                // Return HTML/XML string
722:                return html.toString();
723:            }
724:
725:            /**
726:             * Converts a character to CDATA character.
727:             * @param ch The character to convert.
728:             * @return The converted string.
729:             */
730:            public static final String charToCDATA(char ch) {
731:                int c;
732:
733:                if (ch >= 128) {
734:                    c = ch;
735:
736:                    return ("&#" + c + ';');
737:                }
738:
739:                // No conversion
740:                else {
741:                    // Return character as string
742:                    return (String.valueOf(ch));
743:                }
744:            }
745:
746:        }
w__w_w__.__j__a_v_a__2__s.__c_o_m_ | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.