summaryrefslogtreecommitdiff
path: root/spring-jms/src/test/java/org/springframework/jms/listener/adapter/MessageListenerAdapterTests.java
blob: 3049c7911cd979b66348c91ec4e6c7b5e5a086e2 (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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
/*
 * Copyright 2002-2013 the original author or authors.
 *
 * Licensed 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.springframework.jms.listener.adapter;

import java.io.ByteArrayInputStream;
import java.io.Serializable;
import javax.jms.BytesMessage;
import javax.jms.IllegalStateException;
import javax.jms.InvalidDestinationException;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Queue;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.junit.Test;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import org.springframework.jms.support.converter.MessageConversionException;
import org.springframework.jms.support.converter.SimpleMessageConverter;

import static org.junit.Assert.*;
import static org.mockito.BDDMockito.*;

/**
 * @author Rick Evans
 * @author Juergen Hoeller
 * @author Chris Beams
 */
public class MessageListenerAdapterTests {

	private static final String TEXT = "I fancy a good cuppa right now";

	private static final Integer NUMBER = new Integer(1);

	private static final SerializableObject OBJECT = new SerializableObject();

	private static final String CORRELATION_ID = "100";

	private static final String RESPONSE_TEXT = "... wi' some full fat creamy milk. Top banana.";


	@Test
	public void testWithMessageContentsDelegateForTextMessage() throws Exception {
		TextMessage textMessage = mock(TextMessage.class);
		// TextMessage contents must be unwrapped...
		given(textMessage.getText()).willReturn(TEXT);

		MessageContentsDelegate delegate = mock(MessageContentsDelegate.class);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		adapter.onMessage(textMessage);

		verify(delegate).handleMessage(TEXT);
	}

	@Test
	public void testWithMessageContentsDelegateForBytesMessage() throws Exception {
		BytesMessage bytesMessage = mock(BytesMessage.class);
		// BytesMessage contents must be unwrapped...
		given(bytesMessage.getBodyLength()).willReturn(new Long(TEXT.getBytes().length));
		given(bytesMessage.readBytes(any(byte[].class))).willAnswer(new Answer<Integer>() {
			@Override
			public Integer answer(InvocationOnMock invocation) throws Throwable {
				byte[] bytes = (byte[]) invocation.getArguments()[0];
				ByteArrayInputStream inputStream = new ByteArrayInputStream(TEXT.getBytes());
				return inputStream.read(bytes);
			}
		});

		MessageContentsDelegate delegate = mock(MessageContentsDelegate.class);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		adapter.onMessage(bytesMessage);

		verify(delegate).handleMessage(TEXT.getBytes());
	}

	@Test
	public void testWithMessageContentsDelegateForObjectMessage() throws Exception {
		ObjectMessage objectMessage = mock(ObjectMessage.class);
		given(objectMessage.getObject()).willReturn(NUMBER);

		MessageContentsDelegate delegate = mock(MessageContentsDelegate.class);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		adapter.onMessage(objectMessage);

		verify(delegate).handleMessage(NUMBER);
	}

	@Test
	public void testWithMessageContentsDelegateForObjectMessageWithPlainObject() throws Exception {
		ObjectMessage objectMessage = mock(ObjectMessage.class);
		given(objectMessage.getObject()).willReturn(OBJECT);

		MessageContentsDelegate delegate = mock(MessageContentsDelegate.class);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		adapter.onMessage(objectMessage);

		verify(delegate).handleMessage(OBJECT);
	}

	@Test
	public void testWithMessageDelegate() throws Exception {
		TextMessage textMessage = mock(TextMessage.class);

		MessageDelegate delegate = mock(MessageDelegate.class);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		// we DON'T want the default SimpleMessageConversion happening...
		adapter.setMessageConverter(null);
		adapter.onMessage(textMessage);

		verify(delegate).handleMessage(textMessage);
	}

	@Test
	public void testWhenTheAdapterItselfIsTheDelegate() throws Exception {
		TextMessage textMessage = mock(TextMessage.class);
		// TextMessage contents must be unwrapped...
		given(textMessage.getText()).willReturn(TEXT);

		StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
		adapter.onMessage(textMessage);
		assertTrue(adapter.wasCalled());
	}

	@Test
	public void testRainyDayWithNoApplicableHandlingMethods() throws Exception {
		TextMessage textMessage = mock(TextMessage.class);
		// TextMessage contents must be unwrapped...
		given(textMessage.getText()).willReturn(TEXT);

		StubMessageListenerAdapter adapter = new StubMessageListenerAdapter();
		adapter.setDefaultListenerMethod("walnutsRock");
		adapter.onMessage(textMessage);
		assertFalse(adapter.wasCalled());
	}

	@Test
	public void testThatAnExceptionThrownFromTheHandlingMethodIsSimplySwallowedByDefault() throws Exception {
		final IllegalArgumentException exception = new IllegalArgumentException();

		TextMessage textMessage = mock(TextMessage.class);
		MessageDelegate delegate = mock(MessageDelegate.class);
		willThrow(exception).given(delegate).handleMessage(textMessage);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected void handleListenerException(Throwable ex) {
				assertNotNull("The Throwable passed to the handleListenerException(..) method must never be null.", ex);
				assertTrue("The Throwable passed to the handleListenerException(..) method must be of type [ListenerExecutionFailedException].",
						ex instanceof ListenerExecutionFailedException);
				ListenerExecutionFailedException lefx = (ListenerExecutionFailedException) ex;
				Throwable cause = lefx.getCause();
				assertNotNull("The cause of a ListenerExecutionFailedException must be preserved.", cause);
				assertSame(exception, cause);
			}
		};
		// we DON'T want the default SimpleMessageConversion happening...
		adapter.setMessageConverter(null);
		adapter.onMessage(textMessage);
	}

	@Test
	public void testThatTheDefaultMessageConverterisIndeedTheSimpleMessageConverter() throws Exception {
		MessageListenerAdapter adapter = new MessageListenerAdapter();
		assertNotNull("The default [MessageConverter] must never be null.", adapter.getMessageConverter());
		assertTrue("The default [MessageConverter] must be of the type [SimpleMessageConverter]",
				adapter.getMessageConverter() instanceof SimpleMessageConverter);
	}

	@Test
	public void testThatWhenNoDelegateIsSuppliedTheDelegateIsAssumedToBeTheMessageListenerAdapterItself() throws Exception {
		MessageListenerAdapter adapter = new MessageListenerAdapter();
		assertSame(adapter, adapter.getDelegate());
	}

	@Test
	public void testThatTheDefaultMessageHandlingMethodNameIsTheConstantDefault() throws Exception {
		MessageListenerAdapter adapter = new MessageListenerAdapter();
		assertEquals(MessageListenerAdapter.ORIGINAL_DEFAULT_LISTENER_METHOD, adapter.getDefaultListenerMethod());
	}

	@Test
	public void testWithResponsiveMessageDelegate_DoesNotSendReturnTextMessageIfNoSessionSupplied() throws Exception {
		TextMessage textMessage = mock(TextMessage.class);
		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(textMessage)).willReturn(TEXT);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate);
		// we DON'T want the default SimpleMessageConversion happening...
		adapter.setMessageConverter(null);
		adapter.onMessage(textMessage);
	}

	@Test
	public void testWithResponsiveMessageDelegateWithDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
		Queue destination = mock(Queue.class);
		TextMessage sentTextMessage = mock(TextMessage.class);
		// correlation ID is queried when response is being created...
		given(sentTextMessage.getJMSCorrelationID()).willReturn(
				CORRELATION_ID);
		// Reply-To is queried when response is being created...
		given(sentTextMessage.getJMSReplyTo()).willReturn(null); // we want to fall back to the default...

		TextMessage responseTextMessage = mock(TextMessage.class);

		QueueSender queueSender = mock(QueueSender.class);
		Session session = mock(Session.class);
		given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage);
		given(session.createProducer(destination)).willReturn(queueSender);

		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		adapter.setDefaultResponseDestination(destination);
		adapter.onMessage(sentTextMessage, session);

		verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID);
		verify(queueSender).send(responseTextMessage);
		verify(queueSender).close();
		verify(delegate).handleMessage(sentTextMessage);
	}

	@Test
	public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
		Queue destination = mock(Queue.class);
		TextMessage sentTextMessage = mock(TextMessage.class);
		// correlation ID is queried when response is being created...
		given(sentTextMessage.getJMSCorrelationID()).willReturn(null);
		given(sentTextMessage.getJMSMessageID()).willReturn(CORRELATION_ID);
		// Reply-To is queried when response is being created...
		given(sentTextMessage.getJMSReplyTo()).willReturn(destination);

		TextMessage responseTextMessage = mock(TextMessage.class);
		MessageProducer messageProducer = mock(MessageProducer.class);
		Session session = mock(Session.class);
		given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage);
		given(session.createProducer(destination)).willReturn(messageProducer);

		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

		MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		adapter.onMessage(sentTextMessage, session);

		verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID);
		verify(messageProducer).send(responseTextMessage);
		verify(messageProducer).close();
		verify(delegate).handleMessage(sentTextMessage);
	}

	@Test
	public void testWithResponsiveMessageDelegateNoDefaultDestinationAndNoReplyToDestination_SendsReturnTextMessageWhenSessionSupplied() throws Exception {
		final TextMessage sentTextMessage = mock(TextMessage.class);
		// correlation ID is queried when response is being created...
		given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID);
		// Reply-To is queried when response is being created...
		given(sentTextMessage.getJMSReplyTo()).willReturn(null);

		TextMessage responseTextMessage = mock(TextMessage.class);
		final QueueSession session = mock(QueueSession.class);
		given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage);

		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

		final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		try {
			adapter.onMessage(sentTextMessage, session);
			fail("expected CouldNotSendReplyException with InvalidDestinationException");
		} catch(ReplyFailureException ex) {
			assertEquals(InvalidDestinationException.class, ex.getCause().getClass());
		}

		verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID);
		verify(delegate).handleMessage(sentTextMessage);
	}

	@Test
	public void testWithResponsiveMessageDelegateNoDefaultDestination_SendsReturnTextMessageWhenSessionSupplied_AndSendingThrowsJMSException() throws Exception {
		Queue destination = mock(Queue.class);

		final TextMessage sentTextMessage = mock(TextMessage.class);
		// correlation ID is queried when response is being created...
		given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID);
		// Reply-To is queried when response is being created...
		given(sentTextMessage.getJMSReplyTo()).willReturn(destination);

		TextMessage responseTextMessage = mock(TextMessage.class);
		MessageProducer messageProducer = mock(MessageProducer.class);
		willThrow(new JMSException("Doe!")).given(messageProducer).send(responseTextMessage);

		final QueueSession session = mock(QueueSession.class);
		given(session.createTextMessage(RESPONSE_TEXT)).willReturn(responseTextMessage);
		given(session.createProducer(destination)).willReturn(messageProducer);

		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

		final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		try {
			adapter.onMessage(sentTextMessage, session);
			fail("expected CouldNotSendReplyException with JMSException");
		} catch(ReplyFailureException ex) {
			assertEquals(JMSException.class, ex.getCause().getClass());
		}

		verify(responseTextMessage).setJMSCorrelationID(CORRELATION_ID);
		verify(messageProducer).close();
		verify(delegate).handleMessage(sentTextMessage);
	}

	@Test
	public void testWithResponsiveMessageDelegateDoesNotSendReturnTextMessageWhenSessionSupplied_AndListenerMethodThrowsException() throws Exception {
		final TextMessage message = mock(TextMessage.class);
		final QueueSession session = mock(QueueSession.class);

		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		willThrow(new IllegalArgumentException("Doe!")).given(delegate).handleMessage(message);

		final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		try {
			adapter.onMessage(message, session);
			fail("expected ListenerExecutionFailedException");
		} catch(ListenerExecutionFailedException ex) { /* expected */ }
	}

	@Test
	public void testFailsIfNoDefaultListenerMethodNameIsSupplied() throws Exception {
		final TextMessage message = mock(TextMessage.class);
		given(message.getText()).willReturn(TEXT);

		final MessageListenerAdapter adapter = new MessageListenerAdapter() {
			@Override
			protected void handleListenerException(Throwable ex) {
				assertTrue(ex instanceof IllegalStateException);
			}
		};
		adapter.setDefaultListenerMethod(null);
		adapter.onMessage(message);
	}

	@Test
	public void testFailsWhenOverriddenGetListenerMethodNameReturnsNull() throws Exception {
		final TextMessage message = mock(TextMessage.class);
		given(message.getText()).willReturn(TEXT);

		final MessageListenerAdapter adapter = new MessageListenerAdapter() {
			@Override
			protected void handleListenerException(Throwable ex) {
				assertTrue(ex instanceof javax.jms.IllegalStateException);
			}
			@Override
			protected String getListenerMethodName(Message originalMessage, Object extractedMessage) {
				return null;
			}
		};
		adapter.setDefaultListenerMethod(null);
		adapter.onMessage(message);
	}

	@Test
	public void testWithResponsiveMessageDelegateWhenReturnTypeIsNotAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
		final TextMessage sentTextMessage = mock(TextMessage.class);
		final Session session = mock(Session.class);
		ResponsiveMessageDelegate delegate = mock(ResponsiveMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(RESPONSE_TEXT);

		final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		adapter.setMessageConverter(null);
		try {
			adapter.onMessage(sentTextMessage, session);
			fail("expected CouldNotSendReplyException with MessageConversionException");
		} catch(ReplyFailureException ex) {
			assertEquals(MessageConversionException.class, ex.getCause().getClass());
		}
	}

	@Test
	public void testWithResponsiveMessageDelegateWhenReturnTypeIsAJMSMessageAndNoMessageConverterIsSupplied() throws Exception {
		Queue destination = mock(Queue.class);
		final TextMessage sentTextMessage = mock(TextMessage.class);
		// correlation ID is queried when response is being created...
		given(sentTextMessage.getJMSCorrelationID()).willReturn(CORRELATION_ID);
		// Reply-To is queried when response is being created...
		given(sentTextMessage.getJMSReplyTo()).willReturn(destination);

		TextMessage responseMessage = mock(TextMessage.class);
		QueueSender queueSender = mock(QueueSender.class);

		Session session = mock(Session.class);
		given(session.createProducer(destination)).willReturn(queueSender);

		ResponsiveJmsTextMessageReturningMessageDelegate delegate = mock(ResponsiveJmsTextMessageReturningMessageDelegate.class);
		given(delegate.handleMessage(sentTextMessage)).willReturn(responseMessage);

		final MessageListenerAdapter adapter = new MessageListenerAdapter(delegate) {
			@Override
			protected Object extractMessage(Message message) {
				return message;
			}
		};
		adapter.setMessageConverter(null);
		adapter.onMessage(sentTextMessage, session);

		verify(responseMessage).setJMSCorrelationID(CORRELATION_ID);
		verify(queueSender).send(responseMessage);
		verify(queueSender).close();
	}


	@SuppressWarnings("serial")
	private static class SerializableObject implements Serializable {
	}

}