View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.routing;
8   
9   import org.mule.DefaultMuleMessage;
10  import org.mule.api.MuleEvent;
11  import org.mule.api.MuleMessage;
12  import org.mule.config.i18n.CoreMessages;
13  
14  import java.util.LinkedList;
15  import java.util.List;
16  import java.util.Map;
17  import java.util.Set;
18  import java.util.Map.Entry;
19  
20  /**
21   * Splits a message that has a map payload invoking the next message processor one
22   * for each item in the map in order. The Map entry value is used as the new payload
23   * and the map key is set as a message property with the following property name
24   * 'key'.
25   * <p>
26   * <b>EIP Reference:</b> <a
27   * href="http://www.eaipatterns.com/Sequencer.html">http://www
28   * .eaipatterns.com/Sequencer.html</a>
29   */
30  public class MapSplitter extends AbstractSplitter
31  {
32      public static String MAP_ENTRY_KEY = "key";
33  
34      protected List<MuleMessage> splitMessage(MuleEvent event)
35      {
36          MuleMessage message = event.getMessage();
37          if (message.getPayload() instanceof Map<?, ?>)
38          {
39              List<MuleMessage> list = new LinkedList<MuleMessage>();
40              Set<Map.Entry<?, ?>> set = ((Map) message.getPayload()).entrySet();
41              for (Entry<?, ?> entry : set)
42              {
43                  MuleMessage splitMessage = new DefaultMuleMessage(entry.getValue(), muleContext);
44                  splitMessage.setInvocationProperty(MAP_ENTRY_KEY, entry.getKey());
45                  list.add(splitMessage);
46              }
47              return list;
48          }
49          else
50          {
51              throw new IllegalArgumentException(CoreMessages.objectNotOfCorrectType(
52                  message.getPayload().getClass(), Map.class).getMessage());
53          }
54      }
55  }