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.osgi;
018    
019    import java.io.BufferedInputStream;
020    import java.io.BufferedReader;
021    import java.io.IOException;
022    import java.io.InputStreamReader;
023    import java.net.URL;
024    import java.util.*;
025    import java.util.concurrent.ConcurrentHashMap;
026    
027    import org.apache.camel.CamelContext;
028    import org.apache.camel.Component;
029    import org.apache.camel.Converter;
030    import org.apache.camel.TypeConverter;
031    import org.apache.camel.impl.converter.AnnotationTypeConverterLoader;
032    import org.apache.camel.impl.converter.TypeConverterLoader;
033    import org.apache.camel.impl.osgi.tracker.BundleTracker;
034    import org.apache.camel.impl.osgi.tracker.BundleTrackerCustomizer;
035    import org.apache.camel.impl.scan.AnnotatedWithPackageScanFilter;
036    import org.apache.camel.model.DataFormatDefinition;
037    import org.apache.camel.spi.ComponentResolver;
038    import org.apache.camel.spi.DataFormat;
039    import org.apache.camel.spi.DataFormatResolver;
040    import org.apache.camel.spi.Injector;
041    import org.apache.camel.spi.Language;
042    import org.apache.camel.spi.LanguageResolver;
043    import org.apache.camel.spi.PackageScanFilter;
044    import org.apache.camel.spi.TypeConverterRegistry;
045    import org.apache.camel.util.IOHelper;
046    import org.apache.camel.util.ObjectHelper;
047    import org.apache.commons.logging.Log;
048    import org.apache.commons.logging.LogFactory;
049    import org.osgi.framework.Bundle;
050    import org.osgi.framework.BundleActivator;
051    import org.osgi.framework.BundleContext;
052    import org.osgi.framework.BundleEvent;
053    import org.osgi.framework.ServiceRegistration;
054    
055    public class Activator implements BundleActivator, BundleTrackerCustomizer {
056    
057        public static final String META_INF_COMPONENT = "META-INF/services/org/apache/camel/component/";
058        public static final String META_INF_LANGUAGE = "META-INF/services/org/apache/camel/language/";
059        public static final String META_INF_LANGUAGE_RESOLVER = "META-INF/services/org/apache/camel/language/resolver/";
060        public static final String META_INF_DATAFORMAT = "META-INF/services/org/apache/camel/dataformat/";
061        public static final String META_INF_TYPE_CONVERTER = "META-INF/services/org/apache/camel/TypeConverter";
062        public static final String META_INF_FALLBACK_TYPE_CONVERTER = "META-INF/services/org/apache/camel/FallbackTypeConverter";
063    
064        private static final transient Log LOG = LogFactory.getLog(Activator.class);
065    
066        private BundleTracker tracker;
067        private Map<Long, List<BaseService>> resolvers = new ConcurrentHashMap<Long, List<BaseService>>();
068    
069        public void start(BundleContext context) throws Exception {
070            LOG.info("Camel activator starting");
071            tracker = new BundleTracker(context, Bundle.ACTIVE, this);
072            tracker.open();
073            LOG.info("Camel activator started");
074        }
075    
076        public void stop(BundleContext context) throws Exception {
077            LOG.info("Camel activator stopping");
078            tracker.close();
079            LOG.info("Camel activator stopped");
080        }
081    
082        public Object addingBundle(Bundle bundle, BundleEvent event) {
083            if (LOG.isDebugEnabled()) {
084                LOG.debug("Bundle started: " + bundle.getSymbolicName());
085            }
086            List<BaseService> r = new ArrayList<BaseService>();
087            registerComponents(bundle, r);
088            registerLanguages(bundle, r);
089            registerDataFormats(bundle, r);
090            registerTypeConverterLoader(bundle, r);
091            for (BaseService service : r) {
092                service.register();
093            }
094            resolvers.put(bundle.getBundleId(), r);
095            return bundle;
096        }
097    
098        public void modifiedBundle(Bundle bundle, BundleEvent event, Object object) {
099        }
100    
101        public void removedBundle(Bundle bundle, BundleEvent event, Object object) {
102            if (LOG.isDebugEnabled()) {
103                LOG.debug("Bundle stopped: " + bundle.getSymbolicName());
104            }
105            List<BaseService> r = resolvers.remove(bundle.getBundleId());
106            if (r != null) {
107                for (BaseService service : r) {
108                    service.unregister();
109                }
110            }
111        }
112    
113        protected void registerComponents(Bundle bundle, List<BaseService> resolvers) {
114            if (checkCompat(bundle, Component.class)) {
115                Map<String, String> components = new HashMap<String, String>();
116                for (Enumeration e = bundle.getEntryPaths(META_INF_COMPONENT); e != null && e.hasMoreElements();) {
117                    String path = (String) e.nextElement();
118                    if (LOG.isDebugEnabled()) {
119                        LOG.debug("Found entry: " + path + " in bundle " + bundle.getSymbolicName());
120                    }
121                    String name = path.substring(path.lastIndexOf("/") + 1);
122                    components.put(name, path);
123                }
124                if (!components.isEmpty()) {
125                    resolvers.add(new BundleComponentResolver(bundle, components));
126                }
127            }
128        }
129    
130        protected void registerLanguages(Bundle bundle, List<BaseService> resolvers) {
131            if (checkCompat(bundle, Language.class)) {
132                Map<String, String> languages = new HashMap<String, String>();
133                for (Enumeration e = bundle.getEntryPaths(META_INF_LANGUAGE); e != null && e.hasMoreElements();) {
134                    String path = (String) e.nextElement();
135                    if (LOG.isDebugEnabled()) {
136                        LOG.debug("Found entry: " + path + " in bundle " + bundle.getSymbolicName());
137                    }
138                    String name = path.substring(path.lastIndexOf("/") + 1);
139                    languages.put(name, path);
140                }
141                if (!languages.isEmpty()) {
142                    resolvers.add(new BundleLanguageResolver(bundle, languages));
143                }
144                for (Enumeration e = bundle.getEntryPaths(META_INF_LANGUAGE_RESOLVER); e != null && e.hasMoreElements();) {
145                    String path = (String) e.nextElement();
146                    if (LOG.isDebugEnabled()) {
147                        LOG.debug("Found entry: " + path + " in bundle " + bundle.getSymbolicName());
148                    }
149                    String name = path.substring(path.lastIndexOf("/") + 1);
150                    resolvers.add(new BundleMetaLanguageResolver(bundle, name, path));
151                }
152            }
153        }
154    
155        protected void registerDataFormats(Bundle bundle, List<BaseService> resolvers) {
156            if (checkCompat(bundle, DataFormat.class)) {
157                Map<String, String> dataformats = new HashMap<String, String>();
158                for (Enumeration e = bundle.getEntryPaths(META_INF_DATAFORMAT); e != null && e.hasMoreElements();) {
159                    String path = (String) e.nextElement();
160                    if (LOG.isDebugEnabled()) {
161                        LOG.debug("Found entry: " + path + " in bundle " + bundle.getSymbolicName());
162                    }
163                    String name = path.substring(path.lastIndexOf("/") + 1);
164                    dataformats.put(name, path);
165                }
166                if (!dataformats.isEmpty()) {
167                    resolvers.add(new BundleDataFormatResolver(bundle, dataformats));
168                }
169            }
170        }
171    
172        protected void registerTypeConverterLoader(Bundle bundle, List<BaseService> resolvers) {
173            if (checkCompat(bundle, TypeConverter.class)) {
174                URL url1 = bundle.getEntry(META_INF_TYPE_CONVERTER);
175                URL url2 = bundle.getEntry(META_INF_FALLBACK_TYPE_CONVERTER);
176                if (url1 != null || url2 != null) {
177                    resolvers.add(new BundleTypeConverterLoader(bundle));
178                }
179            }
180        }
181    
182        protected static class BundleComponentResolver extends BaseResolver<Component> implements ComponentResolver {
183    
184            private final Map<String, String> components;
185    
186            public BundleComponentResolver(Bundle bundle, Map<String, String> components) {
187                super(bundle, Component.class);
188                this.components = components;
189            }
190    
191            public Component resolveComponent(String name, CamelContext context) throws Exception {
192                return createInstance(name, components.get(name), context);
193            }
194    
195            public void register() {
196                doRegister(ComponentResolver.class, "component", components.keySet());
197            }
198        }
199    
200        protected static class BundleLanguageResolver extends BaseResolver<Language> implements LanguageResolver {
201    
202            private final Map<String, String> languages;
203    
204            public BundleLanguageResolver(Bundle bundle, Map<String, String> languages) {
205                super(bundle, Language.class);
206                this.languages = languages;
207            }
208    
209            public Language resolveLanguage(String name, CamelContext context) {
210                return createInstance(name, languages.get(name), context);
211            }
212    
213            public void register() {
214                doRegister(LanguageResolver.class, "language", languages.keySet());
215            }
216        }
217    
218        protected static class BundleMetaLanguageResolver extends BaseResolver<LanguageResolver> implements LanguageResolver {
219    
220            private final String name;
221            private final String path;
222    
223            public BundleMetaLanguageResolver(Bundle bundle, String name, String path) {
224                super(bundle, LanguageResolver.class);
225                this.name = name;
226                this.path = path;
227            }
228    
229            public Language resolveLanguage(String name, CamelContext context) {
230                LanguageResolver resolver = createInstance(this.name, path, context);
231                return resolver.resolveLanguage(name, context);
232            }
233    
234            public void register() {
235                doRegister(LanguageResolver.class, "resolver", name);
236            }
237        }
238    
239        protected static class BundleDataFormatResolver extends BaseResolver<DataFormat> implements DataFormatResolver {
240    
241            private final Map<String, String> dataformats;
242    
243            public BundleDataFormatResolver(Bundle bundle, Map<String, String> dataformats) {
244                super(bundle, DataFormat.class);
245                this.dataformats = dataformats;
246            }
247    
248            public DataFormat resolveDataFormat(String name, CamelContext context) {
249                return createInstance(name, dataformats.get(name), context);
250            }
251    
252            public DataFormatDefinition resolveDataFormatDefinition(String name, CamelContext context) {
253                return null;
254            }
255    
256            public void register() {
257                doRegister(DataFormatResolver.class, "dataformat", dataformats.keySet());
258            }
259        }
260    
261        protected static class BundleTypeConverterLoader extends BaseResolver<TypeConverter> implements TypeConverterLoader {
262    
263            private final AnnotationTypeConverterLoader loader = new Loader();
264    
265            public BundleTypeConverterLoader(Bundle bundle) {
266                super(bundle, TypeConverter.class);
267            }
268    
269            public void load(TypeConverterRegistry registry) throws Exception {
270                loader.load(registry);
271            }
272    
273            public void register() {
274                doRegister(TypeConverterLoader.class);
275            }
276    
277            class Loader extends AnnotationTypeConverterLoader {
278    
279                Loader() {
280                    super(null);
281                }
282    
283                @SuppressWarnings("unchecked")
284                public void load(TypeConverterRegistry registry) throws Exception {
285                    PackageScanFilter test = new AnnotatedWithPackageScanFilter(Converter.class, true);
286                    Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
287                    Set<String> packages = getConverterPackages(bundle.getEntry(META_INF_TYPE_CONVERTER));
288                    for (String pkg : packages) {
289                        Enumeration<URL> e = bundle.findEntries("/" + pkg.replace('.', '/'), "*.class", true);
290                        while (e.hasMoreElements()) {
291                            String path = e.nextElement().getPath();
292                            String externalName = path.substring(path.charAt(0) == '/' ? 1 : 0, path.indexOf('.')).replace('/', '.');
293                            try {
294                                Class clazz = bundle.loadClass(externalName);
295                                if (test.matches(clazz)) {
296                                    classes.add(bundle.loadClass(externalName));
297                                }
298                            } catch (Throwable t) {
299                                // Ignore
300                            }
301                        }
302                    }
303                    LOG.info("Found " + classes.size() + " @Converter classes to load");
304                    for (Class type : classes) {
305                        if (LOG.isDebugEnabled()) {
306                            LOG.debug("Loading converter class: " + ObjectHelper.name(type));
307                        }
308                        loadConverterMethods(registry, type);
309                    }
310                    URL fallbackUrl = bundle.getEntry(META_INF_FALLBACK_TYPE_CONVERTER);
311                    if (fallbackUrl != null) {
312                        TypeConverter tc = createInstance("FallbackTypeConverter", fallbackUrl, registry.getInjector());
313                        registry.addFallbackTypeConverter(tc, false);
314                    }
315                    // Clear info
316                    visitedClasses.clear();
317                    visitedURLs.clear();
318                }
319            }
320    
321        }
322    
323        protected abstract static class BaseResolver<T> extends BaseService {
324    
325            private final Class<T> type;
326    
327            public BaseResolver(Bundle bundle, Class<T> type) {
328                super(bundle);
329                this.type = type;
330            }
331    
332            protected T createInstance(String name, String path, CamelContext context) {
333                if (path == null) {
334                    return null;
335                }
336                URL url = bundle.getEntry(path);
337                if (LOG.isDebugEnabled()) {
338                    LOG.debug("The entry " + name + "'s url is" + url);
339                }
340                return createInstance(name, url, context.getInjector());
341            }
342    
343            @SuppressWarnings("unchecked")
344            protected T createInstance(String name, URL url, Injector injector) {
345                try {
346                    Properties properties = loadProperties(url);
347                    String classname = (String) properties.get("class");
348                    Class<T> type = bundle.loadClass(classname);
349                    if (!this.type.isAssignableFrom(type)) {
350                        throw new IllegalArgumentException("Type is not a " + this.type.getName() + " implementation. Found: " + type.getName());
351                    }
352                    return injector.newInstance(type);
353                } catch (ClassNotFoundException e) {
354                    throw new IllegalArgumentException("Invalid URI, no " + this.type.getName() + " registered for scheme : " + name, e);
355                }
356            }
357    
358        }
359    
360        protected abstract static class BaseService {
361    
362            protected final Bundle bundle;
363            private ServiceRegistration reg;
364    
365            protected BaseService(Bundle bundle) {
366                this.bundle = bundle;
367            }
368    
369            public abstract void register();
370    
371            protected void doRegister(Class type, String key, Collection<String> value) {
372                doRegister(type, key, value.toArray(new String[value.size()]));
373            }
374    
375            protected void doRegister(Class type, String key, Object value) {
376                Hashtable<String, Object> props = new Hashtable<String, Object>();
377                props.put(key, value);
378                doRegister(type, props);
379            }
380    
381            protected void doRegister(Class type) {
382                doRegister(type, null);
383            }
384    
385            protected void doRegister(Class type, Dictionary props) {
386                reg = bundle.getBundleContext().registerService(type.getName(), this, props);
387            }
388    
389            public void unregister() {
390                reg.unregister();
391            }
392        }
393    
394        protected static Properties loadProperties(URL url) {
395            Properties properties = new Properties();
396            BufferedInputStream reader = null;
397            try {
398                reader = new BufferedInputStream(url.openStream());
399                properties.load(reader);
400            } catch (IOException e) {
401                throw new RuntimeException(e);
402            } finally {
403                IOHelper.close(reader, "properties", LOG);
404            }
405            return properties;
406        }
407    
408        protected static boolean checkCompat(Bundle bundle, Class clazz) {
409            // Check bundle compatibility
410            try {
411                if (bundle.loadClass(clazz.getName()) != clazz) {
412                    return false;
413                }
414            } catch (Throwable t) {
415                return false;
416            }
417            return true;
418        }
419    
420        protected static Set<String> getConverterPackages(URL resource) {
421            Set<String> packages = new HashSet<String>();
422            if (resource != null) {
423                BufferedReader reader = null;
424                try {
425                    reader = new BufferedReader(new InputStreamReader(resource.openStream()));
426                    while (true) {
427                        String line = reader.readLine();
428                        if (line == null) {
429                            break;
430                        }
431                        line = line.trim();
432                        if (line.startsWith("#") || line.length() == 0) {
433                            continue;
434                        }
435                        StringTokenizer iter = new StringTokenizer(line, ",");
436                        while (iter.hasMoreTokens()) {
437                            String name = iter.nextToken().trim();
438                            if (name.length() > 0) {
439                                packages.add(name);
440                            }
441                        }
442                    }
443                } catch (Exception ignore) {
444                    // Do nothing here
445                } finally {
446                    IOHelper.close(reader, null, LOG);
447                }
448            }
449            return packages;
450        }
451    
452    }
453