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.language.bean;
018    
019    import org.apache.camel.Exchange;
020    import org.apache.camel.ExchangePattern;
021    import org.apache.camel.component.bean.BeanProcessor;
022    import org.apache.camel.component.bean.RegistryBean;
023    import org.apache.camel.impl.ExpressionSupport;
024    
025    /**
026     * Evaluates an expression using a bean method invocation
027     *
028     * @version $Revision: 675833 $
029     */
030    public class BeanExpression<E extends Exchange> extends ExpressionSupport<E> {
031        private String beanName;
032        private String method;
033    
034        public BeanExpression(String beanName, String method) {
035            this.beanName = beanName;
036            this.method = method;
037        }
038    
039        @Override
040        public String toString() {
041            return "BeanExpression[bean: " + beanName + " method: " + method + "]";
042        }
043    
044        protected String assertionFailureMessage(E exchange) {
045            return "bean: " + beanName + " method: " + method;
046        }
047    
048        public Object evaluate(E exchange) {
049            BeanProcessor processor = new BeanProcessor(new RegistryBean(exchange.getContext(), beanName));
050            if (method != null) {
051                processor.setMethod(method);
052            }
053            try {
054                Exchange newExchange = exchange.copy();
055                // The BeanExperession always has a result regardless of the ExchangePattern,
056                // so I add a checker here to make sure we can get the result.
057                if (!newExchange.getPattern().isOutCapable()) {
058                    newExchange.setPattern(ExchangePattern.InOut);
059                }
060                processor.process(newExchange);
061                return newExchange.getOut(true).getBody();
062            } catch (Exception e) {
063                throw new RuntimeBeanExpressionException(exchange, beanName, method, e);
064            }
065        }
066    }