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.spring;
018    
019    import org.apache.camel.Endpoint;
020    import org.apache.camel.Processor;
021    import org.apache.camel.RuntimeCamelException;
022    import org.apache.camel.component.bean.BeanProcessor;
023    import org.apache.camel.component.event.EventComponent;
024    import org.apache.camel.component.event.EventEndpoint;
025    import org.apache.camel.impl.DefaultCamelContext;
026    import org.apache.camel.impl.ProcessorEndpoint;
027    import org.apache.camel.spi.Injector;
028    import org.apache.camel.spi.Registry;
029    import org.apache.camel.spring.spi.ApplicationContextRegistry;
030    import org.apache.camel.spring.spi.SpringInjector;
031    import org.apache.camel.util.ObjectHelper;
032    import org.apache.commons.logging.Log;
033    import org.apache.commons.logging.LogFactory;
034    import org.springframework.beans.BeansException;
035    import org.springframework.beans.factory.DisposableBean;
036    import org.springframework.beans.factory.InitializingBean;
037    import org.springframework.context.ApplicationContext;
038    import org.springframework.context.ApplicationContextAware;
039    import org.springframework.context.ApplicationEvent;
040    import org.springframework.context.ApplicationListener;
041    import org.springframework.context.ConfigurableApplicationContext;
042    import org.springframework.context.event.ContextRefreshedEvent;
043    import org.springframework.context.support.ClassPathXmlApplicationContext;
044    
045    /**
046     * A Spring aware implementation of {@link org.apache.camel.CamelContext} which
047     * will automatically register itself with Springs lifecycle methods plus allows
048     * spring to be used to customize a any <a
049     * href="http://activemq.apache.org/camel/type-converter.html">Type Converters</a>
050     * as well as supporting accessing components and beans via the Spring
051     * {@link ApplicationContext}
052     *
053     * @version $Revision: 46148 $
054     */
055    public class SpringCamelContext extends DefaultCamelContext implements InitializingBean, DisposableBean,
056        ApplicationContextAware, ApplicationListener {
057        private static final transient Log LOG = LogFactory.getLog(SpringCamelContext.class);
058        private ApplicationContext applicationContext;
059        private EventEndpoint eventEndpoint;
060        private boolean shouldStartContext = 
061            ObjectHelper.getSystemProperty("shouldStartContext", Boolean.TRUE); // start context by default 
062    
063        public SpringCamelContext() {
064        }
065    
066        public SpringCamelContext(ApplicationContext applicationContext) {
067            setApplicationContext(applicationContext);
068        }
069    
070        public static SpringCamelContext springCamelContext(ApplicationContext applicationContext)
071            throws Exception {
072            // lets try and look up a configured camel context in the context
073            String[] names = applicationContext.getBeanNamesForType(SpringCamelContext.class);
074            if (names.length == 1) {
075                return (SpringCamelContext)applicationContext.getBean(names[0], SpringCamelContext.class);
076            }
077            SpringCamelContext answer = new SpringCamelContext();
078            answer.setApplicationContext(applicationContext);
079            answer.afterPropertiesSet();
080            return answer;
081        }
082            
083    
084        public static SpringCamelContext springCamelContext(String configLocations) throws Exception {
085            return springCamelContext(new ClassPathXmlApplicationContext(configLocations));
086        }
087    
088        public void afterPropertiesSet() throws Exception {
089            maybeStart();
090        }
091    
092        private void maybeStart() throws Exception {
093            if (getShouldStartContext()) {     
094                LOG.debug("Starting the CamelContext now that the ApplicationContext has started");
095                start();
096            } else {
097                LOG.debug("Not starting the CamelContext since shouldStartContext property was true.");
098            }
099        }
100    
101        public void destroy() throws Exception {
102            stop();
103        }
104    
105        public void onApplicationEvent(ApplicationEvent event) {
106            if (LOG.isDebugEnabled()) {
107                LOG.debug("Publishing event: " + event);
108            }
109    
110            if (event instanceof ContextRefreshedEvent) {
111                // now lets start the CamelContext so that all its possible
112                // dependencies are initialized
113                try {
114                    maybeStart();
115                } catch (RuntimeException e) {
116                    throw e;
117                } catch (Exception e) {
118                    throw new RuntimeCamelException(e);
119                }
120                if (eventEndpoint != null) {
121                    eventEndpoint.onApplicationEvent(event);
122                }
123            } else {
124                if (eventEndpoint != null) {
125                    eventEndpoint.onApplicationEvent(event);
126                } else {
127                    LOG.warn("No eventEndpoint enabled for event: " + event);
128                }
129            }
130        }
131    
132        // Properties
133        // -----------------------------------------------------------------------
134    
135        public ApplicationContext getApplicationContext() {
136            return applicationContext;
137        }
138    
139        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
140            this.applicationContext = applicationContext;
141    
142            if (applicationContext instanceof ConfigurableApplicationContext) {
143                addComponent("event", new EventComponent(applicationContext));
144            }
145        }
146    
147        public EventEndpoint getEventEndpoint() {
148            return eventEndpoint;
149        }
150    
151        public void setEventEndpoint(EventEndpoint eventEndpoint) {
152            this.eventEndpoint = eventEndpoint;
153        }
154    
155        // Implementation methods
156        // -----------------------------------------------------------------------
157    
158        @Override
159        protected void doStart() throws Exception {
160            maybeDoStart();
161        }
162    
163        protected void maybeDoStart() throws Exception {
164            if (getShouldStartContext()) {
165                super.doStart();
166                if (eventEndpoint == null) {
167                    eventEndpoint = createEventEndpoint();
168                }
169            }
170        }   
171        
172        @Override
173        protected Injector createInjector() {
174            if (applicationContext instanceof ConfigurableApplicationContext) {
175                return new SpringInjector((ConfigurableApplicationContext)applicationContext);
176            } else {
177                LOG.warn("Cannot use SpringInjector as applicationContext is not a ConfigurableApplicationContext as its: "
178                          + applicationContext);
179                return super.createInjector();
180            }
181        }
182    
183        protected EventEndpoint createEventEndpoint() {
184            EventEndpoint endpoint = getEndpoint("event:default", EventEndpoint.class);
185            return endpoint;
186        }
187    
188        protected Endpoint convertBeanToEndpoint(String uri, Object bean) {
189            //We will use the type convert to build the endpoint first
190            Endpoint endpoint = getTypeConverter().convertTo(Endpoint.class, bean);
191            if (endpoint != null) {
192                endpoint.setCamelContext(this);
193                return endpoint;
194            }
195            Processor processor = new BeanProcessor(bean, this);
196            return new ProcessorEndpoint(uri, this, processor);
197        }
198    
199        @Override
200        protected Registry createRegistry() {
201            return new ApplicationContextRegistry(getApplicationContext());
202        }
203    
204        public void setShouldStartContext(boolean shouldStartContext) {
205            this.shouldStartContext = shouldStartContext;
206        }
207    
208        public boolean getShouldStartContext() {
209            return shouldStartContext;
210        }
211    }