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 implicity installed and configured for you. So you should never have to
057     * explicitly create or configure one of these instances.
058     *
059     * @version $Revision: 788297 $
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) {
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         * A strategy method to allow implementations to perform some custom JBI
176         * based injection of the POJO
177         *
178         * @param bean the bean to be injected
179         */
180        protected void injectFields(final Object bean) {
181            ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
182                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
183                    EndpointInject endpointInject = field.getAnnotation(EndpointInject.class);
184                    if (endpointInject != null && postProcessor.matchContext(endpointInject.context())) {
185                        injectField(field, endpointInject.uri(), endpointInject.name(), bean);
186                    }
187    
188                    Produce produce = field.getAnnotation(Produce.class);
189                    if (produce != null && postProcessor.matchContext(produce.context())) {
190                        injectField(field, produce.uri(), produce.ref(), bean);
191                    }
192                }
193            });
194        }
195    
196        protected void injectField(Field field, String endpointUri, String endpointRef, Object bean) {
197            ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName()));
198        }
199    
200        protected void injectMethods(final Object bean) {
201            ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
202                @SuppressWarnings("unchecked")
203                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
204                    setterInjection(method, bean);
205                    getPostProcessor().consumerInjection(method, bean);
206                }
207            });
208        }
209    
210        protected void setterInjection(Method method, Object bean) {
211            EndpointInject endpointInject = method.getAnnotation(EndpointInject.class);
212            if (endpointInject != null && postProcessor.matchContext(endpointInject.context())) {
213                setterInjection(method, bean, endpointInject.uri(), endpointInject.name());
214            }
215    
216            Produce produce = method.getAnnotation(Produce.class);
217            if (produce != null && postProcessor.matchContext(produce.context())) {
218                setterInjection(method, bean, produce.uri(), produce.ref());
219            }
220        }
221    
222        protected void setterInjection(Method method, Object bean, String endpointUri, String endpointRef) {
223            Class<?>[] parameterTypes = method.getParameterTypes();
224            if (parameterTypes != null) {
225                if (parameterTypes.length != 1) {
226                    LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method);
227                } else {
228                    String propertyName = ObjectHelper.getPropertyName(method);
229                    Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName);
230                    ObjectHelper.invokeMethod(method, bean, value);
231                }
232            }
233        }
234    
235        public CamelPostProcessorHelper getPostProcessor() {
236            ObjectHelper.notNull(postProcessor, "postProcessor");
237            return postProcessor;
238        }
239    
240    }