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 */ 017package org.apache.camel.util; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.lang.annotation.Annotation; 022import java.lang.reflect.AnnotatedElement; 023import java.lang.reflect.Constructor; 024import java.lang.reflect.Field; 025import java.lang.reflect.Method; 026import java.net.URL; 027import java.nio.charset.Charset; 028import java.util.ArrayList; 029import java.util.Arrays; 030import java.util.Collection; 031import java.util.Collections; 032import java.util.Enumeration; 033import java.util.Iterator; 034import java.util.List; 035import java.util.Locale; 036import java.util.Map; 037import java.util.Objects; 038import java.util.Optional; 039import java.util.function.Consumer; 040import java.util.function.Supplier; 041 042import org.w3c.dom.Node; 043import org.w3c.dom.NodeList; 044 045import org.slf4j.Logger; 046import org.slf4j.LoggerFactory; 047 048/** 049 * A number of useful helper methods for working with Objects 050 */ 051public final class ObjectHelper { 052 053 private static final Logger LOG = LoggerFactory.getLogger(ObjectHelper.class); 054 055 private static final Float FLOAT_NAN = Float.NaN; 056 private static final Double DOUBLE_NAN = Double.NaN; 057 058 /** 059 * Utility classes should not have a public constructor. 060 */ 061 private ObjectHelper() { 062 } 063 064 /** 065 * A helper method for comparing objects for equality while handling nulls 066 */ 067 public static boolean equal(Object a, Object b) { 068 return equal(a, b, false); 069 } 070 071 /** 072 * A helper method for comparing objects for equality while handling case insensitivity 073 */ 074 public static boolean equalIgnoreCase(Object a, Object b) { 075 return equal(a, b, true); 076 } 077 078 /** 079 * A helper method for comparing objects for equality while handling nulls 080 */ 081 public static boolean equal(final Object a, final Object b, final boolean ignoreCase) { 082 if (a == b) { 083 return true; 084 } 085 086 if (a == null || b == null) { 087 return false; 088 } 089 090 if (ignoreCase) { 091 if (a instanceof String && b instanceof String) { 092 return ((String) a).equalsIgnoreCase((String) b); 093 } 094 } 095 096 if (a.getClass().isArray() && b.getClass().isArray()) { 097 // uses array based equals 098 return Objects.deepEquals(a, b); 099 } else { 100 // use regular equals 101 return a.equals(b); 102 } 103 } 104 105 /** 106 * A helper method for comparing byte arrays for equality while handling nulls 107 */ 108 public static boolean equalByteArray(byte[] a, byte[] b) { 109 return Arrays.equals(a, b); 110 } 111 112 /** 113 * Returns true if the given object is equal to any of the expected value 114 */ 115 public static boolean isEqualToAny(Object object, Object... values) { 116 for (Object value : values) { 117 if (equal(object, value)) { 118 return true; 119 } 120 } 121 return false; 122 } 123 124 public static Boolean toBoolean(Object value) { 125 if (value instanceof Boolean) { 126 return (Boolean) value; 127 } 128 if (value instanceof String) { 129 // we only want to accept true or false as accepted values 130 String str = (String) value; 131 if ("true".equalsIgnoreCase(str) || "false".equalsIgnoreCase(str)) { 132 return Boolean.valueOf(str); 133 } 134 } 135 if (value instanceof Integer) { 136 return (Integer) value > 0 ? Boolean.TRUE : Boolean.FALSE; 137 } 138 return null; 139 } 140 141 /** 142 * Asserts whether the value is <b>not</b> <tt>null</tt> 143 * 144 * @param value the value to test 145 * @param name the key that resolved the value 146 * @return the passed {@code value} as is 147 * @throws IllegalArgumentException is thrown if assertion fails 148 */ 149 public static <T> T notNull(T value, String name) { 150 if (value == null) { 151 throw new IllegalArgumentException(name + " must be specified"); 152 } 153 154 return value; 155 } 156 157 /** 158 * Asserts whether the value is <b>not</b> <tt>null</tt> 159 * 160 * @param value the value to test 161 * @param on additional description to indicate where this problem occurred (appended as 162 * toString()) 163 * @param name the key that resolved the value 164 * @return the passed {@code value} as is 165 * @throws IllegalArgumentException is thrown if assertion fails 166 */ 167 public static <T> T notNull(T value, String name, Object on) { 168 if (on == null) { 169 notNull(value, name); 170 } else if (value == null) { 171 throw new IllegalArgumentException(name + " must be specified on: " + on); 172 } 173 174 return value; 175 } 176 177 /** 178 * Tests whether the value is <tt>null</tt> or an empty string. 179 * 180 * @param value the value, if its a String it will be tested for text length as well 181 * @return true if empty 182 */ 183 public static boolean isEmpty(Object value) { 184 if (value == null) { 185 return true; 186 } else if (value instanceof String) { 187 return ((String) value).trim().isEmpty(); 188 } else if (value instanceof Collection) { 189 return ((Collection<?>) value).isEmpty(); 190 } else if (value instanceof Map) { 191 return ((Map<?, ?>) value).isEmpty(); 192 } else { 193 return false; 194 } 195 } 196 197 /** 198 * Tests whether the value is <b>not</b> <tt>null</tt>, an empty string or an empty collection/map. 199 * 200 * @param value the value, if its a String it will be tested for text length as well 201 * @return true if <b>not</b> empty 202 */ 203 public static boolean isNotEmpty(Object value) { 204 if (value == null) { 205 return false; 206 } else if (value instanceof String) { 207 return !((String) value).trim().isEmpty(); 208 } else if (value instanceof Collection) { 209 return !((Collection<?>) value).isEmpty(); 210 } else if (value instanceof Map) { 211 return !((Map<?, ?>) value).isEmpty(); 212 } else { 213 return true; 214 } 215 } 216 217 /** 218 * Returns the first non null object <tt>null</tt>. 219 * 220 * @param values the values 221 * @return an Optional 222 */ 223 public static Optional<Object> firstNotNull(Object... values) { 224 for (Object value : values) { 225 if (value != null) { 226 return Optional.of(value); 227 } 228 } 229 230 return Optional.empty(); 231 } 232 233 /** 234 * Tests whether the value is <tt>null</tt>, an empty string, an empty collection or a map 235 * 236 * @param value the value, if its a String it will be tested for text length as well 237 * @param supplier the supplier, the supplier to be used to get a value if value is null 238 */ 239 public static <T> T supplyIfEmpty(T value, Supplier<T> supplier) { 240 org.apache.camel.util.ObjectHelper.notNull(supplier, "Supplier"); 241 if (isNotEmpty(value)) { 242 return value; 243 } 244 245 return supplier.get(); 246 } 247 248 /** 249 * Tests whether the value is <b>not</b> <tt>null</tt>, an empty string, an empty collection or a map 250 * 251 * @param value the value, if its a String it will be tested for text length as well 252 * @param consumer the consumer, the operation to be executed against value if not empty 253 */ 254 public static <T> void ifNotEmpty(T value, Consumer<T> consumer) { 255 if (isNotEmpty(value)) { 256 consumer.accept(value); 257 } 258 } 259 260 /** 261 * Returns the predicate matching boolean on a {@link List} result set where if the first element is a boolean its 262 * value is used otherwise this method returns true if the collection is not empty 263 * 264 * @return <tt>true</tt> if the first element is a boolean and its value is true or if the list is non empty 265 */ 266 public static boolean matches(List<?> list) { 267 if (!list.isEmpty()) { 268 Object value = list.get(0); 269 if (value instanceof Boolean) { 270 return (Boolean) value; 271 } else { 272 // lets assume non-empty results are true 273 return true; 274 } 275 } 276 return false; 277 } 278 279 /** 280 * A helper method to access a system property, catching any security exceptions 281 * 282 * @param name the name of the system property required 283 * @param defaultValue the default value to use if the property is not available or a security exception prevents 284 * access 285 * @return the system property value or the default value if the property is not available or security 286 * does not allow its access 287 */ 288 public static String getSystemProperty(String name, String defaultValue) { 289 try { 290 return System.getProperty(name, defaultValue); 291 } catch (Exception e) { 292 if (LOG.isDebugEnabled()) { 293 LOG.debug("Caught security exception accessing system property: " + name + ". Will use default value: " 294 + defaultValue, 295 e); 296 } 297 return defaultValue; 298 } 299 } 300 301 /** 302 * A helper method to access a boolean system property, catching any security exceptions 303 * 304 * @param name the name of the system property required 305 * @param defaultValue the default value to use if the property is not available or a security exception prevents 306 * access 307 * @return the boolean representation of the system property value or the default value if the property 308 * is not available or security does not allow its access 309 */ 310 public static boolean getSystemProperty(String name, Boolean defaultValue) { 311 String result = getSystemProperty(name, defaultValue.toString()); 312 return Boolean.parseBoolean(result); 313 } 314 315 /** 316 * Returns the type name of the given type or null if the type variable is null 317 */ 318 public static String name(Class<?> type) { 319 return type != null ? type.getName() : null; 320 } 321 322 /** 323 * Returns the type name of the given value 324 */ 325 public static String className(Object value) { 326 return name(value != null ? value.getClass() : null); 327 } 328 329 /** 330 * Returns the canonical type name of the given value 331 */ 332 public static String classCanonicalName(Object value) { 333 if (value != null) { 334 return value.getClass().getCanonicalName(); 335 } else { 336 return null; 337 } 338 } 339 340 /** 341 * Attempts to load the given class name using the thread context class loader or the class loader used to load this 342 * class 343 * 344 * @param name the name of the class to load 345 * @return the class or <tt>null</tt> if it could not be loaded 346 */ 347 public static Class<?> loadClass(String name) { 348 return loadClass(name, ObjectHelper.class.getClassLoader()); 349 } 350 351 /** 352 * Attempts to load the given class name using the thread context class loader or the given class loader 353 * 354 * @param name the name of the class to load 355 * @param loader the class loader to use after the thread context class loader 356 * @return the class or <tt>null</tt> if it could not be loaded 357 */ 358 public static Class<?> loadClass(String name, ClassLoader loader) { 359 return loadClass(name, loader, false); 360 } 361 362 /** 363 * Attempts to load the given class name using the thread context class loader or the given class loader 364 * 365 * @param name the name of the class to load 366 * @param loader the class loader to use after the thread context class loader 367 * @param needToWarn when <tt>true</tt> logs a warning when a class with the given name could not be loaded 368 * @return the class or <tt>null</tt> if it could not be loaded 369 */ 370 public static Class<?> loadClass(String name, ClassLoader loader, boolean needToWarn) { 371 // must clean the name so its pure java name, eg removing \n or whatever people can do in the Spring XML 372 name = StringHelper.normalizeClassName(name); 373 if (org.apache.camel.util.ObjectHelper.isEmpty(name)) { 374 return null; 375 } 376 377 // Try simple type first 378 Class<?> clazz = loadSimpleType(name); 379 if (clazz == null) { 380 // try context class loader 381 clazz = doLoadClass(name, Thread.currentThread().getContextClassLoader()); 382 } 383 if (clazz == null) { 384 // then the provided loader 385 clazz = doLoadClass(name, loader); 386 } 387 if (clazz == null) { 388 // and fallback to the loader the loaded the ObjectHelper class 389 clazz = doLoadClass(name, ObjectHelper.class.getClassLoader()); 390 } 391 392 if (clazz == null) { 393 if (needToWarn) { 394 LOG.warn("Cannot find class: {}", name); 395 } else { 396 LOG.debug("Cannot find class: {}", name); 397 } 398 } 399 400 return clazz; 401 } 402 403 /** 404 * Load a simple type 405 * 406 * @param name the name of the class to load 407 * @return the class or <tt>null</tt> if it could not be loaded 408 */ 409 //CHECKSTYLE:OFF 410 public static Class<?> loadSimpleType(String name) { 411 // special for byte[] or Object[] as its common to use 412 if ("java.lang.byte[]".equals(name) || "byte[]".equals(name)) { 413 return byte[].class; 414 } else if ("java.lang.Byte[]".equals(name) || "Byte[]".equals(name)) { 415 return Byte[].class; 416 } else if ("java.lang.Object[]".equals(name) || "Object[]".equals(name)) { 417 return Object[].class; 418 } else if ("java.lang.String[]".equals(name) || "String[]".equals(name)) { 419 return String[].class; 420 // and these is common as well 421 } else if ("java.lang.String".equals(name) || "String".equals(name)) { 422 return String.class; 423 } else if ("java.lang.Boolean".equals(name) || "Boolean".equals(name)) { 424 return Boolean.class; 425 } else if ("boolean".equals(name)) { 426 return boolean.class; 427 } else if ("java.lang.Integer".equals(name) || "Integer".equals(name)) { 428 return Integer.class; 429 } else if ("int".equals(name)) { 430 return int.class; 431 } else if ("java.lang.Long".equals(name) || "Long".equals(name)) { 432 return Long.class; 433 } else if ("long".equals(name)) { 434 return long.class; 435 } else if ("java.lang.Short".equals(name) || "Short".equals(name)) { 436 return Short.class; 437 } else if ("short".equals(name)) { 438 return short.class; 439 } else if ("java.lang.Byte".equals(name) || "Byte".equals(name)) { 440 return Byte.class; 441 } else if ("byte".equals(name)) { 442 return byte.class; 443 } else if ("java.lang.Float".equals(name) || "Float".equals(name)) { 444 return Float.class; 445 } else if ("float".equals(name)) { 446 return float.class; 447 } else if ("java.lang.Double".equals(name) || "Double".equals(name)) { 448 return Double.class; 449 } else if ("double".equals(name)) { 450 return double.class; 451 } else if ("java.lang.Character".equals(name) || "Character".equals(name)) { 452 return Character.class; 453 } else if ("char".equals(name)) { 454 return char.class; 455 } 456 return null; 457 } 458 //CHECKSTYLE:ON 459 460 /** 461 * Loads the given class with the provided classloader (may be null). Will ignore any class not found and return 462 * null. 463 * 464 * @param name the name of the class to load 465 * @param loader a provided loader (may be null) 466 * @return the class, or null if it could not be loaded 467 */ 468 private static Class<?> doLoadClass(String name, ClassLoader loader) { 469 StringHelper.notEmpty(name, "name"); 470 if (loader == null) { 471 return null; 472 } 473 474 try { 475 LOG.trace("Loading class: {} using classloader: {}", name, loader); 476 return loader.loadClass(name); 477 } catch (ClassNotFoundException e) { 478 if (LOG.isTraceEnabled()) { 479 LOG.trace("Cannot load class: " + name + " using classloader: " + loader, e); 480 } 481 } 482 483 return null; 484 } 485 486 /** 487 * Attempts to load the given resource as a stream using the thread context class loader or the class loader used to 488 * load this class 489 * 490 * @param name the name of the resource to load 491 * @return the stream or null if it could not be loaded 492 */ 493 public static InputStream loadResourceAsStream(String name) { 494 return loadResourceAsStream(name, null); 495 } 496 497 /** 498 * Attempts to load the given resource as a stream using first the given class loader, then the thread context class 499 * loader and finally the class loader used to load this class 500 * 501 * @param name the name of the resource to load 502 * @param loader optional classloader to attempt first 503 * @return the stream or null if it could not be loaded 504 */ 505 public static InputStream loadResourceAsStream(String name, ClassLoader loader) { 506 try { 507 URL res = loadResourceAsURL(name, loader); 508 return res != null ? res.openStream() : null; 509 } catch (IOException e) { 510 return null; 511 } 512 } 513 514 /** 515 * Attempts to load the given resource as a stream using the thread context class loader or the class loader used to 516 * load this class 517 * 518 * @param name the name of the resource to load 519 * @return the stream or null if it could not be loaded 520 */ 521 public static URL loadResourceAsURL(String name) { 522 return loadResourceAsURL(name, null); 523 } 524 525 /** 526 * Attempts to load the given resource as a stream using the thread context class loader or the class loader used to 527 * load this class 528 * 529 * @param name the name of the resource to load 530 * @param loader optional classloader to attempt first 531 * @return the stream or null if it could not be loaded 532 */ 533 public static URL loadResourceAsURL(String name, ClassLoader loader) { 534 535 URL url = null; 536 String resolvedName = resolveUriPath(name); 537 538 // #1 First, try the given class loader 539 540 if (loader != null) { 541 url = loader.getResource(resolvedName); 542 if (url != null) { 543 return url; 544 } 545 } 546 547 // #2 Next, is the TCCL 548 549 ClassLoader tccl = Thread.currentThread().getContextClassLoader(); 550 if (tccl != null) { 551 552 url = tccl.getResource(resolvedName); 553 if (url != null) { 554 return url; 555 } 556 557 // #3 The TCCL may be able to see camel-core, but not META-INF resources 558 559 try { 560 561 Class<?> clazz = tccl.loadClass("org.apache.camel.impl.DefaultCamelContext"); 562 url = clazz.getClassLoader().getResource(resolvedName); 563 if (url != null) { 564 return url; 565 } 566 567 } catch (ClassNotFoundException e) { 568 // ignore 569 } 570 } 571 572 // #4 Last, for the unlikely case that stuff can be loaded from camel-util 573 574 url = ObjectHelper.class.getClassLoader().getResource(resolvedName); 575 if (url != null) { 576 return url; 577 } 578 579 url = ObjectHelper.class.getResource(resolvedName); 580 return url; 581 } 582 583 /** 584 * Attempts to load the given resources from the given package name using the thread context class loader or the 585 * class loader used to load this class 586 * 587 * @param uri the name of the package to load its resources 588 * @return the URLs for the resources or null if it could not be loaded 589 */ 590 public static Enumeration<URL> loadResourcesAsURL(String uri) { 591 return loadResourcesAsURL(uri, null); 592 } 593 594 /** 595 * Attempts to load the given resources from the given package name using the thread context class loader or the 596 * class loader used to load this class 597 * 598 * @param uri the name of the package to load its resources 599 * @param loader optional classloader to attempt first 600 * @return the URLs for the resources or null if it could not be loaded 601 */ 602 public static Enumeration<URL> loadResourcesAsURL(String uri, ClassLoader loader) { 603 604 Enumeration<URL> res = null; 605 606 // #1 First, try the given class loader 607 608 if (loader != null) { 609 try { 610 res = loader.getResources(uri); 611 if (res != null) { 612 return res; 613 } 614 } catch (IOException e) { 615 // ignore 616 } 617 } 618 619 // #2 Next, is the TCCL 620 621 ClassLoader tccl = Thread.currentThread().getContextClassLoader(); 622 if (tccl != null) { 623 624 try { 625 res = tccl.getResources(uri); 626 if (res != null) { 627 return res; 628 } 629 } catch (IOException e1) { 630 // ignore 631 } 632 633 // #3 The TCCL may be able to see camel-core, but not META-INF resources 634 635 try { 636 637 Class<?> clazz = tccl.loadClass("org.apache.camel.impl.DefaultCamelContext"); 638 res = clazz.getClassLoader().getResources(uri); 639 if (res != null) { 640 return res; 641 } 642 643 } catch (ClassNotFoundException | IOException e) { 644 // ignore 645 } 646 } 647 648 // #4 Last, for the unlikely case that stuff can be loaded from camel-util 649 650 try { 651 res = ObjectHelper.class.getClassLoader().getResources(uri); 652 } catch (IOException e) { 653 // ignore 654 } 655 656 return res; 657 } 658 659 /** 660 * Helper operation used to remove relative path notation from resources. Most critical for resources on the 661 * Classpath as resource loaders will not resolve the relative paths correctly. 662 * 663 * @param name the name of the resource to load 664 * @return the modified or unmodified string if there were no changes 665 */ 666 private static String resolveUriPath(String name) { 667 // compact the path and use / as separator as that's used for loading resources on the classpath 668 return FileUtil.compactPath(name, '/'); 669 } 670 671 /** 672 * Tests whether the target method overrides the source method. 673 * <p/> 674 * Tests whether they have the same name, return type, and parameter list. 675 * 676 * @param source the source method 677 * @param target the target method 678 * @return <tt>true</tt> if it override, <tt>false</tt> otherwise 679 */ 680 public static boolean isOverridingMethod(Method source, Method target) { 681 return isOverridingMethod(source, target, true); 682 } 683 684 /** 685 * Tests whether the target method overrides the source method. 686 * <p/> 687 * Tests whether they have the same name, return type, and parameter list. 688 * 689 * @param source the source method 690 * @param target the target method 691 * @param exact <tt>true</tt> if the override must be exact same types, <tt>false</tt> if the types should be 692 * assignable 693 * @return <tt>true</tt> if it override, <tt>false</tt> otherwise 694 */ 695 public static boolean isOverridingMethod(Method source, Method target, boolean exact) { 696 return isOverridingMethod(target.getDeclaringClass(), source, target, exact); 697 } 698 699 /** 700 * Tests whether the target method overrides the source method from the inheriting class. 701 * <p/> 702 * Tests whether they have the same name, return type, and parameter list. 703 * 704 * @param inheritingClass the class inheriting the target method overriding the source method 705 * @param source the source method 706 * @param target the target method 707 * @param exact <tt>true</tt> if the override must be exact same types, <tt>false</tt> if the types 708 * should be assignable 709 * @return <tt>true</tt> if it override, <tt>false</tt> otherwise 710 */ 711 public static boolean isOverridingMethod(Class<?> inheritingClass, Method source, Method target, boolean exact) { 712 713 if (source.equals(target)) { 714 return true; 715 } else if (target.getDeclaringClass().isAssignableFrom(source.getDeclaringClass())) { 716 return false; 717 } else if (!source.getDeclaringClass().isAssignableFrom(inheritingClass) 718 || !target.getDeclaringClass().isAssignableFrom(inheritingClass)) { 719 return false; 720 } 721 722 if (!source.getName().equals(target.getName())) { 723 return false; 724 } 725 726 if (exact) { 727 if (!source.getReturnType().equals(target.getReturnType())) { 728 return false; 729 } 730 } else { 731 if (!source.getReturnType().isAssignableFrom(target.getReturnType())) { 732 boolean b1 = source.isBridge(); 733 boolean b2 = target.isBridge(); 734 // must not be bridge methods 735 if (!b1 && !b2) { 736 return false; 737 } 738 } 739 } 740 741 // must have same number of parameter types 742 if (source.getParameterCount() != target.getParameterCount()) { 743 return false; 744 } 745 746 Class<?>[] sourceTypes = source.getParameterTypes(); 747 Class<?>[] targetTypes = target.getParameterTypes(); 748 // test if parameter types is the same as well 749 for (int i = 0; i < source.getParameterCount(); i++) { 750 if (exact) { 751 if (!(sourceTypes[i].equals(targetTypes[i]))) { 752 return false; 753 } 754 } else { 755 if (!(sourceTypes[i].isAssignableFrom(targetTypes[i]))) { 756 boolean b1 = source.isBridge(); 757 boolean b2 = target.isBridge(); 758 // must not be bridge methods 759 if (!b1 && !b2) { 760 return false; 761 } 762 } 763 } 764 } 765 766 // the have same name, return type and parameter list, so its overriding 767 return true; 768 } 769 770 /** 771 * Returns a list of methods which are annotated with the given annotation 772 * 773 * @param type the type to reflect on 774 * @param annotationType the annotation type 775 * @return a list of the methods found 776 */ 777 public static List<Method> findMethodsWithAnnotation( 778 Class<?> type, 779 Class<? extends Annotation> annotationType) { 780 return findMethodsWithAnnotation(type, annotationType, false); 781 } 782 783 /** 784 * Returns a list of methods which are annotated with the given annotation 785 * 786 * @param type the type to reflect on 787 * @param annotationType the annotation type 788 * @param checkMetaAnnotations check for meta annotations 789 * @return a list of the methods found 790 */ 791 public static List<Method> findMethodsWithAnnotation( 792 Class<?> type, 793 Class<? extends Annotation> annotationType, 794 boolean checkMetaAnnotations) { 795 List<Method> answer = new ArrayList<>(); 796 do { 797 Method[] methods = type.getDeclaredMethods(); 798 for (Method method : methods) { 799 if (hasAnnotation(method, annotationType, checkMetaAnnotations)) { 800 answer.add(method); 801 } 802 } 803 type = type.getSuperclass(); 804 } while (type != null); 805 return answer; 806 } 807 808 /** 809 * Checks if a Class or Method are annotated with the given annotation 810 * 811 * @param elem the Class or Method to reflect on 812 * @param annotationType the annotation type 813 * @param checkMetaAnnotations check for meta annotations 814 * @return true if annotations is present 815 */ 816 public static boolean hasAnnotation( 817 AnnotatedElement elem, Class<? extends Annotation> annotationType, 818 boolean checkMetaAnnotations) { 819 if (elem.isAnnotationPresent(annotationType)) { 820 return true; 821 } 822 if (checkMetaAnnotations) { 823 for (Annotation a : elem.getAnnotations()) { 824 for (Annotation meta : a.annotationType().getAnnotations()) { 825 if (meta.annotationType().getName().equals(annotationType.getName())) { 826 return true; 827 } 828 } 829 } 830 } 831 return false; 832 } 833 834 /** 835 * Turns the given object arrays into a meaningful string 836 * 837 * @param objects an array of objects or null 838 * @return a meaningful string 839 */ 840 public static String asString(Object[] objects) { 841 if (objects == null) { 842 return "null"; 843 } else { 844 StringBuilder buffer = new StringBuilder("{"); 845 int counter = 0; 846 for (Object object : objects) { 847 if (counter++ > 0) { 848 buffer.append(", "); 849 } 850 String text = (object == null) ? "null" : object.toString(); 851 buffer.append(text); 852 } 853 buffer.append("}"); 854 return buffer.toString(); 855 } 856 } 857 858 /** 859 * Returns true if a class is assignable from another class like the {@link Class#isAssignableFrom(Class)} method 860 * but which also includes coercion between primitive types to deal with Java 5 primitive type wrapping 861 */ 862 public static boolean isAssignableFrom(Class<?> a, Class<?> b) { 863 a = convertPrimitiveTypeToWrapperType(a); 864 b = convertPrimitiveTypeToWrapperType(b); 865 return a.isAssignableFrom(b); 866 } 867 868 /** 869 * Returns if the given {@code clazz} type is a Java primitive array type. 870 * 871 * @param clazz the Java type to be checked 872 * @return {@code true} if the given type is a Java primitive array type 873 */ 874 public static boolean isPrimitiveArrayType(Class<?> clazz) { 875 if (clazz != null && clazz.isArray()) { 876 return clazz.getComponentType().isPrimitive(); 877 } 878 return false; 879 } 880 881 public static int arrayLength(Object[] pojo) { 882 return pojo.length; 883 } 884 885 /** 886 * Converts primitive types such as int to its wrapper type like {@link Integer} 887 */ 888 public static Class<?> convertPrimitiveTypeToWrapperType(Class<?> type) { 889 Class<?> rc = type; 890 if (type.isPrimitive()) { 891 if (type == int.class) { 892 rc = Integer.class; 893 } else if (type == long.class) { 894 rc = Long.class; 895 } else if (type == double.class) { 896 rc = Double.class; 897 } else if (type == float.class) { 898 rc = Float.class; 899 } else if (type == short.class) { 900 rc = Short.class; 901 } else if (type == byte.class) { 902 rc = Byte.class; 903 } else if (type == boolean.class) { 904 rc = Boolean.class; 905 } else if (type == char.class) { 906 rc = Character.class; 907 } 908 } 909 return rc; 910 } 911 912 /** 913 * Helper method to return the default character set name 914 */ 915 public static String getDefaultCharacterSet() { 916 return Charset.defaultCharset().name(); 917 } 918 919 /** 920 * Returns the Java Bean property name of the given method, if it is a setter 921 */ 922 public static String getPropertyName(Method method) { 923 String propertyName = method.getName(); 924 if (propertyName.startsWith("set") && method.getParameterCount() == 1) { 925 propertyName = propertyName.substring(3, 4).toLowerCase(Locale.ENGLISH) + propertyName.substring(4); 926 } 927 return propertyName; 928 } 929 930 /** 931 * Returns true if the given collection of annotations matches the given type 932 */ 933 public static boolean hasAnnotation(Annotation[] annotations, Class<?> type) { 934 for (Annotation annotation : annotations) { 935 if (type.isInstance(annotation)) { 936 return true; 937 } 938 } 939 return false; 940 } 941 942 /** 943 * Gets the annotation from the given instance. 944 * 945 * @param instance the instance 946 * @param type the annotation 947 * @return the annotation, or <tt>null</tt> if the instance does not have the given annotation 948 */ 949 public static <A extends java.lang.annotation.Annotation> A getAnnotation(Object instance, Class<A> type) { 950 return instance.getClass().getAnnotation(type); 951 } 952 953 /** 954 * Converts the given value to the required type or throw a meaningful exception 955 */ 956 @SuppressWarnings("unchecked") 957 public static <T> T cast(Class<T> toType, Object value) { 958 if (toType == boolean.class) { 959 return (T) cast(Boolean.class, value); 960 } else if (toType.isPrimitive()) { 961 Class<?> newType = convertPrimitiveTypeToWrapperType(toType); 962 if (newType != toType) { 963 return (T) cast(newType, value); 964 } 965 } 966 try { 967 return toType.cast(value); 968 } catch (ClassCastException e) { 969 throw new IllegalArgumentException( 970 "Failed to convert: " 971 + value + " to type: " + toType.getName() + " due to: " + e, 972 e); 973 } 974 } 975 976 /** 977 * Does the given class have a default public no-arg constructor. 978 */ 979 public static boolean hasDefaultPublicNoArgConstructor(Class<?> type) { 980 // getConstructors() returns only public constructors 981 for (Constructor<?> ctr : type.getConstructors()) { 982 if (ctr.getParameterCount() == 0) { 983 return true; 984 } 985 } 986 return false; 987 } 988 989 /** 990 * Returns the type of the given object or null if the value is null 991 */ 992 public static Object type(Object bean) { 993 return bean != null ? bean.getClass() : null; 994 } 995 996 /** 997 * Evaluate the value as a predicate which attempts to convert the value to a boolean otherwise true is returned if 998 * the value is not null 999 */ 1000 public static boolean evaluateValuePredicate(Object value) { 1001 if (value instanceof Boolean) { 1002 return (Boolean) value; 1003 } else if (value instanceof String) { 1004 if ("true".equalsIgnoreCase((String) value)) { 1005 return true; 1006 } else if ("false".equalsIgnoreCase((String) value)) { 1007 return false; 1008 } 1009 } else if (value instanceof NodeList) { 1010 // is it an empty dom with empty attributes 1011 if (value instanceof Node && ((Node) value).hasAttributes()) { 1012 return true; 1013 } 1014 NodeList list = (NodeList) value; 1015 return list.getLength() > 0; 1016 } else if (value instanceof Collection) { 1017 // is it an empty collection 1018 return !((Collection<?>) value).isEmpty(); 1019 } 1020 return value != null; 1021 } 1022 1023 /** 1024 * Creates an Iterable to walk the exception from the bottom up (the last caused by going upwards to the root 1025 * exception). 1026 * 1027 * @see java.lang.Iterable 1028 * @param exception the exception 1029 * @return the Iterable 1030 */ 1031 public static Iterable<Throwable> createExceptionIterable(Throwable exception) { 1032 List<Throwable> throwables = new ArrayList<>(); 1033 1034 Throwable current = exception; 1035 // spool to the bottom of the caused by tree 1036 while (current != null) { 1037 throwables.add(current); 1038 current = current.getCause(); 1039 } 1040 Collections.reverse(throwables); 1041 1042 return throwables; 1043 } 1044 1045 /** 1046 * Creates an Iterator to walk the exception from the bottom up (the last caused by going upwards to the root 1047 * exception). 1048 * 1049 * @see Iterator 1050 * @param exception the exception 1051 * @return the Iterator 1052 */ 1053 public static Iterator<Throwable> createExceptionIterator(Throwable exception) { 1054 return createExceptionIterable(exception).iterator(); 1055 } 1056 1057 /** 1058 * Retrieves the given exception type from the exception. 1059 * <p/> 1060 * Is used to get the caused exception that typically have been wrapped in some sort of Camel wrapper exception 1061 * <p/> 1062 * The strategy is to look in the exception hierarchy to find the first given cause that matches the type. Will 1063 * start from the bottom (the real cause) and walk upwards. 1064 * 1065 * @param type the exception type wanted to retrieve 1066 * @param exception the caused exception 1067 * @return the exception found (or <tt>null</tt> if not found in the exception hierarchy) 1068 */ 1069 public static <T> T getException(Class<T> type, Throwable exception) { 1070 if (exception == null) { 1071 return null; 1072 } 1073 1074 //check the suppressed exception first 1075 for (Throwable throwable : exception.getSuppressed()) { 1076 if (type.isInstance(throwable)) { 1077 return type.cast(throwable); 1078 } 1079 } 1080 1081 // walk the hierarchy and look for it 1082 for (final Throwable throwable : createExceptionIterable(exception)) { 1083 if (type.isInstance(throwable)) { 1084 return type.cast(throwable); 1085 } 1086 } 1087 1088 // not found 1089 return null; 1090 } 1091 1092 public static String getIdentityHashCode(Object object) { 1093 return "0x" + Integer.toHexString(System.identityHashCode(object)); 1094 } 1095 1096 /** 1097 * Lookup the constant field on the given class with the given name 1098 * 1099 * @param clazz the class 1100 * @param name the name of the field to lookup 1101 * @return the value of the constant field, or <tt>null</tt> if not found 1102 */ 1103 public static String lookupConstantFieldValue(Class<?> clazz, String name) { 1104 if (clazz == null) { 1105 return null; 1106 } 1107 1108 // remove leading dots 1109 if (name.startsWith(",")) { 1110 name = name.substring(1); 1111 } 1112 1113 for (Field field : clazz.getFields()) { 1114 if (field.getName().equals(name)) { 1115 try { 1116 Object v = field.get(null); 1117 return v.toString(); 1118 } catch (IllegalAccessException e) { 1119 // ignore 1120 return null; 1121 } 1122 } 1123 } 1124 1125 return null; 1126 } 1127 1128 /** 1129 * Is the given value a numeric NaN type 1130 * 1131 * @param value the value 1132 * @return <tt>true</tt> if its a {@link Float#NaN} or {@link Double#NaN}. 1133 */ 1134 public static boolean isNaN(Object value) { 1135 return (value instanceof Number) 1136 && (FLOAT_NAN.equals(value) || DOUBLE_NAN.equals(value)); 1137 } 1138 1139 /** 1140 * Wraps the caused exception in a {@link RuntimeException} if its not already such an exception. 1141 * 1142 * @param e the caused exception 1143 * @return the wrapper exception 1144 * @deprecated Use {@link org.apache.camel.RuntimeCamelException#wrapRuntimeCamelException} instead 1145 */ 1146 @Deprecated 1147 public static RuntimeException wrapRuntimeCamelException(Throwable e) { 1148 try { 1149 Class<? extends RuntimeException> clazz = (Class) Class.forName("org.apache.camel.RuntimeException"); 1150 if (clazz.isInstance(e)) { 1151 // don't double wrap 1152 return clazz.cast(e); 1153 } else { 1154 return clazz.getConstructor(Throwable.class).newInstance(e); 1155 } 1156 } catch (Throwable t) { 1157 // ignore 1158 } 1159 if (e instanceof RuntimeException) { 1160 // don't double wrap 1161 return (RuntimeException) e; 1162 } else { 1163 return new RuntimeException(e); 1164 } 1165 } 1166 1167 /** 1168 * Turns the input array to a list of objects. 1169 * 1170 * @param objects an array of objects or null 1171 * @return an object list 1172 */ 1173 public static List<Object> asList(Object[] objects) { 1174 return objects != null ? Arrays.asList(objects) : Collections.emptyList(); 1175 } 1176 1177}