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