KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > bsf > util > StringUtils


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 2002 The Apache Software Foundation. All rights
5  * reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  *
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  *
14  * 2. Redistributions in binary form must reproduce the above copyright
15  * notice, this list of conditions and the following disclaimer in
16  * the documentation and/or other materials provided with the
17  * distribution.
18  *
19  * 3. The end-user documentation included with the redistribution, if
20  * any, must include the following acknowlegement:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowlegement may appear in the software itself,
24  * if and wherever such third-party acknowlegements normally appear.
25  *
26  * 4. The names "Apache BSF", "Apache", and "Apache Software Foundation"
27  * must not be used to endorse or promote products derived from
28  * this software without prior written permission. For written
29  * permission, please contact apache@apache.org.
30  *
31  * 5. Products derived from this software may not be called "Apache"
32  * nor may "Apache" appear in their names without prior written
33  * permission of the Apache Group.
34  *
35  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46  * SUCH DAMAGE.
47  * ====================================================================
48  *
49  * This software consists of voluntary contributions made by many individuals
50  * on behalf of the Apache Software Foundation and was originally created by
51  * Sanjiva Weerawarana and others at International Business Machines
52  * Corporation. For more information on the Apache Software Foundation,
53  * please see <http://www.apache.org/>.
54  */

55
56 package org.apache.bsf.util;
57
58 import java.io.*;
59 import java.util.*;
60 import java.net.URL JavaDoc;
61 import java.net.MalformedURLException JavaDoc;
62 import java.beans.Introspector JavaDoc;
63
64 /**
65  * Deals with strings (probably need to elaborate some more).
66  *
67  * @author Matthew J. Duftler
68  */

69 public class StringUtils
70 {
71   public static final String JavaDoc lineSeparator =
72     System.getProperty("line.separator", "\n");
73   public static final String JavaDoc lineSeparatorStr = cleanString(lineSeparator);
74
75   public static String JavaDoc classNameToVarName(String JavaDoc className)
76   {
77     // Might represent an array.
78
int arrayDim = 0;
79
80     while (className.endsWith("[]"))
81     {
82       className = className.substring(0, className.length() - 2);
83       arrayDim++;
84     }
85
86     int iLastPeriod = className.lastIndexOf('.');
87     String JavaDoc varName = Introspector.decapitalize(
88                                          iLastPeriod != -1
89                                          ? className.substring(iLastPeriod + 1)
90                                          : className);
91
92     if (arrayDim > 0)
93     {
94       varName += "_" + arrayDim + "D";
95     }
96
97     return getValidIdentifierName(varName);
98   }
99   // Ensure that escape sequences are passed through properly.
100
public static String JavaDoc cleanString(String JavaDoc str)
101   {
102     if (str == null)
103       return null;
104     else
105     {
106       char[] charArray = str.toCharArray();
107       StringBuffer JavaDoc sBuf = new StringBuffer JavaDoc();
108       
109       for (int i = 0; i < charArray.length; i++)
110         switch (charArray[i])
111         {
112           case '\"' : sBuf.append("\\\"");
113                       break;
114           case '\\' : sBuf.append("\\\\");
115                       break;
116           case '\n' : sBuf.append("\\n");
117                       break;
118           case '\r' : sBuf.append("\\r");
119                       break;
120           default : sBuf.append(charArray[i]);
121                       break;
122         }
123       
124       return sBuf.toString();
125     }
126   }
127   /**
128    * Get a string consisting of <code>numberOfChars</code> theChars.
129    *
130    * @return a string consisting of <code>numberOfChars</code> theChars.
131    */

132   public static String JavaDoc getChars(int numberOfChars, char theChar)
133   {
134     if (numberOfChars <= 0)
135       return "";
136
137     StringBuffer JavaDoc sRet = new StringBuffer JavaDoc(numberOfChars);
138
139     for (int i = 0; i < numberOfChars; i++)
140       sRet.append(theChar);
141
142     return sRet.toString();
143   }
144   /*
145     This method will return the correct name for a class object representing
146     a primitive, a single instance of a class, as well as n-dimensional arrays
147     of primitives or instances. This logic is needed to handle the string returned
148     from Class.getName(). If the class object represents a single instance (or
149     a primitive), Class.getName() returns the fully-qualified name of the class
150     and no further work is needed. However, if the class object represents an
151     array (of n dimensions), Class.getName() returns a Descriptor (the Descriptor
152     grammar is defined in section 4.3 of the Java VM Spec). This method will
153     parse the Descriptor if necessary.
154   */

155   public static String JavaDoc getClassName(Class JavaDoc targetClass)
156   {
157     String JavaDoc className = targetClass.getName();
158
159     return targetClass.isArray() ? parseDescriptor(className) : className;
160   }
161   public static String JavaDoc getCommaListFromVector(Vector sourceVector)
162   {
163     StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
164
165     for (int i = 0; i < sourceVector.size(); i++)
166     {
167       strBuf.append((i > 0 ? ", " : "") +
168                     sourceVector.elementAt(i));
169     }
170
171     return strBuf.toString();
172   }
173   /*
174     Returns a Reader for reading from the specified resource, if the resource
175     points to a stream.
176   */

177   public static Reader getContentAsReader(URL JavaDoc url) throws SecurityException JavaDoc,
178                                                           IllegalArgumentException JavaDoc,
179                                                           IOException
180   {
181     if (url == null)
182     {
183       throw new IllegalArgumentException JavaDoc("URL cannot be null.");
184     }
185
186     try
187     {
188       Object JavaDoc content = url.getContent();
189
190       if (content == null)
191       {
192         throw new IllegalArgumentException JavaDoc("No content.");
193       }
194
195       if (content instanceof InputStream)
196       {
197         Reader in = new InputStreamReader((InputStream)content);
198
199         if (in.ready())
200         {
201           return in;
202         }
203         else
204         {
205           throw new FileNotFoundException();
206         }
207       }
208       else
209       {
210         throw new IllegalArgumentException JavaDoc((content instanceof String JavaDoc)
211                                            ? (String JavaDoc)content
212                                            : "This URL points to a: " +
213                                              StringUtils.getClassName(content.getClass()));
214       }
215     }
216     catch (SecurityException JavaDoc e)
217     {
218       throw new SecurityException JavaDoc("Your JVM's SecurityManager has disallowed this.");
219     }
220     catch (FileNotFoundException e)
221     {
222       throw new FileNotFoundException("This file was not found: " + url);
223     }
224   }
225   /*
226     Shorthand for: IOUtils.getStringFromReader(getContentAsReader(url)).
227   */

228   public static String JavaDoc getContentAsString(URL JavaDoc url) throws SecurityException JavaDoc,
229                                                           IllegalArgumentException JavaDoc,
230                                                           IOException
231   {
232     return IOUtils.getStringFromReader(getContentAsReader(url));
233   }
234   // Handles multi-line strings.
235
public static String JavaDoc getSafeString(String JavaDoc scriptStr)
236   {
237     BufferedReader in = new BufferedReader(new StringReader(scriptStr));
238     StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
239     String JavaDoc tempLine,
240                    previousLine = null;
241
242     try
243     {
244       while ((tempLine = in.readLine()) != null)
245       {
246         if (previousLine != null)
247         {
248           strBuf.append("\"" + previousLine + lineSeparatorStr + "\" +" +
249                         lineSeparator);
250         }
251
252         previousLine = cleanString(tempLine);
253       }
254     }
255     catch (IOException e)
256     {
257     }
258
259     strBuf.append("\"" + (previousLine != null ? previousLine : "") + "\"" +
260                   lineSeparator);
261
262     return strBuf.toString();
263   }
264   /*
265   */

266   public static URL JavaDoc getURL(URL JavaDoc contextURL, String JavaDoc spec) throws MalformedURLException JavaDoc
267   {
268     return getURL(contextURL, spec, 1);
269   }
270   /*
271     The recursiveDepth argument is used to insure that the algorithm gives up
272     after hunting 2 levels up in the contextURL's path.
273   */

274   private static URL JavaDoc getURL(URL JavaDoc contextURL, String JavaDoc spec, int recursiveDepth)
275                                                   throws MalformedURLException JavaDoc
276   {
277     URL JavaDoc url = null;
278
279     try
280     {
281       url = new URL JavaDoc(contextURL, spec);
282
283       try
284       {
285         url.openStream();
286       }
287       catch (IOException ioe1)
288       {
289         throw new MalformedURLException JavaDoc("This file was not found: " + url);
290       }
291     }
292     catch (MalformedURLException JavaDoc e1)
293     {
294       url = new URL JavaDoc("file", "", spec);
295
296       try
297       {
298         url.openStream();
299       }
300       catch (IOException ioe2)
301       {
302         if (contextURL != null)
303         {
304           String JavaDoc contextFileName = contextURL.getFile();
305           String JavaDoc parentName = new File(contextFileName).getParent();
306
307           if (parentName != null && recursiveDepth < 3)
308           {
309             return getURL(new URL JavaDoc("file", "", parentName + '/'),
310                           spec,
311                           recursiveDepth + 1);
312           }
313         }
314
315         throw new MalformedURLException JavaDoc("This file was not found: " + url);
316       }
317     }
318
319     return url;
320   }
321   public static String JavaDoc getValidIdentifierName(String JavaDoc identifierName)
322   {
323     if (identifierName == null || identifierName.length() == 0)
324       return null;
325
326     StringBuffer JavaDoc strBuf = new StringBuffer JavaDoc();
327
328     char[] chars = identifierName.toCharArray();
329
330     strBuf.append(Character.isJavaIdentifierStart(chars[0])
331                   ? chars[0]
332                   : '_'
333                  );
334
335     for (int i = 1; i < chars.length; i++)
336     {
337       strBuf.append(Character.isJavaIdentifierPart(chars[i])
338                     ? chars[i]
339                     : '_'
340                    );
341     }
342
343     return strBuf.toString();
344   }
345   public static boolean isValidIdentifierName(String JavaDoc identifierName)
346   {
347     if (identifierName == null || identifierName.length() == 0)
348       return false;
349
350     char[] chars = identifierName.toCharArray();
351
352     if (!Character.isJavaIdentifierStart(chars[0]))
353       return false;
354
355     for (int i = 1; i < chars.length; i++)
356       if (!Character.isJavaIdentifierPart(chars[i]))
357         return false;
358
359     return true;
360   }
361   public static boolean isValidPackageName(String JavaDoc packageName)
362   {
363     if (packageName == null)
364       return false;
365     else if (packageName.length() == 0)
366       // Empty is ok.
367
return true;
368
369     StringTokenizer strTok = new StringTokenizer(packageName, ".", true);
370
371     // Should have an odd number of tokens (including '.' delimiters).
372
if (strTok.countTokens() % 2 != 1)
373       return false;
374
375     // Must start with a valid identifier name.
376
if (!isValidIdentifierName(strTok.nextToken()))
377       return false;
378
379     // ... followed by 0 or more of ".ValidIdentifier".
380
while (strTok.hasMoreTokens())
381     {
382       // Must be a '.'.
383
if (!strTok.nextToken().equals("."))
384         return false;
385
386       // Must be a valid identifier name.
387
if (strTok.hasMoreTokens())
388       {
389         if (!isValidIdentifierName(strTok.nextToken()))
390           return false;
391       }
392       else
393         return false;
394     }
395
396     return true;
397   }
398   /*
399     See the comment above for getClassName(targetClass)...
400   */

401   private static String JavaDoc parseDescriptor(String JavaDoc className)
402   {
403     char[] classNameChars = className.toCharArray();
404     int arrayDim = 0;
405     int i = 0;
406
407     while (classNameChars[i] == '[')
408     {
409       arrayDim++;
410       i++;
411     }
412
413     StringBuffer JavaDoc classNameBuf = new StringBuffer JavaDoc();
414
415     switch (classNameChars[i++])
416     {
417       case 'B' : classNameBuf.append("byte");
418                  break;
419       case 'C' : classNameBuf.append("char");
420                  break;
421       case 'D' : classNameBuf.append("double");
422                  break;
423       case 'F' : classNameBuf.append("float");
424                  break;
425       case 'I' : classNameBuf.append("int");
426                  break;
427       case 'J' : classNameBuf.append("long");
428                  break;
429       case 'S' : classNameBuf.append("short");
430                  break;
431       case 'Z' : classNameBuf.append("boolean");
432                  break;
433       case 'L' : classNameBuf.append(classNameChars,
434                                      i, classNameChars.length - i - 1);
435                  break;
436     }
437
438     for (i = 0; i < arrayDim; i++)
439       classNameBuf.append("[]");
440
441     return classNameBuf.toString();
442   }
443 }
444
Popular Tags