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.correlation;
8   
9   import org.mule.DefaultMuleEvent;
10  import org.mule.DefaultMuleMessage;
11  import org.mule.api.MuleContext;
12  import org.mule.api.MuleEvent;
13  import org.mule.routing.AggregationException;
14  import org.mule.routing.EventGroup;
15  import org.mule.routing.Resequencer;
16  
17  import java.util.Arrays;
18  import java.util.Comparator;
19  
20  /**
21   * A Correlator that correlates messages based on Mule correlation settings. Note
22   * that the {@link #aggregateEvents(org.mule.routing.EventGroup)} method only
23   * resequences the events and returns an MuleEvent[] wrapped in a MuleMessage impl.
24   * This means that this callback can ONLY be used with a {@link Resequencer}
25   */
26  public class ResequenceCorrelatorCallback extends CollectionCorrelatorCallback
27  {
28      protected Comparator<MuleEvent> eventComparator;
29  
30      public ResequenceCorrelatorCallback(Comparator<MuleEvent> eventComparator, MuleContext muleContext)
31      {
32          super(muleContext);
33          this.eventComparator = eventComparator;
34          this.muleContext = muleContext;
35      }
36  
37      /**
38       * This method is invoked if the shouldAggregate method is called and returns
39       * true. Once this method returns an aggregated message, the event group is
40       * removed from the router.
41       *
42       * @param events the event group for this request
43       * @return an aggregated message
44       * @throws AggregationException
45       *          if the aggregation fails. in this scenario the
46       *          whole event group is removed and passed to the exception handler
47       *          for this componenet
48       */
49      @Override
50      public MuleEvent aggregateEvents(EventGroup events) throws AggregationException
51      {
52          MuleEvent results[];
53          if (events == null || events.size() == 0)
54          {
55              results = EventGroup.EMPTY_EVENTS_ARRAY;
56          }
57          else
58          {
59              results = events.toArray();
60              Arrays.sort(results, eventComparator);
61          }
62          //This is a bit of a hack since we wrap the the collection of events in a Mule Message to pass back
63          return new DefaultMuleEvent(new DefaultMuleMessage(results, muleContext), results[0]);
64      }
65  
66  }