KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > info > monitorenter > util > StringUtil


1 /*
2  * StringUtil, utility class for string operations.
3  * Copyright (C) Achim Westermann, created on 09.09.2004, 12:38:21
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2.1 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
18  *
19  * If you modify or optimize the code in a useful way please let me know.
20  * Achim.Westermann@gmx.de
21  *
22  */

23 package info.monitorenter.util;
24
25 import java.lang.reflect.Array JavaDoc;
26 import java.util.List JavaDoc;
27
28 /**
29  * Nice static helpers for working with Strings.
30  * <p>
31  * Maybe not always the fastest solution to call in here, but working. Also
32  * usable for seeing examples and cutting code for manual inlining.
33  * <p>
34  *
35  * @author Achim.Westermann@gmx.de
36  *
37  * @version $Revision: 1.1 $
38  */

39 public final class StringUtil {
40   /** Singleton instance. */
41   private static StringUtil instance = null;
42
43   /**
44    * Appends the given amount of spaces to the String.
45    * <p>
46    *
47    * Not intended for big append -operations because in a loop alway just one
48    * space is added.
49    * <p>
50    *
51    * @param s
52    * the base String to append spaces to.
53    *
54    * @param count
55    * the amount of spaces to append.
56    *
57    * @return a String consisting of s and count trailing whitespaces.
58    */

59   public static final String JavaDoc appendSpaces(final String JavaDoc s, final int count) {
60     StringBuffer JavaDoc tmp = new StringBuffer JavaDoc(s);
61     for (int i = 0; i < count; i++) {
62       tmp.append(" ");
63     }
64     return tmp.toString();
65   }
66
67   /**
68    * Little String output - helper that modifies the given LinkedList by getting
69    * it's Objects and replace them by their toString() - representation.
70    * <p>
71    *
72    * What is special? <br>
73    * If an Object in the given List is an Array (of Objects or primitive
74    * datatypes) reflection will be used to create a String - representation of
75    * them. The changes are reflected in the Objects that are in the given List.
76    * So keep a reference to it. If you are sure, that your List does not contain
77    * Arrays do not use this method to avoid overhead.
78    * <p>
79    *
80    * Avoid structural modifications (remove) of the list while using this
81    * method. This method or better: the given List is only thread - safe if the
82    * list is synchronized.
83    * <p>
84    *
85    * A clever VM (hotspot) will be able to inline this function because of void
86    * return.
87    * <p>
88    *
89    * @param objects
90    * the List of objects that will be changed to a list of the String
91    * representation of the Objects with respect to special array
92    * treatment.
93    *
94    */

95   public static final void arraysToString(final List JavaDoc objects) {
96     if (objects == null) {
97       return;
98     }
99     int stop = objects.size();
100     for (int i = 0; i < stop; i++) {
101       objects.add(i, arrayToString(objects.remove(i)));
102     }
103   }
104
105   /**
106    * If the given Object is no Array, it's toString - method is invoked.
107    * Primitive type - Arrays and Object - Arrays are introspected using
108    * java.lang.reflect.Array. Convention for creation fo String -
109    * representation: <br>
110    *
111    * <code>
112    * // Primitive arrays:
113    * &quot;[&quot;+isArr[0]+&quot;,&quot;+isArr[1]+.. ..+isArr[isArr.length-1]+&quot;]&quot;
114    *
115    *
116    * //Object arrays :
117    * &quot;[&quot;+isArr[0].toString()+&quot;,&quot;+.. ..+isArr[isArr.length-1].toString+&quot;]&quot;
118    * // Two or three - dimensional Arrays are not supported
119    * //(should be reflected in a special output method, e.g.as a field)
120    *
121    * // other Objects:
122    * toString()
123    * </code>
124    *
125    * @param isArr
126    * The Array to represent as String.
127    *
128    * @return a String-represetation of the Object.
129    *
130    *
131    */

132   public static final String JavaDoc arrayToString(final Object JavaDoc isArr) {
133     if (isArr == null) {
134       return "null";
135     }
136     Object JavaDoc element;
137     StringBuffer JavaDoc tmp = new StringBuffer JavaDoc();
138     try {
139       int length = Array.getLength(isArr);
140       tmp.append("[");
141       for (int i = 0; i < length; i++) {
142         element = Array.get(isArr, i);
143         if (element == null) {
144           tmp.append("null");
145         } else {
146           tmp.append(element.toString());
147         }
148         if (i < length - 1) {
149           tmp.append(",");
150         }
151       }
152       tmp.append("]");
153     } catch (ArrayIndexOutOfBoundsException JavaDoc bound) {
154       // programming mistake or bad Array.getLength(obj).
155
tmp.append("]");
156       return tmp.toString();
157
158     } catch (IllegalArgumentException JavaDoc noarr) {
159       return isArr.toString();
160     }
161     return tmp.toString();
162   }
163
164   /**
165    * Returns the system - dependant line separator.
166    * <p>
167    *
168    * Only call this method once (not in a loop) and keep the result.
169    * <p>
170    *
171    * @return the system - dependant line separator.
172    */

173   public static String JavaDoc getNewLine() {
174     return (String JavaDoc) java.security.AccessController
175         .doPrivileged(new sun.security.action.GetPropertyAction("line.separator"));
176   }
177
178   /**
179    * Returns the singleton instance of this class.
180    * <p>
181    *
182    * This method is useless for now as all methods are static. It may be used in
183    * future if VM-global configuration will be put to the state of the instance.
184    * <p>#
185    *
186    * @return the singleton instance of this class.
187    */

188   public static StringUtil instance() {
189     if (StringUtil.instance == null) {
190       StringUtil.instance = new StringUtil();
191     }
192     return StringUtil.instance;
193   }
194
195   /**
196    * Returns true if the argument is null or consists of whitespaces only.
197    * <p>
198    *
199    * @param test
200    * the <code>String</code> to test.
201    *
202    * @return true if the argument is null or consists of whitespaces only.
203    */

204   public static boolean isEmpty(final String JavaDoc test) {
205     boolean result;
206     if (test == null) {
207       result = true;
208     } else {
209       result = test.trim().length() == 0;
210     }
211     return result;
212   }
213
214   /**
215    * Returns the maximum length of a {@link Object#toString()} result in
216    * characters within the given List.
217    * <p>
218    *
219    * No data is changed in the given List at all. But the String -
220    * representation of all Objects, even Arrays is build to inspect. <br>
221    * Convention for creation fo String - representation: <br>
222    *
223    * <pre>
224    * Primitive Arrays : as performed by this classes @see #ArrayToString.
225    * Object Arrays : as performed by this classes @see #ArrayToString
226    * other Objects : toString() (as performed by this classes @see #ArrayToString).
227    * </pre>
228    *
229    * @param objects
230    * the <code>List&lt;Object&gt;</code> to inspect for the maximum
231    * lenght of a {@link Object#toString()} result.
232    *
233    * @return The length of the longest String - representation of an Object in
234    * the List <b>or 0 if objects was null or of size 0. </b>
235    */

236   public static final int longestStringRepresentation(final List JavaDoc objects) {
237     if (objects == null) {
238       return 0;
239     }
240     int maxsize = 0, tint = 0;
241     String JavaDoc tmp;
242     int stop = objects.size();
243     for (int i = 0; i < stop; i++) {
244       tmp = arrayToString(objects.get(i));
245       tint = tmp.length();
246       if (tint > maxsize) {
247         maxsize = tint;
248       }
249     }
250     // maxsize known.
251
return maxsize;
252   }
253
254   /**
255    * Appends the necessary amount of spaces to the string until it has the givn
256    * length. No Exception is thrown, if the length of the String is shorter than
257    * the given length, but nothing will happen and a message will be printed to
258    * the System.out.
259    *
260    *
261    * @param s
262    * the String to expand.
263    * @param length
264    * the desired length of the String to be returned.
265    * @return A String that represents the content of the old String including
266    * extra whitespaces.
267    */

268   public static final String JavaDoc setSize(final String JavaDoc s, final int length) {
269     String JavaDoc result = s;
270     int oldlen = s.length();
271     if (oldlen > length) {
272       System.err.println("greenpeace.util.setSize(String s,int length): length (" + length
273           + ") is smaller than s.length(" + oldlen + ") : " + s);
274     } else {
275       int tofill = length - oldlen;
276       result = appendSpaces(s, tofill);
277     }
278     return result;
279   }
280
281   /**
282    * Modifies the given LinkedList by getting it's Objects and replace them by
283    * their toString() - representation concatenated with the necessary amount of
284    * whitespaces that every String in the List will have the same amount of
285    * characters.
286    * <p>
287    *
288    * Only use this method in following case: <br>
289    * <ul>
290    * <li>You have got an AbstractList or subclass containing Objects you do not
291    * know.</li>
292    * <li>You want to transform all Elements in the List to Strings.</li>
293    * <li>There might be Array's in the Object (whose toString method will
294    * return only their hashcode).</li>
295    * </ul>
296    * <p>
297    *
298    * What happens?
299    * <ul>
300    * <li>All Objects, even primitive Arrays in your List will be turned to
301    * String- representation.</li>
302    * <li>The result will replace the old position of the Object in the given
303    * List. The old Objects will get lost!</li>
304    * <li>All Strings will be filled with whitespaces until each String has the
305    * same length.</li>
306    * </ul>
307    * At least this method will be speeded up by a hotspot VM by inlining this
308    * method. <br>
309    * <i>An example: <br>
310    * You just retrieved data from a db using jdbc and a generic class
311    * (resultset.getObject()). You want to print the data to System.out or to
312    * save it to a file, but do not know, if Arrays are contained. You want the
313    * output to be formatted (each line). </i>
314    * <p>
315    *
316    * @param objects
317    * contains the Objects to replace by their toString()
318    * representation.
319    */

320   public static final void toLongestString(final List JavaDoc objects) {
321     if (objects == null) {
322       return;
323     }
324     int maxsize = 0, tint = 0;
325     String JavaDoc tmp;
326     int stop = objects.size();
327     for (int i = 0; i < stop; i++) {
328       arrayToString(objects.get(i));
329       tmp = (String JavaDoc) objects.get(i);
330       tint = tmp.length();
331       if (tint > maxsize) {
332         maxsize = tint;
333       }
334       objects.add(i, tmp);
335     }
336     // maxsize known.
337
for (int i = 0; i < stop; i++) {
338       objects.add(i, setSize((String JavaDoc) objects.remove(i), maxsize));
339     }
340   }
341
342   /**
343    * Avoids creation from outside for singleton support.
344    * <p>
345    *
346    */

347   private StringUtil() {
348     // nop
349
}
350 }
351
Popular Tags