KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > hibernate > util > StringHelper


1 //$Id: StringHelper.java,v 1.21 2005/07/07 14:22:06 steveebersole Exp $
2
package org.hibernate.util;
3
4 import java.util.Iterator JavaDoc;
5 import java.util.StringTokenizer JavaDoc;
6 import java.util.ArrayList JavaDoc;
7
8 public final class StringHelper {
9
10     private static final int ALIAS_TRUNCATE_LENGTH = 10;
11     public static final String JavaDoc WHITESPACE = " \n\r\f\t";
12
13     private StringHelper() { /* static methods only - hide constructor */
14     }
15     
16     /*public static boolean containsDigits(String string) {
17         for ( int i=0; i<string.length(); i++ ) {
18             if ( Character.isDigit( string.charAt(i) ) ) return true;
19         }
20         return false;
21     }*/

22
23     public static int lastIndexOfLetter(String JavaDoc string) {
24         for ( int i=0; i<string.length(); i++ ) {
25             char character = string.charAt(i);
26             if ( !Character.isLetter(character) /*&& !('_'==character)*/ ) return i-1;
27         }
28         return string.length()-1;
29     }
30
31     public static String JavaDoc join(String JavaDoc seperator, String JavaDoc[] strings) {
32         int length = strings.length;
33         if ( length == 0 ) return "";
34         StringBuffer JavaDoc buf = new StringBuffer JavaDoc( length * strings[0].length() )
35                 .append( strings[0] );
36         for ( int i = 1; i < length; i++ ) {
37             buf.append( seperator ).append( strings[i] );
38         }
39         return buf.toString();
40     }
41
42     public static String JavaDoc join(String JavaDoc seperator, Iterator JavaDoc objects) {
43         StringBuffer JavaDoc buf = new StringBuffer JavaDoc();
44         if ( objects.hasNext() ) buf.append( objects.next() );
45         while ( objects.hasNext() ) {
46             buf.append( seperator ).append( objects.next() );
47         }
48         return buf.toString();
49     }
50
51     public static String JavaDoc[] add(String JavaDoc[] x, String JavaDoc sep, String JavaDoc[] y) {
52         String JavaDoc[] result = new String JavaDoc[x.length];
53         for ( int i = 0; i < x.length; i++ ) {
54             result[i] = x[i] + sep + y[i];
55         }
56         return result;
57     }
58
59     public static String JavaDoc repeat(String JavaDoc string, int times) {
60         StringBuffer JavaDoc buf = new StringBuffer JavaDoc( string.length() * times );
61         for ( int i = 0; i < times; i++ ) buf.append( string );
62         return buf.toString();
63     }
64
65
66     public static String JavaDoc replace(String JavaDoc template, String JavaDoc placeholder, String JavaDoc replacement) {
67         return replace( template, placeholder, replacement, false );
68     }
69
70     public static String JavaDoc[] replace(String JavaDoc templates[], String JavaDoc placeholder, String JavaDoc replacement) {
71         String JavaDoc[] result = new String JavaDoc[templates.length];
72         for ( int i =0; i<templates.length; i++ ) {
73             result[i] = replace( templates[i], placeholder, replacement );;
74         }
75         return result;
76     }
77
78     public static String JavaDoc replace(String JavaDoc template, String JavaDoc placeholder, String JavaDoc replacement, boolean wholeWords) {
79         int loc = template == null ? -1 : template.indexOf( placeholder );
80         if ( loc < 0 ) {
81             return template;
82         }
83         else {
84             final boolean actuallyReplace = !wholeWords ||
85                     loc + placeholder.length() == template.length() ||
86                     !Character.isJavaIdentifierPart( template.charAt( loc + placeholder.length() ) );
87             String JavaDoc actualReplacement = actuallyReplace ? replacement : placeholder;
88             return new StringBuffer JavaDoc( template.substring( 0, loc ) )
89                     .append( actualReplacement )
90                     .append( replace( template.substring( loc + placeholder.length() ),
91                             placeholder,
92                             replacement,
93                             wholeWords ) ).toString();
94         }
95     }
96
97
98     public static String JavaDoc replaceOnce(String JavaDoc template, String JavaDoc placeholder, String JavaDoc replacement) {
99         int loc = template == null ? -1 : template.indexOf( placeholder );
100         if ( loc < 0 ) {
101             return template;
102         }
103         else {
104             return new StringBuffer JavaDoc( template.substring( 0, loc ) )
105                     .append( replacement )
106                     .append( template.substring( loc + placeholder.length() ) )
107                     .toString();
108         }
109     }
110
111
112     public static String JavaDoc[] split(String JavaDoc seperators, String JavaDoc list) {
113         return split( seperators, list, false );
114     }
115
116     public static String JavaDoc[] split(String JavaDoc seperators, String JavaDoc list, boolean include) {
117         StringTokenizer JavaDoc tokens = new StringTokenizer JavaDoc( list, seperators, include );
118         String JavaDoc[] result = new String JavaDoc[ tokens.countTokens() ];
119         int i = 0;
120         while ( tokens.hasMoreTokens() ) {
121             result[i++] = tokens.nextToken();
122         }
123         return result;
124     }
125
126     public static String JavaDoc unqualify(String JavaDoc qualifiedName) {
127         return qualifiedName.substring( qualifiedName.lastIndexOf(".") + 1 );
128     }
129
130     public static String JavaDoc qualifier(String JavaDoc qualifiedName) {
131         int loc = qualifiedName.lastIndexOf(".");
132         return ( loc < 0 ) ? "" : qualifiedName.substring( 0, loc );
133     }
134
135     public static String JavaDoc[] suffix(String JavaDoc[] columns, String JavaDoc suffix) {
136         if ( suffix == null ) return columns;
137         String JavaDoc[] qualified = new String JavaDoc[columns.length];
138         for ( int i = 0; i < columns.length; i++ ) {
139             qualified[i] = suffix( columns[i], suffix );
140         }
141         return qualified;
142     }
143
144     private static String JavaDoc suffix(String JavaDoc name, String JavaDoc suffix) {
145         return ( suffix == null ) ? name : name + suffix;
146     }
147
148     public static String JavaDoc root(String JavaDoc qualifiedName) {
149         int loc = qualifiedName.indexOf( "." );
150         return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( 0, loc );
151     }
152
153     public static String JavaDoc unroot(String JavaDoc qualifiedName) {
154         int loc = qualifiedName.indexOf( "." );
155         return ( loc < 0 ) ? qualifiedName : qualifiedName.substring( loc+1, qualifiedName.length() );
156     }
157
158     public static boolean booleanValue(String JavaDoc tfString) {
159         String JavaDoc trimmed = tfString.trim().toLowerCase();
160         return trimmed.equals( "true" ) || trimmed.equals( "t" );
161     }
162
163     public static String JavaDoc toString(Object JavaDoc[] array) {
164         int len = array.length;
165         if ( len == 0 ) return "";
166         StringBuffer JavaDoc buf = new StringBuffer JavaDoc( len * 12 );
167         for ( int i = 0; i < len - 1; i++ ) {
168             buf.append( array[i] ).append(", ");
169         }
170         return buf.append( array[len - 1] ).toString();
171     }
172
173     public static String JavaDoc[] multiply(String JavaDoc string, Iterator JavaDoc placeholders, Iterator JavaDoc replacements) {
174         String JavaDoc[] result = new String JavaDoc[]{string};
175         while ( placeholders.hasNext() ) {
176             result = multiply( result, ( String JavaDoc ) placeholders.next(), ( String JavaDoc[] ) replacements.next() );
177         }
178         return result;
179     }
180
181     private static String JavaDoc[] multiply(String JavaDoc[] strings, String JavaDoc placeholder, String JavaDoc[] replacements) {
182         String JavaDoc[] results = new String JavaDoc[replacements.length * strings.length];
183         int n = 0;
184         for ( int i = 0; i < replacements.length; i++ ) {
185             for ( int j = 0; j < strings.length; j++ ) {
186                 results[n++] = replaceOnce( strings[j], placeholder, replacements[i] );
187             }
188         }
189         return results;
190     }
191
192     public static int countUnquoted(String JavaDoc string, char character) {
193         if ( '\'' == character ) {
194             throw new IllegalArgumentException JavaDoc( "Unquoted count of quotes is invalid" );
195         }
196         if (string == null)
197             return 0;
198         // Impl note: takes advantage of the fact that an escpaed single quote
199
// embedded within a quote-block can really be handled as two seperate
200
// quote-blocks for the purposes of this method...
201
int count = 0;
202         int stringLength = string.length();
203         boolean inQuote = false;
204         for ( int indx = 0; indx < stringLength; indx++ ) {
205             char c = string.charAt( indx );
206             if ( inQuote ) {
207                 if ( '\'' == c ) {
208                     inQuote = false;
209                 }
210             }
211             else if ( '\'' == c ) {
212                 inQuote = true;
213             }
214             else if ( c == character ) {
215                 count++;
216             }
217         }
218         return count;
219     }
220
221     public static int[] locateUnquoted(String JavaDoc string, char character) {
222         if ( '\'' == character ) {
223             throw new IllegalArgumentException JavaDoc( "Unquoted count of quotes is invalid" );
224         }
225         if (string == null) {
226             return new int[0];
227         }
228
229         ArrayList JavaDoc locations = new ArrayList JavaDoc( 20 );
230
231         // Impl note: takes advantage of the fact that an escpaed single quote
232
// embedded within a quote-block can really be handled as two seperate
233
// quote-blocks for the purposes of this method...
234
int stringLength = string.length();
235         boolean inQuote = false;
236         for ( int indx = 0; indx < stringLength; indx++ ) {
237             char c = string.charAt( indx );
238             if ( inQuote ) {
239                 if ( '\'' == c ) {
240                     inQuote = false;
241                 }
242             }
243             else if ( '\'' == c ) {
244                 inQuote = true;
245             }
246             else if ( c == character ) {
247                 locations.add( new Integer JavaDoc( indx ) );
248             }
249         }
250         return ArrayHelper.toIntArray( locations );
251     }
252
253     public static boolean isNotEmpty(String JavaDoc string) {
254         return string != null && string.length() > 0;
255     }
256
257     public static boolean isEmpty(String JavaDoc string) {
258         return string == null || string.length() == 0;
259     }
260
261     public static String JavaDoc qualify(String JavaDoc prefix, String JavaDoc name) {
262         if ( name == null || prefix == null ) {
263             throw new NullPointerException JavaDoc();
264         }
265         return new StringBuffer JavaDoc( prefix.length() + name.length() + 1 )
266                 .append(prefix)
267                 .append('.')
268                 .append(name)
269                 .toString();
270     }
271
272     public static String JavaDoc[] qualify(String JavaDoc prefix, String JavaDoc[] names) {
273         if ( prefix == null ) return names;
274         int len = names.length;
275         String JavaDoc[] qualified = new String JavaDoc[len];
276         for ( int i = 0; i < len; i++ ) {
277             qualified[i] = qualify( prefix, names[i] );
278         }
279         return qualified;
280     }
281
282     public static int firstIndexOfChar(String JavaDoc sqlString, String JavaDoc string, int startindex) {
283         int matchAt = -1;
284         for ( int i = 0; i < string.length(); i++ ) {
285             int curMatch = sqlString.indexOf( string.charAt( i ), startindex );
286             if ( curMatch >= 0 ) {
287                 if ( matchAt == -1 ) { // first time we find match!
288
matchAt = curMatch;
289                 }
290                 else {
291                     matchAt = Math.min( matchAt, curMatch );
292                 }
293             }
294         }
295         return matchAt;
296     }
297
298     public static String JavaDoc truncate(String JavaDoc string, int length) {
299         if ( string.length() <= length ) {
300             return string;
301         }
302         else {
303             return string.substring( 0, length );
304         }
305     }
306
307     /**
308      * Generate a nice alias for the given class name or collection role
309      * name and unique integer. Subclasses of Loader do <em>not</em> have
310      * to use aliases of this form.
311      * @return an alias of the form <tt>foo1_</tt>
312      */

313     public static String JavaDoc generateAlias(String JavaDoc description, int unique) {
314         return generateAliasRoot(description) +
315             Integer.toString(unique) +
316             '_';
317     }
318
319     private static String JavaDoc generateAliasRoot(String JavaDoc description) {
320         final String JavaDoc result = truncate( unqualifyEntityName(description), ALIAS_TRUNCATE_LENGTH )
321                 .toLowerCase()
322                 .replace( '/', '_' ) // entityNames may now include slashes for the representations
323
.replace( '$', '_' ); //classname may be an inner class
324
if ( Character.isDigit( result.charAt(result.length()-1) ) ) {
325             return result + "x"; //ick!
326
}
327         else {
328             return result;
329         }
330     }
331
332     public static String JavaDoc unqualifyEntityName(String JavaDoc entityName) {
333         String JavaDoc result = unqualify(entityName);
334         int slashPos = result.indexOf( '/' );
335         if ( slashPos > 0 ) {
336             result = result.substring( 0, slashPos - 1 );
337         }
338         return result;
339     }
340
341     public static String JavaDoc generateAlias(String JavaDoc description) {
342         return generateAliasRoot(description) + '_';
343     }
344     
345     public static String JavaDoc toUpperCase(String JavaDoc str) {
346         return str==null ? null : str.toUpperCase();
347     }
348     
349     public static String JavaDoc toLowerCase(String JavaDoc str) {
350         return str==null ? null : str.toLowerCase();
351     }
352
353     public static String JavaDoc moveAndToBeginning(String JavaDoc filter) {
354         if ( filter.trim().length()>0 ){
355             filter += " and ";
356             if ( filter.startsWith(" and ") ) filter = filter.substring(4);
357         }
358         return filter;
359     }
360     
361 }
362
Popular Tags