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.util;
018    
019    import org.apache.camel.Exchange;
020    import org.apache.camel.Expression;
021    
022    /**
023     * A collection of helper methods for working with expressions.
024     *
025     * @version $Revision: 36321 $
026     */
027    public final class ExpressionHelper {
028    
029        /**
030         * Utility classes should not have a public constructor.
031         */
032        private ExpressionHelper() {
033        }
034    
035        /**
036         * Evaluates the given expression on the exchange as a String value
037         *
038         * @param expression the expression to evaluate
039         * @param exchange the exchange to use to evaluate the expression
040         * @return the result of the evaluation as a string.
041         */
042        public static <E extends Exchange> String evaluateAsString(Expression<E> expression, E exchange) {
043            return evaluateAsType(expression, exchange, String.class);
044        }
045    
046        /**
047         * Evaluates the given expression on the exchange, converting the result to
048         * the given type
049         *
050         * @param expression the expression to evaluate
051         * @param exchange the exchange to use to evaluate the expression
052         * @param resultType the type of the result that is required
053         * @return the result of the evaluation as the specified type.
054         */
055        public static <T, E extends Exchange> T evaluateAsType(Expression<E> expression, E exchange,
056                                                               Class<T> resultType) {
057            Object value = expression.evaluate(exchange);
058            return exchange.getContext().getTypeConverter().convertTo(resultType, value);
059        }
060    }