1
2
3
4
5
6
7
8
9
10
11 package org.mule.routing;
12
13 import edu.emory.mathcs.backport.java.util.concurrent.atomic.AtomicInteger;
14 import org.mule.DefaultMuleEvent;
15 import org.mule.api.MessagingException;
16 import org.mule.api.MuleEvent;
17 import org.mule.api.MuleException;
18 import org.mule.api.MuleMessage;
19 import org.mule.api.endpoint.OutboundEndpoint;
20 import org.mule.api.processor.MessageProcessor;
21 import org.mule.api.routing.CouldNotRouteOutboundMessageException;
22 import org.mule.api.routing.RoutingException;
23 import org.mule.routing.outbound.AbstractOutboundRouter;
24
25
26
27
28
29
30
31 public class RoundRobin extends AbstractOutboundRouter implements MessageProcessor
32 {
33
34 AtomicInteger index = new AtomicInteger(0);
35
36
37
38
39 public MuleEvent route(MuleEvent event) throws MessagingException
40 {
41 int index = getAndIncrementModuloN(routes.size());
42 if (index < 0)
43 {
44 throw new CouldNotRouteOutboundMessageException(event, this);
45 }
46 MessageProcessor mp = routes.get(index);
47 MuleEvent toProcess = event;
48 if (mp instanceof OutboundEndpoint)
49 {
50 toProcess = new DefaultMuleEvent(event.getMessage(), (OutboundEndpoint)mp, event.getSession());
51 }
52 try
53 {
54 return mp.process(toProcess);
55 }
56 catch (MuleException ex)
57 {
58 throw new RoutingException(event, this, ex);
59 }
60 }
61
62
63
64
65 private int getAndIncrementModuloN(int modulus)
66 {
67 if (modulus == 0)
68 {
69 return -1;
70 }
71 while (true)
72 {
73 int lastIndex = index.get();
74 int nextIndex = (lastIndex + 1) % modulus;
75 if (index.compareAndSet(lastIndex, nextIndex))
76 {
77 return nextIndex;
78 }
79 }
80 }
81
82 public boolean isMatch(MuleMessage message) throws MuleException
83 {
84 return true;
85 }
86 }