1 9 10 package org.jboss.portal.common.util; 11 12 import java.io.IOException ; 13 import java.io.InputStream ; 14 import java.io.OutputStream ; 15 import java.io.Reader ; 16 import java.io.UnsupportedEncodingException ; 17 import java.io.Writer ; 18 import java.io.PrintWriter ; 19 import java.io.StringWriter ; 20 import java.lang.reflect.InvocationTargetException ; 21 import java.lang.reflect.Method ; 22 import java.lang.reflect.Modifier ; 23 import java.math.BigInteger ; 24 import java.net.URLEncoder ; 25 import java.net.UnknownHostException ; 26 import java.net.URLClassLoader ; 27 import java.net.URL ; 28 import java.security.MessageDigest ; 29 import java.security.NoSuchAlgorithmException ; 30 import java.util.ArrayList ; 31 import java.util.Enumeration ; 32 import java.util.HashSet ; 33 import java.util.Iterator ; 34 import java.util.List ; 35 import java.util.NoSuchElementException ; 36 import java.util.ResourceBundle ; 37 import java.util.Set ; 38 import java.util.Date ; 39 import java.util.Calendar ; 40 import java.util.regex.Pattern ; 41 42 import org.apache.log4j.Logger; 43 import org.apache.log4j.Level; 44 import org.jboss.portal.common.logging.Log4JWriter; 45 46 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 [] EMPTY_ARGS = new Object [0]; 59 60 private static final Class [] EMPTY_PARAMETER_TYPES = new Class [0]; 61 62 public static final String RE_EMAIL_VALIDATION = "^([a-zA-Z0-9]+(([\\.\\-\\_]?[a-zA-Z0-9]+)+)?)\\@(([a-zA-Z0-9]+[\\.\\-\\_])+[a-zA-Z]{2,4})$"; 63 64 70 public static void safeClose(Object closable) 71 { 72 if (closable != null) 73 { 74 try 75 { 76 Method 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 e) 90 { 91 log.warn("The closable object does not have a close() method", e); 92 } 93 catch (IllegalAccessException e) 94 { 95 log.warn("Cannot access close() method on closable object", e); 96 } 97 catch (InvocationTargetException e) 98 { 99 log.error("The close() method threw an exception", e.getTargetException()); 100 } 101 } 102 } 103 104 110 public static void safeClose(OutputStream out) 111 { 112 if (out != null) 113 { 114 try 115 { 116 out.close(); 117 } 118 catch (IOException e) 119 { 120 log.error("Error while closing putstream", e); 121 } 122 } 123 } 124 125 131 public static void safeClose(InputStream in) 132 { 133 if (in != null) 134 { 135 try 136 { 137 in.close(); 138 } 139 catch (IOException e) 140 { 141 log.error("Error while closing inputstream", e); 142 } 143 } 144 } 145 146 152 public static void safeClose(Reader reader) 153 { 154 if (reader != null) 155 { 156 try 157 { 158 reader.close(); 159 } 160 catch (IOException e) 161 { 162 log.error("Error while closing inputstream", e); 163 } 164 } 165 } 166 167 179 public static void copy(InputStream in, OutputStream out) throws IOException 180 { 181 copy(in, out, DEFAULT_BUFFER_SIZE); 182 } 183 184 198 public static void copy(InputStream in, OutputStream out, int bufferSize) throws IOException 199 { 200 if (in == null) 202 { 203 throw new IllegalArgumentException ("null in"); 204 } 205 if (out == null) 206 { 207 throw new IllegalArgumentException ("null out"); 208 } 209 if (bufferSize < 1) 210 { 211 throw new IllegalArgumentException ("Buffer size is too small"); 212 } 213 214 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 232 public static final String VMID = VMID(); 233 234 private static final String VMID() 235 { 236 try 237 { 238 BigInteger 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 ()); 247 bi = bi.add(BigInteger.valueOf(code)); 248 byte[] bytes = bi.toByteArray(); 249 StringBuffer buffer = new StringBuffer (); 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 e) 258 { 259 e.printStackTrace(System.err); 260 throw new Error ("Cannot create VMID"); 261 } 262 } 263 264 public static final Enumeration EMPTY_ENUMERATION = new Enumeration () 265 { 266 public boolean hasMoreElements() 267 { 268 return false; 269 } 270 271 public Object nextElement() 272 { 273 throw new NoSuchElementException(); 274 } 275 }; 276 277 public static final Iterator EMPTY_ITERATOR = new Iterator () 278 { 279 public boolean hasNext() 280 { 281 return false; 282 } 283 284 public Object next() 285 { 286 throw new NoSuchElementException(); 287 } 288 289 public void remove() 290 { 291 throw new UnsupportedOperationException (); 292 } 293 }; 294 295 public static final ResourceBundle EMPTY_BUNDLE = new ResourceBundle () 296 { 297 protected Object handleGetObject(String key) 298 { 299 return null; 300 } 301 302 public Enumeration getKeys() 303 { 304 return EMPTY_ENUMERATION; 305 } 306 }; 307 308 public static Enumeration toEnumeration(final Iterator iterator) 309 { 310 return new Enumeration () 311 { 312 public boolean hasMoreElements() 313 { 314 return iterator.hasNext(); 315 } 316 317 public Object nextElement() 318 { 319 return iterator.next(); 320 } 321 }; 322 } 323 324 public static Set toSet(Enumeration e) 325 { 326 HashSet set = new HashSet (); 327 while (e.hasMoreElements()) 328 { 329 set.add(e.nextElement()); 330 } 331 return set; 332 } 333 334 public static List toList(Enumeration e) 335 { 336 List list = new ArrayList (); 337 while (e.hasMoreElements()) 338 { 339 list.add(e.nextElement()); 340 } 341 return list; 342 } 343 344 public static Set toSet(Object [] objects) 345 { 346 HashSet set = new HashSet (); 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 toSet(final Iterator iterator) 355 { 356 HashSet set = new HashSet (); 357 while (iterator.hasNext()) 358 { 359 set.add(iterator.next()); 360 } 361 return set; 362 } 363 364 public static List toList(final Iterator iterator) 365 { 366 List list = new ArrayList (); 367 while (iterator.hasNext()) 368 { 369 list.add(iterator.next()); 370 } 371 return list; 372 } 373 374 public static Iterator iterator(final Object o) 375 { 376 return new Iterator () 377 { 378 boolean done = false; 379 public boolean hasNext() 380 { 381 return !done; 382 } 383 public Object 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 ("read only"); 395 } 396 }; 397 } 398 399 public static Iterator iterator(final Object [] objects) 400 { 401 return new Iterator () 402 { 403 int index = 0; 404 public boolean hasNext() 405 { 406 return objects != null && index < objects.length; 407 } 408 public Object 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 ("read only"); 423 } 424 }; 425 } 426 427 public static int computeStringHash(int hash, String 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 createXWWWFormURLEncoded(String s) 440 { 441 try 442 { 443 return URLEncoder.encode(s, "UTF-8"); 444 } 445 catch (UnsupportedEncodingException e) 446 { 447 throw new Error ("UTF-8 encoding missing"); 448 } 449 } 450 451 455 public static boolean isEmailValid(String address) 456 { 457 return address == null ? false : Pattern.matches(RE_EMAIL_VALIDATION, address); 458 } 459 460 469 public static byte[] md5(String text) 470 { 471 if (text == null) 473 { 474 throw new NullPointerException ("null text"); 475 } 476 477 try 478 { 479 MessageDigest md = MessageDigest.getInstance("MD5"); 480 md.update(text.getBytes()); 481 return md.digest(); 482 } 483 catch (NoSuchAlgorithmException e) 484 { 485 log.error("Cannot find MD5 algorithm", e); 486 throw new RuntimeException ("Cannot find MD5 algorithm"); 487 } 488 } 489 490 498 public static String md5AsHexString(String text) 499 { 500 return toHexString(md5(text)); 501 } 502 503 510 public static String toHexString(byte[] bytes) 511 { 512 if (bytes == null) 513 { 514 throw new IllegalArgumentException ("byte array must not be null"); 515 } 516 StringBuffer hex = new StringBuffer (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 532 public static byte[] fromHexString(String hex) 533 { 534 if (hex == null) 535 { 536 throw new IllegalArgumentException ("Hex string must not be null"); 537 } 538 if (hex.length() % 2 == 1) 539 { 540 throw new IllegalArgumentException ("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 ("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 ("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 567 public static String generateTemporaryHash(String value, long time) 568 { 569 if (value == null) 570 { 571 throw new IllegalArgumentException ("id must not be null"); 572 } 573 574 Calendar 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 585 public static boolean confirmTemporaryHash(String hash, String value, long time) 586 { 587 if (hash == null) 588 { 589 return false; 590 } 591 if (value == null) 592 { 593 throw new IllegalArgumentException ("value must not be null"); 594 } 595 596 Calendar 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 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 buildClassLoaderInfo(ClassLoader loader) 612 { 613 if (loader == null) 614 { 615 throw new IllegalArgumentException ("no loader"); 616 } 617 StringBuffer buffer = new StringBuffer (); 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 ) 622 { 623 URLClassLoader urlLoader = (URLClassLoader )loader; 624 URL [] urls = urlLoader.getURLs(); 625 for (int i = 0; i < urls.length; i++) 626 { 627 URL url = urls[i]; 628 buffer.append(",URL(").append(i).append(")=").append(url); 629 } 630 } 631 try 632 { 633 Class uclClass = Thread.currentThread().getContextClassLoader().loadClass("org.jboss.mx.loading.UnifiedClassLoader"); 634 Class loaderClass = loader.getClass(); 635 if (uclClass.isAssignableFrom(loaderClass)) 636 { 637 URL url = (URL )loaderClass.getMethod("getURL", new Class [0]).invoke(loader, new Object [0]); 638 buffer.append(",GetURL=").append(url); 639 } 640 } 641 catch (Exception e) 642 { 643 log.error("Cannot get UCL infos", e); 644 } 645 buffer.append("]"); 646 return buffer.toString(); 647 } 648 649 public static String dumpClassLoaderHeirarchyInfo(ClassLoader loader) 650 { 651 StringWriter writer = new StringWriter (); 652 dumpClassLoaderHeirarchyInfo(writer, loader); 653 return writer.toString(); 654 } 655 656 public static void dumpClassLoaderHeirarchyInfo(Writer writer, ClassLoader loader) 657 { 658 if (writer == null) 659 { 660 throw new IllegalArgumentException ("no writer"); 661 } 662 if (loader == null) 663 { 664 throw new IllegalArgumentException ("no loader"); 665 } 666 667 PrintWriter pw = null; 669 if (writer instanceof PrintWriter ) 670 { 671 pw = (PrintWriter )writer; 672 } 673 else 674 { 675 pw = new PrintWriter (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 loader) 689 { 690 Writer writer = new Log4JWriter(log, Level.DEBUG); 691 dumpClassLoaderHeirarchyInfo(writer, loader); 692 } 693 694 public static void dumpClassLoaderHeirarchyInfo(Logger log, Level level, ClassLoader loader) 695 { 696 Writer writer = new Log4JWriter(log, level); 697 dumpClassLoaderHeirarchyInfo(writer, loader); 698 } 699 700 708 public static String replace(String string, String pattern, String replacement) 709 { 710 StringBuffer buffer = new StringBuffer (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 |