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.CamelContextAware;
028    import org.apache.camel.Endpoint;
029    import org.apache.camel.EndpointInject;
030    import org.apache.camel.Produce;
031    import org.apache.camel.impl.CamelPostProcessorHelper;
032    import org.apache.camel.impl.DefaultEndpoint;
033    import org.apache.camel.spring.util.ReflectionUtils;
034    import org.apache.camel.util.ObjectHelper;
035    import org.apache.commons.logging.Log;
036    import org.apache.commons.logging.LogFactory;
037    import org.springframework.beans.BeanInstantiationException;
038    import org.springframework.beans.BeansException;
039    import org.springframework.beans.factory.config.BeanPostProcessor;
040    import org.springframework.context.ApplicationContext;
041    import org.springframework.context.ApplicationContextAware;
042    
043    /**
044     * A bean post processor which implements the <a href="http://activemq.apache.org/camel/bean-integration.html">Bean Integration</a>
045     * features in Camel such as the <a href="http://activemq.apache.org/camel/bean-injection.html">Bean Injection</a> of objects like
046     * {@link Endpoint} and
047     * {@link org.apache.camel.ProducerTemplate} together with support for
048     * <a href="http://activemq.apache.org/camel/pojo-consuming.html">POJO Consuming</a> via the 
049     * {@link org.apache.camel.Consume} and {@link org.apache.camel.MessageDriven} annotations along with
050     * <a href="http://activemq.apache.org/camel/pojo-producing.html">POJO Producing</a> via the
051     * {@link org.apache.camel.Produce} annotation along with other annotations such as
052     * {@link org.apache.camel.RecipientList} for creating <a href="http://activemq.apache.org/camel/recipientlist-annotation.html">a Recipient List router via annotations</a>.
053     * <p>
054     * If you use the &lt;camelContext&gt; element in your <a href="http://activemq.apache.org/camel/spring.html">Spring XML</a> 
055     * then one of these bean post processors is implicity installed and configured for you. So you should never have to
056     * explicitly create or configure one of these instances.
057     *
058     * @version $Revision: 747697 $
059     */
060    @XmlRootElement(name = "beanPostProcessor")
061    @XmlAccessorType(XmlAccessType.FIELD)
062    public class CamelBeanPostProcessor implements BeanPostProcessor, ApplicationContextAware {
063        private static final transient Log LOG = LogFactory.getLog(CamelBeanPostProcessor.class);
064        @XmlTransient
065        private SpringCamelContext camelContext;
066        @XmlTransient
067        private ApplicationContext applicationContext;
068        @XmlTransient
069        private CamelPostProcessorHelper postProcessor;
070    
071        public CamelBeanPostProcessor() {
072        }
073    
074        public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
075            injectFields(bean);
076            injectMethods(bean);
077            if (bean instanceof CamelContextAware) {
078                CamelContextAware contextAware = (CamelContextAware)bean;
079                if (camelContext == null) {
080                    LOG.warn("No CamelContext defined yet so cannot inject into: " + bean);
081                } else {
082                    contextAware.setCamelContext(camelContext);
083                }
084            }
085            return bean;
086        }
087    
088        public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
089            if (bean instanceof DefaultEndpoint) {
090                DefaultEndpoint defaultEndpoint = (DefaultEndpoint) bean;
091                defaultEndpoint.setEndpointUriIfNotSpecified(beanName);
092            }
093            return bean;
094        }
095    
096        // Properties
097        // -------------------------------------------------------------------------
098    
099        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
100            this.applicationContext = applicationContext;
101        }
102    
103        public SpringCamelContext getCamelContext() {
104            return camelContext;
105        }
106    
107        public void setCamelContext(SpringCamelContext camelContext) {
108            this.camelContext = camelContext;
109            postProcessor = new CamelPostProcessorHelper(camelContext) {
110                @Override
111                protected RuntimeException createProxyInstantiationRuntimeException(Class<?> type, Endpoint endpoint, Exception e) {
112                    return new BeanInstantiationException(type, "Could not instantiate proxy of type " + type.getName() + " on endpoint " + endpoint, e);
113                }
114            };
115        }
116    
117        // Implementation methods
118        // -------------------------------------------------------------------------
119    
120        /**
121         * A strategy method to allow implementations to perform some custom JBI
122         * based injection of the POJO
123         *
124         * @param bean the bean to be injected
125         */
126        protected void injectFields(final Object bean) {
127            ReflectionUtils.doWithFields(bean.getClass(), new ReflectionUtils.FieldCallback() {
128                public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
129                    EndpointInject annotation = field.getAnnotation(EndpointInject.class);
130                    if (annotation != null) {
131                        injectField(field, annotation.uri(), annotation.name(), bean);
132                    }
133                    Produce produce = field.getAnnotation(Produce.class);
134                    if (produce != null) {
135                        injectField(field, produce.uri(), produce.ref(), bean);
136                    }
137                }
138            });
139        }
140    
141        protected void injectField(Field field, String endpointUri, String endpointRef, Object bean) {
142            ReflectionUtils.setField(field, bean, getPostProcessor().getInjectionValue(field.getType(), endpointUri, endpointRef, field.getName()));
143        }
144    
145        protected void injectMethods(final Object bean) {
146            ReflectionUtils.doWithMethods(bean.getClass(), new ReflectionUtils.MethodCallback() {
147                @SuppressWarnings("unchecked")
148                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
149                    setterInjection(method, bean);
150                    getPostProcessor().consumerInjection(method, bean);
151                }
152            });
153        }
154    
155        protected void setterInjection(Method method, Object bean) {
156            EndpointInject annoation = method.getAnnotation(EndpointInject.class);
157            if (annoation != null) {
158                setterInjection(method, bean, annoation.uri(), annoation.name());
159            }
160            Produce produce = method.getAnnotation(Produce.class);
161            if (produce != null) {
162                setterInjection(method, bean, produce.uri(), produce.ref());
163            }
164        }
165    
166        protected void setterInjection(Method method, Object bean, String endpointUri, String endpointRef) {
167            Class<?>[] parameterTypes = method.getParameterTypes();
168            if (parameterTypes != null) {
169                if (parameterTypes.length != 1) {
170                    LOG.warn("Ignoring badly annotated method for injection due to incorrect number of parameters: " + method);
171                } else {
172                    String propertyName = ObjectHelper.getPropertyName(method);
173                    Object value = getPostProcessor().getInjectionValue(parameterTypes[0], endpointUri, endpointRef, propertyName);
174                    ObjectHelper.invokeMethod(method, bean, value);
175                }
176            }
177        }
178    
179    
180        protected void consumerInjection(final Object bean) {
181            org.springframework.util.ReflectionUtils.doWithMethods(bean.getClass(), new org.springframework.util.ReflectionUtils.MethodCallback() {
182                @SuppressWarnings("unchecked")
183                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
184                    /*
185                     * TODO support callbacks? if
186                     * (method.getAnnotation(Callback.class) != null) { try {
187                     * Expression e = ExpressionFactory.createExpression(
188                     * method.getAnnotation(Callback.class).condition());
189                     * JexlContext jc = JexlHelper.createContext();
190                     * jc.getVars().put("this", obj); Object r = e.evaluate(jc); if
191                     * (!(r instanceof Boolean)) { throw new
192                     * RuntimeException("Expression did not returned a boolean value
193                     * but: " + r); } Boolean oldVal =
194                     * req.getCallbacks().get(method); Boolean newVal = (Boolean) r;
195                     * if ((oldVal == null || !oldVal) && newVal) {
196                     * req.getCallbacks().put(method, newVal); method.invoke(obj,
197                     * new Object[0]); // TODO: handle return value and sent it as
198                     * the answer } } catch (Exception e) { throw new
199                     * RuntimeException("Unable to invoke callback", e); } }
200                     */
201                }
202            });
203        }
204    
205        public CamelPostProcessorHelper getPostProcessor() {
206            ObjectHelper.notNull(postProcessor, "postProcessor");
207            return postProcessor;
208        }
209    }