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