KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > net > myvietnam > mvncore > util > StringUtil


1 /*
2  * $Header: /cvsroot/mvnforum/myvietnam/src/net/myvietnam/mvncore/util/StringUtil.java,v 1.27 2006/04/15 02:59:20 minhnn Exp $
3  * $Author: minhnn $
4  * $Revision: 1.27 $
5  * $Date: 2006/04/15 02:59:20 $
6  *
7  * ====================================================================
8  *
9  * Copyright (C) 2002-2006 by MyVietnam.net
10  *
11  * All copyright notices regarding MyVietnam and MyVietnam CoreLib
12  * MUST remain intact in the scripts and source code.
13  *
14  * This library is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU Lesser General Public
16  * License as published by the Free Software Foundation; either
17  * version 2.1 of the License, or (at your option) any later version.
18  *
19  * This library is distributed in the hope that it will be useful,
20  * but WITHOUT ANY WARRANTY; without even the implied warranty of
21  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
22  * Lesser General Public License for more details.
23  *
24  * You should have received a copy of the GNU Lesser General Public
25  * License along with this library; if not, write to the Free Software
26  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
27  *
28  * Correspondence and Marketing Questions can be sent to:
29  * info at MyVietnam net
30  *
31  * @author: Minh Nguyen
32  * @author: Mai Nguyen
33  */

34 package net.myvietnam.mvncore.util;
35
36 import net.myvietnam.mvncore.exception.BadInputException;
37 import java.util.*;
38 import net.myvietnam.mvncore.filter.DisableHtmlTagFilter;
39 /**
40  * @todo: add option for SHORT_STRING_LENGTH
41  */

42 public final class StringUtil {
43
44     private StringUtil() {//prevent instantiation
45
}
46
47     private static final int SHORT_STRING_LENGTH = 100;
48
49     /**
50      * This method trim the input variable, so if it contains only spaces,
51      * then it will be empty string, then we have 0 token :-)
52      * The returned value is never null. If the input String is null, an
53      * empty String array will be returned
54      * All tokens are trimed before returning
55      */

56     public static String JavaDoc[] getStringArray(String JavaDoc inputValue, String JavaDoc delim) {
57         if (inputValue == null) inputValue = "";
58         inputValue = inputValue.trim();// very important
59
java.util.StringTokenizer JavaDoc t = new java.util.StringTokenizer JavaDoc(inputValue, delim);
60         String JavaDoc[] ret = new String JavaDoc[t.countTokens()];
61         int index = 0;
62         while(t.hasMoreTokens()) {
63             String JavaDoc token = t.nextToken().trim();
64             // check for valid value here if needed
65
ret[index] = token;
66             index++;
67         }
68         return ret;
69     }
70
71     public static String JavaDoc[] getStringArrays(String JavaDoc to, String JavaDoc cc, String JavaDoc bcc, String JavaDoc delim) {
72         String JavaDoc[] toMail = getStringArray(to, delim);
73         String JavaDoc[] ccMail = getStringArray(cc, delim);
74         String JavaDoc[] bccMail= getStringArray(bcc, delim);
75         String JavaDoc[] ret = new String JavaDoc[toMail.length + ccMail.length + bccMail.length];
76         int index = 0;
77         for (int i = 0 ; i < toMail.length; i++) {
78             ret[index] = toMail[i];
79             index++;
80         }
81         for (int i = 0; i < ccMail.length; i++) {
82             ret[index] = ccMail[i];
83             index++;
84         }
85         for (int i = 0; i < bccMail.length; i++) {
86             ret[index] = bccMail[i];
87             index++;
88         }
89         return ret;
90     }
91
92     public static String JavaDoc[] getDiffStringArrays(String JavaDoc to, String JavaDoc cc, String JavaDoc bcc, String JavaDoc delim) {
93         String JavaDoc[] toMail = getStringArray(to, delim);
94         String JavaDoc[] ccMail = getStringArray(cc, delim);
95         String JavaDoc[] bccMail= getStringArray(bcc, delim);
96         //String[] ret = new String[t.countTokens()];
97
Set set = new HashSet();
98         //int index = 0;
99
for (int i = 0 ; i < toMail.length; i++) {
100             set.add(toMail[i]);
101         }
102         for (int i = 0; i < ccMail.length; i++) {
103             set.add(ccMail[i]);
104         }
105         for (int i = 0; i < bccMail.length; i++) {
106             set.add(bccMail[i]);
107         }
108         return (String JavaDoc[])set.toArray(new String JavaDoc[0]);
109     }
110
111     public static String JavaDoc getEmptyStringIfNull(String JavaDoc str) {
112         if (str == null) return "";
113         return str;
114     }
115
116     /**
117      * This method accepts name with char, number or '_' or '.'
118      * <p>
119      * This method should be used to check all LoginName input from user for security.
120      * @todo: use StringBuffer
121      */

122     public static void checkGoodName(String JavaDoc str) throws BadInputException {
123         int length = str.length();
124         char c = 0;
125
126         for (int i = 0; i < length; i++) {
127             c = str.charAt(i);
128             if ((c >= 'a') && (c <= 'z')) {
129                 // lower char
130
} else if ((c >= 'A') && (c <= 'Z')) {
131                 // upper char
132
} else if ((c >= '0') && (c <= '9')/* && (i != 0)*/) {
133                 // minhnn: as of 31 Jan 2004, i relax the LoginName checking
134
// so that the LoginName can start with an numeric char
135
// hopefully it does not introduce a security bug
136
// because this value will be inserted into sql script
137

138                 // numeric char
139
} else if (((c == '_') || (c == '.') || (c == '@')) && (i != 0)) {
140                 // minhnn: as of 12 Jan 2005, i relax the LoginName checking
141
// so that it can have '@' because manyone use email as a LoginName
142

143                 // _ char
144

145             // If you need to allow non-ASCII chars, please uncomment the below "else if"
146
// However, this is not recommended since there will be potential security
147
//} else if (c >= 0x80) {
148
// by huxn allow NON-ASCII char
149
} else {
150                 // not good char, throw an BadInputException
151
//@todo : localize me
152
throw new BadInputException("The string '" + DisableHtmlTagFilter.filter(str) + "' is not a good name. Reason: character '" + c + "' is not allowed.");
153             }
154         }// for
155
}
156
157     /**
158      * Get the shorter string, the max length is defined as SHORT_STRING_LENGTH
159      * @param str String the input string
160      * @return String the sorter string, with the max length = SHORT_STRING_LENGTH
161      */

162     public static String JavaDoc getShorterString(String JavaDoc str) {
163         return getShorterString(str, SHORT_STRING_LENGTH);
164     }
165
166     /**
167      * Get the shorter string, the current implementation check the
168      * last occurrence of Character.isWhitespace(currentChar) as the break
169      * @param str String the input string
170      * @param maxLength int the max length of the shorter string
171      * @return String the string after being making shorter
172      */

173     public static String JavaDoc getShorterString(String JavaDoc str, int maxLength) {
174
175         if (maxLength < 0) throw new IllegalArgumentException JavaDoc("The maxLength < 0 is not allowed.");
176         if (str == null) {
177             return "";
178         }
179         if (str.length() <= maxLength) {
180             return str;
181         }
182         String JavaDoc s = str.substring(0, maxLength);
183         char currentChar;
184         int index;
185         for (index = s.length() - 1; index >= 0; index--) {
186             currentChar = s.charAt(index);
187             if (Character.isWhitespace(currentChar)) {
188                 break;
189             }
190         }
191         String JavaDoc shortString = s.substring(0, index + 1);
192         return shortString + "...";
193     }
194
195     /**
196      * Get the shorter string, this is the old implementation before 4 Otc, 2004.
197      * This implementation does not check the space as the break one.
198      * @param str String the input string
199      * @param maxLength int the max length of the shorter string
200      * @return String the string after being making shorter
201      */

202     public static String JavaDoc getShorterStringIgnoreSpace(String JavaDoc str, int maxLength) {
203         if (maxLength < 0) throw new IllegalArgumentException JavaDoc("The maxLength < 0 is not allowed.");
204         if (str == null) return "";
205         if (str.length() <= maxLength) return str;
206         return str.substring(0, maxLength) + "...";
207     }
208
209     /**
210      * Replace the occured char to a String
211      * @param input String the input string
212      * @param from char the char that is used to search
213      * @param to String the string that will replace the char
214      * @return String the string after being replaced
215      */

216     public static String JavaDoc replace(String JavaDoc input, char from, String JavaDoc to) {
217         if (input == null) {
218             return null;
219         }
220
221         char[] s = input.toCharArray();
222         int length = s.length;
223         StringBuffer JavaDoc ret = new StringBuffer JavaDoc(length * 2);
224
225         for (int i = 0; i < length; i++) {
226             if (s[i] == from) {
227                 ret.append(to);
228             } else {
229                 ret.append(s[i]);
230             }
231         }// for
232
return ret.toString();
233     }
234
235     /**
236      * This method can be replaced by getStringArray
237      */

238     public static Collection getSeparateString(String JavaDoc strContent, String JavaDoc pattern) {
239         int beginIndex = 0;
240         Collection coResult = new ArrayList();
241         String JavaDoc result;
242         int position = strContent.indexOf(pattern, beginIndex); // Get the first position
243
while (position != -1) {
244             result = strContent.substring(beginIndex, position);
245             if (!result.trim().equals("")) {
246                 coResult.add(result);
247             }
248             beginIndex = position + pattern.length(); //we add the length of the partern such as ';'
249
position = strContent.indexOf(pattern, beginIndex);
250         }
251
252         return coResult;
253     }
254
255     /**
256      * Convert a password to a hidden format, usually the asterisk character is used,
257      * such as 'secret' is converted to '******'
258      *
259      * @param password String the input password that need to convert to hidden format
260      * @return String the password after being converted to the hidden format
261      */

262     public static String JavaDoc getHiddenPassword(String JavaDoc password) {
263         password = getEmptyStringIfNull(password);
264         int length = password.length();
265         if (length == 0) return password;
266         StringBuffer JavaDoc hiddenPassword = new StringBuffer JavaDoc(length);
267         for (int i = 0; i < length; i++) {
268             hiddenPassword.append('*');
269         }
270         return hiddenPassword.toString();
271     }
272
273     // for test only
274
public static void main(String JavaDoc[] args) throws Exception JavaDoc {
275         //String[] s = getStringArray(" fasg;, zdgsag, ,,", ",");
276
// String[] s = getStringArray(" fasg ", ",");
277
// System.out.println("length = " + s.length);
278
// for (int i = 0; i < s.length; i++) {
279
// System.out.println("" + i + " : " + s[i]);
280
// }
281

282         String JavaDoc s1 = " abc das\n\n\n\n\ndasd asd adad as das as da adas da sd ad as sa das das d a .";
283         System.out.println("r = [" + StringUtil.getShorterString(s1, 22) + "]");
284     }
285
286 }
287
Popular Tags