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