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; 018 019 import java.util.Iterator; 020 021 import org.apache.camel.Endpoint; 022 import org.apache.camel.Exchange; 023 import org.apache.camel.Expression; 024 import org.apache.camel.Processor; 025 import org.apache.camel.converter.ObjectConverter; 026 import org.apache.camel.impl.ServiceSupport; 027 import org.apache.camel.util.ExchangeHelper; 028 import org.apache.camel.util.ProducerCache; 029 030 import static org.apache.camel.util.ObjectHelper.notNull; 031 032 /** 033 * Implements a dynamic <a 034 * href="http://activemq.apache.org/camel/recipient-list.html">Recipient List</a> 035 * pattern where the list of actual endpoints to send a message exchange to are 036 * dependent on some dynamic expression. 037 * 038 * @version $Revision: 563607 $ 039 */ 040 public class RecipientList extends ServiceSupport implements Processor { 041 private final Expression<Exchange> expression; 042 private ProducerCache<Exchange> producerCache = new ProducerCache<Exchange>(); 043 044 public RecipientList(Expression<Exchange> expression) { 045 notNull(expression, "expression"); 046 this.expression = expression; 047 } 048 049 @Override 050 public String toString() { 051 return "RecipientList[" + expression + "]"; 052 } 053 054 public void process(Exchange exchange) throws Exception { 055 Object receipientList = expression.evaluate(exchange); 056 Iterator iter = ObjectConverter.iterator(receipientList); 057 while (iter.hasNext()) { 058 Object recipient = iter.next(); 059 Endpoint<Exchange> endpoint = resolveEndpoint(exchange, recipient); 060 producerCache.getProducer(endpoint).process(exchange); 061 } 062 } 063 064 protected Endpoint<Exchange> resolveEndpoint(Exchange exchange, Object recipient) { 065 return ExchangeHelper.resolveEndpoint(exchange, recipient); 066 } 067 068 protected void doStop() throws Exception { 069 producerCache.stop(); 070 } 071 072 protected void doStart() throws Exception { 073 } 074 }