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