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