KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > jboss > portal > common > util > Tools


1 /*****************************************
2  * *
3  * JBoss Portal: The OpenSource Portal *
4  * *
5  * Distributable under LGPL license. *
6  * See terms of license at gnu.org. *
7  * *
8  *****************************************/

9
10 package org.jboss.portal.common.util;
11
12 import java.io.IOException JavaDoc;
13 import java.io.InputStream JavaDoc;
14 import java.io.OutputStream JavaDoc;
15 import java.io.Reader JavaDoc;
16 import java.io.UnsupportedEncodingException JavaDoc;
17 import java.io.Writer JavaDoc;
18 import java.io.PrintWriter JavaDoc;
19 import java.io.StringWriter JavaDoc;
20 import java.lang.reflect.InvocationTargetException JavaDoc;
21 import java.lang.reflect.Method JavaDoc;
22 import java.lang.reflect.Modifier JavaDoc;
23 import java.math.BigInteger JavaDoc;
24 import java.net.URLEncoder JavaDoc;
25 import java.net.UnknownHostException JavaDoc;
26 import java.net.URLClassLoader JavaDoc;
27 import java.net.URL JavaDoc;
28 import java.security.MessageDigest JavaDoc;
29 import java.security.NoSuchAlgorithmException JavaDoc;
30 import java.util.ArrayList JavaDoc;
31 import java.util.Enumeration JavaDoc;
32 import java.util.HashSet JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.List JavaDoc;
35 import java.util.NoSuchElementException JavaDoc;
36 import java.util.ResourceBundle JavaDoc;
37 import java.util.Set JavaDoc;
38 import java.util.Date JavaDoc;
39 import java.util.Calendar JavaDoc;
40 import java.util.regex.Pattern JavaDoc;
41
42 import org.apache.log4j.Logger;
43 import org.apache.log4j.Level;
44 import org.jboss.portal.common.logging.Log4JWriter;
45
46 /**
47  * @author <a HREF="mailto:julien@jboss.org">Julien Viet</a>
48  * @author <a HREF="mailto:theute@jboss.org">Thomas Heute</a>
49  * @version $Revision: 1.12 $
50  */

51 public class Tools
52 {
53
54    public static final int DEFAULT_BUFFER_SIZE = 512;
55
56    public static final Logger log = Logger.getLogger(Tools.class);
57
58    private static final Object JavaDoc[] EMPTY_ARGS = new Object JavaDoc[0];
59
60    private static final Class JavaDoc[] EMPTY_PARAMETER_TYPES = new Class JavaDoc[0];
61
62    public static final String JavaDoc RE_EMAIL_VALIDATION = "^([a-zA-Z0-9]+(([\\.\\-\\_]?[a-zA-Z0-9]+)+)?)\\@(([a-zA-Z0-9]+[\\.\\-\\_])+[a-zA-Z]{2,4})$";
63
64    /**
65     * Close an object that implements a close() method.
66     *
67     * @param closable
68     * the object to close
69     */

70    public static void safeClose(Object JavaDoc closable)
71    {
72       if (closable != null)
73       {
74          try
75          {
76             Method JavaDoc m = closable.getClass().getMethod("close", Tools.EMPTY_PARAMETER_TYPES);
77             if (!Modifier.isPublic(m.getModifiers()))
78             {
79                log.warn("close() method on closable object is not public");
80                return;
81             }
82             if (Modifier.isStatic(m.getModifiers()))
83             {
84                log.warn("close() method on closable object is static");
85                return;
86             }
87             m.invoke(closable, EMPTY_ARGS);
88          }
89          catch (NoSuchMethodException JavaDoc e)
90          {
91             log.warn("The closable object does not have a close() method", e);
92          }
93          catch (IllegalAccessException JavaDoc e)
94          {
95             log.warn("Cannot access close() method on closable object", e);
96          }
97          catch (InvocationTargetException JavaDoc e)
98          {
99             log.error("The close() method threw an exception", e.getTargetException());
100          }
101       }
102    }
103
104    /**
105     * Close an output stream safely.
106     *
107     * @param out
108     * the stream to close
109     */

110    public static void safeClose(OutputStream JavaDoc out)
111    {
112       if (out != null)
113       {
114          try
115          {
116             out.close();
117          }
118          catch (IOException JavaDoc e)
119          {
120             log.error("Error while closing putstream", e);
121          }
122       }
123    }
124
125    /**
126     * Close an input stream safely.
127     *
128     * @param in
129     * the stream to close
130     */

131    public static void safeClose(InputStream JavaDoc in)
132    {
133       if (in != null)
134       {
135          try
136          {
137             in.close();
138          }
139          catch (IOException JavaDoc e)
140          {
141             log.error("Error while closing inputstream", e);
142          }
143       }
144    }
145
146    /**
147     * Close a reader safely.
148     *
149     * @param reader
150     * the stream to close
151     */

152    public static void safeClose(Reader JavaDoc reader)
153    {
154       if (reader != null)
155       {
156          try
157          {
158             reader.close();
159          }
160          catch (IOException JavaDoc e)
161          {
162             log.error("Error while closing inputstream", e);
163          }
164       }
165    }
166
167    /**
168     * Pipe an input stream in an output stream.
169     *
170     * @param in
171     * the incoming stream
172     * @param out
173     * the outcoming stream
174     * @exception NullPointerException
175     * if an argument is null
176     * @exception IllegalArgumentException
177     * if bufferSize < 1
178     */

179    public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out) throws IOException JavaDoc
180    {
181       copy(in, out, DEFAULT_BUFFER_SIZE);
182    }
183
184    /**
185     * Pipe an incoming stream in an outcoming stream.
186     *
187     * @param in
188     * the incoming stream
189     * @param out
190     * the outcoming stream
191     * @param bufferSize
192     * the buffer size
193     * @exception NullPointerException
194     * if an argument is null
195     * @exception IllegalArgumentException
196     * if bufferSize < 1
197     */

198    public static void copy(InputStream JavaDoc in, OutputStream JavaDoc out, int bufferSize) throws IOException JavaDoc
199    {
200       // arguments check
201
if (in == null)
202       {
203          throw new IllegalArgumentException JavaDoc("null in");
204       }
205       if (out == null)
206       {
207          throw new IllegalArgumentException JavaDoc("null out");
208       }
209       if (bufferSize < 1)
210       {
211          throw new IllegalArgumentException JavaDoc("Buffer size is too small");
212       }
213
214       // do the job
215
byte[] buffer = new byte[bufferSize];
216       while (true)
217       {
218          int i = in.read(buffer);
219          if (i == 0)
220          {
221             continue;
222          }
223          if (i == -1)
224          {
225             break;
226          }
227          out.write(buffer, 0, i);
228       }
229    }
230
231    /** 16 chars long VMID. */
232    public static final String JavaDoc VMID = VMID();
233
234    private static final String JavaDoc VMID()
235    {
236       try
237       {
238          BigInteger JavaDoc bi = BigInteger.valueOf(0);
239          byte[] address = java.net.InetAddress.getLocalHost().getAddress();
240          for (int i = 0; i < 4; i++)
241          {
242             bi = bi.shiftLeft(8);
243             bi = bi.add(BigInteger.valueOf(address[i]));
244          }
245          bi = bi.shiftLeft(32);
246          int code = System.identityHashCode(new Object JavaDoc());
247          bi = bi.add(BigInteger.valueOf(code));
248          byte[] bytes = bi.toByteArray();
249          StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
250          char[] chars = "0123456789ABCDEF".toCharArray();
251          for (int i = 0; i < bytes.length; i++)
252          {
253             buffer.append(chars[(bytes[i] & 0xF0) >> 4]).append(chars[bytes[i] & 0xF]);
254          }
255          return buffer.toString();
256       }
257       catch (UnknownHostException JavaDoc e)
258       {
259          e.printStackTrace(System.err);
260          throw new Error JavaDoc("Cannot create VMID");
261       }
262    }
263
264    public static final Enumeration JavaDoc EMPTY_ENUMERATION = new Enumeration JavaDoc()
265    {
266       public boolean hasMoreElements()
267       {
268          return false;
269       }
270
271       public Object JavaDoc nextElement()
272       {
273          throw new NoSuchElementException();
274       }
275    };
276
277    public static final Iterator JavaDoc EMPTY_ITERATOR = new Iterator JavaDoc()
278    {
279       public boolean hasNext()
280       {
281          return false;
282       }
283
284       public Object JavaDoc next()
285       {
286          throw new NoSuchElementException();
287       }
288
289       public void remove()
290       {
291          throw new UnsupportedOperationException JavaDoc();
292       }
293    };
294
295    public static final ResourceBundle JavaDoc EMPTY_BUNDLE = new ResourceBundle JavaDoc()
296    {
297       protected Object JavaDoc handleGetObject(String JavaDoc key)
298       {
299          return null;
300       }
301
302       public Enumeration JavaDoc getKeys()
303       {
304          return EMPTY_ENUMERATION;
305       }
306    };
307
308    public static Enumeration JavaDoc toEnumeration(final Iterator JavaDoc iterator)
309    {
310       return new Enumeration JavaDoc()
311       {
312          public boolean hasMoreElements()
313          {
314             return iterator.hasNext();
315          }
316
317          public Object JavaDoc nextElement()
318          {
319             return iterator.next();
320          }
321       };
322    }
323
324    public static Set JavaDoc toSet(Enumeration JavaDoc e)
325    {
326       HashSet JavaDoc set = new HashSet JavaDoc();
327       while (e.hasMoreElements())
328       {
329          set.add(e.nextElement());
330       }
331       return set;
332    }
333
334    public static List JavaDoc toList(Enumeration JavaDoc e)
335    {
336       List JavaDoc list = new ArrayList JavaDoc();
337       while (e.hasMoreElements())
338       {
339          list.add(e.nextElement());
340       }
341       return list;
342    }
343
344    public static Set JavaDoc toSet(Object JavaDoc[] objects)
345    {
346       HashSet JavaDoc set = new HashSet JavaDoc();
347       for (int i = 0; i < objects.length; i++)
348       {
349          set.add(objects[i]);
350       }
351       return set;
352    }
353
354    public static Set JavaDoc toSet(final Iterator JavaDoc iterator)
355    {
356       HashSet JavaDoc set = new HashSet JavaDoc();
357       while (iterator.hasNext())
358       {
359          set.add(iterator.next());
360       }
361       return set;
362    }
363
364    public static List JavaDoc toList(final Iterator JavaDoc iterator)
365    {
366       List JavaDoc list = new ArrayList JavaDoc();
367       while (iterator.hasNext())
368       {
369          list.add(iterator.next());
370       }
371       return list;
372    }
373
374    public static Iterator JavaDoc iterator(final Object JavaDoc o)
375    {
376       return new Iterator JavaDoc()
377       {
378          boolean done = false;
379          public boolean hasNext()
380          {
381             return !done;
382          }
383          public Object JavaDoc next()
384          {
385             if (done)
386             {
387                throw new NoSuchElementException("Already iterated");
388             }
389             done = true;
390             return o;
391          }
392          public void remove()
393          {
394             throw new UnsupportedOperationException JavaDoc("read only");
395          }
396       };
397    }
398
399    public static Iterator JavaDoc iterator(final Object JavaDoc[] objects)
400    {
401       return new Iterator JavaDoc()
402       {
403          int index = 0;
404          public boolean hasNext()
405          {
406             return objects != null && index < objects.length;
407          }
408          public Object JavaDoc next()
409          {
410             if (objects == null)
411             {
412                throw new NoSuchElementException("Wrapped array is null");
413             }
414             if (index >= objects.length)
415             {
416                throw new NoSuchElementException("Index is greater than the array length");
417             }
418             return objects[index++];
419          }
420          public void remove()
421          {
422             throw new UnsupportedOperationException JavaDoc("read only");
423          }
424       };
425    }
426
427    public static int computeStringHash(int hash, String JavaDoc s)
428    {
429       char[] chars = s.toCharArray();
430       int length = chars.length;
431       for (int i = 0; i < length; i++)
432       {
433          char c = chars[i];
434          hash = 31 * hash + c;
435       }
436       return hash;
437    }
438
439    public static String JavaDoc createXWWWFormURLEncoded(String JavaDoc s)
440    {
441       try
442       {
443          return URLEncoder.encode(s, "UTF-8");
444       }
445       catch (UnsupportedEncodingException JavaDoc e)
446       {
447          throw new Error JavaDoc("UTF-8 encoding missing");
448       }
449    }
450
451    /**
452     * Return true is the address is not null and matches the email validation
453     * regular expression.
454     */

455    public static boolean isEmailValid(String JavaDoc address)
456    {
457       return address == null ? false : Pattern.matches(RE_EMAIL_VALIDATION, address);
458    }
459
460    /**
461     * Computes an md5 hash of a string.
462     *
463     * @param text
464     * the hashed string
465     * @return the string hash
466     * @exception NullPointerException
467     * if text is null
468     */

469    public static byte[] md5(String JavaDoc text)
470    {
471       // arguments check
472
if (text == null)
473       {
474          throw new NullPointerException JavaDoc("null text");
475       }
476
477       try
478       {
479          MessageDigest JavaDoc md = MessageDigest.getInstance("MD5");
480          md.update(text.getBytes());
481          return md.digest();
482       }
483       catch (NoSuchAlgorithmException JavaDoc e)
484       {
485          log.error("Cannot find MD5 algorithm", e);
486          throw new RuntimeException JavaDoc("Cannot find MD5 algorithm");
487       }
488    }
489
490    /**
491     * Computes an md5 hash and returns the result as a string in hexadecimal
492     * format.
493     *
494     * @param text the hashed string
495     * @return the string hash
496     * @exception NullPointerException if text is null
497     */

498    public static String JavaDoc md5AsHexString(String JavaDoc text)
499    {
500       return toHexString(md5(text));
501    }
502
503    /**
504     * Returns a string in the hexadecimal format.
505     *
506     * @param bytes the converted bytes
507     * @return the hexadecimal string representing the bytes data
508     * @throws IllegalArgumentException if the byte array is null
509     */

510    public static String JavaDoc toHexString(byte[] bytes)
511    {
512       if (bytes == null)
513       {
514          throw new IllegalArgumentException JavaDoc("byte array must not be null");
515       }
516       StringBuffer JavaDoc hex = new StringBuffer JavaDoc(bytes.length * 2);
517       for (int i = 0; i < bytes.length; i++)
518       {
519          hex.append(Character.forDigit((bytes[i] & 0XF0) >> 4, 16));
520          hex.append(Character.forDigit((bytes[i] & 0X0F), 16));
521       }
522       return hex.toString();
523    }
524
525    /**
526     * Returns a byte array converted from the hexadecimal format.
527     *
528     * @param hex the string to convert
529     * @return the byte array corresponding
530     * @throws IllegalArgumentException if the string is null or does not have the good format
531     */

532    public static byte[] fromHexString(String JavaDoc hex)
533    {
534       if (hex == null)
535       {
536         throw new IllegalArgumentException JavaDoc("Hex string must not be null");
537       }
538       if (hex.length() % 2 == 1)
539       {
540          throw new IllegalArgumentException JavaDoc("Hex string length is not even : " + hex.length());
541       }
542       int index = 0;
543       byte[] bytes = new byte[hex.length() / 2];
544       for (int i = 0;i < bytes.length;i++)
545       {
546          char chigh = hex.charAt(index++);
547          int high = Character.digit(chigh, 16);
548          if (high == -1)
549          {
550             throw new IllegalArgumentException JavaDoc("Hex string contains a bad char : " + chigh);
551          }
552          char clow = hex.charAt(index++);
553          int low = Character.digit(clow, 16);
554          if (low == -1)
555          {
556             throw new IllegalArgumentException JavaDoc("Hex string contains a bad char : " + clow);
557          }
558          byte value = (byte)((high << 4) + low);
559          bytes[i] = value;
560       }
561       return bytes;
562    }
563
564    /**
565     *
566     */

567    public static String JavaDoc generateTemporaryHash(String JavaDoc value, long time)
568    {
569       if (value == null)
570       {
571          throw new IllegalArgumentException JavaDoc("id must not be null");
572       }
573
574       Calendar JavaDoc calendar = Calendar.getInstance();
575       calendar.setTimeInMillis(time);
576       calendar.set(Calendar.MINUTE, 0);
577       calendar.set(Calendar.SECOND, 0);
578       calendar.set(Calendar.MILLISECOND, 0);
579       return md5AsHexString(value + calendar.getTimeInMillis());
580    }
581
582    /**
583     *
584     */

585    public static boolean confirmTemporaryHash(String JavaDoc hash, String JavaDoc value, long time)
586    {
587       if (hash == null)
588       {
589          return false;
590       }
591       if (value == null)
592       {
593          throw new IllegalArgumentException JavaDoc("value must not be null");
594       }
595
596       Calendar JavaDoc calendar = Calendar.getInstance();
597       calendar.setTimeInMillis(time);
598       calendar.set(Calendar.MINUTE, 0);
599       calendar.set(Calendar.SECOND, 0);
600       calendar.set(Calendar.MILLISECOND, 0);
601       String JavaDoc expected = md5AsHexString(value + calendar.getTimeInMillis());
602       if (expected.equals(hash))
603       {
604          return true;
605       }
606       calendar.add(Calendar.HOUR_OF_DAY, -1);
607       expected = md5AsHexString(value + calendar.getTimeInMillis());
608       return expected.equals(hash);
609    }
610
611    public static String JavaDoc buildClassLoaderInfo(ClassLoader JavaDoc loader)
612    {
613       if (loader == null)
614       {
615          throw new IllegalArgumentException JavaDoc("no loader");
616       }
617       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc();
618       buffer.append("ClassLoader[Name=").append(loader.getClass().getName());
619       buffer.append(",HashCode=").append(loader.hashCode());
620       buffer.append(",IdentityHashCode=").append(System.identityHashCode(loader));
621       if (loader instanceof URLClassLoader JavaDoc)
622       {
623          URLClassLoader JavaDoc urlLoader = (URLClassLoader JavaDoc)loader;
624          URL JavaDoc[] urls = urlLoader.getURLs();
625          for (int i = 0; i < urls.length; i++)
626          {
627             URL JavaDoc url = urls[i];
628             buffer.append(",URL(").append(i).append(")=").append(url);
629          }
630       }
631       try
632       {
633          Class JavaDoc uclClass = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.mx.loading.UnifiedClassLoader");
634          Class JavaDoc loaderClass = loader.getClass();
635          if (uclClass.isAssignableFrom(loaderClass))
636          {
637             URL JavaDoc url = (URL JavaDoc)loaderClass.getMethod("getURL", new Class JavaDoc[0]).invoke(loader, new Object JavaDoc[0]);
638             buffer.append(",GetURL=").append(url);
639          }
640       }
641       catch (Exception JavaDoc e)
642       {
643          log.error("Cannot get UCL infos", e);
644       }
645       buffer.append("]");
646       return buffer.toString();
647    }
648
649    public static String JavaDoc dumpClassLoaderHeirarchyInfo(ClassLoader JavaDoc loader)
650    {
651       StringWriter JavaDoc writer = new StringWriter JavaDoc();
652       dumpClassLoaderHeirarchyInfo(writer, loader);
653       return writer.toString();
654    }
655
656    public static void dumpClassLoaderHeirarchyInfo(Writer JavaDoc writer, ClassLoader JavaDoc loader)
657    {
658       if (writer == null)
659       {
660          throw new IllegalArgumentException JavaDoc("no writer");
661       }
662       if (loader == null)
663       {
664          throw new IllegalArgumentException JavaDoc("no loader");
665       }
666
667       //
668
PrintWriter JavaDoc pw = null;
669       if (writer instanceof PrintWriter JavaDoc)
670       {
671          pw = (PrintWriter JavaDoc)writer;
672       }
673       else
674       {
675          pw = new PrintWriter JavaDoc(writer);
676       }
677
678       pw.println("<classloader-dump>");
679       while (loader != null)
680       {
681          pw.println(buildClassLoaderInfo(loader));
682          loader = loader.getParent();
683       }
684       pw.print("</classloader-dump>");
685       pw.flush();
686    }
687
688    public static void dumpClassLoaderHeirarchyInfo(Logger log, ClassLoader JavaDoc loader)
689    {
690       Writer JavaDoc writer = new Log4JWriter(log, Level.DEBUG);
691       dumpClassLoaderHeirarchyInfo(writer, loader);
692    }
693
694    public static void dumpClassLoaderHeirarchyInfo(Logger log, Level level, ClassLoader JavaDoc loader)
695    {
696       Writer JavaDoc writer = new Log4JWriter(log, level);
697       dumpClassLoaderHeirarchyInfo(writer, loader);
698    }
699
700    /**
701     * Replace occurence in a string.
702     *
703     * @param string the source string
704     * @param pattern the replaced pattern
705     * @param replacement the replacement text
706     * @return the new string
707     */

708    public static String JavaDoc replace(String JavaDoc string, String JavaDoc pattern, String JavaDoc replacement)
709    {
710       StringBuffer JavaDoc buffer = new StringBuffer JavaDoc(string.length());
711       int previous = 0;
712       int current = string.indexOf(pattern);
713       while (current != -1)
714       {
715          buffer.append(string.substring(previous, current));
716          buffer.append(replacement);
717          previous = current + pattern.length();
718          current = string.indexOf(pattern, previous);
719       }
720       buffer.append(string.substring(previous));
721       return buffer.toString();
722    }
723 }
Popular Tags