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.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.ServiceHelper; 027 028 import static org.apache.camel.util.ObjectHelper.notNull; 029 030 /** 031 * Implements a dynamic <a 032 * href="http://activemq.apache.org/camel/splitter.html">Splitter</a> pattern 033 * where an expression is evaluated to iterate through each of the parts of a 034 * message and then each part is then send to some endpoint. 035 * 036 * @version $Revision: 563607 $ 037 */ 038 public class Splitter extends ServiceSupport implements Processor { 039 private final Processor processor; 040 private final Expression expression; 041 042 public Splitter(Expression expression, Processor destination) { 043 this.processor = destination; 044 this.expression = expression; 045 notNull(destination, "destination"); 046 notNull(expression, "expression"); 047 } 048 049 @Override 050 public String toString() { 051 return "Splitter[on: " + expression + " to: " + processor + "]"; 052 } 053 054 public void process(Exchange exchange) throws Exception { 055 Object value = expression.evaluate(exchange); 056 Iterator iter = ObjectConverter.iterator(value); 057 while (iter.hasNext()) { 058 Object part = iter.next(); 059 Exchange newExchange = exchange.copy(); 060 newExchange.getIn().setBody(part); 061 processor.process(newExchange); 062 } 063 } 064 065 protected void doStart() throws Exception { 066 ServiceHelper.startServices(processor); 067 } 068 069 protected void doStop() throws Exception { 070 ServiceHelper.stopServices(processor); 071 } 072 }