Source Code Cross Referenced for StringUtil.java in  » Forum » mvnforum-1.1 » net » myvietnam » mvncore » util » 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 » Forum » mvnforum 1.1 » net.myvietnam.mvncore.util 
Source Cross Referenced  Class Diagram Java Document (Java Doc) 


001:        /*
002:         * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/StringUtil.java,v 1.43 2007/10/24 07:20:03 minhnn Exp $
003:         * $Author: minhnn $
004:         * $Revision: 1.43 $
005:         * $Date: 2007/10/24 07:20:03 $
006:         *
007:         * ====================================================================
008:         *
009:         * Copyright (C) 2002-2007 by MyVietnam.net
010:         *
011:         * All copyright notices regarding MyVietnam and MyVietnam CoreLib
012:         * MUST remain intact in the scripts and source code.
013:         *
014:         * This library is free software; you can redistribute it and/or
015:         * modify it under the terms of the GNU Lesser General Public
016:         * License as published by the Free Software Foundation; either
017:         * version 2.1 of the License, or (at your option) any later version.
018:         *
019:         * This library is distributed in the hope that it will be useful,
020:         * but WITHOUT ANY WARRANTY; without even the implied warranty of
021:         * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
022:         * Lesser General Public License for more details.
023:         *
024:         * You should have received a copy of the GNU Lesser General Public
025:         * License along with this library; if not, write to the Free Software
026:         * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
027:         *
028:         * Correspondence and Marketing Questions can be sent to:
029:         * info at MyVietnam net
030:         *
031:         * @author: Minh Nguyen  
032:         * @author: Mai  Nguyen  
033:         */
034:        package net.myvietnam.mvncore.util;
035:
036:        import java.util.*;
037:
038:        import net.myvietnam.mvncore.exception.BadInputException;
039:        import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
040:        import net.myvietnam.mvncore.service.EncoderService;
041:        import net.myvietnam.mvncore.service.MvnCoreServiceFactory;
042:
043:        import org.apache.commons.lang.StringEscapeUtils;
044:        import org.apache.commons.logging.Log;
045:        import org.apache.commons.logging.LogFactory;
046:
047:        /**
048:         * @todo:  add option for SHORT_STRING_LENGTH
049:         */
050:        public final class StringUtil {
051:
052:            private static Log log = LogFactory.getLog(StringUtil.class);
053:
054:            private static final int SHORT_STRING_LENGTH = 100;
055:
056:            private StringUtil() {//prevent instantiation
057:            }
058:
059:            /**
060:             * This method trim the input variable, so if it contains only spaces,
061:             * then it will be empty string, then we have 0 token :-)
062:             * The returned value is never null. If the input String is null, an
063:             * empty String array will be returned
064:             * All tokens are trimed before returning
065:             */
066:            public static String[] getStringArray(String inputValue,
067:                    String delim) {
068:                if (inputValue == null)
069:                    inputValue = "";
070:                inputValue = inputValue.trim();// very important
071:                java.util.StringTokenizer t = new java.util.StringTokenizer(
072:                        inputValue, delim);
073:                String[] ret = new String[t.countTokens()];
074:                int index = 0;
075:                while (t.hasMoreTokens()) {
076:                    String token = t.nextToken().trim();
077:                    // check for valid value here if needed
078:                    ret[index] = token;
079:                    index++;
080:                }
081:                return ret;
082:            }
083:
084:            public static String[] getStringArrays(String to, String cc,
085:                    String bcc, String delim) {
086:                String[] toMail = getStringArray(to, delim);
087:                String[] ccMail = getStringArray(cc, delim);
088:                String[] bccMail = getStringArray(bcc, delim);
089:                String[] ret = new String[toMail.length + ccMail.length
090:                        + bccMail.length];
091:                int index = 0;
092:                for (int i = 0; i < toMail.length; i++) {
093:                    ret[index] = toMail[i];
094:                    index++;
095:                }
096:                for (int i = 0; i < ccMail.length; i++) {
097:                    ret[index] = ccMail[i];
098:                    index++;
099:                }
100:                for (int i = 0; i < bccMail.length; i++) {
101:                    ret[index] = bccMail[i];
102:                    index++;
103:                }
104:                return ret;
105:            }
106:
107:            public static String[] getDiffStringArrays(String to, String cc,
108:                    String bcc, String delim) {
109:                String[] toMail = getStringArray(to, delim);
110:                String[] ccMail = getStringArray(cc, delim);
111:                String[] bccMail = getStringArray(bcc, delim);
112:                //String[] ret = new String[t.countTokens()];
113:                Set set = new HashSet();
114:                //int index = 0;
115:                for (int i = 0; i < toMail.length; i++) {
116:                    set.add(toMail[i]);
117:                }
118:                for (int i = 0; i < ccMail.length; i++) {
119:                    set.add(ccMail[i]);
120:                }
121:                for (int i = 0; i < bccMail.length; i++) {
122:                    set.add(bccMail[i]);
123:                }
124:                return (String[]) set.toArray(new String[0]);
125:            }
126:
127:            public static String getEmptyStringIfNull(String str) {
128:                if (str == null)
129:                    return "";
130:                return str;
131:            }
132:
133:            /**
134:             * This method accepts name with char, number or '_' or '.'
135:             * <p>
136:             * This method should be used to check all LoginName input from user for security.
137:             * @todo: use StringBuffer
138:             */
139:            public static void checkGoodName(String str)
140:                    throws BadInputException {
141:                int length = str.length();
142:                char c = 0;
143:
144:                for (int i = 0; i < length; i++) {
145:                    c = str.charAt(i);
146:                    if ((c >= 'a') && (c <= 'z')) {
147:                        // lower char
148:                    } else if ((c >= 'A') && (c <= 'Z')) {
149:                        // upper char
150:                    } else if ((c >= '0') && (c <= '9')/* && (i != 0)*/) {
151:                        // minhnn: as of 31 Jan 2004, i relax the LoginName checking
152:                        // so that the LoginName can start with an numeric char
153:                        // hopefully it does not introduce a security bug
154:                        // because this value will be inserted into sql script
155:
156:                        // numeric char
157:                    } else if (((c == '_') || (c == '.') || (c == '@'))
158:                            && (i != 0)) {
159:                        // minhnn: as of 12 Jan 2005, i relax the LoginName checking
160:                        // so that it can have '@' because manyone use email as a LoginName
161:
162:                        // _ char
163:
164:                        // If you need to allow non-ASCII chars, please uncomment the below "else if"
165:                        // However, this is not recommended since there will be potential security
166:                        //} else if (c >= 0x80) {
167:                        // by huxn allow NON-ASCII char
168:                    } else {
169:                        // not good char, throw an BadInputException
170:                        //@todo : localize me
171:                        throw new BadInputException("The string '"
172:                                + DisableHtmlTagFilter.filter(str)
173:                                + "' is not a good name. Reason: character '"
174:                                + c + "' is not allowed.");
175:                    }
176:                }// for
177:            }
178:
179:            /**
180:             * Get the shorter string, the max length is defined as SHORT_STRING_LENGTH
181:             * @param str String the input string
182:             * @return String the sorter string, with the max length = SHORT_STRING_LENGTH
183:             */
184:            public static String getShorterString(String str) {
185:                return getShorterString(str, SHORT_STRING_LENGTH);
186:            }
187:
188:            /**
189:             * Get the shorter string, the current implementation check the
190:             * last occurrence of Character.isWhitespace(currentChar) as the break
191:             * @param str String the input string
192:             * @param maxLength int the max length of the shorter string
193:             * @return String the string after being making shorter
194:             */
195:            public static String getShorterString(String str, int maxLength) {
196:
197:                if (maxLength < 0)
198:                    throw new IllegalArgumentException(
199:                            "The maxLength < 0 is not allowed.");
200:                if (str == null) {
201:                    return "";
202:                }
203:                if (str.length() <= maxLength) {
204:                    return str;
205:                }
206:                String s = str.substring(0, maxLength);
207:                char currentChar;
208:                int index;
209:                for (index = s.length() - 1; index >= 0; index--) {
210:                    currentChar = s.charAt(index);
211:                    if (Character.isWhitespace(currentChar)) {
212:                        break;
213:                    }
214:                }
215:                String shortString = s.substring(0, index + 1);
216:                return shortString + "...";
217:            }
218:
219:            /**
220:             * Get the shorter string, this is the old implementation before 4 Otc, 2004.
221:             * This implementation does not check the space as the break one.
222:             * @param str String the input string
223:             * @param maxLength int the max length of the shorter string
224:             * @return String the string after being making shorter
225:             */
226:            public static String getShorterStringIgnoreSpace(String str,
227:                    int maxLength) {
228:                if (maxLength < 0)
229:                    throw new IllegalArgumentException(
230:                            "The maxLength < 0 is not allowed.");
231:                if (str == null)
232:                    return "";
233:                if (str.length() <= maxLength)
234:                    return str;
235:                return str.substring(0, maxLength) + "...";
236:            }
237:
238:            /**
239:             * Replace the occured char to a String
240:             * @param input String the input string
241:             * @param from char the char that is used to search
242:             * @param to String the string that will replace the char
243:             * @return String the string after being replaced
244:             */
245:            public static String replace(String input, char from, String to) {
246:                if (input == null) {
247:                    return null;
248:                }
249:
250:                char[] s = input.toCharArray();
251:                int length = s.length;
252:                StringBuffer ret = new StringBuffer(length * 2);
253:
254:                for (int i = 0; i < length; i++) {
255:                    if (s[i] == from) {
256:                        ret.append(to);
257:                    } else {
258:                        ret.append(s[i]);
259:                    }
260:                }// for
261:                return ret.toString();
262:            }
263:
264:            /**
265:             * This method can be replaced by getStringArray
266:             */
267:            public static Collection getSeparateString(String strContent,
268:                    String pattern) {
269:                int beginIndex = 0;
270:                Collection coResult = new ArrayList();
271:                String result;
272:                int position = strContent.indexOf(pattern, beginIndex); // Get the first position
273:                while (position != -1) {
274:                    result = strContent.substring(beginIndex, position);
275:                    if (!result.trim().equals("")) {
276:                        coResult.add(result);
277:                    }
278:                    beginIndex = position + pattern.length(); //we add the length of the partern such as ';'
279:                    position = strContent.indexOf(pattern, beginIndex);
280:                }
281:
282:                return coResult;
283:            }
284:
285:            /**
286:             * Convert a password to a hidden format, usually the asterisk character is used,
287:             * such as 'secret' is converted to '******'
288:             *
289:             * @param password String the input password that need to convert to hidden format
290:             * @return String the password after being converted to the hidden format
291:             */
292:            public static String getHiddenPassword(String password) {
293:                password = getEmptyStringIfNull(password);
294:                int length = password.length();
295:                if (length == 0)
296:                    return password;
297:                StringBuffer hiddenPassword = new StringBuffer(length);
298:                for (int i = 0; i < length; i++) {
299:                    hiddenPassword.append('*');
300:                }
301:                return hiddenPassword.toString();
302:            }
303:
304:            //fix bug for pluto 1.1
305:            public static String escapeBackSlash(String str) {
306:                if (str == null) {
307:                    return null;
308:                }
309:                //I didn't use 0x92 because pluto will use 0x9 as # , see PortalURLParserImpl
310:                return str.replaceAll("\\\\", "0y92");
311:            }
312:
313:            //fix bug for pluto 1.1
314:            public static String unEscapeBackSlash(String str) {
315:                if (str == null) {
316:                    return null;
317:                }
318:                return str.replaceAll("0y92", "\\\\");
319:            }
320:
321:            public static String escapeQuote(String input) {
322:                input = StringEscapeUtils.escapeJavaScript(input);
323:                char[] chars = input.toCharArray();
324:                StringBuffer buffer = new StringBuffer();
325:                for (int i = 0; i < chars.length; i++) {
326:                    //            if (isQuote(chars[i])) {
327:                    //                buffer.append('\\').append('"'); // append "\'"
328:                    //            } else if (chars[i] == '\n' || chars[i] == '\r') {
329:                    //                // do nothing
330:                    //            } else if (chars[i] == '\\') {
331:                    //                buffer.append('\\').append('\\'); // append "\'"
332:                    //            } else
333:                    if (i + 5 < chars.length
334:                            && // find '&apos;' ~ single quote
335:                            chars[i] == '&' && chars[i + 1] == 'a'
336:                            && chars[i + 2] == 'p' && chars[i + 3] == 'o'
337:                            && chars[i + 4] == 's' && chars[i + 5] == ';') {
338:                        buffer.append('\\').append('\'');
339:                        i += 5;
340:                        // do nothing
341:                    } else if (i + 4 < chars.length
342:                            && // find '&#39;' ~ single quote
343:                            chars[i] == '&' && chars[i + 1] == '#'
344:                            && chars[i + 2] == '3' && chars[i + 3] == '9'
345:                            && chars[i + 4] == ';') {
346:                        buffer.append('\\').append('\'');
347:                        i += 4;
348:                    } else {
349:                        buffer.append(chars[i]);
350:                    }
351:                }
352:
353:                String result = DisableHtmlTagFilter.filter(buffer.toString());
354:                return result;
355:            }
356:
357:            public static String displayMediaContent(String url, int width,
358:                    int height) {
359:
360:                EncoderService encoderService = MvnCoreServiceFactory
361:                        .getMvnCoreService().getEncoderService();
362:
363:                if ("".equals(url) || url == null) {
364:                    return "";
365:                }
366:
367:                url = encoderService.filterUrl(url);
368:                String result = "";
369:                String size = "";
370:                if (width > 0) {
371:                    size += " width='" + width + "'";
372:                }
373:                if (height > 0) {
374:                    size += " height='" + height + "'";
375:                }
376:
377:                String lowerURL = url.toLowerCase();
378:
379:                if (lowerURL.endsWith(".swf")) {
380:                    result = "<embed src='"
381:                            + url
382:                            + "' quality='high' scale='noborder' wmode='transparent'"
383:                            + " bgcolor='#000000'"
384:                            + size
385:                            + " type='application/x-shockwave-flash'"
386:                            + " pluginspage='http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash'></embed>";
387:                } else if (lowerURL.endsWith(".jpeg")
388:                        || lowerURL.endsWith(".jpg")
389:                        || lowerURL.endsWith(".png")
390:                        || lowerURL.endsWith(".gif")) {
391:                    result = "<img src='" + url + "'" + size
392:                            + " border='0' alt=''>";
393:                } else if (lowerURL.endsWith(".mov")) {
394:                    result = "<OBJECT classid='clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B'"
395:                            + size
396:                            + " codebase='http://www.apple.com/qtactivex/qtplugin.cab'><param name='src' value='"
397:                            + url
398:                            + "'><param name='autoplay' value='true'><param name='controller' value='false'><param name='loop' value='true'><EMBED src='"
399:                            + url
400:                            + "' width='320' height='255' autoplay='true' controller='false' loop='true' pluginspage='http://www.apple.com/quicktime/download/'></EMBED></OBJECT>";
401:                } else if (lowerURL.endsWith(".mpg")
402:                        || lowerURL.endsWith(".wmv")
403:                        || lowerURL.endsWith(".avi")) {
404:                    result = "<embed src='"
405:                            + url
406:                            + "'"
407:                            + size
408:                            + " EnableContextMenu='0' AutoStart='1' loop='1' ShowStatusBar='0' ShowControls='0'></embed>";
409:                } else {
410:                    result = "";
411:                }
412:
413:                return result;
414:            }
415:
416:            // for test only
417:            public static void main(String[] args) throws Exception {
418:                //String[] s = getStringArray("  fasg;,   zdgsag, ,,", ",");
419:                //        String[] s = getStringArray("  fasg  ", ",");
420:                //        System.out.println("length = " + s.length);
421:                //        for (int i = 0; i < s.length; i++) {
422:                //            System.out.println("" + i + " : " + s[i]);
423:                //        }
424:
425:                String s1 = "   abc das\n\n\n\n\ndasd    asd   adad   as   das   as   da    adas        da     sd    ad  as  sa  das  das   d a            .";
426:                System.out.println("r = ["
427:                        + StringUtil.getShorterString(s1, 22) + "]");
428:            }
429:
430:            public static int parseIntSizeValue(String propertyValue,
431:                    int defaultValue) {
432:
433:                try {
434:                    String temp = propertyValue.trim();
435:                    if (temp.endsWith("B") || temp.endsWith("b")) {
436:                        temp = temp.substring(0, temp.length() - 1);
437:                    }
438:                    switch (temp.charAt(temp.length() - 1)) {
439:                    case 'K':
440:                    case 'k':
441:                        //examples (ending 'B' was cut before): "1K", "1KB", "1k", "1kB", "1 K", "1 KB", "1 k", "1 kB"
442:                        return 1024 * Integer.parseInt(temp.substring(0,
443:                                temp.length() - 1).trim());
444:                    case 'M':
445:                    case 'm':
446:                        //examples (ending 'B' was cut before): "1M", "1MB", "1m", "1mB", "1 M", "1 MB", "1 m", "1 mB"
447:                        return 1024 * 1024 * Integer.parseInt(temp.substring(0,
448:                                temp.length() - 1).trim());
449:                    default:
450:                        //examples (ending 'B' was cut before): "1", "1B", "1 B"
451:                        return Integer.parseInt(temp.trim());
452:                    }
453:                } catch (Exception e) {
454:                    log.warn("Error while parsing the value " + propertyValue,
455:                            e);
456:                    return defaultValue;
457:                }
458:
459:            }
460:
461:        }
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.