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: 739202 $
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 // try context class loader first
482 Class clazz = doLoadClass(name, Thread.currentThread().getContextClassLoader());
483 if (clazz == null) {
484 // then the provided loader
485 clazz = doLoadClass(name, loader);
486 }
487 if (clazz == null) {
488 // and fallback to the loader the loaded the ObjectHelper class
489 clazz = doLoadClass(name, ObjectHelper.class.getClassLoader());
490 }
491
492 if (clazz == null) {
493 LOG.warn("Could not find class: " + name);
494 }
495
496 return clazz;
497 }
498
499 /**
500 * Loads the given class with the provided classloader (may be null).
501 * Will ignore any class not found and return null.
502 *
503 * @param name the name of the class to load
504 * @param loader a provided loader (may be null)
505 * @return the class, or null if it could not be loaded
506 */
507 private static Class<?> doLoadClass(String name, ClassLoader loader) {
508 ObjectHelper.notEmpty(name, "name");
509 if (loader == null) {
510 return null;
511 }
512 try {
513 return loader.loadClass(name);
514 } catch (ClassNotFoundException e) {
515 if (LOG.isTraceEnabled()) {
516 LOG.trace("Can not load class: " + name + " using classloader: " + loader, e);
517 }
518
519 }
520 return null;
521 }
522
523 /**
524 * Attempts to load the given resource as a stream using the thread context class
525 * loader or the class loader used to load this class
526 *
527 * @param name the name of the resource to load
528 * @return the stream or null if it could not be loaded
529 */
530 public static InputStream loadResourceAsStream(String name) {
531 InputStream in = null;
532
533 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
534 if (contextClassLoader != null) {
535 in = contextClassLoader.getResourceAsStream(name);
536 }
537 if (in == null) {
538 in = ObjectHelper.class.getClassLoader().getResourceAsStream(name);
539 }
540
541 return in;
542 }
543
544 /**
545 * A helper method to invoke a method via reflection and wrap any exceptions
546 * as {@link RuntimeCamelException} instances
547 *
548 * @param method the method to invoke
549 * @param instance the object instance (or null for static methods)
550 * @param parameters the parameters to the method
551 * @return the result of the method invocation
552 */
553 public static Object invokeMethod(Method method, Object instance, Object... parameters) {
554 try {
555 return method.invoke(instance, parameters);
556 } catch (IllegalAccessException e) {
557 throw new RuntimeCamelException(e);
558 } catch (InvocationTargetException e) {
559 throw new RuntimeCamelException(e.getCause());
560 }
561 }
562
563 /**
564 * Returns a list of methods which are annotated with the given annotation
565 *
566 * @param type the type to reflect on
567 * @param annotationType the annotation type
568 * @return a list of the methods found
569 */
570 public static List<Method> findMethodsWithAnnotation(Class<?> type,
571 Class<? extends Annotation> annotationType) {
572 return findMethodsWithAnnotation(type, annotationType, false);
573 }
574
575 /**
576 * Returns a list of methods which are annotated with the given annotation
577 *
578 * @param type the type to reflect on
579 * @param annotationType the annotation type
580 * @param checkMetaAnnotations check for meta annotations
581 * @return a list of the methods found
582 */
583 public static List<Method> findMethodsWithAnnotation(Class<?> type,
584 Class<? extends Annotation> annotationType, boolean checkMetaAnnotations) {
585 List<Method> answer = new ArrayList<Method>();
586 do {
587 Method[] methods = type.getDeclaredMethods();
588 for (Method method : methods) {
589 if (hasAnnotation(method, annotationType, checkMetaAnnotations)) {
590 answer.add(method);
591 }
592 }
593 type = type.getSuperclass();
594 } while (type != null);
595 return answer;
596 }
597
598 /**
599 * Checks if a Class or Method are annotated with the given annotation
600 *
601 * @param elem the Class or Method to reflect on
602 * @param annotationType the annotation type
603 * @param checkMetaAnnotations check for meta annotations
604 * @return true if annotations is present
605 */
606 public static boolean hasAnnotation(AnnotatedElement elem,
607 Class<? extends Annotation> annotationType, boolean checkMetaAnnotations) {
608 if (elem.isAnnotationPresent(annotationType)) {
609 return true;
610 }
611 if (checkMetaAnnotations) {
612 for (Annotation a : elem.getAnnotations()) {
613 for (Annotation meta : a.annotationType().getAnnotations()) {
614 if (meta.annotationType().getName().equals(annotationType.getName())) {
615 return true;
616 }
617 }
618 }
619 }
620 return false;
621 }
622
623 /**
624 * Turns the given object arrays into a meaningful string
625 *
626 * @param objects an array of objects or null
627 * @return a meaningful string
628 */
629 public static String asString(Object[] objects) {
630 if (objects == null) {
631 return "null";
632 } else {
633 StringBuffer buffer = new StringBuffer("{");
634 int counter = 0;
635 for (Object object : objects) {
636 if (counter++ > 0) {
637 buffer.append(", ");
638 }
639 String text = (object == null) ? "null" : object.toString();
640 buffer.append(text);
641 }
642 buffer.append("}");
643 return buffer.toString();
644 }
645 }
646
647 /**
648 * Returns true if a class is assignable from another class like the
649 * {@link Class#isAssignableFrom(Class)} method but which also includes
650 * coercion between primitive types to deal with Java 5 primitive type
651 * wrapping
652 */
653 public static boolean isAssignableFrom(Class a, Class b) {
654 a = convertPrimitiveTypeToWrapperType(a);
655 b = convertPrimitiveTypeToWrapperType(b);
656 return a.isAssignableFrom(b);
657 }
658
659 /**
660 * Converts primitive types such as int to its wrapper type like
661 * {@link Integer}
662 */
663 public static Class convertPrimitiveTypeToWrapperType(Class type) {
664 Class rc = type;
665 if (type.isPrimitive()) {
666 if (type == int.class) {
667 rc = Integer.class;
668 } else if (type == long.class) {
669 rc = Long.class;
670 } else if (type == double.class) {
671 rc = Double.class;
672 } else if (type == float.class) {
673 rc = Float.class;
674 } else if (type == short.class) {
675 rc = Short.class;
676 } else if (type == byte.class) {
677 rc = Byte.class;
678 // TODO: Why is boolean disabled
679 /*
680 } else if (type == boolean.class) {
681 rc = Boolean.class;
682 */
683 }
684 }
685 return rc;
686 }
687
688 /**
689 * Helper method to return the default character set name
690 */
691 public static String getDefaultCharacterSet() {
692 return Charset.defaultCharset().name();
693 }
694
695 /**
696 * Returns the Java Bean property name of the given method, if it is a setter
697 */
698 public static String getPropertyName(Method method) {
699 String propertyName = method.getName();
700 if (propertyName.startsWith("set") && method.getParameterTypes().length == 1) {
701 propertyName = propertyName.substring(3, 4).toLowerCase() + propertyName.substring(4);
702 }
703 return propertyName;
704 }
705
706 /**
707 * Returns true if the given collection of annotations matches the given type
708 */
709 public static boolean hasAnnotation(Annotation[] annotations, Class<?> type) {
710 for (Annotation annotation : annotations) {
711 if (type.isInstance(annotation)) {
712 return true;
713 }
714 }
715 return false;
716 }
717
718 /**
719 * Closes the given resource if it is available, logging any closing exceptions to the given log
720 *
721 * @param closeable the object to close
722 * @param name the name of the resource
723 * @param log the log to use when reporting closure warnings
724 */
725 public static void close(Closeable closeable, String name, Log log) {
726 if (closeable != null) {
727 try {
728 closeable.close();
729 } catch (IOException e) {
730 if (log != null) {
731 log.warn("Could not close: " + name + ". Reason: " + e, e);
732 }
733 }
734 }
735 }
736
737 /**
738 * Converts the given value to the required type or throw a meaningful exception
739 */
740 public static <T> T cast(Class<T> toType, Object value) {
741 if (toType == boolean.class) {
742 return (T)cast(Boolean.class, value);
743 } else if (toType.isPrimitive()) {
744 Class newType = convertPrimitiveTypeToWrapperType(toType);
745 if (newType != toType) {
746 return (T)cast(newType, value);
747 }
748 }
749 try {
750 return toType.cast(value);
751 } catch (ClassCastException e) {
752 throw new IllegalArgumentException("Failed to convert: " + value + " to type: "
753 + toType.getName() + " due to: " + e, e);
754 }
755 }
756
757 /**
758 * A helper method to create a new instance of a type using the default constructor arguments.
759 */
760 public static <T> T newInstance(Class<T> type) {
761 try {
762 return type.newInstance();
763 } catch (InstantiationException e) {
764 throw new RuntimeCamelException(e);
765 } catch (IllegalAccessException e) {
766 throw new RuntimeCamelException(e);
767 }
768 }
769
770 /**
771 * A helper method to create a new instance of a type using the default constructor arguments.
772 */
773 public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) {
774 try {
775 Object value = actualType.newInstance();
776 return cast(expectedType, value);
777 } catch (InstantiationException e) {
778 throw new RuntimeCamelException();
779 } catch (IllegalAccessException e) {
780 throw new RuntimeCamelException(e);
781 }
782 }
783
784 /**
785 * Returns true if the given name is a valid java identifier
786 */
787 public static boolean isJavaIdentifier(String name) {
788 if (name == null) {
789 return false;
790 }
791 int size = name.length();
792 if (size < 1) {
793 return false;
794 }
795 if (Character.isJavaIdentifierStart(name.charAt(0))) {
796 for (int i = 1; i < size; i++) {
797 if (!Character.isJavaIdentifierPart(name.charAt(i))) {
798 return false;
799 }
800 }
801 return true;
802 }
803 return false;
804 }
805
806 /**
807 * Returns the type of the given object or null if the value is null
808 */
809 public static Object type(Object bean) {
810 return bean != null ? bean.getClass() : null;
811 }
812
813 /**
814 * Evaluate the value as a predicate which attempts to convert the value to
815 * a boolean otherwise true is returned if the value is not null
816 */
817 public static boolean evaluateValuePredicate(Object value) {
818 if (value instanceof Boolean) {
819 Boolean aBoolean = (Boolean)value;
820 return aBoolean.booleanValue();
821 } else if (value instanceof String) {
822 if ("true".equals(value)) {
823 return true;
824 } else if ("false".equals(value)) {
825 return false;
826 }
827 }
828 return value != null;
829 }
830
831 /**
832 * Wraps the caused exception in a {@link RuntimeCamelException} if its not already such an exception.
833 *
834 * @param e the caused exception
835 * @return the wrapper exception
836 */
837 public static RuntimeCamelException wrapRuntimeCamelException(Throwable e) {
838 if (e instanceof RuntimeCamelException) {
839 // don't double wrap if already a RuntimeCamelException
840 return (RuntimeCamelException) e;
841 } else {
842 return new RuntimeCamelException(e);
843 }
844 }
845
846 }