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