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.impl.converter;
018    
019    
020    import java.io.BufferedReader;
021    import java.io.IOException;
022    import java.io.InputStreamReader;
023    
024    import java.lang.reflect.Method;
025    
026    import java.net.URL;
027    import java.util.Enumeration;
028    import java.util.HashSet;
029    import java.util.Set;
030    import java.util.StringTokenizer;
031    import static java.lang.reflect.Modifier.isAbstract;
032    import static java.lang.reflect.Modifier.isPublic;
033    import static java.lang.reflect.Modifier.isStatic;
034    
035    import org.apache.camel.Converter;
036    import org.apache.camel.TypeConverter;
037    import org.apache.camel.util.ObjectHelper;
038    import org.apache.camel.util.ResolverUtil;
039    import org.apache.commons.logging.Log;
040    import org.apache.commons.logging.LogFactory;
041    
042    
043    /**
044     * A class which will auto-discover converter objects and methods to pre-load
045     * the registry of converters on startup
046     *
047     * @version $Revision: 41910 $
048     */
049    public class AnnotationTypeConverterLoader implements TypeConverterLoader {
050        public static final String META_INF_SERVICES = "META-INF/services/org/apache/camel/TypeConverter";
051        private static final transient Log LOG = LogFactory.getLog(AnnotationTypeConverterLoader.class);
052        private ResolverUtil resolver = new ResolverUtil();
053        private Set<Class> visitedClasses = new HashSet<Class>();
054    
055        public void load(TypeConverterRegistry registry) throws Exception {
056            String[] packageNames = findPackageNames();
057            resolver.findAnnotated(Converter.class, packageNames);
058            Set<Class> classes = resolver.getClasses();
059            for (Class type : classes) {
060                if (LOG.isDebugEnabled()) {
061                    LOG.debug("Loading converter class: " + ObjectHelper.name(type));
062                }
063                loadConverterMethods(registry, type);
064            }
065        }
066    
067        /**
068         * Finds the names of the packages to search for on the classpath looking
069         * for text files on the classpath at the {@link #META_INF_SERVICES} location.
070         *
071         * @return a collection of packages to search for
072         * @throws IOException is thrown for IO related errors
073         */
074        protected String[] findPackageNames() throws IOException {
075            Set<String> packages = new HashSet<String>();
076            findPackages(packages, Thread.currentThread().getContextClassLoader());
077            findPackages(packages, getClass().getClassLoader());
078            return packages.toArray(new String[packages.size()]);
079        }
080    
081        protected void findPackages(Set<String> packages, ClassLoader classLoader) throws IOException {
082            Enumeration<URL> resources = classLoader.getResources(META_INF_SERVICES);
083            while (resources.hasMoreElements()) {
084                URL url = resources.nextElement();
085                if (url != null) {
086                    BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
087                    try {
088                        while (true) {
089                            String line = reader.readLine();
090                            if (line == null) {
091                                break;
092                            }
093                            line = line.trim();
094                            if (line.startsWith("#") || line.length() == 0) {
095                                continue;
096                            }
097                            tokenize(packages, line);
098                        }
099                    } finally {
100                        ObjectHelper.close(reader, null, LOG);
101                    }
102                }
103            }
104        }
105    
106        /**
107         * Tokenizes the line from the META-IN/services file using commas and
108         * ignoring whitespace between packages
109         */
110        protected void tokenize(Set<String> packages, String line) {
111            StringTokenizer iter = new StringTokenizer(line, ",");
112            while (iter.hasMoreTokens()) {
113                String name = iter.nextToken().trim();
114                if (name.length() > 0) {
115                    packages.add(name);
116                }
117            }
118        }
119    
120        /**
121         * Loads all of the converter methods for the given type
122         */
123        protected void loadConverterMethods(TypeConverterRegistry registry, Class type) {
124            if (visitedClasses.contains(type)) {
125                return;
126            }
127            visitedClasses.add(type);
128            try {
129                Method[] methods = type.getDeclaredMethods();
130                CachingInjector injector = null;
131    
132                for (Method method : methods) {
133                    Converter annotation = method.getAnnotation(Converter.class);
134                    if (annotation != null) {
135                        Class<?>[] parameterTypes = method.getParameterTypes();
136                        if (parameterTypes == null || parameterTypes.length != 1) {
137                            LOG.warn("Ignoring bad converter on type: " + type.getName() + " method: " + method
138                                    + " as a converter method should have one parameter");
139                        } else {
140                            int modifiers = method.getModifiers();
141                            if (isAbstract(modifiers) || !isPublic(modifiers)) {
142                                LOG.warn("Ignoring bad converter on type: " + type.getName() + " method: " + method
143                                        + " as a converter method is not a public and concrete method");
144                            } else {
145                                Class toType = method.getReturnType();
146                                if (toType.equals(Void.class)) {
147                                    LOG.warn("Ignoring bad converter on type: " + type.getName() + " method: "
148                                            + method + " as a converter method returns a void method");
149                                } else {
150                                    Class fromType = parameterTypes[0];
151                                    if (isStatic(modifiers)) {
152                                        registerTypeConverter(registry, method, toType, fromType,
153                                                              new StaticMethodTypeConverter(method));
154                                    } else {
155                                        if (injector == null) {
156                                            injector = new CachingInjector(registry, type);
157                                        }
158                                        registerTypeConverter(registry, method, toType, fromType,
159                                                new InstanceMethodTypeConverter(injector, method));
160                                    }
161                                }
162                            }
163                        }
164                    }
165                }
166                Class superclass = type.getSuperclass();
167                if (superclass != null && !superclass.equals(Object.class)) {
168                    loadConverterMethods(registry, superclass);
169                }
170            } catch (NoClassDefFoundError e) {
171                LOG.debug("Ignoring converter type: " + type.getName() + " as a dependent class could not be found: " + e, e);
172            }
173        }
174    
175        protected void registerTypeConverter(TypeConverterRegistry registry, Method method,
176                                             Class toType, Class fromType, TypeConverter typeConverter) {
177    
178            registry.addTypeConverter(toType, fromType, typeConverter);
179        }
180    }