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