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: 41272 $ 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 if (text == null) { 175 return null; 176 } 177 int length = text.length(); 178 if (length == 0) { 179 return text; 180 } 181 String answer = text.substring(0, 1).toUpperCase(); 182 if (length > 1) { 183 answer += text.substring(1, length); 184 } 185 return answer; 186 } 187 188 189 /** 190 * Returns true if the collection contains the specified value 191 */ 192 public static boolean contains(Object collectionOrArray, Object value) { 193 if (collectionOrArray instanceof Collection) { 194 Collection collection = (Collection)collectionOrArray; 195 return collection.contains(value); 196 } else if (collectionOrArray instanceof String && value instanceof String) { 197 String str = (String) collectionOrArray; 198 String subStr = (String) value; 199 return str.contains(subStr); 200 } else { 201 Iterator iter = ObjectConverter.iterator(collectionOrArray); 202 while (iter.hasNext()) { 203 if (equal(value, iter.next())) { 204 return true; 205 } 206 } 207 return false; 208 } 209 } 210 211 /** 212 * Returns the predicate matching boolean on a {@link List} result set where 213 * if the first element is a boolean its value is used otherwise this method 214 * returns true if the collection is not empty 215 * 216 * @return <tt>true</tt> if the first element is a boolean and its value is true or 217 * if the list is non empty 218 */ 219 public static boolean matches(List list) { 220 if (!list.isEmpty()) { 221 Object value = list.get(0); 222 if (value instanceof Boolean) { 223 Boolean flag = (Boolean)value; 224 return flag.booleanValue(); 225 } else { 226 // lets assume non-empty results are true 227 return true; 228 } 229 } 230 return false; 231 } 232 233 public static boolean isNotNullAndNonEmpty(String text) { 234 return text != null && text.trim().length() > 0; 235 } 236 237 public static boolean isNullOrBlank(String text) { 238 return text == null || text.trim().length() <= 0; 239 } 240 241 /** 242 * A helper method to access a system property, catching any security 243 * exceptions 244 * 245 * @param name the name of the system property required 246 * @param defaultValue the default value to use if the property is not 247 * available or a security exception prevents access 248 * @return the system property value or the default value if the property is 249 * not available or security does not allow its access 250 */ 251 public static String getSystemProperty(String name, String defaultValue) { 252 try { 253 return System.getProperty(name, defaultValue); 254 } catch (Exception e) { 255 if (LOG.isDebugEnabled()) { 256 LOG.debug("Caught security exception accessing system property: " + name + ". Reason: " + e, 257 e); 258 } 259 return defaultValue; 260 } 261 } 262 263 /** 264 * Returns the type name of the given type or null if the type variable is 265 * null 266 */ 267 public static String name(Class type) { 268 return type != null ? type.getName() : null; 269 } 270 271 /** 272 * Returns the type name of the given value 273 */ 274 public static String className(Object value) { 275 return name(value != null ? value.getClass() : null); 276 } 277 278 /** 279 * Attempts to load the given class name using the thread context class 280 * loader or the class loader used to load this class 281 * 282 * @param name the name of the class to load 283 * @return the class or null if it could not be loaded 284 */ 285 public static Class<?> loadClass(String name) { 286 return loadClass(name, ObjectHelper.class.getClassLoader()); 287 } 288 289 /** 290 * Attempts to load the given class name using the thread context class 291 * loader or the given class loader 292 * 293 * @param name the name of the class to load 294 * @param loader the class loader to use after the thread context class 295 * loader 296 * @return the class or null if it could not be loaded 297 */ 298 public static Class<?> loadClass(String name, ClassLoader loader) { 299 ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); 300 if (contextClassLoader != null) { 301 try { 302 return contextClassLoader.loadClass(name); 303 } catch (ClassNotFoundException e) { 304 try { 305 return loader.loadClass(name); 306 } catch (ClassNotFoundException e1) { 307 LOG.debug("Could not find class: " + name + ". Reason: " + e); 308 } 309 } 310 } 311 return null; 312 } 313 314 /** 315 * A helper method to invoke a method via reflection and wrap any exceptions 316 * as {@link RuntimeCamelException} instances 317 * 318 * @param method the method to invoke 319 * @param instance the object instance (or null for static methods) 320 * @param parameters the parameters to the method 321 * @return the result of the method invocation 322 */ 323 public static Object invokeMethod(Method method, Object instance, Object... parameters) { 324 try { 325 return method.invoke(instance, parameters); 326 } catch (IllegalAccessException e) { 327 throw new RuntimeCamelException(e); 328 } catch (InvocationTargetException e) { 329 throw new RuntimeCamelException(e.getCause()); 330 } 331 } 332 333 /** 334 * Returns a list of methods which are annotated with the given annotation 335 * 336 * @param type the type to reflect on 337 * @param annotationType the annotation type 338 * @return a list of the methods found 339 */ 340 public static List<Method> findMethodsWithAnnotation(Class<?> type, 341 Class<? extends Annotation> annotationType) { 342 List<Method> answer = new ArrayList<Method>(); 343 do { 344 Method[] methods = type.getDeclaredMethods(); 345 for (Method method : methods) { 346 if (method.getAnnotation(annotationType) != null) { 347 answer.add(method); 348 } 349 } 350 type = type.getSuperclass(); 351 } while (type != null); 352 return answer; 353 } 354 355 /** 356 * Turns the given object arrays into a meaningful string 357 * 358 * @param objects an array of objects or null 359 * @return a meaningful string 360 */ 361 public static String asString(Object[] objects) { 362 if (objects == null) { 363 return "null"; 364 } else { 365 StringBuffer buffer = new StringBuffer("{"); 366 int counter = 0; 367 for (Object object : objects) { 368 if (counter++ > 0) { 369 buffer.append(", "); 370 } 371 String text = (object == null) ? "null" : object.toString(); 372 buffer.append(text); 373 } 374 buffer.append("}"); 375 return buffer.toString(); 376 } 377 } 378 379 /** 380 * Returns true if a class is assignable from another class like the 381 * {@link Class#isAssignableFrom(Class)} method but which also includes 382 * coercion between primitive types to deal with Java 5 primitive type 383 * wrapping 384 */ 385 public static boolean isAssignableFrom(Class a, Class b) { 386 a = convertPrimitiveTypeToWrapperType(a); 387 b = convertPrimitiveTypeToWrapperType(b); 388 return a.isAssignableFrom(b); 389 } 390 391 /** 392 * Converts primitive types such as int to its wrapper type like 393 * {@link Integer} 394 */ 395 public static Class convertPrimitiveTypeToWrapperType(Class type) { 396 Class rc = type; 397 if (type.isPrimitive()) { 398 if (type == int.class) { 399 rc = Integer.class; 400 } else if (type == long.class) { 401 rc = Long.class; 402 } else if (type == double.class) { 403 rc = Double.class; 404 } else if (type == float.class) { 405 rc = Float.class; 406 } else if (type == short.class) { 407 rc = Short.class; 408 } else if (type == byte.class) { 409 rc = Byte.class; 410 // TODO: Why is boolean disabled 411 /* 412 } else if (type == boolean.class) { 413 rc = Boolean.class; 414 */ 415 } 416 } 417 return rc; 418 } 419 420 /** 421 * Helper method to return the default character set name 422 */ 423 public static String getDefaultCharacterSet() { 424 return Charset.defaultCharset().name(); 425 } 426 427 /** 428 * Returns the Java Bean property name of the given method, if it is a setter 429 */ 430 public static String getPropertyName(Method method) { 431 String propertyName = method.getName(); 432 if (propertyName.startsWith("set") && method.getParameterTypes().length == 1) { 433 propertyName = propertyName.substring(3, 4).toLowerCase() + propertyName.substring(4); 434 } 435 return propertyName; 436 } 437 438 /** 439 * Returns true if the given collection of annotations matches the given type 440 */ 441 public static boolean hasAnnotation(Annotation[] annotations, Class<?> type) { 442 for (Annotation annotation : annotations) { 443 if (type.isInstance(annotation)) { 444 return true; 445 } 446 } 447 return false; 448 } 449 450 /** 451 * Closes the given resource if it is available, logging any closing exceptions to the given log 452 * 453 * @param closeable the object to close 454 * @param name the name of the resource 455 * @param log the log to use when reporting closure warnings 456 */ 457 public static void close(Closeable closeable, String name, Log log) { 458 if (closeable != null) { 459 try { 460 closeable.close(); 461 } catch (IOException e) { 462 log.warn("Could not close " + name + ". Reason: " + e, e); 463 } 464 } 465 } 466 467 /** 468 * Converts the given value to the required type or throw a meaningful exception 469 */ 470 public static <T> T cast(Class<T> toType, Object value) { 471 if (toType == boolean.class) { 472 return (T)cast(Boolean.class, value); 473 } else if (toType.isPrimitive()) { 474 Class newType = convertPrimitiveTypeToWrapperType(toType); 475 if (newType != toType) { 476 return (T)cast(newType, value); 477 } 478 } 479 try { 480 return toType.cast(value); 481 } catch (ClassCastException e) { 482 throw new IllegalArgumentException("Failed to convert: " + value + " to type: " 483 + toType.getName() + " due to: " + e, e); 484 } 485 } 486 487 /** 488 * A helper method to create a new instance of a type using the default constructor arguments. 489 */ 490 public static <T> T newInstance(Class<T> type) { 491 try { 492 return type.newInstance(); 493 } catch (InstantiationException e) { 494 throw new RuntimeCamelException(e.getCause()); 495 } catch (IllegalAccessException e) { 496 throw new RuntimeCamelException(e); 497 } 498 } 499 500 /** 501 * A helper method to create a new instance of a type using the default constructor arguments. 502 */ 503 public static <T> T newInstance(Class<?> actualType, Class<T> expectedType) { 504 try { 505 Object value = actualType.newInstance(); 506 return cast(expectedType, value); 507 } catch (InstantiationException e) { 508 throw new RuntimeCamelException(e.getCause()); 509 } catch (IllegalAccessException e) { 510 throw new RuntimeCamelException(e); 511 } 512 } 513 514 /** 515 * Returns true if the given name is a valid java identifier 516 */ 517 public static boolean isJavaIdentifier(String name) { 518 if (name == null) { 519 return false; 520 } 521 int size = name.length(); 522 if (size < 1) { 523 return false; 524 } 525 if (Character.isJavaIdentifierStart(name.charAt(0))) { 526 for (int i = 1; i < size; i++) { 527 if (!Character.isJavaIdentifierPart(name.charAt(i))) { 528 return false; 529 } 530 } 531 return true; 532 } 533 return false; 534 } 535 536 /** 537 * Returns the type of the given object or null if the value is null 538 */ 539 public static Object type(Object bean) { 540 return bean != null ? bean.getClass() : null; 541 } 542 }