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