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.aggregate;
018
019import org.apache.camel.Exchange;
020
021/**
022 * An {@link org.apache.camel.processor.aggregate.AggregationStrategy} which just uses the original exchange
023 * which can be needed when you want to preserve the original Exchange. For example when splitting an {@link Exchange}
024 * and then you may want to keep routing using the original {@link Exchange}.
025 *
026 * @see org.apache.camel.processor.Splitter
027 * @version 
028 */
029public class UseOriginalAggregationStrategy implements AggregationStrategy {
030
031    private final Exchange original;
032    private final boolean propagateException;
033
034    public UseOriginalAggregationStrategy() {
035        this(null, true);
036    }
037
038    public UseOriginalAggregationStrategy(Exchange original, boolean propagateException) {
039        this.original = original;
040        this.propagateException = propagateException;
041    }
042
043    public Exchange aggregate(Exchange oldExchange, Exchange newExchange) {
044        if (propagateException) {
045            Exception exception = checkException(oldExchange, newExchange);
046            if (exception != null) {
047                if (original != null) {
048                    original.setException(exception);
049                } else {
050                    oldExchange.setException(exception);
051                }
052            }
053        }
054        return original != null ? original : oldExchange;
055    }
056
057    protected Exception checkException(Exchange oldExchange, Exchange newExchange) {
058        if (oldExchange == null) {
059            return newExchange.getException();
060        } else {
061            return (newExchange != null && newExchange.getException() != null)
062                ? newExchange.getException()
063                : oldExchange.getException();
064        }
065    }
066
067    @Override
068    public String toString() {
069        return "UseOriginalAggregationStrategy";
070    }
071}