KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > blandware > atleap > common > util > StringUtil


1 /*
2  * Copyright 2004 Blandware (http://www.blandware.com)
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not 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.
15  */

16 package com.blandware.atleap.common.util;
17
18 import org.apache.commons.logging.Log;
19 import org.apache.commons.logging.LogFactory;
20 import sun.misc.BASE64Decoder;
21 import sun.misc.BASE64Encoder;
22
23 import java.io.IOException JavaDoc;
24 import java.io.PrintWriter JavaDoc;
25 import java.io.StringWriter JavaDoc;
26 import java.security.MessageDigest JavaDoc;
27 import java.util.ArrayList JavaDoc;
28 import java.util.Map JavaDoc;
29 import java.util.HashMap JavaDoc;
30 import java.util.Iterator JavaDoc;
31
32
33 /**
34  * <p>String Utility Class.
35  * This is used to encode passwords programmatically.
36  * It also encodes string for inserting in database
37  * </p>
38  * <p><a HREF="StringUtil.java.htm"><i>View Source</i></a>
39  * </p>
40  *
41  * @author Sergey Zubtcovskii <a HREF="mailto:sergey.zubtcovskii@blandware.com">&lt;sergey.zubtcovskii@blandware.com&gt;</a>
42  * @author Andrey Grebnev <a HREF="mailto:andrey.grebnev@blandware.com">&lt;andrey.grebnev@blandware.com&gt;</a>
43  * @author Matt Raible <a HREF="mailto:matt@raibledesigns.com">&lt;matt@raibledesigns.com&gt;</a>
44  * @version $Revision: 1.20 $ $Date: 2006/03/16 11:09:36 $
45  */

46 public class StringUtil {
47     //~ Static fields/initializers =============================================
48

49     //~ Methods ================================================================
50

51     /**
52      * Encodes a string using algorithm specified in web.xml and return the
53      * resulting encrypted password. If exception, the plain credentials
54      * string is returned
55      *
56      * @param password Password or other credentials to use in authenticating
57      * this username
58      * @param algorithm Algorithm used to do the digest
59      * @return encypted password based on the algorithm.
60      */

61     public static String JavaDoc encodePassword(String JavaDoc password, String JavaDoc algorithm) {
62
63         if ( password == null ) {
64             return null;
65         }
66
67         Log log = LogFactory.getLog(StringUtil.class);
68         byte[] unencodedPassword = password.getBytes();
69
70         MessageDigest JavaDoc md = null;
71
72         try {
73             // first create an instance, given the provider
74
md = MessageDigest.getInstance(algorithm);
75         } catch ( Exception JavaDoc e ) {
76             StringWriter JavaDoc sw = new StringWriter JavaDoc();
77             e.printStackTrace(new PrintWriter JavaDoc(sw));
78             if ( log.isErrorEnabled() ) {
79                 log.error(sw.toString());
80             }
81             return password;
82         }
83
84         md.reset();
85
86         // call the update method one or more times
87
// (useful when you don't know the size of your data, e.g. stream)
88
md.update(unencodedPassword);
89
90         // now calculate the hash
91
byte[] encodedPassword = md.digest();
92
93         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
94
95         for ( int i = 0; i < encodedPassword.length; i++ ) {
96             if ( (encodedPassword[i] & 0xff) < 0x10 ) {
97                 buf.append("0");
98             }
99
100             buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
101         }
102
103         return buf.toString();
104     }
105
106     /**
107      * Encodes a string using Base64 encoding. Used when storing passwords
108      * as cookies.
109      * <p> * This is weak encoding in that anyone can use the decodeString
110      * routine to reverse the encoding.
111      *
112      * @param str The string to encode
113      * @return Encoded string
114      */

115     public static String JavaDoc encodeString(String JavaDoc str) {
116         BASE64Encoder encoder = new BASE64Encoder();
117         return encoder.encodeBuffer(str.getBytes()).trim();
118     }
119
120     /**
121      * Decodes a string which was encoded using Base64 encoding.
122      *
123      * @param str The string to decode
124      * @return Decoded string
125      */

126     public static String JavaDoc decodeString(String JavaDoc str) {
127         BASE64Decoder dec = new BASE64Decoder();
128         try {
129             return new String JavaDoc(dec.decodeBuffer(str));
130         } catch ( IOException JavaDoc io ) {
131             throw new RuntimeException JavaDoc(io.getMessage(), io.getCause());
132         }
133     }
134
135     /**
136      * Encodes a string for inserting to database table
137      *
138      * @param inputString input string
139      * @return encoded string
140      */

141     public static String JavaDoc escape(String JavaDoc inputString) {
142         if (inputString == null)
143             return null;
144
145         StringBuffer JavaDoc buf = new StringBuffer JavaDoc((int) (inputString.length() * 1.1));
146         int stringLength = inputString.length();
147
148         for ( int i = 0; i < stringLength; ++i ) {
149             char c = inputString.charAt(i);
150
151             switch ( c ) {
152                 case 0: /* Must be escaped for 'mysql' */
153                     buf.append('\\');
154                     buf.append('0');
155
156                     break;
157
158                 case '\n': /* Must be escaped for logs */
159                     buf.append('\\');
160                     buf.append('n');
161
162                     break;
163
164                 case '\r':
165                     buf.append('\\');
166                     buf.append('r');
167
168                     break;
169
170                 case '\\':
171                     buf.append('\\');
172                     buf.append('\\');
173
174                     break;
175
176                 case '\'':
177                     buf.append('\\');
178                     buf.append('\'');
179
180                     break;
181
182                 case '"': /* Better safe than sorry */
183                     buf.append('\\');
184                     buf.append('"');
185
186                     break;
187
188                 case '\032': /* This gives problems on Win32 */
189                     buf.append('\\');
190                     buf.append('Z');
191
192                     break;
193
194                 default:
195                     buf.append(c);
196             }
197         }
198         return buf.toString();
199     }
200
201     /**
202      * Replaces all HTML-sensitive characters with their entity equivalents
203      * @param html String to encode
204      * @return string with all HTML-sensitive characters replaced with their entity equivalents
205      */

206     public static String JavaDoc htmlEncode(String JavaDoc html) {
207         if ( html == null ) {
208             return null;
209         }
210         StringBuffer JavaDoc buf = new StringBuffer JavaDoc((int) (html.length() * 1.1));
211         int stringLength = html.length();
212
213         for ( int i = 0; i < stringLength; ++i ) {
214             char c = html.charAt(i);
215
216             switch ( c ) {
217                 case '\'':
218                     buf.append("&#39;");
219
220                     break;
221
222                 case '"':
223                     buf.append("&quot;");
224
225                     break;
226
227                 case '<':
228                     buf.append("&lt;");
229
230                     break;
231
232                 case '>':
233                     buf.append("&gt;");
234
235                     break;
236
237                 case '&':
238                     buf.append("&amp;");
239
240                     break;
241                 default:
242                     buf.append(c);
243             }
244         }
245         return buf.toString();
246     }
247
248     /**
249      * Replaces all HTML-sensitive characters with their entity equivalents in all string values in specified model
250      * @param model Map of pairs <code>variable -&gt; value</code>.
251      * @return Map with encoded string values
252      */

253     public static Map JavaDoc htmlEncodeModel(Map JavaDoc model) {
254         Map JavaDoc result = new HashMap JavaDoc(model.size());
255         for ( Iterator JavaDoc i = model.entrySet().iterator(); i.hasNext(); ) {
256             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) i.next();
257             String JavaDoc key = (String JavaDoc) entry.getKey();
258             Object JavaDoc value = (Object JavaDoc) entry.getValue();
259             if ( value instanceof String JavaDoc ) {
260                 result.put(key, htmlEncode((String JavaDoc) value));
261             } else {
262                 result.put(key, value);
263             }
264         }
265         return result;
266     }
267
268     /**
269      * Replaces all EL (end of line) characters with HTML BR tag
270      *
271      * @param html text in which to replace
272      * @return string with EL replaced with BR
273      */

274     public static String JavaDoc elToBr(String JavaDoc html) {
275         if ( html == null ) {
276             return null;
277         }
278         StringBuffer JavaDoc buf = new StringBuffer JavaDoc((int) (html.length() * 1.1));
279         int stringLength = html.length();
280
281         for ( int i = 0; i < stringLength; ++i ) {
282             char c = html.charAt(i);
283
284             switch ( c ) {
285                 case '\n':
286                     buf.append("<br />");
287
288                     break;
289                 default:
290                     buf.append(c);
291             }
292         }
293         return buf.toString();
294     }
295
296     /**
297      * Capitalizes string
298      * @param s String to capitalize
299      * @return Capitalized string
300      */

301     public static String JavaDoc capitalize(String JavaDoc s) {
302         if ( s == null || s.length() == 0 ) {
303             return s;
304         }
305         char[] chars = s.toCharArray();
306         chars[0] = Character.toUpperCase(chars[0]);
307         return String.valueOf(chars);
308     }
309
310     /**
311      * Splits template name to get identifier, field name and locale
312      * @param templateName String in form <code>identifier_field_locale</code>
313      * @return Array containing identifier, field and locale or empty array if string format is incorrect
314      */

315     public static String JavaDoc[] splitTemplateName(String JavaDoc templateName) {
316         ArrayList JavaDoc result = new ArrayList JavaDoc();
317         int k = templateName.lastIndexOf("_");
318         if ( k != -1 ) {
319         String JavaDoc locale = templateName.substring(k + 1);
320         templateName = templateName.substring(0, k);
321         k = templateName.lastIndexOf("_");
322             if ( k != -1 ) {
323                 String JavaDoc field = templateName.substring(k + 1);
324                 templateName = templateName.substring(0, k);
325                 result.add(templateName);
326                 result.add(field);
327                 result.add(locale);
328             }
329         }
330         return (String JavaDoc[]) result.toArray(new String JavaDoc[0]);
331     }
332
333     /**
334      * Concatenates arguments into template name
335      * @param identifier Identifier of mail template
336      * @param field Field (from, subject or body)
337      * @param locale Locale identifier
338      * @return Template name to use in resource loader
339      */

340     public static String JavaDoc createTemplateName(String JavaDoc identifier, String JavaDoc field, String JavaDoc locale) {
341         StringBuffer JavaDoc result = new StringBuffer JavaDoc(identifier);
342         result.append("_");
343         result.append(field);
344         result.append("_");
345         result.append(locale);
346         return result.toString();
347     }
348
349     /**
350      * Shortens string to be no more than number of symbols specified
351      * @param s String to shorten
352      * @param requiredLength Length to shorten string to
353      * @return Shortened string
354      */

355     public static String JavaDoc shortenString(String JavaDoc s, int requiredLength) {
356         if ( s != null && s.length() > requiredLength ) {
357             s = s.substring(0, requiredLength + 1);
358             int space = s.lastIndexOf(" ");
359             int lineFeed = s.lastIndexOf("\n");
360             int tab = s.lastIndexOf("\t");
361             if ( space > 0 || lineFeed > 0 || tab > 0 ) {
362                 int cut = space > lineFeed ? ( space > tab ? space : tab ) : ( lineFeed > tab ? lineFeed : tab );
363                 s = s.substring(0, cut);
364             }
365             s += "...";
366         }
367         return s;
368     }
369
370     /**
371      * Completes number to be no less than specified number of signs
372      *
373      * @param number Number to complete
374      * @param signs Length of number to reach
375      * @return Adds zero-by-zero from to the left of number until its length will be greater or equal than specified number of signs.
376      * For example if number = 67 and signs = 3 are specified, result string will be "067" and so on
377      */

378     public static String JavaDoc completeNumber(int number, int signs) {
379
380         // if number of signs is equal to zero, return empty string
381
if ( signs == 0 ) {
382             return "";
383         }
384
385         // calculate radix: it is equal to the (signs - 1) power of ten
386
int radix = (int) Math.pow(10, signs - 1);
387
388         StringBuffer JavaDoc result = new StringBuffer JavaDoc();
389         while ( (number / radix == 0) && (number % radix > 0) ) {
390             result.append("0");
391             radix = radix / 10;
392         }
393
394         // create result string
395
result.append(number);
396
397         return result.toString();
398     }
399
400 }
401
Popular Tags