1
2
3
4
5
6
7 package org.mule.transport.xmpp;
8
9 import org.mule.module.client.MuleClient;
10 import org.mule.tck.functional.FunctionalTestComponent;
11 import org.mule.transport.xmpp.JabberSender.Callback;
12 import org.mule.util.concurrent.Latch;
13
14 import java.util.List;
15
16 import edu.emory.mathcs.backport.java.util.concurrent.CountDownLatch;
17 import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
18 import org.jivesoftware.smack.packet.Message;
19 import org.junit.Test;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertTrue;
23
24 public class XmppMessageAsyncTestCase extends AbstractXmppTestCase
25 {
26
27 protected static final long JABBER_SEND_THREAD_SLEEP_TIME = 1000;
28 private static final String RECEIVE_SERVICE_NAME = "receiveFromJabber";
29
30 private CountDownLatch latch = new CountDownLatch(1);
31
32 @Override
33 protected String getXmppConfigResources()
34 {
35 return "xmpp-message-async-config.xml";
36 }
37
38 @Override
39 protected void configureJabberClient(JabberClient client)
40 {
41 client.setSynchronous(false);
42 client.setMessageLatch(latch);
43 }
44
45 @Test
46 public void testDispatch() throws Exception
47 {
48 MuleClient client = new MuleClient(muleContext);
49 client.dispatch("vm://in", TEST_MESSAGE, null);
50
51 assertTrue(latch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS));
52
53 List<Message> receivedMessages = jabberClient.getReceivedMessages();
54 assertEquals(1, receivedMessages.size());
55
56 Message message = receivedMessages.get(0);
57 assertXmppMessage(message);
58 }
59
60 @Test
61 public void testReceiveAsync() throws Exception
62 {
63 startService(RECEIVE_SERVICE_NAME);
64
65 Latch receiveLatch = new Latch();
66 setupTestServiceComponent(receiveLatch);
67
68 sendJabberMessageFromNewThread();
69 assertTrue(receiveLatch.await(RECEIVE_TIMEOUT, TimeUnit.MILLISECONDS));
70 }
71
72 private void setupTestServiceComponent(Latch receiveLatch) throws Exception
73 {
74 Object testComponent = getComponent(RECEIVE_SERVICE_NAME);
75 assertTrue(testComponent instanceof FunctionalTestComponent);
76 FunctionalTestComponent component = (FunctionalTestComponent) testComponent;
77
78 XmppCallback callback = new XmppCallback(receiveLatch, expectedXmppMessageType());
79 component.setEventCallback(callback);
80 }
81
82 protected Message.Type expectedXmppMessageType()
83 {
84 return Message.Type.normal;
85 }
86
87 protected void assertXmppMessage(Message message)
88 {
89 assertEquals(Message.Type.normal, message.getType());
90 assertEquals(TEST_MESSAGE, message.getBody());
91 }
92
93 protected void sendJabberMessageFromNewThread()
94 {
95 JabberSender sender = new JabberSender(new Callback()
96 {
97 public void doit() throws Exception
98 {
99 Thread.sleep(JABBER_SEND_THREAD_SLEEP_TIME);
100 jabberClient.sendMessage(muleJabberUserId, TEST_MESSAGE);
101 }
102 });
103 startSendThread(sender);
104 }
105 }