ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.setWatchTopicAdvisories(watchTopicAdvisories);
cf.setDispatchAsync(false);
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue destination = producerSession.createQueue(QUEUE_NAME
+ "?consumer.prefetchSize=" + prefetch);
final Queue signalDestination = producerSession.createQueue(QUEUE_NAME + ".signal"
+ "?consumer.prefetchSize=" + prefetch);
final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
final CountDownLatch commitDoneLatch = new CountDownLatch(1);
final CountDownLatch messagesReceived = new CountDownLatch(3);
final AtomicBoolean gotCommitException = new AtomicBoolean(false);
final ArrayList<TextMessage> receivedMessages = new ArrayList<TextMessage>();
final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
testConsumer.setMessageListener(new MessageListener() {
public void onMessage(Message message) {
LOG.info("consume one and commit: " + message);
assertNotNull("got message", message);
receivedMessages.add((TextMessage) message);
try {
produceMessage(consumerSession, signalDestination, 1);
consumerSession.commit();
} catch (JMSException e) {
LOG.info("commit exception", e);
gotCommitException.set(true);
}
commitDoneLatch.countDown();
messagesReceived.countDown();
LOG.info("done commit");
}
});
// may block if broker shutdown happens quickly
Executors.newSingleThreadExecutor().execute(new Runnable() {
public void run() {
LOG.info("producer started");
try {
produceMessage(producerSession, destination, prefetch * 2);
} catch (JMSException e) {
e.printStackTrace();
fail("unexpceted ex on producer: " + e);
}
LOG.info("producer done");
}
});
// will be stopped by the plugin
broker.waitUntilStopped();
broker = createBroker(false, url);
broker.start();
assertTrue("commit done through failover", commitDoneLatch.await(20, TimeUnit.SECONDS));
assertTrue("commit failed", gotCommitException.get());
assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS));
assertEquals("get message 0 first", MESSAGE_TEXT + "0", receivedMessages.get(0).getText());
// it was redelivered
assertEquals("get message 0 second", MESSAGE_TEXT + "0", receivedMessages.get(1).getText());
assertTrue("another message was received", messagesReceived.await(20, TimeUnit.SECONDS));
assertEquals("get message 1 eventually", MESSAGE_TEXT + "1", receivedMessages.get(2).getText());
connection.close();
}