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.api.MuleContext;
10  import org.mule.api.MuleEvent;
11  import org.mule.api.MuleException;
12  import org.mule.api.lifecycle.InitialisationException;
13  import org.mule.config.i18n.CoreMessages;
14  import org.mule.routing.correlation.CorrelationSequenceComparator;
15  import org.mule.routing.correlation.EventCorrelatorCallback;
16  import org.mule.routing.correlation.ResequenceMessagesCorrelatorCallback;
17  
18  import java.util.Comparator;
19  
20  /**
21   * <code>Resequencer</code> is used to resequence events according to their dispatch
22   * sequence in the correlation group. When the message splitter router splits an
23   * event it assigns a correlation sequence to the individual message parts so that
24   * another router such as the <i>Resequencer</i> can receive the parts and reorder or
25   * merge them.
26   * <p>
27   * <b>EIP Reference:</b> <a href="http://www.eaipatterns.com/Resequencer.html">http://www.eaipatterns.com/Resequencer.html<a/>
28   */
29  public class Resequencer extends AbstractAggregator
30  {
31      protected Comparator eventComparator;
32  
33      public Resequencer()
34      {
35          super();
36          this.setEventComparator(new CorrelationSequenceComparator());
37      }
38  
39      @Override
40      public void initialise() throws InitialisationException
41      {
42          if (eventComparator == null)
43          {
44              throw new InitialisationException(CoreMessages.objectIsNull("eventComparator"), this);
45          }
46          super.initialise();
47      }
48  
49      public Comparator getEventComparator()
50      {
51          return eventComparator;
52      }
53  
54      public void setEventComparator(Comparator eventComparator)
55      {
56          this.eventComparator = eventComparator;
57      }
58  
59      @Override
60      protected EventCorrelatorCallback getCorrelatorCallback(MuleContext muleContext)
61      {
62          return new ResequenceMessagesCorrelatorCallback(getEventComparator(), muleContext);
63      }
64  
65      @Override
66      public MuleEvent process(MuleEvent event) throws MuleException
67      {
68          MuleEvent result = eventCorrelator.process(event);
69          if (result == null)
70          {
71              return null;
72          }
73          MuleEvent last = null;
74          for (MuleEvent muleEvent : (MuleEvent[]) result.getMessage().getPayload())
75          {
76              last = processNext(muleEvent);
77          }
78          // Respect existing behaviour by returning last event
79          return last;
80      }
81  
82  }