KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > config > backup > 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.config.backup.util;
25
26 /* WBN Valentine's Day, 2000 -- place for handy String utils.
27  */

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

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

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

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

60     public static int maxWidth(Vector v)
61     {
62         // find longest String in a vector of Strings...
63
int max = 0;
64
65         if(v == null || v.size() <= 0 || !(v.elementAt(0) instanceof String JavaDoc))
66             return 0;
67
68         for(int i = v.size() - 1; i >= 0; i--)
69         {
70             int len = ((String JavaDoc)v.elementAt(i)).length();
71
72             if(len > max)
73                 max = len;
74         }
75
76         return max;
77     }
78
79     ////////////////////////////////////////////////////////////////////////////
80

81     public static boolean isHex(String JavaDoc s)
82     {
83         // is this the String representation of a valid hex number?
84
// "5", "d", "D", "F454ecbb" all return true...
85
// p.s. there MUST be a better and faster way of doing this...
86

87         final int slen = s.length();
88
89         for(int i = 0; i < slen; i++)
90             if(isHex(s.charAt(i)) == false)
91                 return false;
92         return true;
93     }
94
95     ////////////////////////////////////////////////////////////////////////////
96

97     public static boolean isHex(char c)
98     {
99         // is this the char a valid hex digit?
100

101         String JavaDoc hex = "0123456789abcdefABCDEF";
102         int hexlen = hex.length();
103
104         for(int i = 0; i < hexlen; i++)
105             if(hex.charAt(i) == c)
106                 return true;
107
108         return false;
109     }
110
111     ////////////////////////////////////////////////////////////////////////////
112

113     public static String JavaDoc getPenultimateDirName(String JavaDoc s)
114     {
115         // e.g. input: "a/b/c/d/foobar.txt" output: "d"
116

117         if(s == null || s.length() <= 0)
118             return s;
119
120         // must be a plain file name -- return empty string...
121
if( (s.indexOf('/') < 0) && (s.indexOf('\\') < 0) )
122             return "";
123
124         s = s.replace('\\', '/'); // make life easier for the next steps...
125

126         int index = s.lastIndexOf('/');
127
128         if(index < 0)
129             return ""; // can't happen!!!
130

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

133         index = s.lastIndexOf('/');
134
135         if(index >= 0)
136             s = s.substring(index + 1);
137
138         return s;
139     }
140
141     ////////////////////////////////////////////////////////////////////////////
142

143     public static String JavaDoc toShortClassName(String JavaDoc className)
144     {
145         int index = className.lastIndexOf('.');
146
147         if(index >= 0 && index < className.length() - 1)
148             return className.substring(index + 1);
149
150         return className;
151     }
152
153     ////////////////////////////////////////////////////////////////////////////
154

155     public static String JavaDoc padRight(String JavaDoc s, int len)
156     {
157         if(s == null || s.length() >= len)
158             return s;
159
160         for(int i = len - s.length(); i > 0; --i)
161             s += ' ';
162
163         return s;
164     }
165
166     ////////////////////////////////////////////////////////////////////////////
167

168     public static String JavaDoc padLeft(String JavaDoc s, int len)
169     {
170         String JavaDoc ss = "";
171
172         if(s == null || s.length() >= len)
173             return s;
174
175         for(int i = len - s.length(); i > 0; --i)
176             ss += ' ';
177
178         return ss + s;
179     }
180
181     ////////////////////////////////////////////////////////////////////////////
182

183     public static String JavaDoc[] toLines(String JavaDoc s)
184     {
185         if(s == null)
186             return new String JavaDoc[0];
187
188         Vector v = new Vector();
189
190         int start = 0;
191         int end = 0;
192
193         for(end = s.indexOf('\n', start); end >= 0 && start < s.length(); end = s.indexOf('\n', start))
194         {
195             v.addElement(s.substring(start, end)); // does NOT include the '\n'
196
start = end + 1;
197         }
198
199         if(start < s.length())
200             v.addElement(s.substring(start));
201
202         String JavaDoc[] ss = new String JavaDoc[v.size()];
203
204         v.copyInto(ss);
205
206         return ss;
207     }
208
209     ////////////////////////////////////////////////////////////////////////////
210

211     public static void prepend(String JavaDoc[] ss, String JavaDoc what)
212     {
213         for(int i = 0; i < ss.length; i++)
214             ss[i] = what + ss[i];
215     }
216
217     ////////////////////////////////////////////////////////////////////////////
218

219     public static String JavaDoc UpperCaseFirstLetter(String JavaDoc s)
220     {
221         if(s == null || s.length() <= 0)
222             return s;
223         
224         return s.substring(0, 1).toUpperCase() + s.substring(1);
225     }
226
227     ////////////////////////////////////////////////////////////////////////////
228

229     public static String JavaDoc replace(String JavaDoc s, String JavaDoc token, String JavaDoc replace)
230     {
231         if(s == null || s.length() <= 0 || token == null || token.length() <= 0)
232             return s;
233         
234         int index = s.indexOf(token);
235
236         if(index < 0)
237             return s;
238
239         int tokenLength = token.length();
240         String JavaDoc ret = s.substring(0, index);
241         ret += replace;
242         ret += s.substring(index + tokenLength);
243
244         return ret;
245     }
246
247     ////////////////////////////////////////////////////////////////////////////
248

249     public static String JavaDoc toString(Properties props)
250     {
251         if(props == null || props.size() <= 0)
252             return "No entries";
253         
254         Set entries = props.entrySet();
255         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
256         
257         // first -- to line things up nicely -- find the longest key...
258
int keyWidth = 0;
259         for(Iterator it = entries.iterator(); it.hasNext(); )
260         {
261             Map.Entry me = (Map.Entry)it.next();
262             String JavaDoc key = (String JavaDoc)me.getKey();
263             int len = key.length();
264         
265             if(len > keyWidth)
266                 keyWidth = len;
267         }
268         
269         ++keyWidth;
270         
271         // now make the strings...
272
for(Iterator it = entries.iterator(); it.hasNext(); )
273         {
274             Map.Entry me = (Map.Entry)it.next();
275             String JavaDoc key = (String JavaDoc)me.getKey();
276             String JavaDoc val = (String JavaDoc)me.getValue();
277
278             sb.append(padRight(key, keyWidth));
279             sb.append("= ");
280             sb.append(val);
281             sb.append('\n');
282         }
283         
284         return sb.toString();
285     }
286     
287
288     // Test Code...
289

290     public static void main(String JavaDoc[] args)
291     {
292         final int len = args.length;
293
294         if((len == 1) && args[0].equalsIgnoreCase("toLine"))
295             testToLine();
296         else if((len > 1) && args[0].equalsIgnoreCase("isHex"))
297             testHex(args);
298         else
299             usage();
300     }
301
302     ////////////////////////////////////////////////////////////////////////////
303

304     private static void usage()
305     {
306         System.out.println("StringUtils -- main() for testing usage:\n");
307         System.out.println("java netscape.blizzard.util.StringUtils toLine");
308         System.out.println("java netscape.blizzard.util.StringUtils isHex number1 number2 ...");
309     }
310
311     ////////////////////////////////////////////////////////////////////////////
312

313     private static void testHex(String JavaDoc[] args)
314     {
315         System.out.println("StringUtils -- Testing Hex");
316
317         for(int i = 1; i < args.length; i++)
318             System.out.println(padRight(args[i], 16) + " " + (isHex(args[i]) ? "yesHex" : "notHex"));
319     }
320
321     ////////////////////////////////////////////////////////////////////////////
322

323     private static void testToLine()
324     {
325         System.out.println("StringUtils -- Testing toLine()");
326         String JavaDoc[] ss =
327         {
328             null,
329             "",
330             "abc\ndef\n",
331             "abc\ndef",
332             "abc",
333             "abc\n",
334             "abc\n\n",
335             "q",
336             "\n\nk\n\nz\n\n",
337             "sd.adj;ld"
338         };
339
340         for(int k = 0; k < ss.length; k++)
341         {
342             String JavaDoc[] s2 = StringUtils.toLines(ss[k]);
343             System.out.println("String #" + k + ", Number of Lines: " + s2.length);
344
345             for(int i = 0; i < s2.length; i++)
346                 System.out.println(s2[i]);
347         }
348     }
349
350     
351     public static void testUpperCase()
352     {
353         String JavaDoc[] test = new String JavaDoc[] { "xyz", "HITHERE", "123aa", "aSSS", "yothere" };//NOI18N
354

355         for(int i = 0; i < test.length; i++)
356         {
357             System.out.println(test[i] + " >>> " + UpperCaseFirstLetter(test[i]));//NOI18N
358
}
359     }
360         
361     /**
362         A utility to get the Operating System specific path from given array
363         of Strings.
364         @param strings an array of Strings participating in the path.
365         @param addTrailing a boolean that determines whether the returned
366             String should have a trailing File Separator character. None of
367             the strings may be null or empty String. An exception is thrown.
368         @return a String that concatenates these Strings and gets a path. Returns
369             a null if the array is null or contains no elements.
370         @throws IllegalArgumentException if any of the arguments is null or is
371             an empty string.
372     */

373     
374     public static String JavaDoc makeFilePath(String JavaDoc[] strings, boolean addTrailing)
375     {
376         StringBuffer JavaDoc path = null;
377         String JavaDoc separator = System.getProperty("file.separator");
378         if (strings != null)
379         {
380             path = new StringBuffer JavaDoc();
381             for (int i = 0 ; i < strings.length ; i++)
382             {
383                 String JavaDoc element = strings[i];
384                 if (element == null || element.length () == 0)
385                 {
386                     throw new IllegalArgumentException JavaDoc();
387                 }
388                 path.append(element);
389                 if (i < strings.length - 1)
390                 {
391                     path.append(separator);
392                 }
393             }
394             if (addTrailing)
395             {
396                 path.append(separator);
397             }
398         }
399         return ( path.toString() );
400     }
401
402     /**
403      * Parses a string containing substrings separated from
404      * each other by the standard separator characters and returns
405      * a list of strings.
406      *
407      * Splits the string <code>line</code> into individual string elements
408      * separated by the field separators, and returns these individual
409      * strings as a list of strings. The individual string elements are
410      * trimmed of leading and trailing whitespace. Only non-empty strings
411      * are returned in the list.
412      *
413      * @param line The string to split
414      * @return Returns the list containing the individual strings that
415      * the input string was split into.
416      */

417     public static List parseStringList(String JavaDoc line)
418     {
419         return parseStringList(line, null);
420     }
421
422     /**
423      * Parses a string containing substrings separated from
424      * each other by the specified set of 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 specified in <code>sep</code>,
429      * and returns these individual strings as a list of strings. The
430      * individual string elements are trimmed of leading and trailing
431      * whitespace. Only non-empty strings are returned in the list.
432      *
433      * @param line The string to split
434      * @param sep The list of separators to use for determining where the
435      * string should be split. If null, then the standard
436      * separators (see StringTokenizer javadocs) are used.
437      * @return Returns the list containing the individual strings that
438      * the input string was split into.
439      */

440     public static List parseStringList(String JavaDoc line, String JavaDoc sep)
441     {
442         if (line == null)
443             return null;
444
445         StringTokenizer st;
446         if (sep == null)
447             st = new StringTokenizer(line);
448         else
449             st = new StringTokenizer(line, sep);
450
451         String JavaDoc token;
452
453         List tokens = new Vector();
454         while (st.hasMoreTokens())
455         {
456             token = st.nextToken().trim();
457             if (token.length() > 0)
458                 tokens.add(token);
459         }
460
461         return tokens;
462     }
463
464 }
465
Popular Tags