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: 749562 $
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    
072        public CamelBeanPostProcessor() {
073        }
074    
075        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
076            injectFields(bean);
077            injectMethods(bean);
078            if (bean instanceof CamelContextAware) {
079                CamelContextAware contextAware = (CamelContextAware)bean;
080                if (camelContext == null) {
081                    LOG.warn("No CamelContext defined yet so cannot inject into: " + bean);
082                } else {
083                    contextAware.setCamelContext(camelContext);
084                }
085            }
086            return bean;
087        }
088    
089        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
090            if (bean instanceof DefaultEndpoint) {
091                DefaultEndpoint defaultEndpoint = (DefaultEndpoint) bean;
092                defaultEndpoint.setEndpointUriIfNotSpecified(beanName);
093            }
094            return bean;
095        }
096    
097        // Properties
098        // -------------------------------------------------------------------------
099    
100        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
101            this.applicationContext = applicationContext;
102        }
103    
104        public CamelContext getCamelContext() {
105            return camelContext;
106        }
107    
108        public void setCamelContext(CamelContext camelContext) {
109            this.camelContext = camelContext;
110            postProcessor = new CamelPostProcessorHelper(camelContext) {
111                @Override
112                protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) {
113                    return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e);
114                }
115            };
116        }
117    
118        // Implementation methods
119        // -------------------------------------------------------------------------
120    
121        /**
122         * A strategy method to allow implementations to perform some custom JBI
123         * based injection of the POJO
124         *
125         * @param bean the bean to be injected
126         */
127        protected void injectFields(final Object bean) {
128            ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
129                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
130                    EndpointInject annotation = field.getAnnotation(EndpointInject.class);
131                    if (annotation != null) {
132                        injectField(field, annotation.uri(), annotation.name(), bean);
133                    }
134                    Produce produce = field.getAnnotation(Produce.class);
135                    if (produce != null) {
136                        injectField(field, produce.uri(), produce.ref(), bean);
137                    }
138                }
139            });
140        }
141    
142        protected void injectField(Field field, String endpointUri, String endpointRef, Object bean) {
143            ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName()));
144        }
145    
146        protected void injectMethods(final Object bean) {
147            ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
148                @SuppressWarnings("unchecked")
149                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
150                    setterInjection(method, bean);
151                    getPostProcessor().consumerInjection(method, bean);
152                }
153            });
154        }
155    
156        protected void setterInjection(Method method, Object bean) {
157            EndpointInject annoation = method.getAnnotation(EndpointInject.class);
158            if (annoation != null) {
159                setterInjection(method, bean, annoation.uri(), annoation.name());
160            }
161            Produce produce = method.getAnnotation(Produce.class);
162            if (produce != null) {
163                setterInjection(method, bean, produce.uri(), produce.ref());
164            }
165        }
166    
167        protected void setterInjection(Method method, Object bean, String endpointUri, String endpointRef) {
168            Class<?>[] parameterTypes = method.getParameterTypes();
169            if (parameterTypes != null) {
170                if (parameterTypes.length != 1) {
171                    LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method);
172                } else {
173                    String propertyName = ObjectHelper.getPropertyName(method);
174                    Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName);
175                    ObjectHelper.invokeMethod(method, bean, value);
176                }
177            }
178        }
179    
180        public CamelPostProcessorHelper getPostProcessor() {
181            ObjectHelper.notNull(postProcessor, "postProcessor");
182            return postProcessor;
183        }
184    }