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.processor;
018
019import org.apache.camel.AsyncCallback;
020import org.apache.camel.AsyncProcessor;
021import org.apache.camel.Exchange;
022import org.apache.camel.Expression;
023import org.apache.camel.Traceable;
024import org.apache.camel.util.AsyncProcessorHelper;
025
026/**
027 * A {@link org.apache.camel.Processor} which evaluates an {@link Expression}
028 * and stores the result as a property on the {@link Exchange} with the key
029 * {@link Exchange#EVALUATE_EXPRESSION_RESULT}.
030 * <p/>
031 * This processor will in case of evaluation exceptions, set the caused exception
032 * on the {@link Exchange}.
033 */
034public class EvaluateExpressionProcessor implements AsyncProcessor, Traceable {
035
036    private final Expression expression;
037
038    public EvaluateExpressionProcessor(Expression expression) {
039        this.expression = expression;
040    }
041
042    @Override
043    public void process(Exchange exchange) throws Exception {
044        AsyncProcessorHelper.process(this, exchange);
045    }
046
047    @Override
048    public boolean process(Exchange exchange, AsyncCallback callback) {
049        try {
050            Object result = expression.evaluate(exchange, Object.class);
051            exchange.setProperty(Exchange.EVALUATE_EXPRESSION_RESULT, result);
052        } catch (Throwable e) {
053            exchange.setException(e);
054        } finally {
055            callback.done(true);
056        }
057        return true;
058    }
059
060    @Override
061    public String toString() {
062        return "EvalExpression[" + expression + "]";
063    }
064
065    public String getTraceLabel() {
066        return "eval[" + expression + "]";
067    }
068
069}