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