View Javadoc

1   /*
2    * Copyright 2004-2005 Emmanouil Batsis
3    * 
4    * Licensed under the GNU General Public License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * 
8    *      http://www.gnu.org/licenses/gpl.txt
9    * 
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   * 
16   */
17  package com.geekologue.md4j.util;
18  
19  import java.io.UnsupportedEncodingException;
20  import java.lang.reflect.Array;
21  import java.security.MessageDigest;
22  import java.security.NoSuchAlgorithmException;
23  import java.text.SimpleDateFormat;
24  import java.util.*;
25  import org.apache.log4j.Logger;
26  
27  /***
28   * @author Manos Batsis Jun 28, 2004
29   */
30  public class StringUtil {
31      private static Logger log = Logger.getLogger(StringUtil.class);
32  
33      public static String getNullIfEmpty(String s) {
34          return s != null && s.length() > 0 ? s : null;
35      }
36  
37      // TODO: modify so that if string-number and greater than zero,
38      // return true
39      public static boolean getBoolean(Object o, boolean bDefault) {
40          boolean b = bDefault;
41          if (o != null) {
42              if (o instanceof Boolean) {
43                  b = ((Boolean) o).booleanValue();
44              } else if (o instanceof Integer) {
45                  b = ((Integer) o).intValue() > 0;
46              } else {
47                  String s = o.toString();
48                  if (s.length() > 0) {
49                      if (s.equalsIgnoreCase("true"))
50                          b = true;
51                      else if (s.equalsIgnoreCase("false"))
52                          b = false;
53                      else if (s.equals("1"))
54                          b = true;
55                      else if (s.equals("0"))
56                          b = false;
57                      else if (s.equalsIgnoreCase("yes"))
58                          b = true;
59                      else if (s.equalsIgnoreCase("no"))
60                          b = false;
61                      else if (s.equalsIgnoreCase("on"))
62                          b = true;
63                      else if (s.equalsIgnoreCase("off"))
64                          b = false;
65                  }
66              }
67          }
68          return b;
69      }
70  
71      public static Integer getInteger(String s) {
72          Integer i = null;
73          if (s != null && s.length() > 0) {
74              try {
75                  i = new Integer(s);
76              } catch (NumberFormatException e) {
77                  log.warn(e);
78              }
79          }
80          return i;
81      }
82  
83      public static Long getLong(String s) {
84          Long l = null;
85          if (s != null && s.length() > 0) {
86              try {
87                  l = new Long(s);
88              } catch (NumberFormatException e) {
89                  log.warn(e);
90              }
91          }
92          return l;
93      }
94  
95      public static Float getFloat(String s) {
96          Float f = null;
97          if (s != null && s.length() > 0) {
98              try {
99                  f = new Float(s);
100             } catch (NumberFormatException e) {
101                 log.error(e);
102             }
103         }
104         return f;
105     }
106 
107     public static Double getDouble(String s) {
108         Double f = null;
109         if (s != null && s.length() > 0) {
110             try {
111                 f = new Double(s);
112             } catch (NumberFormatException e) {
113                 log.error(e);
114             }
115         }
116         return f;
117     }
118 
119     public static Integer getIntegerOrZero(String s) {
120         Integer i = getInteger(s);
121         return i != null ? i : new Integer(0);
122     }
123 
124     public static boolean equalsHash(String s, String hash, String algorithm)
125             throws NoSuchAlgorithmException, UnsupportedEncodingException {
126         String base64 = "";
127         base64 = getHash(s);
128         // log.debug("Hash Value for: "+str+"="+base64);
129         return base64.equals(hash);
130     }
131 
132     /***
133      * Get an MD5 hash for the given string. <b>Note </b>: only MD5 mode has
134      * been tested.
135      * 
136      * @param s
137      *            The String to hash
138      * @param algorithm
139      *            The algorithm to use (see finals). If if <code>null</code>,
140      *            the default will be used (MD5)
141      * @return
142      * @throws NoSuchAlgorithmException
143      * @throws UnsupportedEncodingException
144      */
145     public static String getHash(String s) throws NoSuchAlgorithmException,
146             UnsupportedEncodingException {
147         MessageDigest md = MessageDigest.getInstance("MD5");
148         md.update(s.getBytes());
149         byte digest[] = md.digest();
150         return toHex(digest);
151     }
152 
153     /***
154      * Get a hexadecimal String from a byte array
155      * 
156      * @param arr
157      * @return
158      */
159     private static String toHex(byte[] arr) {
160         final StringBuffer hexString = new StringBuffer();
161         final String ZERO = "0";
162         int z = 0;
163         final int dig = arr.length;
164         for (int i = 0; i < dig; i++) {
165             z = 0xFF & arr[i];
166             if (z < 16)
167                 hexString.append(ZERO);
168             hexString.append(Integer.toHexString(z));
169         }
170         return hexString.toString();
171     }
172 
173     public static String toHex(String s) {
174         return toHex(s.getBytes());
175     }
176 
177     /***
178      * Look for the occurence of a string in an array. Case insensitive.
179      * 
180      * @param s
181      *            The string to look for
182      * @param arr
183      *            The array of strings to look in
184      * @return True if the string is found in the array, false otherwise or if
185      *         either of the arguments is null
186      */
187     public static boolean isInArrayIgnoreCase(String s, String[] arr) {
188         boolean found = false;
189         if (s != null && arr != null)
190             for (int i = 0; i < arr.length && !found; i++)
191                 found = s.equalsIgnoreCase(arr[i]);
192         return found;
193     }
194 
195     /***
196      * Look for the occurence of a string in an array. Case sensitive.
197      * 
198      * @param s
199      *            The string to look for
200      * @param arr
201      *            The array of strings to look in
202      * @return True if the string is found in the array, false otherwise or if
203      *         either of the arguments is null
204      */
205     public static boolean isInArray(String s, String[] arr) {
206         boolean found = false;
207         if (s != null && arr != null)
208             for (int i = 0; i < arr.length && !found; i++)
209                 found = s.equals(arr[i]);
210         return found;
211     }
212 
213     public static String getValueOrDefault(String s, String defaultValue) {
214         return s != null ? s : defaultValue;
215     }
216 
217     /***
218      * Return the string representation of a primitive array. Uses the
219      * <code>AbstractCollection.toString</code> format.
220      * 
221      * @param obj
222      *            the array
223      * @return the string representation
224      */
225     public static String toString(Object obj) {
226         if (obj == null)
227             return "null";
228         if (!isArray(obj))
229             throw new IllegalArgumentException("Object is not an array ");
230         StringBuffer result = new StringBuffer("[");
231         int length = Array.getLength(obj);
232         for (int idx = 0; idx < length; ++idx) {
233             Object item = Array.get(obj, idx);
234             if (isNonNullArray(item)) {
235                 // recursive for arrays of arrays
236                 result.append(toString(item));
237             } else {
238                 result.append(item);
239             }
240             if (!isLastItem(idx, length)) {
241                 result.append(", ");
242             }
243         }
244         result.append("]");
245         return result.toString();
246     }
247 
248     private static boolean isArray(Object obj) {
249         if (obj.getClass().isArray())
250             return true;
251         else
252             return false;
253     }
254 
255     private static boolean isNonNullArray(Object obj) {
256         return obj != null && obj.getClass().isArray();
257     }
258 
259     private static boolean isLastItem(int i, int length) {
260         return (i == length - 1);
261     }
262 
263     public static boolean isEmpty(String s) {
264         boolean result = true;
265         if ((s != null) && !s.trim().equals(""))
266             result = false;
267         return result;
268     }
269 
270     public static String toXMLString(String str) {
271         StringBuffer buffer;
272         char ch;
273         String entity;
274         buffer = null;
275         for (int i = 0; i < str.length(); i++) {
276             ch = str.charAt(i);
277             switch (ch) {
278             case '<':
279                 entity = "&lt;";
280                 break;
281             case '>':
282                 entity = "&gt;";
283                 break;
284             case '&':
285                 entity = "&amp;";
286                 break;
287             case '\"':
288                 entity = "&quot;";
289                 break;
290             case '\'':
291                 entity = "&apos;";
292                 break;
293             default:
294                 entity = null;
295                 break;
296             }
297             if (buffer == null) {
298                 if (entity != null) {
299                     // An entity occurred, so we'll have to use StringBuffer
300                     // (allocate room for it plus a few more entities).
301                     buffer = new StringBuffer(str.length() + 20);
302                     // Copy previous skipped characters and fall through
303                     // to pickup current character
304                     buffer.append(str.substring(0, i));
305                     buffer.append(entity);
306                 }
307             } else {
308                 if (entity == null) {
309                     buffer.append(ch);
310                 } else {
311                     buffer.append(entity);
312                 }
313             }
314         }
315         // If there were any entities, return the escaped characters
316         // that we put in the StringBuffer. Otherwise, just return
317         // the unmodified input string.
318         return (buffer == null) ? str : buffer.toString();
319     }
320 
321     /***
322      * Enforce a trailing '/' or '\' depending on platform, to ensure the path
323      * denotes a directory
324      * 
325      * @param s
326      * @return
327      */
328     public static String enforceTrailingChar(String s, char c) {
329         if (s.lastIndexOf(c) != s.length() - 1)
330             s += c;
331         return s;
332     }
333 
334     /***
335      * @param string
336      * @return
337      */
338     public static Date getDate(String s) {
339         Date d = null;
340         try {
341             SimpleDateFormat sdf = null;
342             String pattern = null;
343             int sepIndex;
344             if (s != null) {
345                 sepIndex = s.indexOf("/");
346                 if (sepIndex != -1) {
347                     if (sepIndex == 2) {
348                         pattern = "dd/MM/yyyy";
349                     } else if (sepIndex == 4) {
350                         pattern = "yyyy/MM/dd";
351                     }
352                 } else {
353                     sepIndex = s.indexOf("-");
354                     if (sepIndex != -1) {
355                         if (sepIndex == 2) {
356                             pattern = "dd-MM-yyyy";
357                         } else if (sepIndex == 4) {
358                             pattern = "yyyy-MM-dd";
359                         }
360                     }
361                 }
362             }
363             d = sdf.parse(s);
364         } catch (Exception e) {
365         }
366         return d;
367     }
368 }