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