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.test.routing;
8   
9   import org.mule.api.MuleException;
10  import org.mule.api.MuleMessage;
11  import org.mule.module.client.MuleClient;
12  import org.mule.tck.junit4.FunctionalTestCase;
13  
14  import java.util.ArrayList;
15  import java.util.List;
16  
17  import org.junit.Test;
18  
19  import static org.junit.Assert.assertNotNull;
20  
21  public class RoundRobinTestCase extends FunctionalTestCase
22  {
23  
24      private static final int NUMBER_OF_MESSAGES = 10;
25      private static final int NUMBER_OF_WRITERS = 10;
26      private static final int NUMBER_OF_ENDPOINTS = 5;
27      private MuleClient client;
28  
29      @Override
30      protected String getConfigResources()
31      {
32          return "round-robin-test.xml";
33      }
34  
35      @Test
36      public void testRoundRobin() throws Exception
37      {
38          client = new MuleClient(muleContext);
39          List<Thread> writers = new ArrayList<Thread>();
40          for (int i = 0; i < NUMBER_OF_WRITERS; i++)
41          {
42              writers.add(new Thread(new MessageWriter(i)));
43          }
44          for (Thread writer : writers)
45          {
46              writer.start();
47          }
48          for (Thread writer : writers)
49          {
50              writer.join();
51          }
52  
53          for (int i = 0, j = 0; i < NUMBER_OF_WRITERS * NUMBER_OF_MESSAGES; i++)
54          {
55              // Message should be disrtibuted uniformly among endpoints
56              String path = "vm://output" + j;
57              MuleMessage msg = client.request(path, 0);
58              assertNotNull(msg);
59              logger.debug(path + ": " + msg.getPayloadAsString());
60              j = (j + 1) % NUMBER_OF_ENDPOINTS;
61          }
62      }
63  
64      class MessageWriter implements Runnable
65      {
66          private int id;
67  
68          MessageWriter(int id)
69          {
70              this.id = id;
71          }
72  
73          public void run()
74          {
75              for (int i = 0; i < NUMBER_OF_MESSAGES; i++)
76              {
77                  try
78                  {
79                      client.send("vm://input", "Writer " + id + " Message " + i, null);
80                  }
81                  catch (MuleException ex)
82                  {
83                      logger.info("Unexpected exception dispatching message", ex);
84                  }
85              }
86          }
87      }
88  }