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 java.lang.reflect.Field;
020    import java.lang.reflect.Method;
021    import java.util.LinkedHashSet;
022    import java.util.Set;
023    
024    import javax.xml.bind.annotation.XmlAccessType;
025    import javax.xml.bind.annotation.XmlAccessorType;
026    import javax.xml.bind.annotation.XmlRootElement;
027    import javax.xml.bind.annotation.XmlTransient;
028    
029    import org.apache.camel.CamelContext;
030    import org.apache.camel.CamelContextAware;
031    import org.apache.camel.Endpoint;
032    import org.apache.camel.EndpointInject;
033    import org.apache.camel.Produce;
034    import org.apache.camel.Service;
035    import org.apache.camel.core.xml.CamelJMXAgentDefinition;
036    import org.apache.camel.impl.CamelPostProcessorHelper;
037    import org.apache.camel.impl.DefaultEndpoint;
038    import org.apache.camel.spring.util.ReflectionUtils;
039    import org.apache.camel.util.ObjectHelper;
040    import org.apache.camel.util.ServiceHelper;
041    import org.slf4j.Logger;
042    import org.slf4j.LoggerFactory;
043    import org.springframework.beans.BeanInstantiationException;
044    import org.springframework.beans.BeansException;
045    import org.springframework.beans.factory.config.BeanPostProcessor;
046    import org.springframework.context.ApplicationContext;
047    import org.springframework.context.ApplicationContextAware;
048    
049    /**
050     * A bean post processor which implements the <a href="http://camel.apache.org/bean-integration.html">Bean Integration</a>
051     * features in Camel. Features such as the <a href="http://camel.apache.org/bean-injection.html">Bean Injection</a> of objects like
052     * {@link Endpoint} and
053     * {@link org.apache.camel.ProducerTemplate} together with support for
054     * <a href="http://camel.apache.org/pojo-consuming.html">POJO Consuming</a> via the
055     * {@link org.apache.camel.Consume} annotation along with
056     * <a href="http://camel.apache.org/pojo-producing.html">POJO Producing</a> via the
057     * {@link org.apache.camel.Produce} annotation along with other annotations such as
058     * {@link org.apache.camel.DynamicRouter} for creating <a href="http://camel.apache.org/dynamicrouter-annotation.html">a Dynamic router via annotations</a>.
059     * {@link org.apache.camel.RecipientList} for creating <a href="http://camel.apache.org/recipientlist-annotation.html">a Recipient List router via annotations</a>.
060     * {@link org.apache.camel.RoutingSlip} for creating <a href="http://camel.apache.org/routingslip-annotation.html">a Routing Slip router via annotations</a>.
061     * <p>
062     * If you use the &lt;camelContext&gt; element in your <a href="http://camel.apache.org/spring.html">Spring XML</a>
063     * then one of these bean post processors is implicitly installed and configured for you. So you should never have to
064     * explicitly create or configure one of these instances.
065     *
066     * @version 
067     */
068    @XmlRootElement(name = "beanPostProcessor")
069    @XmlAccessorType(XmlAccessType.FIELD)
070    public class CamelBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
071        private static final transient Logger LOG = LoggerFactory.getLogger(CamelBeanPostProcessor.class);
072        @XmlTransient
073        Set<String> prototypeBeans = new LinkedHashSet<String>();
074        @XmlTransient
075        private CamelContext camelContext;
076        @XmlTransient
077        private ApplicationContext applicationContext;
078        @XmlTransient
079        private CamelPostProcessorHelper postProcessor;
080        @XmlTransient
081        private String camelId;
082    
083        public CamelBeanPostProcessor() {
084        }
085    
086        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
087            LOG.trace("Camel bean processing before initialization for bean: {}", beanName);
088    
089            // some beans cannot be post processed at this given time, so we gotta check beforehand
090            if (!canPostProcessBean(bean, beanName)) {
091                return bean;
092            }
093    
094            injectFields(bean, beanName);
095            injectMethods(bean, beanName);
096    
097            if (bean instanceof CamelContextAware && canSetCamelContext(bean, beanName)) {
098                CamelContextAware contextAware = (CamelContextAware)bean;
099                CamelContext context = getOrLookupCamelContext();
100                if (context == null) {
101                    LOG.warn("No CamelContext defined yet so cannot inject into bean: " + beanName);
102                } else {
103                    contextAware.setCamelContext(context);
104                }
105            }
106    
107            return bean;
108        }
109    
110        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
111            LOG.trace("Camel bean processing after initialization for bean: {}", beanName);
112    
113            // some beans cannot be post processed at this given time, so we gotta check beforehand
114            if (!canPostProcessBean(bean, beanName)) {
115                return bean;
116            }
117    
118            if (bean instanceof DefaultEndpoint) {
119                DefaultEndpoint defaultEndpoint = (DefaultEndpoint) bean;
120                defaultEndpoint.setEndpointUriIfNotSpecified(beanName);
121            }
122    
123            return bean;
124        }
125    
126        // Properties
127        // -------------------------------------------------------------------------
128    
129        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
130            this.applicationContext = applicationContext;
131        }
132    
133        public CamelContext getCamelContext() {
134            return camelContext;
135        }
136    
137        public void setCamelContext(CamelContext camelContext) {
138            this.camelContext = camelContext;
139        }
140    
141        public String getCamelId() {
142            return camelId;
143        }
144    
145        public void setCamelId(String camelId) {
146            this.camelId = camelId;
147        }
148    
149        // Implementation methods
150        // -------------------------------------------------------------------------
151    
152        /**
153         * Can we post process the given bean?
154         *
155         * @param bean the bean
156         * @param beanName the bean name
157         * @return true to process it
158         */
159        protected boolean canPostProcessBean(Object bean, String beanName) {
160            // the JMXAgent is a bit strange and causes Spring issues if we let it being
161            // post processed by this one. It does not need it anyway so we are good to go.
162            // We should also avoid to process the null object bean (in Spring 2.5.x) 
163            if (bean == null || bean instanceof CamelJMXAgentDefinition) {
164                return false;
165            }
166    
167            // all other beans can of course be processed
168            return true;
169        }
170        
171        
172        protected boolean canSetCamelContext(Object bean, String beanName) {
173            if (bean instanceof CamelContextAware) {
174                CamelContextAware camelContextAware = (CamelContextAware) bean;
175                CamelContext context = camelContextAware.getCamelContext();
176                if (context != null) {
177                    LOG.trace("CamelContext already set on bean with id [{}]. Will keep existing CamelContext on bean.", beanName);
178                    return false;
179                }
180            }
181    
182            return true;
183        }
184    
185        /**
186         * A strategy method to allow implementations to perform some custom JBI
187         * based injection of the POJO
188         *
189         * @param bean the bean to be injected
190         */
191        protected void injectFields(final Object bean, final String beanName) {
192            ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
193                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
194                    EndpointInject endpointInject = field.getAnnotation(EndpointInject.class);
195                    if (endpointInject != null && getPostProcessor().matchContext(endpointInject.context())) {
196                        injectField(field, endpointInject.uri(), endpointInject.ref(), bean, beanName);
197                    }
198    
199                    Produce produce = field.getAnnotation(Produce.class);
200                    if (produce != null && getPostProcessor().matchContext(produce.context())) {
201                        injectField(field, produce.uri(), produce.ref(), bean, beanName);
202                    }
203                }
204            });
205        }
206    
207        protected void injectField(Field field, String endpointUri, String endpointRef, Object bean, String beanName) {
208            ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName(), bean, beanName));
209        }
210    
211        protected void injectMethods(final Object bean, final String beanName) {
212            ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {           
213                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
214                    setterInjection(method, bean, beanName);
215                    getPostProcessor().consumerInjection(method, bean, beanName);
216                }
217            });
218        }
219    
220        protected void setterInjection(Method method, Object bean, String beanName) {
221            EndpointInject endpointInject = method.getAnnotation(EndpointInject.class);
222            if (endpointInject != null && getPostProcessor().matchContext(endpointInject.context())) {
223                setterInjection(method, bean, beanName, endpointInject.uri(), endpointInject.ref());
224            }
225    
226            Produce produce = method.getAnnotation(Produce.class);
227            if (produce != null && getPostProcessor().matchContext(produce.context())) {
228                setterInjection(method, bean, beanName, produce.uri(), produce.ref());
229            }
230        }
231    
232        protected void setterInjection(Method method, Object bean, String beanName, String endpointUri, String endpointRef) {
233            Class<?>[] parameterTypes = method.getParameterTypes();
234            if (parameterTypes != null) {
235                if (parameterTypes.length != 1) {
236                    LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method);
237                } else {
238                    String propertyName = ObjectHelper.getPropertyName(method);
239                    Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName, bean, beanName);
240                    ObjectHelper.invokeMethod(method, bean, value);
241                }
242            }
243        }
244    
245        protected CamelContext getOrLookupCamelContext() {
246            if (camelContext == null && applicationContext.containsBean(camelId)) {
247                camelContext = applicationContext.getBean(camelId, CamelContext.class);
248            }
249            return camelContext;
250        }
251    
252        public CamelPostProcessorHelper getPostProcessor() {
253            // lets lazily create the post processor
254            if (postProcessor == null) {
255                postProcessor = new CamelPostProcessorHelper() {
256    
257                    @Override
258                    public CamelContext getCamelContext() {
259                        // lets lazily lookup the camel context here
260                        // as doing this will cause this context to be started immediately
261                        // breaking the lifecycle ordering of different camel contexts
262                        // so we only want to do this on demand
263                        return getOrLookupCamelContext();
264                    }
265    
266                    @Override
267                    protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) {
268                        return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e);
269                    }
270    
271                    protected boolean isSingleton(Object bean, String beanName) {
272                        // no application context has been injected which means the bean
273                        // has not been enlisted in Spring application context
274                        if (applicationContext == null || beanName == null) {
275                            return super.isSingleton(bean, beanName);
276                        } else {
277                            return applicationContext.isSingleton(beanName);
278                        }
279                    }
280    
281                    protected void startService(Service service, Object bean, String beanName) throws Exception {
282                        if (isSingleton(bean, beanName)) {
283                            getCamelContext().addService(service);
284                        } else {
285                            // only start service and do not add it to CamelContext
286                            ServiceHelper.startService(service);
287                            if (prototypeBeans.add(beanName)) {
288                                // do not spam the log with WARN so do this only once per bean name
289                                LOG.warn("The bean with id [" + beanName + "] is prototype scoped and cannot stop the injected service when bean is destroyed: "
290                                        + service + ". You may want to stop the service manually from the bean.");
291                            }
292                        }
293                    }
294                };
295            }
296            return postProcessor;
297        }
298    
299    }