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 | 0 | public class RoundRobin extends AbstractOutboundRouter implements MessageProcessor |
32 | |
{ |
33 | |
|
34 | 0 | AtomicInteger index = new AtomicInteger(0); |
35 | |
|
36 | |
|
37 | |
|
38 | |
|
39 | |
public MuleEvent route(MuleEvent event) throws MessagingException |
40 | |
{ |
41 | 0 | int index = getAndIncrementModuloN(routes.size()); |
42 | 0 | if (index < 0) |
43 | |
{ |
44 | 0 | throw new CouldNotRouteOutboundMessageException(event, this); |
45 | |
} |
46 | 0 | MessageProcessor mp = routes.get(index); |
47 | 0 | MuleEvent toProcess = event; |
48 | 0 | if (mp instanceof OutboundEndpoint) |
49 | |
{ |
50 | 0 | toProcess = new DefaultMuleEvent(event.getMessage(), (OutboundEndpoint)mp, event.getSession()); |
51 | |
} |
52 | |
try |
53 | |
{ |
54 | 0 | return mp.process(toProcess); |
55 | |
} |
56 | 0 | catch (MuleException ex) |
57 | |
{ |
58 | 0 | throw new RoutingException(event, this, ex); |
59 | |
} |
60 | |
} |
61 | |
|
62 | |
|
63 | |
|
64 | |
|
65 | |
private int getAndIncrementModuloN(int modulus) |
66 | |
{ |
67 | 0 | if (modulus == 0) |
68 | |
{ |
69 | 0 | return -1; |
70 | |
} |
71 | |
while (true) |
72 | |
{ |
73 | 0 | int lastIndex = index.get(); |
74 | 0 | int nextIndex = (lastIndex + 1) % modulus; |
75 | 0 | if (index.compareAndSet(lastIndex, nextIndex)) |
76 | |
{ |
77 | 0 | return nextIndex; |
78 | |
} |
79 | 0 | } |
80 | |
} |
81 | |
|
82 | |
public boolean isMatch(MuleMessage message) throws MuleException |
83 | |
{ |
84 | 0 | return true; |
85 | |
} |
86 | |
} |