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.processor.aggregate; 018 019 import java.util.AbstractCollection; 020 import java.util.Iterator; 021 import java.util.LinkedHashMap; 022 import java.util.Map; 023 024 import org.apache.camel.Exchange; 025 import org.apache.camel.Expression; 026 027 /** 028 * A {@link Collection} which aggregates exchanges together using a correlation 029 * expression so that there is only a single message exchange sent for a single 030 * correlation key. 031 * 032 * @version $Revision: 1.1 $ 033 */ 034 public class AggregationCollection extends AbstractCollection<Exchange> { 035 private final Expression<Exchange> correlationExpression; 036 private final AggregationStrategy aggregationStrategy; 037 private Map<Object, Exchange> map = new LinkedHashMap<Object, Exchange>(); 038 039 public AggregationCollection(Expression<Exchange> correlationExpression, 040 AggregationStrategy aggregationStrategy) { 041 this.correlationExpression = correlationExpression; 042 this.aggregationStrategy = aggregationStrategy; 043 } 044 045 @Override 046 public boolean add(Exchange exchange) { 047 Object correlationKey = correlationExpression.evaluate(exchange); 048 Exchange oldExchange = map.get(correlationKey); 049 Exchange newExchange = exchange; 050 if (oldExchange != null) { 051 newExchange = aggregationStrategy.aggregate(oldExchange, newExchange); 052 } 053 054 // the strategy may just update the old exchange and return it 055 if (newExchange != oldExchange) { 056 map.put(correlationKey, newExchange); 057 } 058 return true; 059 } 060 061 public Iterator<Exchange> iterator() { 062 return map.values().iterator(); 063 } 064 065 public int size() { 066 return map.size(); 067 } 068 }