View Javadoc

1   /*
2    * $Id: CollectionSplitter.java 22272 2011-06-27 16:17:16Z mike.schilling $
3    * --------------------------------------------------------------------------------------
4    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
5    *
6    * The software in this package is published under the terms of the CPAL v1.0
7    * license, a copy of which has been included with this distribution in the
8    * LICENSE.txt file.
9    */
10  
11  package org.mule.routing;
12  
13  import java.util.Collection;
14  import java.util.Iterator;
15  import java.util.LinkedList;
16  
17  import org.mule.api.MuleEvent;
18  import org.mule.config.i18n.CoreMessages;
19  import org.mule.routing.outbound.AbstractMessageSequenceSplitter;
20  import org.mule.routing.outbound.CollectionMessageSequence;
21  import org.mule.routing.outbound.IteratorMessageSequence;
22  
23  /**
24   * Splits a message that has a Collection, Iterable, MessageSequence or Iterator
25   * payload invoking the next message processor one
26   * for each item in it.
27   * <p>
28   * <b>EIP Reference:</b> <a href="http://www.eaipatterns.com/Sequencer.html">http
29   * ://www.eaipatterns.com/Sequencer.html</a>
30   */
31  public class CollectionSplitter extends AbstractMessageSequenceSplitter
32  {
33      @SuppressWarnings("unchecked")
34      protected MessageSequence<?> splitMessageIntoSequence(MuleEvent event)
35      {
36          Object payload = event.getMessage().getPayload();
37          if (payload instanceof MessageSequence<?>)
38          {
39              return ((MessageSequence<?>) payload);
40          }
41          if (payload instanceof Iterator<?>)
42          {
43              return new IteratorMessageSequence<Object>(((Iterator<Object>) payload));
44          }
45          if (payload instanceof Collection)
46          {
47              return new CollectionMessageSequence(new LinkedList((Collection) payload));
48          }
49          if (payload instanceof Iterable<?>)
50          {
51              return new IteratorMessageSequence<Object>(((Iterable<Object>) payload).iterator());
52          }
53          else
54          {
55              throw new IllegalArgumentException(CoreMessages.objectNotOfCorrectType(payload.getClass(),
56                  new Class[]{Iterable.class, Iterator.class, MessageSequence.class, Collection.class})
57                  .getMessage());
58          }
59      }
60  }