root/trunk/src/java/org/jcoderz/commons/util/StringUtil.java

Revision 1587, 13.7 kB (checked in by amandel, 8 months ago)

StringUtil?.isAscii: Stop check loop if invalid character is found.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1/*
2 * $Id$
3 *
4 * Copyright 2006, The jCoderZ.org Project. All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are
8 * met:
9 *
10 *    * Redistributions of source code must retain the above copyright
11 *      notice, this list of conditions and the following disclaimer.
12 *    * Redistributions in binary form must reproduce the above
13 *      copyright notice, this list of conditions and the following
14 *      disclaimer in the documentation and/or other materials
15 *      provided with the distribution.
16 *    * Neither the name of the jCoderZ.org Project nor the names of
17 *      its contributors may be used to endorse or promote products
18 *      derived from this software without specific prior written
19 *      permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
28 * BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
29 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
30 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
31 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32 */
33package org.jcoderz.commons.util;
34
35import org.jcoderz.commons.ArgumentMalformedException;
36
37
38/**
39 * This class provides string related utility functions.
40 *
41 * @author Michael Griffel
42 */
43public final class StringUtil
44{
45   /**
46    * The empty string <code>&quot;&quot;</code>.
47    */
48   public static final String EMPTY_STRING = "";
49
50   private static final int ASCII_MAX_VALUE = 127;
51
52   /**
53    * No instance of this class allowed.
54    */
55   private StringUtil ()
56   {
57      // only static utility methods.
58   }
59
60   /**
61    * Converts a byte array to a String using UTF-8 encoding.
62    * If the given byte array is <code>null</code>, the returned string
63    * is also <code>null</code>.
64    *
65    * @param bytes The byte array to be converted.
66    * @return The string representation of the byte array or
67    *       <code>null</code> if the given byte array is <code>null</code>.
68    */
69   public static String toString (byte[] bytes)
70   {
71      return bytes == null ? null : toString(bytes, 0, bytes.length);
72   }
73
74   /**
75    * Converts a byte array to a String using UTF-8 encoding.
76    * If the given byte array is <code>null</code>, the returned string
77    * is also <code>null</code>.
78    *
79    * @param bytes The byte array to be converted.
80    * @param offset The index of the first byte to encode.
81    * @param length The number of bytes to encode.
82    * @return The string representation of the byte array or
83    *       <code>null</code> if the given byte array is <code>null</code>.
84    * @throws RuntimeException if the UTF-8 encoding is not supported by the
85    *       JDK.
86    */
87   public static String toString (byte[] bytes, int offset, int length)
88       throws RuntimeException
89   {
90      final String result;
91      try
92      {
93         if (bytes == null)
94         {
95            result = null;
96         }
97         else
98         {
99            result = new String(bytes, offset, length, Constants.ENCODING_UTF8);
100         }
101      }
102      catch (java.io.UnsupportedEncodingException e)
103      {
104         // this should not occur because the UTF-8 encoder is always
105         // supported by the JDK
106         throw new RuntimeException(
107               "UTF-8 character encoding not supported?", e);
108      }
109      return result;
110   }
111
112   /**
113    * Converts a String to an byte array using UTF-8 encoding.
114    *
115    * @param s The string to be converted.
116    * @return The bytes of the given string in UTF-8 encoding.
117    * @throws RuntimeException if the UTF-8 encoding is not supported by the
118    *       JDK.
119    */
120   public static byte[] toBytes (String s)
121       throws RuntimeException
122   {
123      try
124      {
125         return s.getBytes(Constants.ENCODING_UTF8);
126      }
127      catch (java.io.UnsupportedEncodingException e)
128      {
129         // this should not occur because the UTF-8 encoder is always
130         // supported by the JDK
131         throw new RuntimeException(
132               "UTF-8 character encoding not supported?", e);
133      }
134   }
135
136   /**
137    * Converts a byte array to a String using ASCII encoding.
138    * If the given byte array is <code>null</code>, the returned string
139    * is also <code>null</code>.
140    *
141    * @param bytes The byte array to be converted.
142    * @param offset The index of the first byte to encode.
143    * @param length The number of bytes to encode.
144    * @return The String representation of the byte array.
145    */
146   public static String asciiToString (byte[] bytes, int offset, int length)
147   {
148      final String result;
149
150      try
151      {
152         if (bytes != null)
153         {
154            result = new String(
155                  bytes, offset, length, Constants.ENCODING_ASCII);
156         }
157         else
158         {
159            result = null;
160         }
161      }
162      catch (java.io.UnsupportedEncodingException e)
163      {
164         // this should not occur because the ASCII encoder is always
165         // supported by the JDK
166         throw new RuntimeException(
167               "ASCII character encoding not supported?", e);
168      }
169      return result;
170   }
171
172   /**
173    * Converts a byte array to a String using ASCII encoding.
174    * If the given byte array is <code>null</code>, the returned string
175    * is also <code>null</code>.
176    *
177    * @param bytes The byte array to be converted.
178    * @return The String representation of the byte array.
179    */
180   public static String asciiToString (byte[] bytes)
181   {
182      return bytes == null ? null : asciiToString(bytes, 0, bytes.length);
183   }
184
185   /**
186    * Tests if the given character is an ASCII character, i.e. if it's
187    * integer value is less than or equal to 127.
188    *
189    * @param c the character to test.
190    * @return <code>true</code> if c &lt;= 127, <code>false</code> otherwise.
191    */
192   public static boolean isAscii (final char c)
193   {
194      return (c <= ASCII_MAX_VALUE);
195   }
196
197   /**
198    * Determines if the specified string consists only of ASCII characters.
199    *
200    * @param c the characters to check.
201    * @return <code>true</code> if the specified characters are 7-bit
202    *         ASCII clean; <code>false</code> otherwise.
203    */
204   public static boolean isAscii (CharSequence c)
205   {
206      boolean result = true;
207      for (int i = c.length() - 1; i >= 0; --i)
208      {
209         if (!isAscii(c.charAt(i)))
210         {
211            result = false;
212            break;
213         }
214      }
215      return result;
216   }
217
218   /**
219    * Returns <code>true</code> if given string is <code>null</code> or the
220    * length is zero (empty string).
221    * @param s the string to test.
222    * @return Returns <code>true</code> if given string is <code>null</code>
223    *       or the length is zero (empty string); <code>false</code> otherwise.
224    */
225   public static boolean isNullOrEmpty (String s)
226   {
227      return (s == null || s.length() == 0);
228   }
229
230   /**
231    * Returns <code>true</code> if given string is <code>null</code> or the
232    * length is zero (empty string).
233    * @param s the string to test.
234    * @return Returns <code>true</code> if given string is <code>null</code>
235    *       or the length is zero (empty string); <code>false</code> otherwise.
236    */
237   public static boolean isEmptyOrNull (String s)
238   {
239      return isNullOrEmpty(s);
240   }
241
242   /**
243    * Returns <code>true</code> if given string is <code>null</code>, the
244    * length is zero (empty string) or if it only contains white spaces.
245    * The whitespace check is done using Character.isWhitespace().
246    * @param s the string to test.
247    * @return Returns <code>true</code> if given string is <code>null</code>,
248    *       the length is zero (empty string) or the String contains only
249    *       whitespace characters; <code>false</code> otherwise.
250    */
251   public static boolean isNullOrBlank (String s)
252   {
253       boolean result = true;
254       if (s != null)
255       {
256           final int length = s.length();
257           for (int i = 0; i < length; i++)
258           {
259               if (!Character.isWhitespace(s.charAt(i)))
260               {
261                   result = false;
262                   break;
263               }
264           }
265      }
266      return result;
267   }
268
269   /**
270    * Returns <code>true</code> if given string is <code>null</code>, the
271    * length is zero (empty string) or if it only contains white spaces.
272    * The whitespace check is done using Character.isWhitespace().
273    * @param s the string to test.
274    * @return Returns <code>true</code> if given string is <code>null</code>,
275    *       the length is zero (empty string) or the String contains only
276    *       whitespace characters; <code>false</code> otherwise.
277    */
278   public static boolean isBlankOrNull (String s)
279   {
280      return isNullOrBlank(s);
281   }
282
283   /**
284    * Returns <tt>true</tt> if the two specified strings are
285    * <i>equal</i> to one another. Two strings <tt>a</tt>
286    * and <tt>b</tt> are considered <i>equal</i> if <tt>(a==null ? b == null
287    * : a.equals(b))</tt>. Also, two string references are considered
288    * equal if both are <tt>null</tt>.
289    *
290    * @param a one string to be tested for equality.
291    * @param b the other string to be tested for equality.
292    * @return <tt>true</tt> if the two strings are equal; <tt>false</tt>
293    *       otherwise.
294    */
295   public static boolean equals (String a, String b)
296   {
297      final boolean result;
298      if (a == b)
299      {
300         result = true;
301      }
302      else if (a == null || b == null)
303      {
304         result = false;
305      }
306      else
307      {
308         result = a.equals(b);
309      }
310      return result;
311   }
312
313   /**
314    * Pads or truncates the given argument to be at least minLength chars
315    * and at most maxLength chars long.
316    * @param s the string to pad or truncate
317    * @param minLength the minimum length of the string
318    * @param maxLength the maximum length of the string
319    * @return a string padded with spaces if its length is less than
320    *       minLength, or truncated to be no longer than maxLength,
321    *       or the string itself if its length is between minLength
322    *       and maxLength
323    * @throws ArgumentMalformedException if the string argument is null,
324    *       or if minLength is greater than maxLength
325    */
326   public static String fitToLength (String s, int minLength, int maxLength)
327         throws ArgumentMalformedException
328   {
329      Assert.notNull(s, "s");
330      if (minLength > maxLength)
331      {
332         throw new ArgumentMalformedException(
333               "minLength", String.valueOf(minLength),
334               "minLength must be less than or equal to maxLength");
335      }
336      final StringBuffer sbuf = new StringBuffer(s);
337      while (sbuf.length() < minLength)
338      {
339         sbuf.append(' ');
340      }
341      if (sbuf.length() > maxLength)
342      {
343         sbuf.setLength(maxLength);
344      }
345      return sbuf.toString();
346   }
347
348   /**
349    * Adds the character <tt>pad</tt> to the left-side of the string
350    * <tt>s</tt> until the string size will be <tt>size</tt>.
351    * @param s the string to pad.
352    * @param pad the padding character.
353    * @param size the final string size.
354    * @return the padded string.
355    */
356   public static String padLeft (String s, char pad, int size)
357   {
358      final StringBuffer sb = new StringBuffer(s);
359      while (sb.length() < size)
360      {
361         sb.insert(0, pad);
362      }
363      return sb.toString();
364   }
365
366   /**
367    * Trims the length of the given string to the given maxlength, if
368    * the string length is below the given maxlength the string
369    * returned unmodified.
370    * @param str the string to trim.
371    * @param maxLength the maximum length
372    * @return the string, trimmed to a maximum length of maxLength
373    */
374   public static String trimLength (String str, int maxLength)
375   {
376      Assert.assertTrue("maxLength must not be negative.", maxLength >= 0);
377      final String result;
378      if (str != null && str.length() > maxLength)
379      {
380         result = str.substring(0, maxLength);
381      }
382      else
383      {
384         result = str;
385      }
386      return result;
387   }
388
389   /**
390    * Trims the length of the given string to the given maxlength by cutting of
391    * data at the left side (beginning) of the string, if
392    * the string length is below the given maxlength the string is returned
393    * unmodified.
394    * @param str the string to trim.
395    * @param maxLength the maximum length
396    * @return the string, trimmed to a maximum length of maxLength
397    */
398   public static String trimLengthLeft (String str, int maxLength)
399   {
400      Assert.assertTrue("maxLength must not be negative.", maxLength >= 0);
401      final String result;
402      if (str != null && str.length() > maxLength)
403      {
404         result = str.substring(str.length() - maxLength);
405      }
406      else
407      {
408         result = str;
409      }
410      return result;
411   }
412
413   /**
414    * Returns true if the first argument string
415    * contains the second argument string, and otherwise returns false.
416    * This is no regular expression matching!
417    *
418    * @param str the string to test.
419    * @param subString the substring to look for in <code>str</code>.
420    *
421    * @return true if the first argument string
422    *   contains the second argument string, and otherwise returns false.
423    */
424   public static boolean contains (String str, String subString)
425   {
426       Assert.notNull(str, "str");
427       Assert.notNull(subString, "subString");
428       return str.indexOf(subString) >= 0;
429   }
430}
Note: See TracBrowser for help on using the browser.