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