KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > util > StringUtils


1 /*
2  * The contents of this file are subject to the terms
3  * of the Common Development and Distribution License
4  * (the License). You may not use this file except in
5  * compliance with the License.
6  *
7  * You can obtain a copy of the license at
8  * https://glassfish.dev.java.net/public/CDDLv1.0.html or
9  * glassfish/bootstrap/legal/CDDLv1.0.txt.
10  * See the License for the specific language governing
11  * permissions and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL
14  * Header Notice in each file and include the License file
15  * at glassfish/bootstrap/legal/CDDLv1.0.txt.
16  * If applicable, add the following below the CDDL Header,
17  * with the fields enclosed by brackets [] replaced by
18  * you own identifying information:
19  * "Portions Copyrighted [year] [name of copyright owner]"
20  *
21  * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
22  */

23
24 package com.sun.enterprise.util;
25
26 /* WBN Valentine's Day, 2000 -- place for handy String utils.
27  */

28
29 import java.util.*;
30 import java.sql.SQLException JavaDoc;
31
32 public class StringUtils
33 {
34     private StringUtils()
35     {
36         
37     }
38
39     ////////////////////////////////////////////////////////////////////////////
40

41     /**
42      * return the length of the String - or 0 if it's null
43      */

44     public static int safeLength(String JavaDoc s)
45     {
46         if(s == null)
47             return 0;
48         
49         return s.length();
50     }
51
52     ////////////////////////////////////////////////////////////////////////////
53

54     public static boolean ok(String JavaDoc s)
55     {
56         return s != null && s.length() > 0;
57     }
58
59     ////////////////////////////////////////////////////////////////////////////
60

61     public static String JavaDoc formatSQLException(SQLException JavaDoc ex)
62     {
63         Assertion.check(ex);
64
65         String JavaDoc s = "SQLException:\n";
66
67         do
68         {
69             s += "SQLState: " + ex.getSQLState() + "\n";
70             s += "Message: " + ex.getMessage() + "\n";
71             s += "Vendor: " + ex.getErrorCode()+ "\n";
72             s += "\n";
73         }while( (ex = ex.getNextException()) != null);
74
75         return s;
76     }
77
78     ////////////////////////////////////////////////////////////////////////////
79

80     public static int maxWidth(Vector v)
81     {
82         // find longest String in a vector of Strings...
83
int max = 0;
84
85         if(v == null || v.size() <= 0 || !(v.elementAt(0) instanceof String JavaDoc))
86             return 0;
87
88         for(int i = v.size() - 1; i >= 0; i--)
89         {
90             int len = ((String JavaDoc)v.elementAt(i)).length();
91
92             if(len > max)
93                 max = len;
94         }
95
96         return max;
97     }
98
99     ////////////////////////////////////////////////////////////////////////////
100

101     public static boolean isHex(String JavaDoc s)
102     {
103         // is this the String representation of a valid hex number?
104
// "5", "d", "D", "F454ecbb" all return true...
105
// p.s. there MUST be a better and faster way of doing this...
106

107         final int slen = s.length();
108
109         for(int i = 0; i < slen; i++)
110             if(isHex(s.charAt(i)) == false)
111                 return false;
112         return true;
113     }
114
115     ////////////////////////////////////////////////////////////////////////////
116

117     public static boolean isHex(char c)
118     {
119         // is this the char a valid hex digit?
120

121         String JavaDoc hex = "0123456789abcdefABCDEF";
122         int hexlen = hex.length();
123
124         for(int i = 0; i < hexlen; i++)
125             if(hex.charAt(i) == c)
126                 return true;
127
128         return false;
129     }
130
131     ////////////////////////////////////////////////////////////////////////////
132

133     public static String JavaDoc getPenultimateDirName(String JavaDoc s)
134     {
135         // e.g. input: "a/b/c/d/foobar.txt" output: "d"
136

137         if(s == null || s.length() <= 0)
138             return s;
139
140         // must be a plain file name -- return empty string...
141
if( (s.indexOf('/') < 0) && (s.indexOf('\\') < 0) )
142             return "";
143
144         s = s.replace('\\', '/'); // make life easier for the next steps...
145

146         int index = s.lastIndexOf('/');
147
148         if(index < 0)
149             return ""; // can't happen!!!
150

151         s = s.substring(0, index); // this will truncate the last '/'
152

153         index = s.lastIndexOf('/');
154
155         if(index >= 0)
156             s = s.substring(index + 1);
157
158         return s;
159     }
160
161     ////////////////////////////////////////////////////////////////////////////
162

163     public static String JavaDoc toShortClassName(String JavaDoc className)
164     {
165         int index = className.lastIndexOf('.');
166
167         if(index >= 0 && index < className.length() - 1)
168             return className.substring(index + 1);
169
170         return className;
171     }
172
173     ////////////////////////////////////////////////////////////////////////////
174

175     public static String JavaDoc padRight(String JavaDoc s, int len)
176     {
177         if(s == null || s.length() >= len)
178             return s;
179
180         for(int i = len - s.length(); i > 0; --i)
181             s += ' ';
182
183         return s;
184     }
185
186     ////////////////////////////////////////////////////////////////////////////
187

188     public static String JavaDoc padLeft(String JavaDoc s, int len)
189     {
190         String JavaDoc ss = "";
191
192         if(s == null || s.length() >= len)
193             return s;
194
195         for(int i = len - s.length(); i > 0; --i)
196             ss += ' ';
197
198         return ss + s;
199     }
200
201     ////////////////////////////////////////////////////////////////////////////
202

203     public static String JavaDoc[] toLines(String JavaDoc s)
204     {
205         if(s == null)
206             return new String JavaDoc[0];
207
208         Vector v = new Vector();
209
210         int start = 0;
211         int end = 0;
212
213         for(end = s.indexOf('\n', start); end >= 0 && start < s.length(); end = s.indexOf('\n', start))
214         {
215             v.addElement(s.substring(start, end)); // does NOT include the '\n'
216
start = end + 1;
217         }
218
219         if(start < s.length())
220             v.addElement(s.substring(start));
221
222         String JavaDoc[] ss = new String JavaDoc[v.size()];
223
224         v.copyInto(ss);
225
226         return ss;
227     }
228
229     ////////////////////////////////////////////////////////////////////////////
230

231     public static void prepend(String JavaDoc[] ss, String JavaDoc what)
232     {
233         for(int i = 0; i < ss.length; i++)
234             ss[i] = what + ss[i];
235     }
236
237     ////////////////////////////////////////////////////////////////////////////
238

239     public static String JavaDoc UpperCaseFirstLetter(String JavaDoc s)
240     {
241         if(s == null || s.length() <= 0)
242             return s;
243         
244         return s.substring(0, 1).toUpperCase() + s.substring(1);
245     }
246
247     ////////////////////////////////////////////////////////////////////////////
248

249     public static String JavaDoc replace(String JavaDoc s, String JavaDoc token, String JavaDoc replace)
250     {
251         if(s == null || s.length() <= 0 || token == null || token.length() <= 0)
252             return s;
253         
254         int index = s.indexOf(token);
255
256         if(index < 0)
257             return s;
258
259         int tokenLength = token.length();
260         String JavaDoc ret = s.substring(0, index);
261         ret += replace;
262         ret += s.substring(index + tokenLength);
263
264         return ret;
265     }
266
267     ////////////////////////////////////////////////////////////////////////////
268

269     public static String JavaDoc toString(Properties props)
270     {
271         if(props == null || props.size() <= 0)
272             return "No entries";
273         
274         Set entries = props.entrySet();
275         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
276         
277         // first -- to line things up nicely -- find the longest key...
278
int keyWidth = 0;
279         for(Iterator it = entries.iterator(); it.hasNext(); )
280         {
281             Map.Entry me = (Map.Entry)it.next();
282             String JavaDoc key = (String JavaDoc)me.getKey();
283             int len = key.length();
284         
285             if(len > keyWidth)
286                 keyWidth = len;
287         }
288         
289         ++keyWidth;
290         
291         // now make the strings...
292
for(Iterator it = entries.iterator(); it.hasNext(); )
293         {
294             Map.Entry me = (Map.Entry)it.next();
295             String JavaDoc key = (String JavaDoc)me.getKey();
296             String JavaDoc val = (String JavaDoc)me.getValue();
297
298             sb.append(padRight(key, keyWidth));
299             sb.append("= ");
300             sb.append(val);
301             sb.append('\n');
302         }
303         
304         return sb.toString();
305     }
306     
307
308     // Test Code...
309

310     public static void main(String JavaDoc[] args)
311     {
312         final int len = args.length;
313
314         if((len == 1) && args[0].equalsIgnoreCase("toLine"))
315             testToLine();
316         else if((len > 1) && args[0].equalsIgnoreCase("isHex"))
317             testHex(args);
318         else
319             usage();
320     }
321
322     ////////////////////////////////////////////////////////////////////////////
323

324     private static void usage()
325     {
326         System.out.println("StringUtils -- main() for testing usage:\n");
327         System.out.println("java netscape.blizzard.util.StringUtils toLine");
328         System.out.println("java netscape.blizzard.util.StringUtils isHex number1 number2 ...");
329     }
330
331     ////////////////////////////////////////////////////////////////////////////
332

333     private static void testHex(String JavaDoc[] args)
334     {
335         System.out.println("StringUtils -- Testing Hex");
336
337         for(int i = 1; i < args.length; i++)
338             System.out.println(padRight(args[i], 16) + " " + (isHex(args[i]) ? "yesHex" : "notHex"));
339     }
340
341     ////////////////////////////////////////////////////////////////////////////
342

343     private static void testToLine()
344     {
345         System.out.println("StringUtils -- Testing toLine()");
346         String JavaDoc[] ss =
347         {
348             null,
349             "",
350             "abc\ndef\n",
351             "abc\ndef",
352             "abc",
353             "abc\n",
354             "abc\n\n",
355             "q",
356             "\n\nk\n\nz\n\n",
357             "sd.adj;ld"
358         };
359
360         for(int k = 0; k < ss.length; k++)
361         {
362             String JavaDoc[] s2 = StringUtils.toLines(ss[k]);
363             System.out.println("String #" + k + ", Number of Lines: " + s2.length);
364
365             for(int i = 0; i < s2.length; i++)
366                 System.out.println(s2[i]);
367         }
368     }
369
370     
371     public static void testUpperCase()
372     {
373         String JavaDoc[] test = new String JavaDoc[] { "xyz", "HITHERE", "123aa", "aSSS", "yothere" };//NOI18N
374

375         for(int i = 0; i < test.length; i++)
376         {
377             System.out.println(test[i] + " >>> " + UpperCaseFirstLetter(test[i]));//NOI18N
378
}
379     }
380         
381     /**
382         A utility to get the Operating System specific path from given array
383         of Strings.
384         @param strings an array of Strings participating in the path.
385         @param addTrailing a boolean that determines whether the returned
386             String should have a trailing File Separator character. None of
387             the strings may be null or empty String. An exception is thrown.
388         @return a String that concatenates these Strings and gets a path. Returns
389             a null if the array is null or contains no elements.
390         @throws IllegalArgumentException if any of the arguments is null or is
391             an empty string.
392     */

393     
394     public static String JavaDoc makeFilePath(String JavaDoc[] strings, boolean addTrailing)
395     {
396         StringBuffer JavaDoc path = null;
397         String JavaDoc separator = System.getProperty("file.separator");
398         if (strings != null)
399         {
400             path = new StringBuffer JavaDoc();
401             for (int i = 0 ; i < strings.length ; i++)
402             {
403                 String JavaDoc element = strings[i];
404                 if (element == null || element.length () == 0)
405                 {
406                     throw new IllegalArgumentException JavaDoc();
407                 }
408                 path.append(element);
409                 if (i < strings.length - 1)
410                 {
411                     path.append(separator);
412                 }
413             }
414             if (addTrailing)
415             {
416                 path.append(separator);
417             }
418         }
419         return ( path.toString() );
420     }
421
422     /**
423      * Parses a string containing substrings separated from
424      * each other by the standard separator characters and returns
425      * a list of strings.
426      *
427      * Splits the string <code>line</code> into individual string elements
428      * separated by the field separators, and returns these individual
429      * strings as a list of strings. The individual string elements are
430      * trimmed of leading and trailing whitespace. Only non-empty strings
431      * are returned in the list.
432      *
433      * @param line The string to split
434      * @return Returns the list containing the individual strings that
435      * the input string was split into.
436      */

437     public static List parseStringList(String JavaDoc line)
438     {
439         return parseStringList(line, null);
440     }
441
442     /**
443      * Parses a string containing substrings separated from
444      * each other by the specified set of separator characters and returns
445      * a list of strings.
446      *
447      * Splits the string <code>line</code> into individual string elements
448      * separated by the field separators specified in <code>sep</code>,
449      * and returns these individual strings as a list of strings. The
450      * individual string elements are trimmed of leading and trailing
451      * whitespace. Only non-empty strings are returned in the list.
452      *
453      * @param line The string to split
454      * @param sep The list of separators to use for determining where the
455      * string should be split. If null, then the standard
456      * separators (see StringTokenizer javadocs) are used.
457      * @return Returns the list containing the individual strings that
458      * the input string was split into.
459      */

460     public static List parseStringList(String JavaDoc line, String JavaDoc sep)
461     {
462         if (line == null)
463             return null;
464
465         StringTokenizer st;
466         if (sep == null)
467             st = new StringTokenizer(line);
468         else
469             st = new StringTokenizer(line, sep);
470
471         String JavaDoc token;
472
473         List tokens = new Vector();
474         while (st.hasMoreTokens())
475         {
476             token = st.nextToken().trim();
477             if (token.length() > 0)
478                 tokens.add(token);
479         }
480
481         return tokens;
482     }
483
484 }
485
Popular Tags