001 /** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 package org.apache.camel.processor; 019 020 import org.apache.camel.Endpoint; 021 import org.apache.camel.Exchange; 022 import org.apache.camel.Expression; 023 import org.apache.camel.Processor; 024 import org.apache.camel.converter.ObjectConverter; 025 import org.apache.camel.impl.ServiceSupport; 026 import org.apache.camel.util.ExchangeHelper; 027 import static org.apache.camel.util.ObjectHelper.notNull; 028 import org.apache.camel.util.ProducerCache; 029 030 import java.util.Iterator; 031 032 /** 033 * Implements a dynamic <a href="http://activemq.apache.org/camel/recipient-list.html">Recipient List</a> pattern 034 * where the list of actual endpoints to send a message exchange to are dependent on some dynamic expression. 035 * 036 * @version $Revision: 534145 $ 037 */ 038 public class RecipientList extends ServiceSupport implements Processor { 039 private final Expression<Exchange> expression; 040 private ProducerCache<Exchange> producerCache = new ProducerCache<Exchange>(); 041 042 public RecipientList(Expression<Exchange> expression) { 043 notNull(expression, "expression"); 044 this.expression = expression; 045 } 046 047 @Override 048 public String toString() { 049 return "RecipientList[" + expression + "]"; 050 } 051 052 public void process(Exchange exchange) throws Exception { 053 Object receipientList = expression.evaluate(exchange); 054 Iterator iter = ObjectConverter.iterator(receipientList); 055 while (iter.hasNext()) { 056 Object recipient = iter.next(); 057 Endpoint<Exchange> endpoint = resolveEndpoint(exchange, recipient); 058 producerCache.getProducer(endpoint).process(exchange); 059 } 060 } 061 062 protected Endpoint<Exchange> resolveEndpoint(Exchange exchange, Object recipient) { 063 return ExchangeHelper.resolveEndpoint(exchange, recipient); 064 } 065 066 protected void doStop() throws Exception { 067 producerCache.stop(); 068 } 069 070 protected void doStart() throws Exception { 071 } 072 }