new RuntimeException("Channel aware listener runtime exception")));
}
@Test
public void testRejectingErrorHandler() throws Exception {
RabbitTemplate template = createTemplate(1);
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(template.getConnectionFactory());
MessageListenerAdapter messageListener = new MessageListenerAdapter();
messageListener.setDelegate(new Object());
container.setMessageListener(messageListener);
RabbitAdmin admin = new RabbitAdmin(template.getConnectionFactory());
Map<String, Object> args = new HashMap<String, Object>();
args.put("x-dead-letter-exchange", "test.DLE");
Queue queue = new Queue("", false, false, true, args);
String testQueueName = admin.declareQueue(queue);
// Create a DeadLetterExchange and bind a queue to it with the original routing key
DirectExchange dle = new DirectExchange("test.DLE", false, true);
admin.declareExchange(dle);
Queue dlq = new AnonymousQueue();
admin.declareQueue(dlq);
admin.declareBinding(BindingBuilder.bind(dlq).to(dle).with(testQueueName));
container.setQueueNames(testQueueName);
container.afterPropertiesSet();
container.start();
Message message = MessageBuilder.withBody("foo".getBytes())
.setContentType("text/plain")
.setContentEncoding("junk")
.build();
template.send("", testQueueName, message);
Message rejected = template.receive(dlq.getName());
int n = 0;
while (n++ < 100 && rejected == null) {
Thread.sleep(100);
rejected = template.receive(dlq.getName());
}
assertTrue("Message did not arrive in DLQ", n < 100);
assertEquals("foo", new String(rejected.getBody()));
// Verify that the exception strategy has access to the message
final AtomicReference<Message> failed = new AtomicReference<Message>();
ConditionalRejectingErrorHandler eh = new ConditionalRejectingErrorHandler(new FatalExceptionStrategy() {
@Override
public boolean isFatal(Throwable t) {
if (t instanceof ListenerExecutionFailedException) {
failed.set(((ListenerExecutionFailedException) t).getFailedMessage());
}
return t instanceof ListenerExecutionFailedException
&& t.getCause() instanceof MessageConversionException;
}
});
container.setErrorHandler(eh);
template.send("", testQueueName, message);
rejected = template.receive(dlq.getName());
n = 0;
while (n++ < 100 && rejected == null) {
Thread.sleep(100);
rejected = template.receive(dlq.getName());
}
assertTrue("Message did not arrive in DLQ", n < 100);
assertEquals("foo", new String(rejected.getBody()));
assertNotNull(failed.get());