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