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: 46148 $
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 comparison 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 * A helper method to access a boolean system property, catching any security
326 * exceptions
327 *
328 * @param name the name of the system property required
329 * @param defaultValue the default value to use if the property is not
330 * available or a security exception prevents access
331 * @return the boolean representation of the system property value
332 * or the default value if the property is not available or
333 * security does not allow its access
334 */
335 public static boolean getSystemProperty(String name, Boolean defaultValue) {
336 String result = getSystemProperty(name, defaultValue.toString());
337 return Boolean.parseBoolean(result);
338 }
339
340 /**
341 * Returns the type name of the given type or null if the type variable is
342 * null
343 */
344 public static String name(Class type) {
345 return type != null ? type.getName() : null;
346 }
347
348 /**
349 * Returns the type name of the given value
350 */
351 public static String className(Object value) {
352 return name(value != null ? value.getClass() : null);
353 }
354
355 /**
356 * Returns the canonical type name of the given value
357 */
358 public static String classCanonicalName(Object value) {
359 if (value != null) {
360 return value.getClass().getCanonicalName();
361 } else {
362 return null;
363 }
364 }
365
366 /**
367 * Attempts to load the given class name using the thread context class
368 * loader or the class loader used to load this class
369 *
370 * @param name the name of the class to load
371 * @return the class or null if it could not be loaded
372 */
373 public static Class<?> loadClass(String name) {
374 return loadClass(name, ObjectHelper.class.getClassLoader());
375 }
376
377 /**
378 * Attempts to load the given class name using the thread context class
379 * loader or the given class loader
380 *
381 * @param name the name of the class to load
382 * @param loader the class loader to use after the thread context class
383 * loader
384 * @return the class or null if it could not be loaded
385 */
386 public static Class<?> loadClass(String name, ClassLoader loader) {
387 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
388 if (contextClassLoader != null) {
389 try {
390 return contextClassLoader.loadClass(name);
391 } catch (ClassNotFoundException e) {
392 try {
393 return loader.loadClass(name);
394 } catch (ClassNotFoundException e1) {
395 LOG.debug("Could not find class: " + name + ". Reason: " + e);
396 }
397 }
398 }
399 return null;
400 }
401
402 /**
403 * Attempts to load the given resource as a stream using the thread context class
404 * loader or the class loader used to load this class
405 *
406 * @param name the name of the resource to load
407 * @return the stream or null if it could not be loaded
408 */
409 public static InputStream loadResourceAsStream(String name) {
410 InputStream in = null;
411
412 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
413 if (contextClassLoader != null) {
414 in = contextClassLoader.getResourceAsStream(name);
415 }
416 if (in == null) {
417 in = ObjectHelper.class.getClassLoader().getResourceAsStream(name);
418 }
419
420 return in;
421 }
422
423 /**
424 * A helper method to invoke a method via reflection and wrap any exceptions
425 * as {@link RuntimeCamelException} instances
426 *
427 * @param method the method to invoke
428 * @param instance the object instance (or null for static methods)
429 * @param parameters the parameters to the method
430 * @return the result of the method invocation
431 */
432 public static Object invokeMethod(Method method, Object instance, Object... parameters) {
433 try {
434 return method.invoke(instance, parameters);
435 } catch (IllegalAccessException e) {
436 throw new RuntimeCamelException(e);
437 } catch (InvocationTargetException e) {
438 throw new RuntimeCamelException(e.getCause());
439 }
440 }
441
442 /**
443 * Returns a list of methods which are annotated with the given annotation
444 *
445 * @param type the type to reflect on
446 * @param annotationType the annotation type
447 * @return a list of the methods found
448 */
449 public static List<Method> findMethodsWithAnnotation(Class<?> type,
450 Class<? extends Annotation> annotationType) {
451 List<Method> answer = new ArrayList<Method>();
452 do {
453 Method[] methods = type.getDeclaredMethods();
454 for (Method method : methods) {
455 if (method.getAnnotation(annotationType) != null) {
456 answer.add(method);
457 }
458 }
459 type = type.getSuperclass();
460 } while (type != null);
461 return answer;
462 }
463
464 /**
465 * Turns the given object arrays into a meaningful string
466 *
467 * @param objects an array of objects or null
468 * @return a meaningful string
469 */
470 public static String asString(Object[] objects) {
471 if (objects == null) {
472 return "null";
473 } else {
474 StringBuffer buffer = new StringBuffer("{");
475 int counter = 0;
476 for (Object object : objects) {
477 if (counter++ > 0) {
478 buffer.append(", ");
479 }
480 String text = (object == null) ? "null" : object.toString();
481 buffer.append(text);
482 }
483 buffer.append("}");
484 return buffer.toString();
485 }
486 }
487
488 /**
489 * Returns true if a class is assignable from another class like the
490 * {@link Class#isAssignableFrom(Class)} method but which also includes
491 * coercion between primitive types to deal with Java 5 primitive type
492 * wrapping
493 */
494 public static boolean isAssignableFrom(Class a, Class b) {
495 a = convertPrimitiveTypeToWrapperType(a);
496 b = convertPrimitiveTypeToWrapperType(b);
497 return a.isAssignableFrom(b);
498 }
499
500 /**
501 * Converts primitive types such as int to its wrapper type like
502 * {@link Integer}
503 */
504 public static Class convertPrimitiveTypeToWrapperType(Class type) {
505 Class rc = type;
506 if (type.isPrimitive()) {
507 if (type == int.class) {
508 rc = Integer.class;
509 } else if (type == long.class) {
510 rc = Long.class;
511 } else if (type == double.class) {
512 rc = Double.class;
513 } else if (type == float.class) {
514 rc = Float.class;
515 } else if (type == short.class) {
516 rc = Short.class;
517 } else if (type == byte.class) {
518 rc = Byte.class;
519 // TODO: Why is boolean disabled
520 /*
521 } else if (type == boolean.class) {
522 rc = Boolean.class;
523 */
524 }
525 }
526 return rc;
527 }
528
529 /**
530 * Helper method to return the default character set name
531 */
532 public static String getDefaultCharacterSet() {
533 return Charset.defaultCharset().name();
534 }
535
536 /**
537 * Returns the Java Bean property name of the given method, if it is a setter
538 */
539 public static String getPropertyName(Method method) {
540 String propertyName = method.getName();
541 if (propertyName.startsWith("set") && method.getParameterTypes().length == 1) {
542 propertyName = propertyName.substring(3, 4).toLowerCase() + propertyName.substring(4);
543 }
544 return propertyName;
545 }
546
547 /**
548 * Returns true if the given collection of annotations matches the given type
549 */
550 public static boolean hasAnnotation(Annotation[] annotations, Class<?> type) {
551 for (Annotation annotation : annotations) {
552 if (type.isInstance(annotation)) {
553 return true;
554 }
555 }
556 return false;
557 }
558
559 /**
560 * Closes the given resource if it is available, logging any closing exceptions to the given log
561 *
562 * @param closeable the object to close
563 * @param name the name of the resource
564 * @param log the log to use when reporting closure warnings
565 */
566 public static void close(Closeable closeable, String name, Log log) {
567 if (closeable != null) {
568 try {
569 closeable.close();
570 } catch (IOException e) {
571 if (log != null) {
572 log.warn("Could not close: " + name + ". Reason: " + e, e);
573 }
574 }
575 }
576 }
577
578 /**
579 * Converts the given value to the required type or throw a meaningful exception
580 */
581 public static <T> T cast(Class<T> toType, Object value) {
582 if (toType == boolean.class) {
583 return (T)cast(Boolean.class, value);
584 } else if (toType.isPrimitive()) {
585 Class newType = convertPrimitiveTypeToWrapperType(toType);
586 if (newType != toType) {
587 return (T)cast(newType, value);
588 }
589 }
590 try {
591 return toType.cast(value);
592 } catch (ClassCastException e) {
593 throw new IllegalArgumentException("Failed to convert: " + value + " to type: "
594 + toType.getName() + " due to: " + e, e);
595 }
596 }
597
598 /**
599 * A helper method to create a new instance of a type using the default constructor arguments.
600 */
601 public static <T> T newInstance(Class<T> type) {
602 try {
603 return type.newInstance();
604 } catch (InstantiationException e) {
605 throw new RuntimeCamelException(e.getCause());
606 } catch (IllegalAccessException e) {
607 throw new RuntimeCamelException(e);
608 }
609 }
610
611 /**
612 * A helper method to create a new instance of a type using the default constructor arguments.
613 */
614 public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) {
615 try {
616 Object value = actualType.newInstance();
617 return cast(expectedType, value);
618 } catch (InstantiationException e) {
619 throw new RuntimeCamelException(e.getCause());
620 } catch (IllegalAccessException e) {
621 throw new RuntimeCamelException(e);
622 }
623 }
624
625 /**
626 * Returns true if the given name is a valid java identifier
627 */
628 public static boolean isJavaIdentifier(String name) {
629 if (name == null) {
630 return false;
631 }
632 int size = name.length();
633 if (size < 1) {
634 return false;
635 }
636 if (Character.isJavaIdentifierStart(name.charAt(0))) {
637 for (int i = 1; i < size; i++) {
638 if (!Character.isJavaIdentifierPart(name.charAt(i))) {
639 return false;
640 }
641 }
642 return true;
643 }
644 return false;
645 }
646
647 /**
648 * Returns the type of the given object or null if the value is null
649 */
650 public static Object type(Object bean) {
651 return bean != null ? bean.getClass() : null;
652 }
653
654 /**
655 * Evaluate the value as a predicate which attempts to convert the value to
656 * a boolean otherwise true is returned if the value is not null
657 */
658 public static boolean evaluateValuePredicate(Object value) {
659 if (value instanceof Boolean) {
660 Boolean aBoolean = (Boolean)value;
661 return aBoolean.booleanValue();
662 }
663 return value != null;
664 }
665 }