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://camel.apache.org/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: 747759 $
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 = ObjectHelper.getSystemProperty("shouldStartContext", Boolean.TRUE);
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 false.");
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 spring-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 wrapRuntimeCamelException(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 spring-event endpoint enabled for: " + 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("spring-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("spring-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            try {
191                Endpoint endpoint = getTypeConverter().convertTo(Endpoint.class, bean);
192                if (endpoint != null) {
193                    endpoint.setCamelContext(this);
194                    return endpoint;
195                }
196            } catch (NoTypeConversionAvailableException ex) {
197                // ignore, handled below
198            }
199    
200            return new ProcessorEndpoint(uri, this, new BeanProcessor(bean, this));
201        }
202    
203        @Override
204        protected Registry createRegistry() {
205            return new ApplicationContextRegistry(getApplicationContext());
206        }
207    
208        public void setShouldStartContext(boolean shouldStartContext) {
209            this.shouldStartContext = shouldStartContext;
210        }
211    
212        public boolean getShouldStartContext() {
213            return shouldStartContext;
214        }    
215        
216    }