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
22   * Note that the {@link #aggregateEvents(org.mule.routing.EventGroup)} method only resequences the events and
23   * returns an MuleEvent[] wrapped in a MuleMessage impl.  This means that this callback can ONLY be used with a
24   * {@link Resequencer}
25   */
26  public class ResequenceMessagesCorrelatorCallback extends CollectionCorrelatorCallback
27  {
28      protected Comparator eventComparator;
29      protected MuleContext muleContext;
30  
31      public ResequenceMessagesCorrelatorCallback(Comparator eventComparator, MuleContext muleContext)
32      {
33          super(muleContext);
34          this.eventComparator = eventComparator;
35          this.muleContext = muleContext;
36      }
37  
38      /**
39       * This method is invoked if the shouldAggregate method is called and returns
40       * true. Once this method returns an aggregated message, the event group is
41       * removed from the router.
42       *
43       * @param events the event group for this request
44       * @return an aggregated message
45       * @throws org.mule.routing.AggregationException if the aggregation fails. in
46       *             this scenario the whole event group is removed and passed to the
47       *             exception handler for this componenet
48       */
49      @Override
50      public MuleEvent aggregateEvents(EventGroup events) throws AggregationException
51      {
52          MuleEvent[] results = (events == null) ? new MuleEvent[0] : events.toArray();
53          Arrays.sort(results, eventComparator);
54          //This is a bit of a hack since we return a collection of events on one message
55          return new DefaultMuleEvent(new DefaultMuleMessage(results, muleContext), results[0]);
56      }
57  
58  }