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