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 import java.io.BufferedReader;
020 import java.io.IOException;
021 import java.io.InputStreamReader;
022 import java.lang.reflect.Method;
023
024 import java.net.URL;
025 import java.util.Enumeration;
026 import java.util.HashSet;
027 import java.util.Set;
028 import java.util.StringTokenizer;
029 import static java.lang.reflect.Modifier.isAbstract;
030 import static java.lang.reflect.Modifier.isPublic;
031 import static java.lang.reflect.Modifier.isStatic;
032
033 import org.apache.camel.Converter;
034 import org.apache.camel.Exchange;
035 import org.apache.camel.FallbackConverter;
036 import org.apache.camel.TypeConverter;
037 import org.apache.camel.spi.PackageScanClassResolver;
038 import org.apache.camel.spi.TypeConverterRegistry;
039 import org.apache.camel.util.CastUtils;
040 import org.apache.camel.util.ObjectHelper;
041 import org.apache.commons.logging.Log;
042 import org.apache.commons.logging.LogFactory;
043
044 /**
045 * A class which will auto-discover converter objects and methods to pre-load
046 * the registry of converters on startup
047 *
048 * @version $Revision: 901136 $
049 */
050 public class AnnotationTypeConverterLoader implements TypeConverterLoader {
051 public static final String META_INF_SERVICES = "META-INF/services/org/apache/camel/TypeConverter";
052 private static final transient Log LOG = LogFactory.getLog(AnnotationTypeConverterLoader.class);
053 protected PackageScanClassResolver resolver;
054 private Set<Class<?>> visitedClasses = new HashSet<Class<?>>();
055
056 public AnnotationTypeConverterLoader(PackageScanClassResolver resolver) {
057 this.resolver = resolver;
058 }
059
060 @SuppressWarnings("unchecked")
061 public void load(TypeConverterRegistry registry) throws Exception {
062 String[] packageNames = findPackageNames();
063 Set<Class<?>> classes = resolver.findAnnotated(Converter.class, packageNames);
064 for (Class type : classes) {
065 if (LOG.isDebugEnabled()) {
066 LOG.debug("Loading converter class: " + ObjectHelper.name(type));
067 }
068 loadConverterMethods(registry, type);
069 }
070 }
071
072 /**
073 * Finds the names of the packages to search for on the classpath looking
074 * for text files on the classpath at the {@link #META_INF_SERVICES} location.
075 *
076 * @return a collection of packages to search for
077 * @throws IOException is thrown for IO related errors
078 */
079 protected String[] findPackageNames() throws IOException {
080 Set<String> packages = new HashSet<String>();
081 ClassLoader ccl = Thread.currentThread().getContextClassLoader();
082 if (ccl != null) {
083 findPackages(packages, ccl);
084 }
085 findPackages(packages, getClass().getClassLoader());
086 return packages.toArray(new String[packages.size()]);
087 }
088
089 protected void findPackages(Set<String> packages, ClassLoader classLoader) throws IOException {
090 Enumeration<URL> resources = classLoader.getResources(META_INF_SERVICES);
091 while (resources.hasMoreElements()) {
092 URL url = resources.nextElement();
093 if (url != null) {
094 BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
095 try {
096 while (true) {
097 String line = reader.readLine();
098 if (line == null) {
099 break;
100 }
101 line = line.trim();
102 if (line.startsWith("#") || line.length() == 0) {
103 continue;
104 }
105 tokenize(packages, line);
106 }
107 } finally {
108 ObjectHelper.close(reader, null, LOG);
109 }
110 }
111 }
112 }
113
114 /**
115 * Tokenizes the line from the META-IN/services file using commas and
116 * ignoring whitespace between packages
117 */
118 private void tokenize(Set<String> packages, String line) {
119 StringTokenizer iter = new StringTokenizer(line, ",");
120 while (iter.hasMoreTokens()) {
121 String name = iter.nextToken().trim();
122 if (name.length() > 0) {
123 packages.add(name);
124 }
125 }
126 }
127
128 /**
129 * Loads all of the converter methods for the given type
130 */
131 protected void loadConverterMethods(TypeConverterRegistry registry, Class<?> type) {
132 if (visitedClasses.contains(type)) {
133 return;
134 }
135 visitedClasses.add(type);
136 try {
137 Method[] methods = type.getDeclaredMethods();
138 CachingInjector<?> injector = null;
139
140 for (Method method : methods) {
141 // this may be prone to ClassLoader or packaging problems when the same class is defined
142 // in two different jars (as is the case sometimes with specs).
143 if (ObjectHelper.hasAnnotation(method, Converter.class, true)) {
144 injector = handleHasConverterAnnotation(registry, type, injector, method);
145 } else if (ObjectHelper.hasAnnotation(method, FallbackConverter.class, true)) {
146 injector = handleHasFallbackConverterAnnotation(registry, type, injector, method);
147 }
148 }
149
150 Class<?> superclass = type.getSuperclass();
151 if (superclass != null && !superclass.equals(Object.class)) {
152 loadConverterMethods(registry, superclass);
153 }
154 } catch (NoClassDefFoundError e) {
155 LOG.warn("Ignoring converter type: " + type.getCanonicalName() + " as a dependent class could not be found: " + e, e);
156 }
157 }
158
159 private CachingInjector<?> handleHasConverterAnnotation(TypeConverterRegistry registry, Class<?> type, CachingInjector<?> injector, Method method) {
160 if (isValidConverterMethod(method)) {
161 int modifiers = method.getModifiers();
162 if (isAbstract(modifiers) || !isPublic(modifiers)) {
163 LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method
164 + " as a converter method is not a public and concrete method");
165 } else {
166 Class<?> toType = method.getReturnType();
167 if (toType.equals(Void.class)) {
168 LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: "
169 + method + " as a converter method returns a void method");
170 } else {
171 Class<?> fromType = method.getParameterTypes()[0];
172 if (isStatic(modifiers)) {
173 registerTypeConverter(registry, method, toType, fromType,
174 new StaticMethodTypeConverter(method));
175 } else {
176 if (injector == null) {
177 injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class));
178 }
179 registerTypeConverter(registry, method, toType, fromType,
180 new InstanceMethodTypeConverter(injector, method, registry));
181 }
182 }
183 }
184 } else {
185 LOG.warn("Ignoring bad converter on type: " + type.getCanonicalName() + " method: " + method
186 + " as a converter method should have one parameter");
187 }
188 return injector;
189 }
190
191 private CachingInjector<?> handleHasFallbackConverterAnnotation(TypeConverterRegistry registry, Class<?> type, CachingInjector<?> injector, Method method) {
192 if (isValidFallbackConverterMethod(method)) {
193 int modifiers = method.getModifiers();
194 if (isAbstract(modifiers) || !isPublic(modifiers)) {
195 LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method
196 + " as a fallback converter method is not a public and concrete method");
197 } else {
198 Class<?> toType = method.getReturnType();
199 if (toType.equals(Void.class)) {
200 LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: "
201 + method + " as a fallback converter method returns a void method");
202 } else {
203 if (isStatic(modifiers)) {
204 registerFallbackTypeConverter(registry, new StaticMethodFallbackTypeConverter(method, registry));
205 } else {
206 if (injector == null) {
207 injector = new CachingInjector<Object>(registry, CastUtils.cast(type, Object.class));
208 }
209 registerFallbackTypeConverter(registry, new InstanceMethodFallbackTypeConverter(injector, method, registry));
210 }
211 }
212 }
213 } else {
214 LOG.warn("Ignoring bad fallback converter on type: " + type.getCanonicalName() + " method: " + method
215 + " as a fallback converter method should have one parameter");
216 }
217 return injector;
218 }
219
220 protected void registerTypeConverter(TypeConverterRegistry registry,
221 Method method, Class<?> toType, Class<?> fromType, TypeConverter typeConverter) {
222 registry.addTypeConverter(toType, fromType, typeConverter);
223 }
224
225 protected boolean isValidConverterMethod(Method method) {
226 Class<?>[] parameterTypes = method.getParameterTypes();
227 return (parameterTypes != null) && (parameterTypes.length == 1
228 || (parameterTypes.length == 2 && Exchange.class.isAssignableFrom(parameterTypes[1])));
229 }
230
231 protected void registerFallbackTypeConverter(TypeConverterRegistry registry, TypeConverter typeConverter) {
232 registry.addFallbackTypeConverter(typeConverter);
233 }
234
235 protected boolean isValidFallbackConverterMethod(Method method) {
236 Class<?>[] parameterTypes = method.getParameterTypes();
237 return (parameterTypes != null) && (parameterTypes.length == 3
238 || (parameterTypes.length == 4 && Exchange.class.isAssignableFrom(parameterTypes[1]))
239 && (TypeConverterRegistry.class.isAssignableFrom(parameterTypes[parameterTypes.length - 1])));
240 }
241 }