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