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.blueprint;
018    
019    import java.util.ArrayList;
020    import java.util.Collection;
021    import java.util.List;
022    import javax.xml.bind.annotation.XmlAccessType;
023    import javax.xml.bind.annotation.XmlAccessorType;
024    import javax.xml.bind.annotation.XmlAttribute;
025    import javax.xml.bind.annotation.XmlElement;
026    import javax.xml.bind.annotation.XmlElements;
027    import javax.xml.bind.annotation.XmlRootElement;
028    import javax.xml.bind.annotation.XmlTransient;
029    
030    import org.apache.aries.blueprint.ExtendedBlueprintContainer;
031    import org.apache.camel.RoutesBuilder;
032    import org.apache.camel.ShutdownRoute;
033    import org.apache.camel.ShutdownRunningTask;
034    import org.apache.camel.builder.RouteBuilder;
035    import org.apache.camel.component.properties.PropertiesComponent;
036    import org.apache.camel.core.osgi.OsgiCamelContextPublisher;
037    import org.apache.camel.core.osgi.OsgiEventAdminNotifier;
038    import org.apache.camel.core.osgi.utils.BundleDelegatingClassLoader;
039    import org.apache.camel.core.xml.AbstractCamelContextFactoryBean;
040    import org.apache.camel.core.xml.CamelJMXAgentDefinition;
041    import org.apache.camel.core.xml.CamelPropertyPlaceholderDefinition;
042    import org.apache.camel.core.xml.CamelServiceExporterDefinition;
043    import org.apache.camel.model.ContextScanDefinition;
044    import org.apache.camel.model.InterceptDefinition;
045    import org.apache.camel.model.InterceptFromDefinition;
046    import org.apache.camel.model.InterceptSendToEndpointDefinition;
047    import org.apache.camel.model.OnCompletionDefinition;
048    import org.apache.camel.model.OnExceptionDefinition;
049    import org.apache.camel.model.PackageScanDefinition;
050    import org.apache.camel.model.RouteBuilderDefinition;
051    import org.apache.camel.model.RouteContextRefDefinition;
052    import org.apache.camel.model.RouteDefinition;
053    import org.apache.camel.model.ThreadPoolProfileDefinition;
054    import org.apache.camel.model.config.PropertiesDefinition;
055    import org.apache.camel.model.dataformat.DataFormatsDefinition;
056    import org.apache.camel.spi.PackageScanFilter;
057    import org.apache.camel.spi.Registry;
058    import org.osgi.framework.BundleContext;
059    import org.osgi.service.blueprint.container.BlueprintContainer;
060    import org.slf4j.Logger;
061    import org.slf4j.LoggerFactory;
062    
063    /**
064     * A bean to create and initialize a {@link BlueprintCamelContext}
065     * and install routes either explicitly configured in
066     * Blueprint XML or found by searching the classpath for Java classes which extend
067     * {@link RouteBuilder} using the nested {@link #setPackages(String[])}.
068     *
069     * @version 
070     */
071    @XmlRootElement(name = "camelContext")
072    @XmlAccessorType(XmlAccessType.FIELD)
073    public class CamelContextFactoryBean extends AbstractCamelContextFactoryBean<BlueprintCamelContext> {
074        private static final Logger LOG = LoggerFactory.getLogger(CamelContextFactoryBean.class);
075    
076        @XmlAttribute(name = "depends-on", required = false)
077        private String dependsOn;
078        @XmlAttribute(required = false)
079        private String trace;
080        @XmlAttribute(required = false)
081        private String streamCache = "false";
082        @XmlAttribute(required = false)
083        private String delayer;
084        @XmlAttribute(required = false)
085        private String handleFault;
086        @XmlAttribute(required = false)
087        private String errorHandlerRef;
088        @XmlAttribute(required = false)
089        private String autoStartup = "true";
090        @XmlAttribute(required = false)
091        private String useMDCLogging;
092        @XmlAttribute(required = false)
093        private Boolean useBlueprintPropertyResolver;
094        @XmlAttribute(required = false)
095        private ShutdownRoute shutdownRoute;
096        @XmlAttribute(required = false)
097        private ShutdownRunningTask shutdownRunningTask;
098        @XmlAttribute(required = false)
099        private Boolean lazyLoadTypeConverters = Boolean.FALSE;
100        @XmlElement(name = "properties", required = false)
101        private PropertiesDefinition properties;
102        @XmlElement(name = "propertyPlaceholder", type = CamelPropertyPlaceholderDefinition.class, required = false)
103        private CamelPropertyPlaceholderDefinition camelPropertyPlaceholder;
104        @XmlElement(name = "package", required = false)
105        private String[] packages = {};
106        @XmlElement(name = "packageScan", type = PackageScanDefinition.class, required = false)
107        private PackageScanDefinition packageScan;
108        @XmlElement(name = "contextScan", type = ContextScanDefinition.class, required = false)
109        private ContextScanDefinition contextScan;
110        @XmlElement(name = "jmxAgent", type = CamelJMXAgentDefinition.class, required = false)
111        private CamelJMXAgentDefinition camelJMXAgent;
112        @XmlElements({
113            @XmlElement(name = "template", type = CamelProducerTemplateFactoryBean.class, required = false),
114            @XmlElement(name = "consumerTemplate", type = CamelConsumerTemplateFactoryBean.class, required = false),
115            @XmlElement(name = "proxy", type = CamelProxyFactoryBean.class, required = false),
116            @XmlElement(name = "export", type = CamelServiceExporterDefinition.class, required = false),
117            @XmlElement(name = "errorHandler", type = CamelErrorHandlerFactoryBean.class, required = false)
118        })
119        private List beans;
120        @XmlElement(name = "routeBuilder", required = false)
121        private List<RouteBuilderDefinition> builderRefs = new ArrayList<RouteBuilderDefinition>();
122        @XmlElement(name = "routeContextRef", required = false)
123        private List<RouteContextRefDefinition> routeRefs = new ArrayList<RouteContextRefDefinition>();
124        @XmlElement(name = "threadPoolProfile", required = false)
125        private List<ThreadPoolProfileDefinition> threadPoolProfiles;
126        @XmlElement(name = "threadPool", required = false)
127        private List<CamelThreadPoolFactoryBean> threadPools;
128        @XmlElement(name = "endpoint", required = false)
129        private List<CamelEndpointFactoryBean> endpoints;
130        @XmlElement(name = "dataFormats", required = false)
131        private DataFormatsDefinition dataFormats;
132        @XmlElement(name = "redeliveryPolicyProfile", required = false)
133        private List<CamelRedeliveryPolicyFactoryBean> redeliveryPolicies;
134        @XmlElement(name = "onException", required = false)
135        private List<OnExceptionDefinition> onExceptions = new ArrayList<OnExceptionDefinition>();
136        @XmlElement(name = "onCompletion", required = false)
137        private List<OnCompletionDefinition> onCompletions = new ArrayList<OnCompletionDefinition>();
138        @XmlElement(name = "intercept", required = false)
139        private List<InterceptDefinition> intercepts = new ArrayList<InterceptDefinition>();
140        @XmlElement(name = "interceptFrom", required = false)
141        private List<InterceptFromDefinition> interceptFroms = new ArrayList<InterceptFromDefinition>();
142        @XmlElement(name = "interceptSendToEndpoint", required = false)
143        private List<InterceptSendToEndpointDefinition> interceptSendToEndpoints = new ArrayList<InterceptSendToEndpointDefinition>();
144        @XmlElement(name = "route", required = false)
145        private List<RouteDefinition> routes = new ArrayList<RouteDefinition>();
146        @XmlTransient
147        private BlueprintCamelContext context;
148        @XmlTransient
149        private BlueprintContainer blueprintContainer;
150        @XmlTransient
151        private BundleContext bundleContext;
152        @XmlTransient
153        private boolean implicitId;
154    
155    
156        public Class getObjectType() {
157            return BlueprintCamelContext.class;
158        }
159    
160        @Override
161        public BlueprintCamelContext getContext(boolean create) {
162            if (context == null && create) {
163                context = createContext();
164                if (!isImplicitId()) {
165                    context.setName(getId());
166                }
167            }
168            return context;
169        }
170    
171        public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
172            this.blueprintContainer = blueprintContainer;
173        }
174    
175        public void setBundleContext(BundleContext bundleContext) {
176            this.bundleContext = bundleContext;
177        }
178    
179        protected BlueprintCamelContext createContext() {
180            return new BlueprintCamelContext(bundleContext, blueprintContainer);
181        }
182    
183        @Override
184        protected void initCustomRegistry(BlueprintCamelContext context) {
185            Registry registry = getBeanForType(Registry.class);
186            if (registry != null) {
187                LOG.info("Using custom Registry: " + registry);
188                context.setRegistry(registry);
189            }
190        }
191    
192        @Override
193        protected <S> S getBeanForType(Class<S> clazz) {
194            Collection<S> objects = BlueprintContainerRegistry.lookupByType(blueprintContainer, clazz).values();
195            if (objects.size() == 1) {
196                return objects.iterator().next();
197            }
198            return null;
199        }
200    
201        @Override
202        protected void initPropertyPlaceholder() throws Exception {
203            super.initPropertyPlaceholder();
204    
205            // if blueprint property resolver is enabled on CamelContext then bridge PropertiesComponent to blueprint
206            if (isUseBlueprintPropertyResolver()) {
207                // lookup existing configured properties component
208                PropertiesComponent pc = getContext().getComponent("properties", PropertiesComponent.class);
209    
210                BlueprintPropertiesParser parser = new BlueprintPropertiesParser(blueprintContainer, pc.getPropertiesParser());
211                BlueprintPropertiesResolver resolver = new BlueprintPropertiesResolver(pc.getPropertiesResolver(), parser);
212    
213                // no locations has been set, so its a default component
214                if (pc.getLocations() == null) {
215                    StringBuilder sb = new StringBuilder();
216                    String[] ids = parser.lookupPropertyPlaceholderIds();
217                    for (String id : ids) {
218                        sb.append("blueprint:").append(id).append(",");
219                    }
220                    // location supports multiple separated by comma
221                    pc.setLocation(sb.toString());
222                }
223    
224                if (pc.getLocations() != null) {
225                    // bridge camel properties with blueprint
226                    pc.setPropertiesParser(parser);
227                    pc.setPropertiesResolver(resolver);
228                }
229            }
230        }
231    
232        @Override
233        protected void initBeanPostProcessor(BlueprintCamelContext context) {
234        }
235    
236        @Override
237        protected void postProcessBeforeInit(RouteBuilder builder) {
238        }
239    
240        @Override
241        protected void findRouteBuildersByPackageScan(String[] packages, PackageScanFilter filter, List<RoutesBuilder> builders) throws Exception {
242            // add filter to class resolver which then will filter
243            getContext().getPackageScanClassResolver().addFilter(filter);
244            ClassLoader classLoader = new BundleDelegatingClassLoader(((ExtendedBlueprintContainer) blueprintContainer).getBundleContext().getBundle());
245            PackageScanRouteBuilderFinder finder = new PackageScanRouteBuilderFinder(getContext(), packages, classLoader,
246                                                                                     /*getBeanPostProcessor(),*/ getContext().getPackageScanClassResolver());
247            finder.appendBuilders(builders);
248    
249            // and remove the filter
250            getContext().getPackageScanClassResolver().removeFilter(filter);
251        }
252    
253        @Override
254        protected void findRouteBuildersByContextScan(PackageScanFilter filter, List<RoutesBuilder> builders) throws Exception {
255            ContextScanRouteBuilderFinder finder = new ContextScanRouteBuilderFinder(getContext(), filter);
256            finder.appendBuilders(builders);
257        }
258    
259        @Override
260        public void afterPropertiesSet() throws Exception {
261            super.afterPropertiesSet();
262            getContext().getManagementStrategy().addEventNotifier(new OsgiCamelContextPublisher(bundleContext));
263            try {
264                getClass().getClassLoader().loadClass("org.osgi.service.event.EventAdmin");
265                getContext().getManagementStrategy().addEventNotifier(new OsgiEventAdminNotifier(bundleContext));
266            } catch (Throwable t) {
267                // Ignore, if the EventAdmin package is not available, just don't use it
268                LOG.debug("EventAdmin package is not available, just don't use it");
269            }
270        }
271    
272        public String getDependsOn() {
273            return dependsOn;
274        }
275    
276        public void setDependsOn(String dependsOn) {
277            this.dependsOn = dependsOn;
278        }
279    
280        public String getAutoStartup() {
281            return autoStartup;
282        }
283    
284        public void setAutoStartup(String autoStartup) {
285            this.autoStartup = autoStartup;
286        }
287    
288        public String getUseMDCLogging() {
289            return useMDCLogging;
290        }
291    
292        public void setUseMDCLogging(String useMDCLogging) {
293            this.useMDCLogging = useMDCLogging;
294        }
295    
296        public Boolean getLazyLoadTypeConverters() {
297            return lazyLoadTypeConverters;
298        }
299    
300        public void setLazyLoadTypeConverters(Boolean lazyLoadTypeConverters) {
301            this.lazyLoadTypeConverters = lazyLoadTypeConverters;
302        }
303    
304        public ShutdownRoute getShutdownRoute() {
305            return shutdownRoute;
306        }
307    
308        public void setShutdownRoute(ShutdownRoute shutdownRoute) {
309            this.shutdownRoute = shutdownRoute;
310        }
311    
312        public ShutdownRunningTask getShutdownRunningTask() {
313            return shutdownRunningTask;
314        }
315    
316        public void setShutdownRunningTask(ShutdownRunningTask shutdownRunningTask) {
317            this.shutdownRunningTask = shutdownRunningTask;
318        }
319    
320        public CamelPropertyPlaceholderDefinition getCamelPropertyPlaceholder() {
321            return camelPropertyPlaceholder;
322        }
323    
324        public void setCamelPropertyPlaceholder(CamelPropertyPlaceholderDefinition camelPropertyPlaceholder) {
325            this.camelPropertyPlaceholder = camelPropertyPlaceholder;
326        }
327    
328        public List<RouteContextRefDefinition> getRouteRefs() {
329            return routeRefs;
330        }
331    
332        public void setRouteRefs(List<RouteContextRefDefinition> routeRefs) {
333            this.routeRefs = routeRefs;
334        }
335    
336        public List<CamelRedeliveryPolicyFactoryBean> getRedeliveryPolicies() {
337            return redeliveryPolicies;
338        }
339    
340        public void setRedeliveryPolicies(List<CamelRedeliveryPolicyFactoryBean> redeliveryPolicies) {
341            this.redeliveryPolicies = redeliveryPolicies;
342        }
343    
344        public List<ThreadPoolProfileDefinition> getThreadPoolProfiles() {
345            return threadPoolProfiles;
346        }
347    
348        public void setThreadPoolProfiles(List<ThreadPoolProfileDefinition> threadPoolProfiles) {
349            this.threadPoolProfiles = threadPoolProfiles;
350        }
351    
352        public List<CamelThreadPoolFactoryBean> getThreadPools() {
353            return threadPools;
354        }
355    
356        public void setThreadPools(List<CamelThreadPoolFactoryBean> threadPools) {
357            this.threadPools = threadPools;
358        }
359    
360        public String getTrace() {
361            return trace;
362        }
363    
364        public void setTrace(String trace) {
365            this.trace = trace;
366        }
367    
368        public String getStreamCache() {
369            return streamCache;
370        }
371    
372        public void setStreamCache(String streamCache) {
373            this.streamCache = streamCache;
374        }
375    
376        public String getDelayer() {
377            return delayer;
378        }
379    
380        public void setDelayer(String delayer) {
381            this.delayer = delayer;
382        }
383    
384        public String getHandleFault() {
385            return handleFault;
386        }
387    
388        public void setHandleFault(String handleFault) {
389            this.handleFault = handleFault;
390        }
391    
392        public String getErrorHandlerRef() {
393            return errorHandlerRef;
394        }
395    
396        public void setErrorHandlerRef(String errorHandlerRef) {
397            this.errorHandlerRef = errorHandlerRef;
398        }
399    
400        public PropertiesDefinition getProperties() {
401            return properties;
402        }
403    
404        public void setProperties(PropertiesDefinition properties) {
405            this.properties = properties;
406        }
407    
408        public String[] getPackages() {
409            return packages;
410        }
411    
412        public void setPackages(String[] packages) {
413            this.packages = packages;
414        }
415    
416        public PackageScanDefinition getPackageScan() {
417            return packageScan;
418        }
419    
420        public void setPackageScan(PackageScanDefinition packageScan) {
421            this.packageScan = packageScan;
422        }
423    
424        public ContextScanDefinition getContextScan() {
425            return contextScan;
426        }
427    
428        public void setContextScan(ContextScanDefinition contextScan) {
429            this.contextScan = contextScan;
430        }
431    
432        public CamelJMXAgentDefinition getCamelJMXAgent() {
433            return camelJMXAgent;
434        }
435    
436        public void setCamelJMXAgent(CamelJMXAgentDefinition camelJMXAgent) {
437            this.camelJMXAgent = camelJMXAgent;
438        }
439    
440        public List getBeans() {
441            return beans;
442        }
443    
444        public void setBeans(List beans) {
445            this.beans = beans;
446        }
447    
448        public List<RouteBuilderDefinition> getBuilderRefs() {
449            return builderRefs;
450        }
451    
452        public void setBuilderRefs(List<RouteBuilderDefinition> builderRefs) {
453            this.builderRefs = builderRefs;
454        }
455    
456        public List<CamelEndpointFactoryBean> getEndpoints() {
457            return endpoints;
458        }
459    
460        public void setEndpoints(List<CamelEndpointFactoryBean> endpoints) {
461            this.endpoints = endpoints;
462        }
463    
464        public DataFormatsDefinition getDataFormats() {
465            return dataFormats;
466        }
467    
468        public void setDataFormats(DataFormatsDefinition dataFormats) {
469            this.dataFormats = dataFormats;
470        }
471    
472        public List<OnExceptionDefinition> getOnExceptions() {
473            return onExceptions;
474        }
475    
476        public void setOnExceptions(List<OnExceptionDefinition> onExceptions) {
477            this.onExceptions = onExceptions;
478        }
479    
480        public List<OnCompletionDefinition> getOnCompletions() {
481            return onCompletions;
482        }
483    
484        public void setOnCompletions(List<OnCompletionDefinition> onCompletions) {
485            this.onCompletions = onCompletions;
486        }
487    
488        public List<InterceptDefinition> getIntercepts() {
489            return intercepts;
490        }
491    
492        public void setIntercepts(List<InterceptDefinition> intercepts) {
493            this.intercepts = intercepts;
494        }
495    
496        public List<InterceptFromDefinition> getInterceptFroms() {
497            return interceptFroms;
498        }
499    
500        public void setInterceptFroms(List<InterceptFromDefinition> interceptFroms) {
501            this.interceptFroms = interceptFroms;
502        }
503    
504        public List<InterceptSendToEndpointDefinition> getInterceptSendToEndpoints() {
505            return interceptSendToEndpoints;
506        }
507    
508        public void setInterceptSendToEndpoints(List<InterceptSendToEndpointDefinition> interceptSendToEndpoints) {
509            this.interceptSendToEndpoints = interceptSendToEndpoints;
510        }
511    
512        public List<RouteDefinition> getRoutes() {
513            return routes;
514        }
515    
516        public void setRoutes(List<RouteDefinition> routes) {
517            this.routes = routes;
518        }
519    
520        public boolean isImplicitId() {
521            return implicitId;
522        }
523        
524        public void setImplicitId(boolean flag) {
525            implicitId = flag;
526        }
527    
528        public Boolean getUseBlueprintPropertyResolver() {
529            return useBlueprintPropertyResolver;
530        }
531    
532        public void setUseBlueprintPropertyResolver(Boolean useBlueprintPropertyResolver) {
533            this.useBlueprintPropertyResolver = useBlueprintPropertyResolver;
534        }
535    
536        public boolean isUseBlueprintPropertyResolver() {
537            // enable by default
538            return useBlueprintPropertyResolver == null || useBlueprintPropertyResolver.booleanValue();
539        }
540    
541    }