KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > util > Strings


1 /*
2   * JBoss, Home of Professional Open Source
3   * Copyright 2005, JBoss Inc., and individual contributors as indicated
4   * by the @authors tag. See the copyright.txt in the distribution for a
5   * full listing of individual contributors.
6   *
7   * This is free software; you can redistribute it and/or modify it
8   * under the terms of the GNU Lesser General Public License as
9   * published by the Free Software Foundation; either version 2.1 of
10   * the License, or (at your option) any later version.
11   *
12   * This software is distributed in the hope that it will be useful,
13   * but WITHOUT ANY WARRANTY; without even the implied warranty of
14   * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15   * Lesser General Public License for more details.
16   *
17   * You should have received a copy of the GNU Lesser General Public
18   * License along with this software; if not, write to the Free
19   * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
20   * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
21   */

22 package org.jboss.util;
23
24 import java.io.File JavaDoc;
25 import java.io.IOException JavaDoc;
26 import java.net.MalformedURLException JavaDoc;
27 import java.net.URI JavaDoc;
28 import java.net.URISyntaxException JavaDoc;
29 import java.net.URL JavaDoc;
30 import java.net.URLEncoder JavaDoc;
31 import java.util.Map JavaDoc;
32
33 /**
34  * A collection of String utilities.
35  *
36  * @author <a HREF="mailto:jason@planet57.com">Jason Dillon</a>
37  * @author <a HREF="Scott.Stark@jboss.org">Scott Stark</a>
38  * @author <a HREF="claudio.vesco@previnet.it">Claudio Vesco</a>
39  * @author <a HREF="mailto:dimitris@jboss.org">Dimitris Andreadis</a>
40  * @version <tt>$Revision: 2162 $</tt>
41  */

42 public final class Strings
43 {
44    /** An empty string constant */
45    public static final String JavaDoc EMPTY = "";
46
47    /** Millisecond conversion constants */
48    private static final long MSEC = 1;
49    private static final long SECS = 1000;
50    private static final long MINS = 60 * 1000;
51    private static final long HOUR = 60 * 60 * 1000;
52    
53    /**
54     * List of valid Java keywords, see The Java Language Specification
55     * Second Edition Section 3.9, 3.10.3 and 3.10.7
56     */

57    private static final String JavaDoc[] keywords =
58       {
59          "abstract",
60          "boolean",
61          "break",
62          "byte",
63          "case",
64          "catch",
65          "char",
66          "class",
67          "const",
68          "continue",
69          "default",
70          "do",
71          "double",
72          "else",
73          "extends",
74          "final",
75          "finally",
76          "float",
77          "for",
78          "goto",
79          "if",
80          "implements",
81          "import",
82          "instanceof",
83          "int",
84          "interface",
85          "long",
86          "native",
87          "new",
88          "package",
89          "private",
90          "protected",
91          "public",
92          "return",
93          "short",
94          "static",
95          "strictfp",
96          "super",
97          "switch",
98          "synchronized",
99          "this",
100          "throw",
101          "throws",
102          "transient",
103          "try",
104          "void",
105          "volatile",
106          "while",
107
108          "true", // technically no keywords but we are not picky
109
"false",
110          "null"
111       };
112
113    /**
114     * List of EJB-QL Identifiers as defined in the EJB 2.0 Specification
115     * Section 11.2.6.1
116     */

117    private static final String JavaDoc[] ejbQlIdentifiers =
118       {
119          "AND",
120          "AS",
121          "BETWEEN",
122          "DISTINCT",
123          "EMPTY",
124          "FALSE",
125          "FROM",
126          "IN",
127          "IS",
128          "LIKE",
129          "MEMBER",
130          "NOT",
131          "NULL",
132          "OBJECT",
133          "OF",
134          "OR",
135          "SELECT",
136          "UNKNOWN",
137          "TRUE",
138          "WHERE",
139       };
140
141    /////////////////////////////////////////////////////////////////////////
142
// Substitution Methods //
143
/////////////////////////////////////////////////////////////////////////
144

145    /**
146     * Substitute sub-strings in side of a string.
147     *
148     * @param buff Stirng buffer to use for substitution (buffer is not reset)
149     * @param from String to substitute from
150     * @param to String to substitute to
151     * @param string String to look for from in
152     * @return Substituted string
153     */

154    public static String JavaDoc subst(final StringBuffer JavaDoc buff, final String JavaDoc from,
155       final String JavaDoc to, final String JavaDoc string)
156    {
157       int begin = 0, end = 0;
158
159       while ((end = string.indexOf(from, end)) != -1)
160       {
161          // append the first part of the string
162
buff.append(string.substring(begin, end));
163
164          // append the replaced string
165
buff.append(to);
166
167          // update positions
168
begin = end + from.length();
169          end = begin;
170       }
171
172       // append the rest of the string
173
buff.append(string.substring(begin, string.length()));
174
175       return buff.toString();
176    }
177
178    /**
179     * Substitute sub-strings in side of a string.
180     *
181     * @param from String to substitute from
182     * @param to String to substitute to
183     * @param string String to look for from in
184     * @return Substituted string
185     */

186    public static String JavaDoc subst(final String JavaDoc from, final String JavaDoc to,
187       final String JavaDoc string)
188    {
189       return subst(new StringBuffer JavaDoc(), from, to, string);
190    }
191
192    /**
193     * Substitute sub-strings in side of a string.
194     *
195     * @param buff String buffer to use for substitution (buffer is not reset)
196     * @param string String to subst mappings in
197     * @param map Map of from->to strings
198     * @param beginToken Beginning token
199     * @param endToken Ending token
200     * @return Substituted string
201     */

202    public static String JavaDoc subst(final StringBuffer JavaDoc buff, final String JavaDoc string,
203       final Map JavaDoc map, final String JavaDoc beginToken,
204       final String JavaDoc endToken)
205    {
206       int begin = 0, rangeEnd = 0;
207       Range range;
208
209       while ((range = rangeOf(beginToken, endToken, string, rangeEnd)) != null)
210       {
211          // append the first part of the string
212
buff.append(string.substring(begin, range.begin));
213
214          // Get the string to replace from the map
215
String JavaDoc key = string.substring(range.begin + beginToken.length(),
216             range.end);
217          Object JavaDoc value = map.get(key);
218          // if mapping does not exist then use empty;
219
if (value == null) value = EMPTY;
220
221          // append the replaced string
222
buff.append(value);
223
224          // update positions
225
begin = range.end + endToken.length();
226          rangeEnd = begin;
227       }
228
229       // append the rest of the string
230
buff.append(string.substring(begin, string.length()));
231
232       return buff.toString();
233    }
234
235    /**
236     * Substitute sub-strings in side of a string.
237     *
238     * @param string String to subst mappings in
239     * @param map Map of from->to strings
240     * @param beginToken Beginning token
241     * @param endToken Ending token
242     * @return Substituted string
243     */

244    public static String JavaDoc subst(final String JavaDoc string, final Map JavaDoc map,
245       final String JavaDoc beginToken, final String JavaDoc endToken)
246    {
247       return subst(new StringBuffer JavaDoc(), string, map, beginToken, endToken);
248    }
249
250    /**
251     * Substitute index identifiers with the replacement value from the
252     * given array for the corresponding index.
253     *
254     * @param buff The string buffer used for the substitution
255     * (buffer is not reset).
256     * @param string String substitution format.
257     * @param replace Array of strings whose values will be used as
258     * replacements in the given string when a token with
259     * their index is found.
260     * @param token The character token to specify the start of an index
261     * reference.
262     * @return Substituted string.
263     */

264    public static String JavaDoc subst(final StringBuffer JavaDoc buff, final String JavaDoc string,
265       final String JavaDoc replace[], final char token)
266    {
267       int i = string.length();
268       for (int j = 0; j >= 0 && j < i; j++)
269       {
270          char c = string.charAt(j);
271
272          // if the char is the token, then get the index
273
if (c == token)
274          {
275
276             // if we aren't at the end of the string, get the index
277
if (j != i)
278             {
279                int k = Character.digit(string.charAt(j + 1), 10);
280
281                if (k == -1)
282                {
283                   buff.append(string.charAt(j + 1));
284                }
285                else if (k < replace.length)
286                {
287                   buff.append(replace[k]);
288                }
289
290                j++;
291             }
292          }
293          else
294          {
295             buff.append(c);
296          }
297       }
298
299       return buff.toString();
300    }
301
302    /**
303     * Substitute index identifiers with the replacement value from the
304     * given array for the corresponding index.
305     *
306     * @param string String substitution format.
307     * @param replace Array of strings whose values will be used as
308     * replacements in the given string when a token with
309     * their index is found.
310     * @param token The character token to specify the start of an index
311     * reference.
312     * @return Substituted string.
313     */

314    public static String JavaDoc subst(final String JavaDoc string, final String JavaDoc replace[],
315       final char token)
316    {
317       return subst(new StringBuffer JavaDoc(), string, replace, token);
318    }
319
320    /**
321     * Substitute index identifiers (with <code>%</code> for the index token)
322     * with the replacement value from the given array for the corresponding
323     * index.
324     *
325     * @param string String substitution format.
326     * @param replace Array of strings whose values will be used as
327     * replacements in the given string when a token with
328     * their index is found.
329     * @return Substituted string.
330     */

331    public static String JavaDoc subst(final String JavaDoc string, final String JavaDoc replace[])
332    {
333       return subst(new StringBuffer JavaDoc(), string, replace, '%');
334    }
335
336    /////////////////////////////////////////////////////////////////////////
337
// Range Methods //
338
/////////////////////////////////////////////////////////////////////////
339

340    /**
341     * Represents a range between two integers.
342     */

343    public static class Range
344    {
345       /** The beginning of the range. */
346       public int begin;
347
348       /** The end of the range. */
349       public int end;
350
351       /**
352        * Construct a new range.
353        *
354        * @param begin The beginning of the range.
355        * @param end The end of the range.
356        */

357       public Range(int begin, int end)
358       {
359          this.begin = begin;
360          this.end = end;
361       }
362
363       /**
364        * Default constructor.
365        */

366       public Range()
367       {
368       }
369    }
370
371    /**
372     * Return the range from a begining token to an ending token.
373     *
374     * @param beginToken String to indicate begining of range.
375     * @param endToken String to indicate ending of range.
376     * @param string String to look for range in.
377     * @param fromIndex Beginning index.
378     * @return (begin index, end index) or <i>null</i>.
379     */

380    public static Range rangeOf(final String JavaDoc beginToken, final String JavaDoc endToken,
381       final String JavaDoc string, final int fromIndex)
382    {
383       int begin = string.indexOf(beginToken, fromIndex);
384
385       if (begin != -1)
386       {
387          int end = string.indexOf(endToken, begin + 1);
388          if (end != -1)
389          {
390             return new Range(begin, end);
391          }
392       }
393
394       return null;
395    }
396
397    /**
398     * Return the range from a begining token to an ending token.
399     *
400     * @param beginToken String to indicate begining of range.
401     * @param endToken String to indicate ending of range.
402     * @param string String to look for range in.
403     * @return (begin index, end index) or <i>null</i>.
404     */

405    public static Range rangeOf(final String JavaDoc beginToken, final String JavaDoc endToken,
406       final String JavaDoc string)
407    {
408       return rangeOf(beginToken, endToken, string, 0);
409    }
410
411
412    /////////////////////////////////////////////////////////////////////////
413
// Spliting Methods //
414
/////////////////////////////////////////////////////////////////////////
415

416    /**
417     * Split up a string into multiple strings based on a delimiter.
418     *
419     * @param string String to split up.
420     * @param delim Delimiter.
421     * @param limit Limit the number of strings to split into
422     * (-1 for no limit).
423     * @return Array of strings.
424     */

425    public static String JavaDoc[] split(final String JavaDoc string, final String JavaDoc delim,
426       final int limit)
427    {
428       // get the count of delim in string, if count is > limit
429
// then use limit for count. The number of delimiters is less by one
430
// than the number of elements, so add one to count.
431
int count = count(string, delim) + 1;
432       if (limit > 0 && count > limit)
433       {
434          count = limit;
435       }
436
437       String JavaDoc strings[] = new String JavaDoc[count];
438       int begin = 0;
439
440       for (int i = 0; i < count; i++)
441       {
442          // get the next index of delim
443
int end = string.indexOf(delim, begin);
444          
445          // if the end index is -1 or if this is the last element
446
// then use the string's length for the end index
447
if (end == -1 || i + 1 == count)
448             end = string.length();
449
450          // if end is 0, then the first element is empty
451
if (end == 0)
452             strings[i] = EMPTY;
453          else
454             strings[i] = string.substring(begin, end);
455
456          // update the begining index
457
begin = end + 1;
458       }
459
460       return strings;
461    }
462
463    /**
464     * Split up a string into multiple strings based on a delimiter.
465     *
466     * @param string String to split up.
467     * @param delim Delimiter.
468     * @return Array of strings.
469     */

470    public static String JavaDoc[] split(final String JavaDoc string, final String JavaDoc delim)
471    {
472       return split(string, delim, -1);
473    }
474
475
476    /////////////////////////////////////////////////////////////////////////
477
// Joining/Concatenation Methods //
478
/////////////////////////////////////////////////////////////////////////
479

480    /**
481     * Join an array of strings into one delimited string.
482     *
483     * @param buff String buffered used for join (buffer is not reset).
484     * @param array Array of objects to join as strings.
485     * @param delim Delimiter to join strings with or <i>null</i>.
486     * @return Joined string.
487     */

488    public static String JavaDoc join(final StringBuffer JavaDoc buff, final Object JavaDoc array[],
489       final String JavaDoc delim)
490    {
491       boolean haveDelim = (delim != null);
492
493       for (int i = 0; i < array.length; i++)
494       {
495          buff.append(array[i]);
496
497          // if this is the last element then don't append delim
498
if (haveDelim && (i + 1) < array.length)
499          {
500             buff.append(delim);
501          }
502       }
503
504       return buff.toString();
505    }
506
507    /**
508     * Join an array of strings into one delimited string.
509     *
510     * @param array Array of objects to join as strings.
511     * @param delim Delimiter to join strings with or <i>null</i>.
512     * @return Joined string.
513     */

514    public static String JavaDoc join(final Object JavaDoc array[], final String JavaDoc delim)
515    {
516       return join(new StringBuffer JavaDoc(), array, delim);
517    }
518
519    /**
520     * Convert and join an array of objects into one string.
521     *
522     * @param array Array of objects to join as strings.
523     * @return Converted and joined objects.
524     */

525    public static String JavaDoc join(final Object JavaDoc array[])
526    {
527       return join(array, null);
528    }
529
530    /**
531     * Convert and join an array of bytes into one string.
532     *
533     * @param array Array of objects to join as strings.
534     * @return Converted and joined objects.
535     */

536    public static String JavaDoc join(final byte array[])
537    {
538       Byte JavaDoc bytes[] = new Byte JavaDoc[array.length];
539       for (int i = 0; i < bytes.length; i++)
540       {
541          bytes[i] = new Byte JavaDoc(array[i]);
542       }
543
544       return join(bytes, null);
545    }
546
547    /**
548     * Return a string composed of the given array.
549     *
550     * @param buff Buffer used to construct string value (not reset).
551     * @param array Array of objects.
552     * @param prefix String prefix.
553     * @param separator Element sepearator.
554     * @param suffix String suffix.
555     * @return String in the format of:
556     * prefix + n ( + separator + n+i)* + suffix.
557     */

558    public static String JavaDoc join(final StringBuffer JavaDoc buff, final Object JavaDoc[] array,
559       final String JavaDoc prefix, final String JavaDoc separator,
560       final String JavaDoc suffix)
561    {
562       buff.append(prefix);
563       join(buff, array, separator);
564       buff.append(suffix);
565
566       return buff.toString();
567    }
568
569    /**
570     * Return a string composed of the given array.
571     *
572     * @param array Array of objects.
573     * @param prefix String prefix.
574     * @param separator Element sepearator.
575     * @param suffix String suffix.
576     * @return String in the format of:
577     * prefix + n ( + separator + n+i)* + suffix.
578     */

579    public static String JavaDoc join(final Object JavaDoc[] array, final String JavaDoc prefix,
580       final String JavaDoc separator, final String JavaDoc suffix)
581    {
582       return join(new StringBuffer JavaDoc(), array, prefix, separator, suffix);
583    }
584
585
586    /////////////////////////////////////////////////////////////////////////
587
// Counting Methods //
588
/////////////////////////////////////////////////////////////////////////
589

590    /**
591     * Count the number of instances of substring within a string.
592     *
593     * @param string String to look for substring in.
594     * @param substring Sub-string to look for.
595     * @return Count of substrings in string.
596     */

597    public static int count(final String JavaDoc string, final String JavaDoc substring)
598    {
599       int count = 0;
600       int idx = 0;
601
602       while ((idx = string.indexOf(substring, idx)) != -1)
603       {
604          idx++;
605          count++;
606       }
607
608       return count;
609    }
610
611    /**
612     * Count the number of instances of character within a string.
613     *
614     * @param string String to look for substring in.
615     * @param c Character to look for.
616     * @return Count of substrings in string.
617     */

618    public static int count(final String JavaDoc string, final char c)
619    {
620       return count(string, String.valueOf(c));
621    }
622
623
624    /////////////////////////////////////////////////////////////////////////
625
// Padding Methods //
626
/////////////////////////////////////////////////////////////////////////
627

628    /**
629     * Return a string padded with the given string for the given count.
630     *
631     * @param buff String buffer used for padding (buffer is not reset).
632     * @param string Pad element.
633     * @param count Pad count.
634     * @return Padded string.
635     */

636    public static String JavaDoc pad(final StringBuffer JavaDoc buff, final String JavaDoc string,
637       final int count)
638    {
639       for (int i = 0; i < count; i++)
640       {
641          buff.append(string);
642       }
643
644       return buff.toString();
645    }
646
647    /**
648     * Return a string padded with the given string for the given count.
649     *
650     * @param string Pad element.
651     * @param count Pad count.
652     * @return Padded string.
653     */

654    public static String JavaDoc pad(final String JavaDoc string, final int count)
655    {
656       return pad(new StringBuffer JavaDoc(), string, count);
657    }
658
659    /**
660     * Return a string padded with the given string value of an object
661     * for the given count.
662     *
663     * @param obj Object to convert to a string.
664     * @param count Pad count.
665     * @return Padded string.
666     */

667    public static String JavaDoc pad(final Object JavaDoc obj, final int count)
668    {
669       return pad(new StringBuffer JavaDoc(), String.valueOf(obj), count);
670    }
671
672
673    /////////////////////////////////////////////////////////////////////////
674
// Misc Methods //
675
/////////////////////////////////////////////////////////////////////////
676

677    /**
678     * <p>Compare two strings.
679     *
680     * <p>Both or one of them may be null.
681     *
682     * @return true if object equals or intern ==, else false.
683     */

684    public static boolean compare(final String JavaDoc me, final String JavaDoc you)
685    {
686       // If both null or intern equals
687
if (me == you)
688          return true;
689       
690       // if me null and you are not
691
if (me == null && you != null)
692          return false;
693       
694       // me will not be null, test for equality
695
return me.equals(you);
696    }
697
698    /**
699     * Check if the given string is empty.
700     *
701     * @param string String to check
702     * @return True if string is empty
703     */

704    public static boolean isEmpty(final String JavaDoc string)
705    {
706       return string.equals(EMPTY);
707    }
708
709    /**
710     * Return the <i>nth</i> index of the given token occurring in the given string.
711     *
712     * @param string String to search.
713     * @param token Token to match.
714     * @param index <i>Nth</i> index.
715     * @return Index of <i>nth</i> item or -1.
716     */

717    public static int nthIndexOf(final String JavaDoc string, final String JavaDoc token,
718       final int index)
719    {
720       int j = 0;
721
722       for (int i = 0; i < index; i++)
723       {
724          j = string.indexOf(token, j + 1);
725          if (j == -1) break;
726       }
727
728       return j;
729    }
730
731    /**
732     * Capitalize the first character of the given string.
733     *
734     * @param string String to capitalize.
735     * @return Capitalized string.
736     *
737     * @throws IllegalArgumentException String is <kk>null</kk> or empty.
738     */

739    public static String JavaDoc capitalize(final String JavaDoc string)
740    {
741       if (string == null)
742          throw new NullArgumentException("string");
743       if (string.equals(""))
744          throw new EmptyStringException("string");
745
746       return Character.toUpperCase(string.charAt(0)) + string.substring(1);
747    }
748
749    /**
750     * Trim each string in the given string array.
751     *
752     * <p>This modifies the string array.
753     *
754     * @param strings String array to trim.
755     * @return String array with each element trimmed.
756     */

757    public static String JavaDoc[] trim(final String JavaDoc[] strings)
758    {
759       for (int i = 0; i < strings.length; i++)
760       {
761          strings[i] = strings[i].trim();
762       }
763
764       return strings;
765    }
766
767    /**
768     * Make a URL from the given string.
769     *
770     * <p>
771     * If the string is a properly formatted file URL, then the file
772     * portion will be made canonical.
773     *
774     * <p>
775     * If the string is an invalid URL then it will be converted into a
776     * file URL.
777     *
778     * @param urlspec The string to construct a URL for.
779     * @param relativePrefix The string to prepend to relative file
780     * paths, or null to disable prepending.
781     * @return A URL for the given string.
782     *
783     * @throws MalformedURLException Could not make a URL for the given string.
784     */

785    public static URL JavaDoc toURL(String JavaDoc urlspec, final String JavaDoc relativePrefix) throws MalformedURLException JavaDoc
786    {
787       urlspec = urlspec.trim();
788
789       URL JavaDoc url;
790
791       try
792       {
793          url = new URL JavaDoc(urlspec);
794          if (url.getProtocol().equals("file"))
795          {
796             url = makeURLFromFilespec(url.getFile(), relativePrefix);
797          }
798       }
799       catch (Exception JavaDoc e)
800       {
801          // make sure we have a absolute & canonical file url
802
try
803          {
804             url = makeURLFromFilespec(urlspec, relativePrefix);
805          }
806          catch (IOException JavaDoc n)
807          {
808             //
809
// jason: or should we rethrow e?
810
//
811
throw new MalformedURLException JavaDoc(n.toString());
812          }
813       }
814
815       return url;
816    }
817
818    public static URI JavaDoc toURI(String JavaDoc urispec, final String JavaDoc relativePrefix)
819       throws URISyntaxException JavaDoc
820    {
821       urispec = urispec.trim();
822
823       URI JavaDoc uri;
824
825       if( urispec.startsWith("file:") )
826       {
827          uri = makeURIFromFilespec(urispec.substring(5), relativePrefix);
828       }
829       else
830       {
831          uri = new URI JavaDoc(urispec);
832       }
833
834       return uri;
835    }
836
837    /** A helper to make a URL from a filespec. */
838    private static URL JavaDoc makeURLFromFilespec(final String JavaDoc filespec, final String JavaDoc relativePrefix)
839       throws IOException JavaDoc
840    {
841       // make sure the file is absolute & canonical file url
842
File JavaDoc file = new File JavaDoc(filespec);
843       
844       // if we have a prefix and the file is not abs then prepend
845
if (relativePrefix != null && !file.isAbsolute())
846       {
847          file = new File JavaDoc(relativePrefix, filespec);
848       }
849       
850       // make sure it is canonical (no ../ and such)
851
file = file.getCanonicalFile();
852
853       return file.toURL();
854    }
855    private static URI JavaDoc makeURIFromFilespec(final String JavaDoc filespec, final String JavaDoc relativePrefix)
856    {
857       // make sure the file is absolute & canonical file url
858
File JavaDoc file = new File JavaDoc(filespec);
859       
860       // if we have a prefix and the file is not abs then prepend
861
if (relativePrefix != null && !file.isAbsolute())
862       {
863          file = new File JavaDoc(relativePrefix, filespec);
864       }
865       
866       return file.toURI();
867    }
868
869    /**
870     * Make a URL from the given string.
871     *
872     * @see #toURL(String,String)
873     *
874     * @param urlspec The string to construct a URL for.
875     * @return A URL for the given string.
876     *
877     * @throws MalformedURLException Could not make a URL for the given string.
878     */

879    public static URL JavaDoc toURL(final String JavaDoc urlspec) throws MalformedURLException JavaDoc
880    {
881       return toURL(urlspec, null);
882    }
883
884    /**
885     *
886     * @param urispec
887     * @return
888     * @throws MalformedURLException
889     */

890    public static URI JavaDoc toURI(final String JavaDoc urispec)
891       throws URISyntaxException JavaDoc
892    {
893       return toURI(urispec, null);
894    }
895
896    /**
897     * Check whether the given String is a reserved Java Keyword
898     * according to the Java Language Specifications.
899     *
900     * @param s String to check
901     *
902     * @return <code>true</code> if the given String is a reserved Java
903     * keyword, <code>false</code> otherwise.
904     */

905    public final static boolean isJavaKeyword(String JavaDoc s)
906    {
907       if (s == null || s.length() == 0)
908       {
909          return false;
910       }
911
912       for (int i = 0; i < keywords.length; i++)
913       {
914          if (keywords[i].equals(s))
915          {
916             return true;
917          }
918       }
919
920       return false;
921    }
922
923    /**
924     * Check whether the given String is an identifier according to the
925     * EJB-QL definition. See The EJB 2.0 Documentation Section 11.2.6.1.
926     *
927     * @param s String to check
928     *
929     * @return <code>true</code> if the given String is a reserved
930     * identifier in EJB-QL, <code>false</code> otherwise.
931     */

932    public final static boolean isEjbQlIdentifier(String JavaDoc s)
933    {
934       if (s == null || s.length() == 0)
935       {
936          return false;
937       }
938
939       for (int i = 0; i < ejbQlIdentifiers.length; i++)
940       {
941          if (ejbQlIdentifiers[i].equalsIgnoreCase(s))
942          {
943             return true;
944          }
945       }
946
947       return false;
948    }
949
950    /**
951     * Check whether the given String is a valid identifier according
952     * to the Java Language specifications.
953     *
954     * See The Java Language Specification Second Edition, Section 3.8
955     * for the definition of what is a valid identifier.
956     *
957     * @param s String to check
958     *
959     * @return <code>true</code> if the given String is a valid Java
960     * identifier, <code>false</code> otherwise.
961     */

962    public final static boolean isValidJavaIdentifier(String JavaDoc s)
963    {
964       // an empty or null string cannot be a valid identifier
965
if (s == null || s.length() == 0)
966       {
967          return false;
968       }
969
970       char[] c = s.toCharArray();
971       if (!Character.isJavaIdentifierStart(c[0]))
972       {
973          return false;
974       }
975
976       for (int i = 1; i < c.length; i++)
977       {
978          if (!Character.isJavaIdentifierPart(c[i]))
979          {
980             return false;
981          }
982       }
983
984       return true;
985    }
986
987    /**
988     * Returns a new string with all the whitespace removed
989     *
990     * @param s the source string
991     * @return the string without whitespace or null
992     */

993    public static String JavaDoc removeWhiteSpace(String JavaDoc s)
994    {
995       String JavaDoc retn = null;
996       
997       if (s != null)
998       {
999          int len = s.length();
1000         StringBuffer JavaDoc sbuf = new StringBuffer JavaDoc(len);
1001         
1002         for (int i = 0; i < len; i++)
1003         {
1004            char c = s.charAt(i);
1005            
1006            if (!Character.isWhitespace(c))
1007                sbuf.append(c);
1008         }
1009         retn = sbuf.toString();
1010      }
1011      return retn;
1012   }
1013
1014   /**
1015    * The default toString implementation of an object
1016    *
1017    * @param object the object
1018    * @return a string in the form className@hexHashCode
1019    */

1020   public static final String JavaDoc defaultToString(Object JavaDoc object)
1021   {
1022      if (object == null)
1023         return "null";
1024      else
1025         return object.getClass().getName() + '@' + Integer.toHexString(System.identityHashCode(object));
1026   }
1027
1028   /**
1029    * The default toString implementation of an object
1030    *
1031    * @param object the object
1032    * @param buffer the string builder
1033    * @return a string in the form className@hexHashCode
1034    */

1035   public static final void defaultToString(JBossStringBuilder buffer, Object JavaDoc object)
1036   {
1037      if (object == null)
1038         buffer.append("null");
1039      else
1040      {
1041         buffer.append(object.getClass().getName());
1042         buffer.append('@');
1043         buffer.append(Integer.toHexString(System.identityHashCode(object)));
1044      }
1045   }
1046
1047   /**
1048    * The default toString implementation of an object
1049    *
1050    * @param object the object
1051    * @param buffer the string buffer
1052    * @return a string in the form className@hexHashCode
1053    */

1054   public static final void defaultToString(StringBuffer JavaDoc buffer, Object JavaDoc object)
1055   {
1056      if (object == null)
1057         buffer.append("null");
1058      else
1059      {
1060         buffer.append(object.getClass().getName());
1061         buffer.append('@');
1062         buffer.append(Integer.toHexString(System.identityHashCode(object)));
1063      }
1064   }
1065   
1066   /**
1067    * Parses a time period into a long.
1068    *
1069    * Translates possible [msec|sec|min|h] suffixes
1070    *
1071    * For example:
1072    * "1" -> 1 (msec)
1073    * "1msec -> 1 (msec)
1074    * "1sec" -> 1000 (msecs)
1075    * "1min" -> 60000 (msecs)
1076    * "1h" -> 3600000 (msecs)
1077    *
1078    * Accepts negative periods, e.g. "-1"
1079    *
1080    * @param period the stringfied time period
1081    * @return the parsed time period as long
1082    * @throws NumberFormatException
1083    */

1084   public static long parseTimePeriod(String JavaDoc period)
1085   {
1086      try
1087      {
1088         String JavaDoc s = period.toLowerCase();
1089         long factor;
1090         
1091         // look for suffix
1092
if (s.endsWith("msec"))
1093         {
1094            s = s.substring(0, s.lastIndexOf("msec"));
1095            factor = MSEC;
1096         }
1097         else if (s.endsWith("sec"))
1098         {
1099            s = s.substring(0, s.lastIndexOf("sec"));
1100            factor = SECS;
1101         }
1102         else if (s.endsWith("min"))
1103         {
1104            s = s.substring(0, s.lastIndexOf("min"));
1105            factor = MINS;
1106         }
1107         else if (s.endsWith("h"))
1108         {
1109            s = s.substring(0, s.lastIndexOf("h"));
1110            factor = HOUR;
1111         }
1112         else
1113         {
1114            factor = 1;
1115         }
1116         return Long.parseLong(s) * factor;
1117      }
1118      catch (RuntimeException JavaDoc e)
1119      {
1120         // thrown in addition when period is 'null'
1121
throw new NumberFormatException JavaDoc("For input time period: '" + period + "'");
1122      }
1123   }
1124   
1125   /**
1126    * Same like parseTimePeriod(), but guards for negative entries.
1127    *
1128    * @param period the stringfied time period
1129    * @return the parsed time period as long
1130    * @throws NumberFormatException
1131    */

1132   public static long parsePositiveTimePeriod(String JavaDoc period)
1133   {
1134      long retval = parseTimePeriod(period);
1135      if (retval < 0)
1136      {
1137         throw new NumberFormatException JavaDoc("Negative input time period: '" + period + "'");
1138      }
1139      return retval;
1140   }
1141}
1142
Popular Tags