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;
018
019import org.slf4j.LoggerFactory;
020
021/**
022 * A strategy for aggregating two exchanges together into a single exchange.
023 * <p/>
024 * On the first invocation of the {@link #aggregate(org.apache.camel.Exchange, org.apache.camel.Exchange) aggregate}
025 * method the <tt>oldExchange</tt> parameter is <tt>null</tt>. The reason is that we have not aggregated anything yet.
026 * So its only the <tt>newExchange</tt> that has a value. Usually you just return the <tt>newExchange</tt> in this
027 * situation. But you still have the power to decide what to do, for example you can do some alternation on the exchange
028 * or remove some headers. And a more common use case is for instance to count some values from the body payload. That
029 * could be to sum up a total amount etc.
030 * <p/>
031 * Note that <tt>oldExchange</tt> may be <tt>null</tt> more than once when this strategy is throwing a {@link java.lang.RuntimeException}
032 * and <tt>parallelProcessing</tt> is used. You can work around this behavior using the <tt>stopOnAggregateException</tt> option.
033 * <p/>
034 * It is possible that <tt>newExchange</tt> is <tt>null</tt> which could happen if there was no data possible
035 * to acquire. Such as when using a <tt>PollEnricher</tt> to poll from a JMS queue which
036 * is empty and a timeout was set.
037 * <p/>
038 * Important: In the aggregate method, do not create a new exchange instance to return,
039 * instead return either the old or new exchange from the input parameters; favor returning the old exchange whenever possible.
040 * <p/>
041 * Possible implementations include performing some kind of combining or delta processing, such as adding line items
042 * together into an invoice or just using the newest exchange and removing old exchanges such as for state tracking or
043 * market data prices; where old values are of little use.
044 * <p/>
045 * If an implementation also implements {@link org.apache.camel.Service} then any <a href="http://camel.apache.org/eip">EIP</a>
046 * that allowing configuring a {@link AggregationStrategy} will invoke the {@link org.apache.camel.Service#start()}
047 * and {@link org.apache.camel.Service#stop()} to control the lifecycle aligned with the EIP itself.
048 * <p/>
049 * If an implementation also implements {@link org.apache.camel.CamelContextAware} then any <a href="http://camel.apache.org/eip">EIP</a>
050 * that allowing configuring a {@link AggregationStrategy} will inject the {@link org.apache.camel.CamelContext} prior
051 * to using the aggregation strategy.
052 */
053public interface AggregationStrategy {
054
055    /**
056     * Aggregates an old and new exchange together to create a single combined exchange
057     * <p/>
058     * Important: In the aggregate method, do not create a new exchange instance to return,
059     * instead return either the old or new exchange from the input parameters; favor returning the old exchange whenever possible.
060     *
061     * @param oldExchange the oldest exchange (is <tt>null</tt> on first aggregation as we only have the new exchange)
062     * @param newExchange the newest exchange (can be <tt>null</tt> if there was no data possible to acquire)
063     * @return a combined composite of the two exchanges, return either the old or new exchange from the input parameters;
064     * favor returning the old exchange whenever possible)
065     */
066    Exchange aggregate(Exchange oldExchange, Exchange newExchange);
067
068    /**
069     * Aggregates an old and new exchange together to create a single combined exchange.
070     * <p/>
071     * Important: In the aggregate method, do not create a new exchange instance to return,
072     * instead return either the old or new exchange from the input parameters; favor returning the old exchange whenever possible.
073     * <p/>
074     * Important: Only Multicast and Recipient List EIP supports this method with access to the input exchange. All other EIPs
075     * does not and uses the {@link #aggregate(Exchange, Exchange)} method instead.
076     *
077     * @param oldExchange    the oldest exchange (is <tt>null</tt> on first aggregation as we only have the new exchange)
078     * @param newExchange    the newest exchange (can be <tt>null</tt> if there was no data possible to acquire)
079     * @param inputExchange  the input exchange (input to the EIP)
080     * @return a combined composite of the two exchanges, return either the old or new exchange from the input parameters;
081     * favor returning the old exchange whenever possible)
082     */
083    default Exchange aggregate(Exchange oldExchange, Exchange newExchange, Exchange inputExchange) {
084        return aggregate(oldExchange, newExchange);
085    }
086
087    /**
088     * Indicates if this aggregation strategy uses pre-completion mode.
089     * @return <tt>true</tt> if this strategy uses pre-completion mode, or <tt>false</tt> otherwise.
090     */
091    default boolean canPreComplete() {
092        return false;
093    }
094
095    /**
096     * Determines if the aggregation should complete the current group, and start a new group, or the aggregation
097     * should continue using the current group. This callback will only be called if {@link #canPreComplete()}
098     * returns <tt>true</tt>.
099     *
100     * @param oldExchange the oldest exchange (is <tt>null</tt> on first aggregation as we only have the new exchange)
101     * @param newExchange the newest exchange (can be <tt>null</tt> if there was no data possible to acquire)
102     * @return <tt>true</tt> to complete current group and start a new group, or <tt>false</tt> to keep using current
103     */
104    default boolean preComplete(Exchange oldExchange, Exchange newExchange) {
105        return false;
106    }
107
108    /**
109     * The aggregated {@link Exchange} has completed
110     *
111     * <b>Important: </b> This method must <b>not</b> throw any exceptions.
112     *
113     * @param exchange  the current aggregated exchange, or the original {@link org.apache.camel.Exchange} if no aggregation
114     *                  has been done before the completion occurred
115     */
116    default void onCompletion(Exchange exchange) {
117    }
118
119    /**
120     * A timeout occurred.
121     * <p/>
122     * <b>Important: </b> This method must <b>not</b> throw any exceptions.
123     *
124     * @param exchange  the current aggregated exchange, or the original {@link Exchange} if no aggregation
125     *                  has been done before the timeout occurred
126     * @param index     the index, may be <tt>-1</tt> if not possible to determine the index
127     * @param total     the total, may be <tt>-1</tt> if not possible to determine the total
128     * @param timeout   the timeout value in millis, may be <tt>-1</tt> if not possible to determine the timeout
129     */
130    default void timeout(Exchange exchange, int index, int total, long timeout) {
131        // log a WARN we timed out since it will not be aggregated and the Exchange will be lost
132        LoggerFactory.getLogger(getClass()).warn("Parallel processing timed out after {} millis for number {}. This task will be cancelled and will not be aggregated.", timeout, index);
133    }
134
135    /**
136     * Callback when the aggregated {@link Exchange} fails to add
137     * in the {@link org.apache.camel.spi.OptimisticLockingAggregationRepository} because of
138     * an {@link org.apache.camel.spi.OptimisticLockingAggregationRepository.OptimisticLockingException}.
139     * <p/>
140     * Please note that when aggregating {@link Exchange}'s to be careful not to modify and return the {@code oldExchange}
141     * from the {@link AggregationStrategy#aggregate(org.apache.camel.Exchange, org.apache.camel.Exchange)} method.
142     * If you are using the default MemoryAggregationRepository this will mean you have modified the value of an object
143     * already referenced/stored by the MemoryAggregationRepository. This makes it impossible for optimistic locking
144     * to work correctly with the MemoryAggregationRepository.
145     * <p/>
146     * You should instead return either the new {@code newExchange} or a completely new instance of {@link Exchange}. This
147     * is due to the nature of how the underlying {@link java.util.concurrent.ConcurrentHashMap} performs CAS operations
148     * on the value identity.
149     *
150     * @see java.util.concurrent.ConcurrentHashMap
151     */
152    default void onOptimisticLockFailure(Exchange oldExchange, Exchange newExchange) {
153        LoggerFactory.getLogger(getClass()).trace("onOptimisticLockFailure with AggregationStrategy: {}, oldExchange: {}, newExchange: {}", this, oldExchange, newExchange);
154    }
155
156}