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