001 /** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017 package org.apache.camel.util; 018 019 import java.io.Closeable; 020 import java.io.IOException; 021 import java.io.InputStream; 022 import java.lang.annotation.Annotation; 023 import java.lang.reflect.InvocationTargetException; 024 import java.lang.reflect.Method; 025 import java.nio.charset.Charset; 026 import java.util.ArrayList; 027 import java.util.Arrays; 028 import java.util.Collection; 029 import java.util.Collections; 030 import java.util.Iterator; 031 import java.util.List; 032 033 import org.w3c.dom.Node; 034 import org.w3c.dom.NodeList; 035 036 037 import org.apache.camel.RuntimeCamelException; 038 import org.apache.commons.logging.Log; 039 import org.apache.commons.logging.LogFactory; 040 041 042 /** 043 * A number of useful helper methods for working with Objects 044 * 045 * @version $Revision: 51090 $ 046 */ 047 public final class ObjectHelper { 048 private static final transient Log LOG = LogFactory.getLog(ObjectHelper.class); 049 050 /** 051 * Utility classes should not have a public constructor. 052 */ 053 private ObjectHelper() { 054 } 055 056 /** 057 * @deprecated use the equal method instead. Will be removed in Camel 2.0. 058 * 059 * @see #equal(Object, Object) 060 */ 061 @Deprecated 062 public static boolean equals(Object a, Object b) { 063 return equal(a, b); 064 } 065 066 /** 067 * A helper method for comparing objects for equality while handling nulls 068 */ 069 public static boolean equal(Object a, Object b) { 070 if (a == b) { 071 return true; 072 } 073 074 if (a instanceof byte[] && b instanceof byte[]) { 075 return equalByteArray((byte[]) a, (byte[]) b); 076 } 077 078 return a != null && b != null && a.equals(b); 079 } 080 081 /** 082 * A helper method for comparing byte arrays for equality while handling nulls 083 */ 084 public static boolean equalByteArray(byte[] a, byte[] b) { 085 if (a == b) { 086 return true; 087 } 088 089 // loop and compare each byte 090 if (a != null && b != null && a.length == b.length) { 091 for (int i = 0; i < a.length; i++) { 092 if (a[i] != b[i]) { 093 return false; 094 } 095 } 096 // all bytes are equal 097 return true; 098 } 099 100 return false; 101 } 102 103 /** 104 * Returns true if the given object is equal to any of the expected value 105 */ 106 public static boolean isEqualToAny(Object object, Object... values) { 107 for (Object value : values) { 108 if (equal(object, value)) { 109 return true; 110 } 111 } 112 return false; 113 } 114 115 /** 116 * A helper method for performing an ordered comparison on the objects 117 * handling nulls and objects which do not handle sorting gracefully 118 */ 119 public static int compare(Object a, Object b) { 120 if (a == b) { 121 return 0; 122 } 123 if (a == null) { 124 return -1; 125 } 126 if (b == null) { 127 return 1; 128 } 129 if (a instanceof Comparable) { 130 Comparable comparable = (Comparable)a; 131 return comparable.compareTo(b); 132 } else { 133 int answer = a.getClass().getName().compareTo(b.getClass().getName()); 134 if (answer == 0) { 135 answer = a.hashCode() - b.hashCode(); 136 } 137 return answer; 138 } 139 } 140 141 public static Boolean toBoolean(Object value) { 142 if (value instanceof Boolean) { 143 return (Boolean)value; 144 } 145 if (value instanceof String) { 146 return "true".equalsIgnoreCase(value.toString()) ? Boolean.TRUE : Boolean.FALSE; 147 } 148 if (value instanceof Integer) { 149 return (Integer)value > 0 ? Boolean.TRUE : Boolean.FALSE; 150 } 151 return null; 152 } 153 154 public static void notNull(Object value, String name) { 155 if (value == null) { 156 throw new IllegalArgumentException(name + " must be specified"); 157 } 158 } 159 160 public static String[] splitOnCharacter(String value, String needle, int count) { 161 String rc[] = new String[count]; 162 rc[0] = value; 163 for (int i = 1; i < count; i++) { 164 String v = rc[i - 1]; 165 int p = v.indexOf(needle); 166 if (p < 0) { 167 return rc; 168 } 169 rc[i - 1] = v.substring(0, p); 170 rc[i] = v.substring(p + 1); 171 } 172 return rc; 173 } 174 175 /** 176 * Removes any starting characters on the given text which match the given 177 * character 178 * 179 * @param text the string 180 * @param ch the initial characters to remove 181 * @return either the original string or the new substring 182 */ 183 public static String removeStartingCharacters(String text, char ch) { 184 int idx = 0; 185 while (text.charAt(idx) == ch) { 186 idx++; 187 } 188 if (idx > 0) { 189 return text.substring(idx); 190 } 191 return text; 192 } 193 194 public static String capitalize(String text) { 195 if (text == null) { 196 return null; 197 } 198 int length = text.length(); 199 if (length == 0) { 200 return text; 201 } 202 String answer = text.substring(0, 1).toUpperCase(); 203 if (length > 1) { 204 answer += text.substring(1, length); 205 } 206 return answer; 207 } 208 209 210 /** 211 * Returns true if the collection contains the specified value 212 */ 213 @SuppressWarnings("unchecked") 214 public static boolean contains(Object collectionOrArray, Object value) { 215 if (collectionOrArray instanceof Collection) { 216 Collection collection = (Collection)collectionOrArray; 217 return collection.contains(value); 218 } else if (collectionOrArray instanceof String && value instanceof String) { 219 String str = (String) collectionOrArray; 220 String subStr = (String) value; 221 return str.contains(subStr); 222 } else { 223 Iterator iter = createIterator(collectionOrArray); 224 while (iter.hasNext()) { 225 if (equal(value, iter.next())) { 226 return true; 227 } 228 } 229 } 230 return false; 231 } 232 233 /** 234 * Creates an iterator over the value if the value is a collection, an 235 * Object[] or a primitive type array; otherwise to simplify the caller's 236 * code, we just create a singleton collection iterator over a single value 237 */ 238 @SuppressWarnings("unchecked") 239 public static Iterator createIterator(Object value) { 240 if (value == null) { 241 return Collections.EMPTY_LIST.iterator(); 242 } else if (value instanceof Iterator) { 243 return (Iterator) value; 244 } else if (value instanceof Collection) { 245 Collection collection = (Collection)value; 246 return collection.iterator(); 247 } else if (value.getClass().isArray()) { 248 // TODO we should handle primitive array types? 249 List<Object> list = Arrays.asList((Object[]) value); 250 return list.iterator(); 251 } else if (value instanceof NodeList) { 252 // lets iterate through DOM results after performing XPaths 253 final NodeList nodeList = (NodeList) value; 254 return new Iterator<Node>() { 255 int idx = -1; 256 257 public boolean hasNext() { 258 return ++idx < nodeList.getLength(); 259 } 260 261 public Node next() { 262 return nodeList.item(idx); 263 } 264 265 public void remove() { 266 throw new UnsupportedOperationException(); 267 } 268 }; 269 } else { 270 return Collections.singletonList(value).iterator(); 271 } 272 } 273 274 /** 275 * Returns the predicate matching boolean on a {@link List} result set where 276 * if the first element is a boolean its value is used otherwise this method 277 * returns true if the collection is not empty 278 * 279 * @return <tt>true</tt> if the first element is a boolean and its value is true or 280 * if the list is non empty 281 */ 282 public static boolean matches(List list) { 283 if (!list.isEmpty()) { 284 Object value = list.get(0); 285 if (value instanceof Boolean) { 286 Boolean flag = (Boolean)value; 287 return flag.booleanValue(); 288 } else { 289 // lets assume non-empty results are true 290 return true; 291 } 292 } 293 return false; 294 } 295 296 public static boolean isNotNullAndNonEmpty(String text) { 297 return text != null && text.trim().length() > 0; 298 } 299 300 public static boolean isNullOrBlank(String text) { 301 return text == null || text.trim().length() <= 0; 302 } 303 304 /** 305 * A helper method to access a system property, catching any security 306 * exceptions 307 * 308 * @param name the name of the system property required 309 * @param defaultValue the default value to use if the property is not 310 * available or a security exception prevents access 311 * @return the system property value or the default value if the property is 312 * not available or security does not allow its access 313 */ 314 public static String getSystemProperty(String name, String defaultValue) { 315 try { 316 return System.getProperty(name, defaultValue); 317 } catch (Exception e) { 318 if (LOG.isDebugEnabled()) { 319 LOG.debug("Caught security exception accessing system property: " + name + ". Reason: " + e, 320 e); 321 } 322 return defaultValue; 323 } 324 } 325 326 /** 327 * A helper method to access a boolean system property, catching any security 328 * exceptions 329 * 330 * @param name the name of the system property required 331 * @param defaultValue the default value to use if the property is not 332 * available or a security exception prevents access 333 * @return the boolean representation of the system property value 334 * or the default value if the property is not available or 335 * security does not allow its access 336 */ 337 public static boolean getSystemProperty(String name, Boolean defaultValue) { 338 String result = getSystemProperty(name, defaultValue.toString()); 339 return Boolean.parseBoolean(result); 340 } 341 342 /** 343 * Returns the type name of the given type or null if the type variable is 344 * null 345 */ 346 public static String name(Class type) { 347 return type != null ? type.getName() : null; 348 } 349 350 /** 351 * Returns the type name of the given value 352 */ 353 public static String className(Object value) { 354 return name(value != null ? value.getClass() : null); 355 } 356 357 /** 358 * Returns the canonical type name of the given value 359 */ 360 public static String classCanonicalName(Object value) { 361 if (value != null) { 362 return value.getClass().getCanonicalName(); 363 } else { 364 return null; 365 } 366 } 367 368 /** 369 * Attempts to load the given class name using the thread context class 370 * loader or the class loader used to load this class 371 * 372 * @param name the name of the class to load 373 * @return the class or null if it could not be loaded 374 */ 375 public static Class<?> loadClass(String name) { 376 return loadClass(name, ObjectHelper.class.getClassLoader()); 377 } 378 379 /** 380 * Attempts to load the given class name using the thread context class 381 * loader or the given class loader 382 * 383 * @param name the name of the class to load 384 * @param loader the class loader to use after the thread context class 385 * loader 386 * @return the class or null if it could not be loaded 387 */ 388 public static Class<?> loadClass(String name, ClassLoader loader) { 389 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 390 if (contextClassLoader != null) { 391 try { 392 return contextClassLoader.loadClass(name); 393 } catch (ClassNotFoundException e) { 394 try { 395 return loader.loadClass(name); 396 } catch (ClassNotFoundException e1) { 397 LOG.debug("Could not find class: " + name + ". Reason: " + e); 398 } 399 } 400 } 401 return null; 402 } 403 404 /** 405 * Attempts to load the given resource as a stream using the thread context class 406 * loader or the class loader used to load this class 407 * 408 * @param name the name of the resource to load 409 * @return the stream or null if it could not be loaded 410 */ 411 public static InputStream loadResourceAsStream(String name) { 412 InputStream in = null; 413 414 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 415 if (contextClassLoader != null) { 416 in = contextClassLoader.getResourceAsStream(name); 417 } 418 if (in == null) { 419 in = ObjectHelper.class.getClassLoader().getResourceAsStream(name); 420 } 421 422 return in; 423 } 424 425 /** 426 * A helper method to invoke a method via reflection and wrap any exceptions 427 * as {@link RuntimeCamelException} instances 428 * 429 * @param method the method to invoke 430 * @param instance the object instance (or null for static methods) 431 * @param parameters the parameters to the method 432 * @return the result of the method invocation 433 */ 434 public static Object invokeMethod(Method method, Object instance, Object... parameters) { 435 try { 436 return method.invoke(instance, parameters); 437 } catch (IllegalAccessException e) { 438 throw new RuntimeCamelException(e); 439 } catch (InvocationTargetException e) { 440 throw new RuntimeCamelException(e.getCause()); 441 } 442 } 443 444 /** 445 * Returns a list of methods which are annotated with the given annotation 446 * 447 * @param type the type to reflect on 448 * @param annotationType the annotation type 449 * @return a list of the methods found 450 */ 451 public static List<Method> findMethodsWithAnnotation(Class<?> type, 452 Class<? extends Annotation> annotationType) { 453 List<Method> answer = new ArrayList<Method>(); 454 do { 455 Method[] methods = type.getDeclaredMethods(); 456 for (Method method : methods) { 457 if (method.getAnnotation(annotationType) != null) { 458 answer.add(method); 459 } 460 } 461 type = type.getSuperclass(); 462 } while (type != null); 463 return answer; 464 } 465 466 /** 467 * Turns the given object arrays into a meaningful string 468 * 469 * @param objects an array of objects or null 470 * @return a meaningful string 471 */ 472 public static String asString(Object[] objects) { 473 if (objects == null) { 474 return "null"; 475 } else { 476 StringBuffer buffer = new StringBuffer("{"); 477 int counter = 0; 478 for (Object object : objects) { 479 if (counter++ > 0) { 480 buffer.append(", "); 481 } 482 String text = (object == null) ? "null" : object.toString(); 483 buffer.append(text); 484 } 485 buffer.append("}"); 486 return buffer.toString(); 487 } 488 } 489 490 /** 491 * Returns true if a class is assignable from another class like the 492 * {@link Class#isAssignableFrom(Class)} method but which also includes 493 * coercion between primitive types to deal with Java 5 primitive type 494 * wrapping 495 */ 496 public static boolean isAssignableFrom(Class a, Class b) { 497 a = convertPrimitiveTypeToWrapperType(a); 498 b = convertPrimitiveTypeToWrapperType(b); 499 return a.isAssignableFrom(b); 500 } 501 502 /** 503 * Converts primitive types such as int to its wrapper type like 504 * {@link Integer} 505 */ 506 public static Class convertPrimitiveTypeToWrapperType(Class type) { 507 Class rc = type; 508 if (type.isPrimitive()) { 509 if (type == int.class) { 510 rc = Integer.class; 511 } else if (type == long.class) { 512 rc = Long.class; 513 } else if (type == double.class) { 514 rc = Double.class; 515 } else if (type == float.class) { 516 rc = Float.class; 517 } else if (type == short.class) { 518 rc = Short.class; 519 } else if (type == byte.class) { 520 rc = Byte.class; 521 // TODO: Why is boolean disabled 522 /* 523 } else if (type == boolean.class) { 524 rc = Boolean.class; 525 */ 526 } 527 } 528 return rc; 529 } 530 531 /** 532 * Helper method to return the default character set name 533 */ 534 public static String getDefaultCharacterSet() { 535 return Charset.defaultCharset().name(); 536 } 537 538 /** 539 * Returns the Java Bean property name of the given method, if it is a setter 540 */ 541 public static String getPropertyName(Method method) { 542 String propertyName = method.getName(); 543 if (propertyName.startsWith("set") && method.getParameterTypes().length == 1) { 544 propertyName = propertyName.substring(3, 4).toLowerCase() + propertyName.substring(4); 545 } 546 return propertyName; 547 } 548 549 /** 550 * Returns true if the given collection of annotations matches the given type 551 */ 552 public static boolean hasAnnotation(Annotation[] annotations, Class<?> type) { 553 for (Annotation annotation : annotations) { 554 if (type.isInstance(annotation)) { 555 return true; 556 } 557 } 558 return false; 559 } 560 561 /** 562 * Closes the given resource if it is available, logging any closing exceptions to the given log 563 * 564 * @param closeable the object to close 565 * @param name the name of the resource 566 * @param log the log to use when reporting closure warnings 567 */ 568 public static void close(Closeable closeable, String name, Log log) { 569 if (closeable != null) { 570 try { 571 closeable.close(); 572 } catch (IOException e) { 573 if (log != null) { 574 log.warn("Could not close: " + name + ". Reason: " + e, e); 575 } 576 } 577 } 578 } 579 580 /** 581 * Converts the given value to the required type or throw a meaningful exception 582 */ 583 public static <T> T cast(Class<T> toType, Object value) { 584 if (toType == boolean.class) { 585 return (T)cast(Boolean.class, value); 586 } else if (toType.isPrimitive()) { 587 Class newType = convertPrimitiveTypeToWrapperType(toType); 588 if (newType != toType) { 589 return (T)cast(newType, value); 590 } 591 } 592 try { 593 return toType.cast(value); 594 } catch (ClassCastException e) { 595 throw new IllegalArgumentException("Failed to convert: " + value + " to type: " 596 + toType.getName() + " due to: " + e, e); 597 } 598 } 599 600 /** 601 * A helper method to create a new instance of a type using the default constructor arguments. 602 */ 603 public static <T> T newInstance(Class<T> type) { 604 try { 605 return type.newInstance(); 606 } catch (InstantiationException e) { 607 throw new RuntimeCamelException(e.getCause()); 608 } catch (IllegalAccessException e) { 609 throw new RuntimeCamelException(e); 610 } 611 } 612 613 /** 614 * A helper method to create a new instance of a type using the default constructor arguments. 615 */ 616 public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) { 617 try { 618 Object value = actualType.newInstance(); 619 return cast(expectedType, value); 620 } catch (InstantiationException e) { 621 throw new RuntimeCamelException(e.getCause()); 622 } catch (IllegalAccessException e) { 623 throw new RuntimeCamelException(e); 624 } 625 } 626 627 /** 628 * Returns true if the given name is a valid java identifier 629 */ 630 public static boolean isJavaIdentifier(String name) { 631 if (name == null) { 632 return false; 633 } 634 int size = name.length(); 635 if (size < 1) { 636 return false; 637 } 638 if (Character.isJavaIdentifierStart(name.charAt(0))) { 639 for (int i = 1; i < size; i++) { 640 if (!Character.isJavaIdentifierPart(name.charAt(i))) { 641 return false; 642 } 643 } 644 return true; 645 } 646 return false; 647 } 648 649 /** 650 * Returns the type of the given object or null if the value is null 651 */ 652 public static Object type(Object bean) { 653 return bean != null ? bean.getClass() : null; 654 } 655 656 /** 657 * Evaluate the value as a predicate which attempts to convert the value to 658 * a boolean otherwise true is returned if the value is not null 659 */ 660 public static boolean evaluateValuePredicate(Object value) { 661 if (value instanceof Boolean) { 662 Boolean aBoolean = (Boolean)value; 663 return aBoolean.booleanValue(); 664 } 665 return value != null; 666 } 667 }