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: 641676 $
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        public static SpringCamelContext springCamelContext(String configLocations) throws Exception {
081            return springCamelContext(new ClassPathXmlApplicationContext(configLocations));
082        }
083    
084        public void afterPropertiesSet() throws Exception {
085            start();
086        }
087    
088        public void destroy() throws Exception {
089            stop();
090        }
091    
092        public void onApplicationEvent(ApplicationEvent event) {
093            if (LOG.isDebugEnabled()) {
094                LOG.debug("Publishing event: " + event);
095            }
096    
097            if (event instanceof ContextRefreshedEvent) {
098                // now lets start the CamelContext so that all its possible
099                // dependencies are initailized
100                try {
101                    LOG.debug("Starting the CamelContext now that the ApplicationContext has started");
102                    start();
103                } catch (RuntimeException e) {
104                    throw e;
105                } catch (Exception e) {
106                    throw new RuntimeCamelException(e);
107                }
108                if (eventEndpoint != null) {
109                    eventEndpoint.onApplicationEvent(event);
110                }
111            } else {
112                if (eventEndpoint != null) {
113                    eventEndpoint.onApplicationEvent(event);
114                } else {
115                    LOG.warn("No eventEndpoint enabled for event: " + event);
116                }
117            }
118        }
119    
120        // Properties
121        // -----------------------------------------------------------------------
122    
123        public ApplicationContext getApplicationContext() {
124            return applicationContext;
125        }
126    
127        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
128            this.applicationContext = applicationContext;
129    
130            if (applicationContext instanceof ConfigurableApplicationContext) {
131                addComponent("event", new EventComponent(applicationContext));
132            }
133        }
134    
135        public EventEndpoint getEventEndpoint() {
136            return eventEndpoint;
137        }
138    
139        public void setEventEndpoint(EventEndpoint eventEndpoint) {
140            this.eventEndpoint = eventEndpoint;
141        }
142    
143        // Implementation methods
144        // -----------------------------------------------------------------------
145    
146        @Override
147        protected void doStart() throws Exception {
148            super.doStart();
149            if (eventEndpoint == null) {
150                eventEndpoint = createEventEndpoint();
151            }
152        }
153    
154        @Override
155        protected Injector createInjector() {
156            if (applicationContext instanceof ConfigurableApplicationContext) {
157                return new SpringInjector((ConfigurableApplicationContext)applicationContext);
158            } else {
159                LOG.warn("Cannot use SpringInjector as applicationContext is not a ConfigurableApplicationContext as its: "
160                          + applicationContext);
161                return super.createInjector();
162            }
163        }
164    
165        protected EventEndpoint createEventEndpoint() {
166            EventEndpoint endpoint = getEndpoint("event:default", EventEndpoint.class);
167            return endpoint;
168        }
169    
170        protected Endpoint convertBeanToEndpoint(String uri, Object bean) {
171            Processor processor = new BeanProcessor(bean, this);
172            return new ProcessorEndpoint(uri, this, processor);
173        }
174    
175        @Override
176        protected Registry createRegistry() {
177            return new ApplicationContextRegistry(getApplicationContext());
178        }
179    }