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 */
017package org.apache.camel.component.bean;
018
019import java.lang.annotation.Annotation;
020import java.lang.reflect.Method;
021
022import org.apache.camel.CamelContext;
023import org.apache.camel.Expression;
024import org.apache.camel.language.LanguageAnnotation;
025import org.apache.camel.language.bean.BeanExpression;
026import org.apache.camel.util.ObjectHelper;
027import org.apache.camel.util.StringHelper;
028
029/**
030 * @version 
031 */
032public class BeanAnnotationExpressionFactory extends DefaultAnnotationExpressionFactory {
033
034    @Override
035    public Expression createExpression(CamelContext camelContext, Annotation annotation, LanguageAnnotation languageAnnotation, Class<?> expressionReturnType) {
036        String beanName = getFromAnnotation(annotation, "ref");
037        String method = getFromAnnotation(annotation, "method");
038
039        // ref is mandatory
040        StringHelper.notEmpty(beanName, "ref", annotation);
041
042        // method is optional but provide it as null to the bean expression
043        if (ObjectHelper.isEmpty(method)) {
044            method = null;
045        }
046
047        return new BeanExpression(beanName, method);
048    }
049
050    protected String getFromAnnotation(Annotation annotation, String attribute) {
051        try {
052            Method method = annotation.getClass().getMethod(attribute);
053            Object value = ObjectHelper.invokeMethod(method, annotation);
054            if (value == null) {
055                throw new IllegalArgumentException("Cannot determine the " + attribute + " from the annotation: " + annotation);
056            }
057            return value.toString();
058        } catch (NoSuchMethodException e) {
059            throw new IllegalArgumentException("Cannot determine the " + attribute
060                + " of the annotation: " + annotation + " as it does not have a " + attribute + "() method");
061        }
062    }
063}
064