KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > jdon > util > StringUtil


1 /*
2  * $Id: StringUtil.java,v 1.2 2005/01/31 05:27:54 jdon Exp $
3  *
4  * Copyright (c) 2001, 2002 The Open For Business Project - www.ofbiz.org
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10  * and/or sell copies of the Software, and to permit persons to whom the
11  * Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice shall be included
14  * in all copies or substantial portions of the Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT
21  * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
22  * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23  */

24
25 package com.jdon.util;
26
27 import java.io.BufferedReader JavaDoc;
28 import java.io.ByteArrayOutputStream JavaDoc;
29 import java.io.IOException JavaDoc;
30 import java.io.InputStream JavaDoc;
31 import java.io.InputStreamReader JavaDoc;
32 import java.io.PrintWriter JavaDoc;
33 import java.io.StringReader JavaDoc;
34
35 import java.util.ArrayList JavaDoc;
36 import java.util.List JavaDoc;
37 import java.security.MessageDigest JavaDoc;
38
39 /**
40  *
41  * @author Brian Chan
42  * @version $Revision: 1.2 $
43  *
44  */

45 public class StringUtil {
46
47   public static boolean contains(String JavaDoc s, String JavaDoc text, String JavaDoc delimiter) {
48     if ( (s == null) || (text == null) || (delimiter == null)) {
49       return false;
50     }
51
52     if (!s.endsWith(delimiter)) {
53       s += delimiter;
54     }
55
56     int pos = s.indexOf(delimiter + text + delimiter);
57
58     if (pos == -1) {
59       if (s.startsWith(text + delimiter)) {
60         return true;
61       }
62
63       return false;
64     }
65
66     return true;
67   }
68
69   public static int count(String JavaDoc s, String JavaDoc text) {
70     if ( (s == null) || (text == null)) {
71       return 0;
72     }
73
74     int count = 0;
75
76     int pos = s.indexOf(text);
77
78     while (pos != -1) {
79       pos = s.indexOf(text, pos + text.length());
80       count++;
81     }
82
83     return count;
84   }
85
86   public static String JavaDoc merge(String JavaDoc array[], String JavaDoc delimiter) {
87     if (array == null) {
88       return null;
89     }
90
91     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
92
93     for (int i = 0; i < array.length; i++) {
94       sb.append(array[i].trim());
95
96       if ( (i + 1) != array.length) {
97         sb.append(delimiter);
98       }
99     }
100
101     return sb.toString();
102   }
103
104   public static String JavaDoc read(ClassLoader JavaDoc classLoader, String JavaDoc name) throws
105       IOException JavaDoc {
106
107     return read(classLoader.getResourceAsStream(name));
108   }
109
110   public static String JavaDoc read(InputStream JavaDoc is) throws IOException JavaDoc {
111     BufferedReader JavaDoc br = new BufferedReader JavaDoc(new InputStreamReader JavaDoc(is));
112
113     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
114     String JavaDoc line = null;
115
116     while ( (line = br.readLine()) != null) {
117       sb.append(line).append('\n');
118     }
119
120     br.close();
121
122     return sb.toString().trim();
123   }
124
125   public static String JavaDoc remove(String JavaDoc s, String JavaDoc remove, String JavaDoc delimiter) {
126     if ( (s == null) || (remove == null) || (delimiter == null)) {
127       return null;
128     }
129
130     if (UtilValidate.isNotEmpty(s) && !s.endsWith(delimiter)) {
131       s += delimiter;
132     }
133
134     while (contains(s, remove, delimiter)) {
135       int pos = s.indexOf(delimiter + remove + delimiter);
136
137       if (pos == -1) {
138         if (s.startsWith(remove + delimiter)) {
139           s = s.substring(
140               remove.length() + delimiter.length(), s.length());
141         }
142       } else {
143         s = s.substring(0, pos) + s.substring(pos + remove.length() +
144                                               delimiter.length(), s.length());
145       }
146     }
147
148     return s;
149   }
150
151   public static String JavaDoc replace(String JavaDoc s, String JavaDoc oldSub, String JavaDoc newSub) {
152     if ( (s == null) || (oldSub == null) || (newSub == null)) {
153       return null;
154     }
155
156     int y = s.indexOf(oldSub);
157
158     if (y >= 0) {
159       StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
160       int length = oldSub.length();
161       int x = 0;
162
163       while (x <= y) {
164         sb.append(s.substring(x, y));
165         sb.append(newSub);
166         x = y + length;
167         y = s.indexOf(oldSub, x);
168       }
169
170       sb.append(s.substring(x));
171
172       return sb.toString();
173     } else {
174       return s;
175     }
176   }
177
178   public static String JavaDoc replace(String JavaDoc s, String JavaDoc[] oldSubs, String JavaDoc[] newSubs) {
179     if ( (s == null) || (oldSubs == null) || (newSubs == null)) {
180       return null;
181     }
182
183     if (oldSubs.length != newSubs.length) {
184       return s;
185     }
186
187     for (int i = 0; i < oldSubs.length; i++) {
188       s = replace(s, oldSubs[i], newSubs[i]);
189     }
190
191     return s;
192   }
193
194   public static String JavaDoc reverse(String JavaDoc s) {
195     if (s == null) {
196       return null;
197     }
198
199     char[] c = s.toCharArray();
200     char[] reverse = new char[c.length];
201
202     for (int i = 0; i < c.length; i++) {
203       reverse[i] = c[c.length - i - 1];
204     }
205
206     return new String JavaDoc(reverse);
207   }
208
209   public static String JavaDoc shorten(String JavaDoc s) {
210     return shorten(s, 20);
211   }
212
213   public static String JavaDoc shorten(String JavaDoc s, int length) {
214     return shorten(s, length, "..");
215   }
216
217   public static String JavaDoc shorten(String JavaDoc s, String JavaDoc suffix) {
218     return shorten(s, 20, suffix);
219   }
220
221   public static String JavaDoc shorten(String JavaDoc s, int length, String JavaDoc suffix) {
222     if (s == null || suffix == null) {
223       return null;
224     }
225
226     if (s.length() > length) {
227       s = s.substring(0, length) + suffix;
228     }
229
230     return s;
231   }
232
233   public static String JavaDoc[] split(String JavaDoc s, String JavaDoc delimiter) {
234     if (s == null || delimiter == null) {
235       return new String JavaDoc[0];
236     }
237
238     if (!s.endsWith(delimiter)) {
239       s += delimiter;
240     }
241
242     s = s.trim();
243
244     if (s.equals(delimiter)) {
245       return new String JavaDoc[0];
246     }
247
248     List JavaDoc nodeValues = new ArrayList JavaDoc();
249
250     if (delimiter.equals("\n") || delimiter.equals("\r")) {
251       try {
252         BufferedReader JavaDoc br = new BufferedReader JavaDoc(new StringReader JavaDoc(s));
253
254         String JavaDoc line = null;
255
256         while ( (line = br.readLine()) != null) {
257           nodeValues.add(line);
258         }
259
260         br.close();
261       } catch (IOException JavaDoc ioe) {
262         ioe.printStackTrace();
263       }
264     } else {
265       int offset = 0;
266       int pos = s.indexOf(delimiter, offset);
267
268       while (pos != -1) {
269         nodeValues.add(s.substring(offset, pos));
270
271         offset = pos + delimiter.length();
272         pos = s.indexOf(delimiter, offset);
273       }
274     }
275
276     return (String JavaDoc[]) nodeValues.toArray(new String JavaDoc[0]);
277   }
278
279   public static boolean[] split(String JavaDoc s, String JavaDoc delimiter, boolean x) {
280     String JavaDoc[] array = split(s, delimiter);
281     boolean[] newArray = new boolean[array.length];
282
283     for (int i = 0; i < array.length; i++) {
284       boolean value = x;
285
286       try {
287         value = Boolean.valueOf(array[i]).booleanValue();
288       } catch (Exception JavaDoc e) {
289       }
290
291       newArray[i] = value;
292     }
293
294     return newArray;
295   }
296
297   public static double[] split(String JavaDoc s, String JavaDoc delimiter, double x) {
298     String JavaDoc[] array = split(s, delimiter);
299     double[] newArray = new double[array.length];
300
301     for (int i = 0; i < array.length; i++) {
302       double value = x;
303
304       try {
305         value = Double.parseDouble(array[i]);
306       } catch (Exception JavaDoc e) {
307       }
308
309       newArray[i] = value;
310     }
311
312     return newArray;
313   }
314
315   public static float[] split(String JavaDoc s, String JavaDoc delimiter, float x) {
316     String JavaDoc[] array = split(s, delimiter);
317     float[] newArray = new float[array.length];
318
319     for (int i = 0; i < array.length; i++) {
320       float value = x;
321
322       try {
323         value = Float.parseFloat(array[i]);
324       } catch (Exception JavaDoc e) {
325       }
326
327       newArray[i] = value;
328     }
329
330     return newArray;
331   }
332
333   public static int[] split(String JavaDoc s, String JavaDoc delimiter, int x) {
334     String JavaDoc[] array = split(s, delimiter);
335     int[] newArray = new int[array.length];
336
337     for (int i = 0; i < array.length; i++) {
338       int value = x;
339
340       try {
341         value = Integer.parseInt(array[i]);
342       } catch (Exception JavaDoc e) {
343       }
344
345       newArray[i] = value;
346     }
347
348     return newArray;
349   }
350
351   public static long[] split(String JavaDoc s, String JavaDoc delimiter, long x) {
352     String JavaDoc[] array = split(s, delimiter);
353     long[] newArray = new long[array.length];
354
355     for (int i = 0; i < array.length; i++) {
356       long value = x;
357
358       try {
359         value = Long.parseLong(array[i]);
360       } catch (Exception JavaDoc e) {
361       }
362
363       newArray[i] = value;
364     }
365
366     return newArray;
367   }
368
369   public static short[] split(String JavaDoc s, String JavaDoc delimiter, short x) {
370     String JavaDoc[] array = split(s, delimiter);
371     short[] newArray = new short[array.length];
372
373     for (int i = 0; i < array.length; i++) {
374       short value = x;
375
376       try {
377         value = Short.parseShort(array[i]);
378       } catch (Exception JavaDoc e) {
379       }
380
381       newArray[i] = value;
382     }
383
384     return newArray;
385   }
386
387   public static final String JavaDoc stackTrace(Throwable JavaDoc t) {
388     String JavaDoc s = null;
389
390     try {
391       ByteArrayOutputStream JavaDoc baos = new ByteArrayOutputStream JavaDoc();
392       t.printStackTrace(new PrintWriter JavaDoc(baos, true));
393       s = baos.toString();
394     } catch (Exception JavaDoc e) {
395     }
396
397     return s;
398   }
399
400   public static boolean startsWith(String JavaDoc s, char begin) {
401     return startsWith(s, (new Character JavaDoc(begin)).toString());
402   }
403
404   public static boolean startsWith(String JavaDoc s, String JavaDoc begin) {
405     if ( (s == null) || (begin == null)) {
406       return false;
407     }
408
409     if (begin.length() > s.length()) {
410       return false;
411     }
412
413     String JavaDoc temp = s.substring(0, begin.length());
414
415     if (temp.equalsIgnoreCase(begin)) {
416       return true;
417     } else {
418       return false;
419     }
420   }
421
422   public static String JavaDoc wrap(String JavaDoc text) {
423     return wrap(text, 80);
424   }
425
426   public static String JavaDoc wrap(String JavaDoc text, int width) {
427     if (text == null) {
428       return null;
429     }
430
431     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
432
433     try {
434       BufferedReader JavaDoc br = new BufferedReader JavaDoc(new StringReader JavaDoc(text));
435
436       String JavaDoc s = "";
437
438       while ( (s = br.readLine()) != null) {
439         if (s.length() == 0) {
440           sb.append("\n");
441         } else {
442           while (true) {
443             int pos = s.lastIndexOf(' ', width);
444
445             if ( (pos == -1) && (s.length() > width)) {
446               sb.append(s.substring(0, width));
447               sb.append("\n");
448
449               s = s.substring(width, s.length()).trim();
450             } else if ( (pos != -1) && (s.length() > width)) {
451               sb.append(s.substring(0, pos));
452               sb.append("\n");
453
454               s = s.substring(pos, s.length()).trim();
455             } else {
456               sb.append(s);
457               sb.append("\n");
458
459               break;
460             }
461           }
462         }
463       }
464     } catch (IOException JavaDoc ioe) {
465       ioe.printStackTrace();
466     }
467
468     return sb.toString();
469   }
470
471   public static String JavaDoc getPassword(int length, String JavaDoc key) {
472
473     StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
474
475     for (int i = 0; i < length; i++) {
476       sb.append(key.charAt( (int) (Math.random() * key.length())));
477     }
478
479     return sb.toString();
480   }
481
482   public static String JavaDoc getPassword(int length) {
483     String JavaDoc key =
484         "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
485     return getPassword(length, key);
486   }
487
488   /**
489    * Encode a string using algorithm specified in web.xml and return the
490    * resulting encrypted password. If exception, the plain credentials
491    * string is returned
492    *
493    * @param password Password or other credentials to use in authenticating
494    * this username
495    * @param algorithm Algorithm used to do the digest
496    *
497    * @return encypted password based on the algorithm.
498    */

499   public static String JavaDoc encodePassword(String JavaDoc password, String JavaDoc algorithm) {
500     byte[] unencodedPassword = password.getBytes();
501
502     MessageDigest JavaDoc md = null;
503
504     try {
505       // first create an instance, given the provider
506
md = MessageDigest.getInstance(algorithm);
507     } catch (Exception JavaDoc e) {
508       System.err.print("Exception: " + e);
509
510       return password;
511     }
512
513     md.reset();
514
515     // call the update method one or more times
516
// (useful when you don't know the size of your data, eg. stream)
517
md.update(unencodedPassword);
518
519     // now calculate the hash
520
byte[] encodedPassword = md.digest();
521
522     StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
523
524     for (int i = 0; i < encodedPassword.length; i++) {
525       if ( ( (int) encodedPassword[i] & 0xff) < 0x10) {
526         buf.append("0");
527       }
528
529       buf.append(Long.toString( (int) encodedPassword[i] & 0xff, 16));
530     }
531
532     return buf.toString();
533   }
534
535   /**
536    * Encode a string using Base64 encoding. Used when storing passwords
537    * as cookies.
538    *
539    * This is weak encoding in that anyone can use the decodeString
540    * routine to reverse the encoding.
541    *
542    * @param str
543    * @return String
544    */

545   public static String JavaDoc encodeString(String JavaDoc str) {
546     sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
547     return new String JavaDoc(encoder.encodeBuffer(str.getBytes())).trim();
548   }
549
550   /**
551    * Decode a string using Base64 encoding.
552    *
553    * @param str
554    * @return String
555    */

556   public static String JavaDoc decodeString(String JavaDoc str) {
557     sun.misc.BASE64Decoder dec = new sun.misc.BASE64Decoder();
558     try {
559       return new String JavaDoc(dec.decodeBuffer(str));
560     } catch (IOException JavaDoc io) {
561       throw new RuntimeException JavaDoc(io.getMessage(), io.getCause());
562     }
563   }
564
565 }
566
Popular Tags