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