summaryrefslogtreecommitdiff
path: root/qpid/java/systests/src/test/java/org/apache/qpid/client/AsynchMessageListenerTest.java
blob: a13bf71d5ed5ebeb31e9392fd45316eb2b4309fb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 *
 *
 */
package org.apache.qpid.client;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import javax.jms.Connection;
import javax.jms.ExceptionListener;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.Session;

import org.apache.qpid.test.utils.QpidBrokerTestCase;
import org.apache.qpid.util.LogMonitor;

/**
 * Tests the behaviour of JMS asynchronous message listeners as provided by
 * {@link MessageListener#onMessage(Message)}.
 *
 */
public class AsynchMessageListenerTest extends QpidBrokerTestCase
{
    private static final int MSG_COUNT = 10;
    private static final long AWAIT_MESSAGE_TIMEOUT = 2000;
    private static final long AWAIT_MESSAGE_TIMEOUT_NEGATIVE = 250;
    private String _testQueueName;
    private Connection _consumerConnection;
    private Session _consumerSession;
    private MessageConsumer _consumer;
    private Queue _queue;

    protected void setUp() throws Exception
    {
        super.setUp();
        _testQueueName = getTestQueueName();
        _consumerConnection = getConnection();
        _consumerConnection.start();
        _consumerSession = _consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        _queue = _consumerSession.createQueue(_testQueueName);
        _consumer = _consumerSession.createConsumer(_queue);

        // Populate queue
        Connection producerConnection = getConnection();
        Session producerSession = producerConnection.createSession(true, Session.SESSION_TRANSACTED);
        sendMessage(producerSession, _queue, MSG_COUNT);
        producerConnection.close();

    }

    public void testMessageListener() throws Exception
    {
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT);
        _consumer.setMessageListener(countingMessageListener);
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        assertEquals("Unexpected number of outstanding messages", 0, countingMessageListener.getOutstandingCount());
    }

    public void testSynchronousReceiveFollowedByMessageListener() throws Exception
    {
        // Receive initial message synchronously
        assertNotNull("Could not receive first message synchronously", _consumer.receive(AWAIT_MESSAGE_TIMEOUT) != null);
        final int numberOfMessagesToReceiveByMessageListener = MSG_COUNT - 1;

        // Consume remainder asynchronously
        CountingMessageListener countingMessageListener = new CountingMessageListener(numberOfMessagesToReceiveByMessageListener);
        _consumer.setMessageListener(countingMessageListener);
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        assertEquals("Unexpected number of outstanding messages", 0, countingMessageListener.getOutstandingCount());
    }

    public void testMessageListenerSetDisallowsSynchronousReceive() throws Exception
    {
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT);
        _consumer.setMessageListener(countingMessageListener);

        try
        {
            _consumer.receive();
            fail("Exception not thrown");
        }
        catch (JMSException e)
        {
            // PASS
            assertEquals("A listener has already been set.", e.getMessage());
        }
    }


    public void testConnectionStopThenStart() throws Exception
    {
        int messageToReceivedBeforeConnectionStop = 2;
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT, messageToReceivedBeforeConnectionStop);

        // Consume at least two messages
        _consumer.setMessageListener(countingMessageListener);
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        _consumerConnection.stop();

        assertTrue("Too few messages received afer Connection#stop()", countingMessageListener.getReceivedCount() >= messageToReceivedBeforeConnectionStop);
        countingMessageListener.resetLatch();

        // Restart connection
        _consumerConnection.start();

        // Consume the remainder
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        assertEquals("Unexpected number of outstanding messages", 0, countingMessageListener.getOutstandingCount());
    }

    public void testConnectionStopAndMessageListenerChange() throws Exception
    {
        int messageToReceivedBeforeConnectionStop = 2;
        CountingMessageListener countingMessageListener1 = new CountingMessageListener(MSG_COUNT, messageToReceivedBeforeConnectionStop);

        // Consume remainder asynchronously
        _consumer.setMessageListener(countingMessageListener1);
        countingMessageListener1.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        _consumerConnection.stop();
        assertTrue("Too few messages received afer Connection#stop()", countingMessageListener1.getReceivedCount() >= messageToReceivedBeforeConnectionStop);

        CountingMessageListener countingMessageListener2 = new CountingMessageListener(countingMessageListener1.getOutstandingCount());

        // Reset Message Listener
        _consumer.setMessageListener(countingMessageListener2);

        _consumerConnection.start();

        // Consume the remainder
        countingMessageListener2.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        assertEquals("Unexpected number of outstanding messages", 0, countingMessageListener2.getOutstandingCount());

    }

    public void testConnectionStopHaltsDeliveryToListener() throws Exception
    {
        int messageToReceivedBeforeConnectionStop = 2;
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT, messageToReceivedBeforeConnectionStop);

        // Consume at least two messages
        _consumer.setMessageListener(countingMessageListener);
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        _consumerConnection.stop();

        // Connection should now be stopped and listener should receive no more
        final int outstandingCountAtStop = countingMessageListener.getOutstandingCount();
        countingMessageListener.resetLatch();
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT_NEGATIVE);

        assertEquals("Unexpected number of outstanding messages", outstandingCountAtStop, countingMessageListener.getOutstandingCount());
    }

    public void testSessionCloseHaltsDelivery() throws Exception
    {
        int messageToReceivedBeforeConnectionStop = 2;
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT, messageToReceivedBeforeConnectionStop);

        // Consume at least two messages
        _consumer.setMessageListener(countingMessageListener);
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        _consumerSession.close();

        // Once a session is closed, the listener should receive no more
        final int outstandingCountAtClose = countingMessageListener.getOutstandingCount();
        countingMessageListener.resetLatch();
        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT_NEGATIVE);

        assertEquals("Unexpected number of outstanding messages", outstandingCountAtClose, countingMessageListener.getOutstandingCount());
    }

    public void testImmediatePrefetchWithMessageListener() throws Exception
    {
        // Close connection provided by setup so we can set IMMEDIATE_PREFETCH
        _consumerConnection.close();
        setTestClientSystemProperty(AMQSession.IMMEDIATE_PREFETCH, "true");

        _consumerConnection = getConnection();
        _consumerConnection.start();
        _consumerSession = _consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        _consumer = _consumerSession.createConsumer(_queue);
        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT);
        _consumer.setMessageListener(countingMessageListener);

        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);

        assertEquals("Unexpected number of messages received", MSG_COUNT, countingMessageListener.getReceivedCount());
    }

    public void testReceiveTwoConsumers() throws Exception
    {
        Session consumerSession2 = _consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer _consumer2 = consumerSession2.createConsumer(_queue);

        CountingMessageListener countingMessageListener = new CountingMessageListener(MSG_COUNT);
        _consumer.setMessageListener(countingMessageListener);
        _consumer2.setMessageListener(countingMessageListener);

        countingMessageListener.awaitMessages(AWAIT_MESSAGE_TIMEOUT);
        assertEquals("Unexpected number of messages received", MSG_COUNT, countingMessageListener.getReceivedCount());
    }

    /**
     * Tests the case where the message listener throws an java.lang.Error.
     * TODO - a useful test?.
     */
    public void testMessageListenerThrowsError() throws Exception
    {
        int expectedMessages = 1;  // The error will kill the dispatcher so only one message will be delivered.
        final CountDownLatch awaitMessages = new CountDownLatch(expectedMessages);
        final AtomicInteger receivedCount = new AtomicInteger(0);
        final String javaLangErrorMessageText = "MessageListener failed with java.lang.Error";
        CountingExceptionListener countingExceptionListener = new CountingExceptionListener();
        _consumerConnection.setExceptionListener(countingExceptionListener);

        _consumer.setMessageListener(new MessageListener()
        {
            @Override
            public void onMessage(Message message)
            {
                try
                {
                    throw new Error(javaLangErrorMessageText);
                }
                finally
                {
                    receivedCount.incrementAndGet();
                    awaitMessages.countDown();
                }
            }
        });

        awaitMessages.await(AWAIT_MESSAGE_TIMEOUT, TimeUnit.MILLISECONDS);

        assertEquals("Unexpected number of messages received", expectedMessages, receivedCount.get());
        assertEquals("onException should NOT have been called", 0, countingExceptionListener.getErrorCount());

        // Check that Error has been written to the application log.

        LogMonitor _monitor = new LogMonitor(_outputFile);
        assertTrue("The expected message not written to log file.",
                _monitor.waitForMessage(javaLangErrorMessageText, LOGMONITOR_TIMEOUT));

        if (_consumerConnection != null)
        {
            try
            {
                _consumerConnection.close();
            }
            catch (JMSException e)
            {
                // Ignore connection close errors for this test.
            }
            finally
            {
                _consumerConnection = null;
            }
        }
    }

    private final class CountingExceptionListener implements ExceptionListener
    {
        private final AtomicInteger _errorCount = new AtomicInteger();

        @Override
        public void onException(JMSException arg0)
        {
            _errorCount.incrementAndGet();
        }

        public int getErrorCount()
        {
            return _errorCount.intValue();
        }
    }

    private final class CountingMessageListener implements MessageListener
    {
        private volatile CountDownLatch _awaitMessages;
        private final AtomicInteger _receivedCount;
        private final AtomicInteger _outstandingMessageCount;

        public CountingMessageListener(final int totalExpectedMessageCount)
        {
            this(totalExpectedMessageCount, totalExpectedMessageCount);
        }


        public CountingMessageListener(int totalExpectedMessageCount, int numberOfMessagesToAwait)
        {
            _receivedCount = new AtomicInteger(0);
            _outstandingMessageCount = new AtomicInteger(totalExpectedMessageCount);
            _awaitMessages = new CountDownLatch(numberOfMessagesToAwait);
        }

        public int getOutstandingCount()
        {
            return _outstandingMessageCount.get();
        }

        public int getReceivedCount()
        {
            return _receivedCount.get();
        }

        public void resetLatch()
        {
            _awaitMessages = new CountDownLatch(_outstandingMessageCount.get());
        }

        @Override
        public void onMessage(Message message)
        {
            _receivedCount.incrementAndGet();
            _outstandingMessageCount.decrementAndGet();
            _awaitMessages.countDown();
        }

        public boolean awaitMessages(long timeout)
        {
            try
            {
                return _awaitMessages.await(timeout, TimeUnit.MILLISECONDS);
            }
            catch (InterruptedException e)
            {
                Thread.currentThread().interrupt();
                return false;
            }
        }
    }

}