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