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