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 */
017package org.apache.camel.blueprint;
018
019import java.io.IOException;
020import java.util.Map;
021import java.util.Properties;
022
023import org.apache.camel.TypeConverter;
024import org.apache.camel.blueprint.handler.CamelNamespaceHandler;
025import org.apache.camel.core.osgi.OsgiCamelContextHelper;
026import org.apache.camel.core.osgi.OsgiCamelContextPublisher;
027import org.apache.camel.core.osgi.OsgiFactoryFinderResolver;
028import org.apache.camel.core.osgi.OsgiTypeConverter;
029import org.apache.camel.core.osgi.utils.BundleContextUtils;
030import org.apache.camel.core.osgi.utils.BundleDelegatingClassLoader;
031import org.apache.camel.impl.DefaultCamelContext;
032import org.apache.camel.spi.EventNotifier;
033import org.apache.camel.spi.FactoryFinder;
034import org.apache.camel.spi.ModelJAXBContextFactory;
035import org.apache.camel.spi.Registry;
036import org.apache.camel.util.LoadPropertiesException;
037import org.osgi.framework.BundleContext;
038import org.osgi.framework.ServiceEvent;
039import org.osgi.framework.ServiceListener;
040import org.osgi.framework.ServiceRegistration;
041import org.osgi.service.blueprint.container.BlueprintContainer;
042import org.osgi.service.blueprint.container.BlueprintEvent;
043import org.osgi.service.blueprint.container.BlueprintListener;
044import org.slf4j.Logger;
045import org.slf4j.LoggerFactory;
046
047/**
048 * OSGi Blueprint based {@link org.apache.camel.CamelContext}.
049 */
050public class BlueprintCamelContext extends DefaultCamelContext implements ServiceListener, BlueprintListener {
051
052    private static final Logger LOG = LoggerFactory.getLogger(BlueprintCamelContext.class);
053    
054    private BundleContext bundleContext;
055    private BlueprintContainer blueprintContainer;
056    private ServiceRegistration<?> registration;
057
058    public BlueprintCamelContext() {
059    }
060
061    public BlueprintCamelContext(BundleContext bundleContext, BlueprintContainer blueprintContainer) {
062        this.bundleContext = bundleContext;
063        this.blueprintContainer = blueprintContainer;
064
065        // inject common osgi
066        OsgiCamelContextHelper.osgiUpdate(this, bundleContext);
067
068        // and these are blueprint specific
069        setComponentResolver(new BlueprintComponentResolver(bundleContext));
070        setLanguageResolver(new BlueprintLanguageResolver(bundleContext));
071        setDataFormatResolver(new BlueprintDataFormatResolver(bundleContext));
072        setApplicationContextClassLoader(new BundleDelegatingClassLoader(bundleContext.getBundle()));
073    }
074
075    @Override
076    protected ModelJAXBContextFactory createModelJAXBContextFactory() {
077        // must use classloader of the namespace handler
078        return new BlueprintModelJAXBContextFactory(CamelNamespaceHandler.class.getClassLoader());
079    }
080
081    public BundleContext getBundleContext() {
082        return bundleContext;
083    }
084
085    public void setBundleContext(BundleContext bundleContext) {
086        this.bundleContext = bundleContext;
087    }
088
089    public BlueprintContainer getBlueprintContainer() {
090        return blueprintContainer;
091    }
092
093    public void setBlueprintContainer(BlueprintContainer blueprintContainer) {
094        this.blueprintContainer = blueprintContainer;
095    }
096   
097    public void init() throws Exception {
098        LOG.trace("init {}", this);
099
100        // add service listener so we can be notified when blueprint container is done
101        // and we would be ready to start CamelContext
102        bundleContext.addServiceListener(this);
103        // add blueprint listener as service, as we need this for the blueprint container
104        // to support change events when it changes states
105        registration = bundleContext.registerService(BlueprintListener.class, this, null);
106    }
107
108    public void destroy() throws Exception {
109        LOG.trace("destroy {}", this);
110
111        // remove listener and stop this CamelContext
112        try {
113            bundleContext.removeServiceListener(this);
114        } catch (Exception e) {
115            LOG.warn("Error removing ServiceListener " + this + ". This exception is ignored.", e);
116        }
117        if (registration != null) {
118            try {
119                registration.unregister();
120            } catch (Exception e) {
121                LOG.warn("Error unregistering service registration " + registration + ". This exception is ignored.", e);
122            }
123            registration = null;
124        }
125
126        // must stop Camel
127        stop();
128    }
129
130    @Override
131    public Map<String, Properties> findComponents() throws LoadPropertiesException, IOException {
132        return BundleContextUtils.findComponents(bundleContext, this);
133    }
134
135    @Override
136    public String getComponentDocumentation(String componentName) throws IOException {
137        return BundleContextUtils.getComponentDocumentation(bundleContext, this, componentName);
138    }
139
140    @Override
141    public void blueprintEvent(BlueprintEvent event) {
142        // noop as we just needed to enlist the BlueprintListener to have events triggered to serviceChanged method
143    }
144
145    @Override
146    public void serviceChanged(ServiceEvent event) {
147        if (LOG.isDebugEnabled()) {
148            LOG.debug("Service {} changed to {}", event, event.getType());
149        }
150        // look for blueprint container to be registered, and then we can start the CamelContext
151        if (event.getType() == ServiceEvent.REGISTERED
152                && event.getServiceReference().isAssignableTo(bundleContext.getBundle(), "org.osgi.service.blueprint.container.BlueprintContainer")
153                && bundleContext.getBundle().equals(event.getServiceReference().getBundle())) {
154            try {
155                maybeStart();
156            } catch (Exception e) {
157                LOG.error("Error occurred during starting Camel: " + this + " due " + e.getMessage(), e);
158            }
159        }
160    }
161
162    @Override
163    protected TypeConverter createTypeConverter() {
164        // CAMEL-3614: make sure we use a bundle context which imports org.apache.camel.impl.converter package
165        BundleContext ctx = BundleContextUtils.getBundleContext(getClass());
166        if (ctx == null) {
167            ctx = bundleContext;
168        }
169        FactoryFinder finder = new OsgiFactoryFinderResolver(bundleContext).resolveDefaultFactoryFinder(getClassResolver());
170        return new OsgiTypeConverter(ctx, this, getInjector(), finder);
171    }
172
173    @Override
174    protected Registry createRegistry() {
175        Registry reg = new BlueprintContainerRegistry(getBlueprintContainer());
176        return OsgiCamelContextHelper.wrapRegistry(this, reg, bundleContext);
177    }
178    
179    @Override
180    public void start() throws Exception {
181        final ClassLoader original = Thread.currentThread().getContextClassLoader();
182        try {
183            // let's set a more suitable TCCL while starting the context
184            Thread.currentThread().setContextClassLoader(getApplicationContextClassLoader());
185            super.start();
186        } finally {
187            Thread.currentThread().setContextClassLoader(original);
188        }
189    }
190
191    private void maybeStart() throws Exception {
192        LOG.trace("maybeStart: {}", this);
193
194        // allow to register the BluerintCamelContext eager in the OSGi Service Registry, which ex is needed
195        // for unit testing with camel-test-blueprint
196        boolean eager = "true".equalsIgnoreCase(System.getProperty("registerBlueprintCamelContextEager"));
197        if (eager) {
198            for (EventNotifier notifier : getManagementStrategy().getEventNotifiers()) {
199                if (notifier instanceof OsgiCamelContextPublisher) {
200                    OsgiCamelContextPublisher publisher = (OsgiCamelContextPublisher) notifier;
201                    publisher.registerCamelContext(this);
202                    break;
203                }
204            }
205        }
206
207        // for example from unit testing we want to start Camel later and not
208        // when blueprint loading the bundle
209        boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"));
210        if (skip) {
211            LOG.trace("maybeStart: {} is skipping as System property skipStartingCamelContext is set", this);
212            return;
213        }
214
215        if (!isStarted() && !isStarting()) {
216            LOG.debug("Starting {}", this);
217            start();
218        } else {
219            // ignore as Camel is already started
220            LOG.trace("Ignoring maybeStart() as {} is already started", this);
221        }
222    }
223
224}