Here are the examples of the java api org.apache.activemq.ActiveMQConnection.createSession() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
68 Examples
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
@Override
public <T extends ClientRequestResult> Collection<T> sendRequest(final JsonRequest<T> jsonRequest, final String queueName, final int timeout, final ClientRequestReportListener reportListener) throws JMSException {
if (queueName == null) {
throw new NullPointerException("sendRequest(..) method called with null queue name argument");
}
if (jsonRequest == null) {
throw new NullPointerException("sendRequest(..) method called with null request argument");
}
ensureConnection();
if (connected) {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
Message message = null;
if (jsonRequest.isObjectRequest()) {
// used for EXECUTE_COMMAND_REQUESTS
// send only the object
// CommandExecuteRequest o = (CommandExecuteRequest) jsonRequest.getObjectParameter();
message = session.createObjectMessage((Serializable) jsonRequest.getObjectParameter());
} else {
// used for all other request types
// send the Client Request as a Json Text Message
message = session.createTextMessage(jsonRequest.toJson());
}
TemporaryQueue replyQueue = session.createTemporaryQueue();
MessageConsumer consumer = session.createConsumer(replyQueue);
try {
message.setJMSReplyTo(replyQueue);
MessageProducer producer = session.createProducer(new ActiveMQQueue(queueName));
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
producer.setTimeToLive(JMS_MESSAGE_TIMEOUT);
producer.send(message);
while (connected && !shutdownRequested) {
// until we receive the result
// (it is possible to receive progress and / or error reports during this process)
Message replyMessage = consumer.receive(timeout);
if (replyMessage == null) {
log.error("No reply received from server on ClientRequest. I was waiting for " + timeout + " milliseconds..");
throw new RuntimeException("No reply received from server - possible timeout?");
}
if (replyMessage instanceof ObjectMessage) {
return (Collection<T>) ((ObjectMessage) replyMessage).getObject();
} else {
// replyMessage is an instanceof TextMessage (json)
TextMessage textMessage = (TextMessage) (replyMessage);
Collection<T> resultCollection = handleJsonResponse(textMessage, jsonRequest, reportListener);
if (resultCollection != null)
return resultCollection;
}
}
throw new RuntimeException("Disconnected from JMS, so unable to process request.");
} finally {
if (consumer != null) {
consumer.close();
}
replyQueue.delete();
}
} finally {
session.close();
}
} else {
throw new JMSException("Not currently connected: unable to send request at this time.");
}
}
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
@Override
public void registerUpdateListener(final TagUpdateListener serverUpdateListener, final TopicRegistrationDetails topicRegistrationDetails) throws JMSException {
if (topicRegistrationDetails == null) {
throw new NullPointerException("Trying to register a TagUpdateListener with null RegistrationDetails!");
}
if (serverUpdateListener == null) {
throw new NullPointerException("TagUpdateListener must not be null!");
}
ensureConnection();
refreshLock.readLock().lock();
try {
listenerLock.lock();
try {
boolean refreshSubscriptions = refreshLock.isWriteLocked();
if (refreshSubscriptions || !isRegisteredListener(serverUpdateListener)) {
// throw exception if
// TagUpdateListener
// null
try {
if (refreshSubscriptions || connected) {
String topicName = topicRegistrationDetails.getTopicName();
if (topicToWrapper.containsKey(topicName)) {
topicToWrapper.get(topicName).addListener(serverUpdateListener, topicRegistrationDetails.getId());
} else {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Topic topic = session.createTopic(topicRegistrationDetails.getTopicName());
MessageConsumer consumer = session.createConsumer(topic);
MessageListenerWrapper wrapper = new MessageListenerWrapper(topicRegistrationDetails.getId(), serverUpdateListener, HIGH_LISTENER_QUEUE_SIZE, slowConsumerListener, topicPollingExecutor);
wrapper.start();
consumer.setMessageListener(wrapper);
topicToWrapper.put(topicName, wrapper);
sessions.put(wrapper, session);
}
if (!refreshSubscriptions) {
registeredListeners.put(serverUpdateListener, topicRegistrationDetails);
}
} else {
throw new JMSException("Not currently connected - will attempt to subscribe on reconnection. Attempting to reconnect.");
}
} catch (JMSException e) {
log.error("Failed to subscribe to topic - will do so on reconnection.", e);
if (!refreshSubscriptions) {
registeredListeners.put(serverUpdateListener, topicRegistrationDetails);
}
throw e;
}
} else {
log.debug("Update listener already registered; skipping registration (for Tag " + topicRegistrationDetails.getId() + ")");
}
} finally {
listenerLock.unlock();
}
} finally {
refreshLock.readLock().unlock();
}
}
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
@Override
public void publish(final String message, final String topicName, final long timeToLive) throws JMSException {
if (topicName == null) {
throw new NullPointerException("publish(..) method called with null queue name argument");
}
if (message == null) {
throw new NullPointerException("publish(..) method called with null message argument");
}
if (connected) {
final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
try {
final Message messageObj = session.createTextMessage(message);
final MessageProducer producer = session.createProducer(new ActiveMQTopic(topicName));
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
producer.setTimeToLive(JMS_MESSAGE_TIMEOUT);
producer.send(messageObj);
} finally {
session.close();
}
} else {
throw new JMSException("Not currently connected: unable to send message at this time.");
}
}
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
/**
* Called when refreshing subscriptions at start up and again if the
* connection goes down.
*
* @throws JMSException
* if unable to subscribe
*/
private void subscribeToAdminMessageTopic() throws JMSException {
if (adminMessageTopic != null) {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final MessageConsumer consumer = session.createConsumer(adminMessageTopic);
consumer.setMessageListener(broadcastMessageListenerWrapper);
}
}
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
/**
* Subscribes to the heartbeat topic. Called when refreshing all
* subscriptions.
* @throws JMSException if problem subscribing
*/
private void subscribeToHeartbeatTopic() throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(heartbeatTopic);
consumer.setMessageListener(heartbeatListenerWrapper);
}
19
View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
/**
* Called when refreshing subscriptions at start up and again if the
* connection goes down.
*
* @throws JMSException
* if unable to subscribe
*/
private void subscribeToSupervisionTopic() throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(supervisionTopic);
consumer.setMessageListener(supervisionListenerWrapper);
}
18
View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private Message receiveMessage(ActiveMQConnectionFactory cf, Queue destination) throws Exception {
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
final MessageConsumer consumer = consumerSession.createConsumer(destination);
Message msg = consumer.receive(5000);
consumerSession.commit();
connection.close();
return msg;
}
18
View Complete Implementation : ActiveMQueue.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private Session getSession() throws Exception {
if (connection == null) {
init();
}
return connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
}
18
View Complete Implementation : ActiveMQueue.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Override
public void init() {
try {
createAndStartConnection("", "", brokerUrl);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(destinationName);
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
LOG.info("Initialized Queue on ActiveMQ: {}", destinationName);
} catch (Exception e) {
throw new RuntimeException("Error starting ActiveMQ connection for delayed queue", e);
}
}
18
View Complete Implementation : ActiveMqMessagingService.java
Copyright Apache License 2.0
Author : gocd
Copyright Apache License 2.0
Author : gocd
@Override
public JMSMessageListenerAdapter addListener(String topic, final GoMessageListener listener) {
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createTopic(topic));
return JMSMessageListenerAdapter.startListening(consumer, listener, daemonThreadStatsCollector, systemEnvironment, serverHealthService);
} catch (Exception e) {
throw bomb(e);
}
}
18
View Complete Implementation : ActiveMqMessagingService.java
Copyright Apache License 2.0
Author : gocd
Copyright Apache License 2.0
Author : gocd
@Override
public MessageSender createSender(String topic) {
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(session.createTopic(topic));
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
return new ActiveMqMessageSender(session, producer);
} catch (Exception e) {
throw bomb(e);
}
}
18
View Complete Implementation : ActiveMqMessagingService.java
Copyright Apache License 2.0
Author : gocd
Copyright Apache License 2.0
Author : gocd
@Override
public JMSMessageListenerAdapter addQueueListener(String queueName, final GoMessageListener listener) {
try {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(session.createQueue(queueName));
return JMSMessageListenerAdapter.startListening(consumer, listener, daemonThreadStatsCollector, systemEnvironment, serverHealthService);
} catch (Exception e) {
throw bomb(e);
}
}
18
View Complete Implementation : ActiveMQueue.java
Copyright Apache License 2.0
Author : sriksun
Copyright Apache License 2.0
Author : sriksun
@Override
public void init() {
try {
createAndStartConnection("", "", brokerUrl);
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(destinationName);
producer = session.createProducer(destination);
consumer = session.createConsumer(destination);
LOG.info("Initialized Queue on activeMQ: " + destinationName);
} catch (Exception e) {
LOG.error("Error starting ActiveMQueue connection for dealyed queue", e);
throw new RuntimeException("Error starting ActiveMQueue connection for delayed queue", e);
}
}
18
View Complete Implementation : BrokerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testNoScheduledRedeliveryOfExpired() throws Exception {
startBroker(true);
ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
consumerConnection.start();
Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(destination);
sendMessage(1500);
Message message = consumer.receive(1000);
replacedertNotNull("got message", message);
// ensure there is another consumer to redispatch to
MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination);
// allow consumed to expire so it gets redelivered
TimeUnit.SECONDS.sleep(2);
consumer.close();
// should go to dlq as it has expired
// validate DLQ
MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
Message dlqMessage = dlqConsumer.receive(2000);
replacedertNotNull("Got message from dql", dlqMessage);
replacedertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
}
18
View Complete Implementation : ActiveMQueue.java
Copyright Apache License 2.0
Author : sriksun
Copyright Apache License 2.0
Author : sriksun
private Session getSession() throws Exception {
if (connection == null) {
init();
}
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
return session;
}
17
View Complete Implementation : AbortSlowAckConsumer0Test.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testIdleConsumerCanBeAborted() throws Exception {
strategy.setIgnoreIdleConsumers(false);
// Make it shorter
strategy.setMaxTimeSinceLastAck(2000);
ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
conn.setExceptionListener(this);
connections.add(conn);
Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageConsumer consumer = sess.createConsumer(destination);
replacedertNotNull(consumer);
conn.start();
startProducers(destination, 1);
Message message = consumer.receive(5000);
replacedertNotNull(message);
message.acknowledge();
// Consumer needs to be closed before the receive call.
TimeUnit.SECONDS.sleep(15);
try {
consumer.receive(5000);
fail("Idle consumer not aborted.");
} catch (Exception ex) {
}
}
17
View Complete Implementation : AbortSlowAckConsumer0Test.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testZeroPrefetchConsumerIsAborted() throws Exception {
// Make it shorter
strategy.setMaxTimeSinceLastAck(2000);
ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
conn.setExceptionListener(this);
connections.add(conn);
Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageConsumer consumer = sess.createConsumer(destination);
replacedertNotNull(consumer);
conn.start();
startProducers(destination, 20);
Message message = consumer.receive(5000);
replacedertNotNull(message);
TimeUnit.SECONDS.sleep(15);
try {
consumer.receive(5000);
fail("Slow consumer not aborted.");
} catch (Exception ex) {
}
}
17
View Complete Implementation : AbortSlowAckConsumer0Test.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testIdleConsumerCanBeAbortedNoMessages() throws Exception {
strategy.setIgnoreIdleConsumers(false);
// Make it shorter
strategy.setMaxTimeSinceLastAck(2000);
ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
conn.setExceptionListener(this);
connections.add(conn);
Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageConsumer consumer = sess.createConsumer(destination);
replacedertNotNull(consumer);
conn.start();
startProducers(destination, 1);
Message message = consumer.receive(5000);
replacedertNotNull(message);
// Consumer needs to be closed before the receive call.
TimeUnit.SECONDS.sleep(15);
try {
consumer.receive(5000);
fail("Idle consumer not aborted.");
} catch (Exception ex) {
}
}
17
View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagAfterRestartNoTx() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(20000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
consumer.close();
restartBroker();
// make failover aware of the restarted auto replacedigned port
connection.getTransport().narrow(FailoverTransport.clreplaced).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
consumer = session.createConsumer(destination);
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("re delivery flag", true, msg.getJMSRedelivered());
replacedertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
// consume the rest that were not redeliveries
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(20000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
connection.close();
}
17
View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testDurableSubRedeliveryFlagAfterRestartNotSupported() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.setClientID("id");
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
ActiveMQTopic destination = new ActiveMQTopic(queueName);
TopicSubscriber durableSub = session.createDurableSubscriber(destination, "id");
populateDestination(10, destination, connection);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = (TextMessage) durableSub.receive(20000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
durableSub.close();
restartBroker();
// make failover aware of the restarted auto replacedigned port
connection.getTransport().narrow(FailoverTransport.clreplaced).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
durableSub = session.createDurableSubscriber(destination, "id");
for (int i = 0; i < 10; i++) {
msg = (TextMessage) durableSub.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("no reDelivery flag", false, msg.getJMSRedelivered());
msg.acknowledge();
}
connection.close();
}
17
View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagAfterRecovery() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Destination destination = session.createQueue(queueName);
populateDestination(1, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = (TextMessage) consumer.receive(5000);
LOG.info("got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
stopBrokerWithStoreFailure(broker, persistenceAdapterChoice);
broker = createRestartedBroker();
broker.start();
connection.close();
connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString());
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
session = connection.createSession(true, Session.SESSION_TRANSACTED);
consumer = session.createConsumer(destination);
msg = (TextMessage) consumer.receive(10000);
replacedertNotNull("got the message again", msg);
replacedertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("re delivery flag", true, msg.getJMSRedelivered());
session.commit();
connection.close();
}
17
View Complete Implementation : RedeliveryRestartWithExceptionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagAfterTransientFailureConnectionDrop() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection, true);
TextMessage msg = null;
MessageConsumer consumer = session.createConsumer(destination);
Exception expectedException = null;
try {
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(5000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertTrue("Should not receive the 5th message", i < 4);
// The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered
}
} catch (Exception e) {
// Expecting an exception and disconnect on the 5th message
LOG.info("Got expected:", e);
expectedException = e;
}
replacedertNotNull("Expecting an exception when updateMessage fails", expectedException);
consumer.close();
connection.close();
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = session.createQueue(queueName);
consumer = session.createConsumer(destination);
// consume the messages that were previously delivered
for (int i = 0; i < 4; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("re delivery flag on:" + i, true, msg.getJMSRedelivered());
replacedertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1);
msg.acknowledge();
}
// consume the rest that were not redeliveries
for (int i = 0; i < 6; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
connection.close();
}
17
View Complete Implementation : RedeliveryRestartWithExceptionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagOnNonPersistentAfterTransientFailureConnectionDrop() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection, false);
TextMessage msg = null;
MessageConsumer consumer = session.createConsumer(destination);
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(5000);
replacedertNotNull("got the message", msg);
replacedertFalse("not redelivered", msg.getJMSRedelivered());
}
connection.getTransport().narrow(TcpTransport.clreplaced).getTransportListener().onException(new IOException("Die"));
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = session.createQueue(queueName);
consumer = session.createConsumer(destination);
// consume the messages that were previously delivered
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("redelivery flag set on:" + i, true, msg.getJMSRedelivered());
replacedertTrue("redelivery count survives reconnect for:" + i, msg.getLongProperty("JMSXDeliveryCount") > 1);
msg.acknowledge();
}
// consume the rest that were not redeliveries
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
connection.close();
}
17
View Complete Implementation : RedeliveryRestartWithExceptionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagAfterRestart() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection, true);
TextMessage msg = null;
MessageConsumer consumer = session.createConsumer(destination);
Exception expectedException = null;
try {
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(5000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertTrue("Should not receive the 5th message", i < 4);
// The first 4 messages will be ok but the 5th one should hit an exception in updateMessage and should not be delivered
}
} catch (Exception e) {
// Expecting an exception and disconnect on the 5th message
LOG.info("Got expected:", e);
expectedException = e;
}
replacedertNotNull("Expecting an exception when updateMessage fails", expectedException);
consumer.close();
connection.close();
restartBroker();
connectionFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString() + "?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
destination = session.createQueue(queueName);
consumer = session.createConsumer(destination);
// consume the messages that were previously delivered
for (int i = 0; i < 4; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("re delivery flag", true, msg.getJMSRedelivered());
replacedertTrue("redelivery count survives restart", msg.getLongProperty("JMSXDeliveryCount") > 1);
msg.acknowledge();
}
// consume the rest that were not redeliveries
for (int i = 0; i < 6; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
msg.acknowledge();
}
connection.close();
}
17
View Complete Implementation : FailoverClusterTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected void createClients() throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl);
for (int i = 0; i < NUMBER; i++) {
System.out.println("*****create connection using url: " + clientUrl);
ActiveMQConnection c = (ActiveMQConnection) factory.createConnection();
System.out.println("got connection, starting it ...");
c.start();
System.out.println("******Started");
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = s.createQueue(getClreplaced().getName());
MessageConsumer consumer = s.createConsumer(queue);
connections.add(c);
}
}
17
View Complete Implementation : FailoverComplexClusterTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
protected void createClients(int numOfClients) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl);
for (int i = 0; i < numOfClients; i++) {
ActiveMQConnection c = (ActiveMQConnection) factory.createConnection();
c.start();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = s.createQueue(getClreplaced().getName());
MessageConsumer consumer = s.createConsumer(queue);
connections.add(c);
}
}
17
View Complete Implementation : FailoverConsumerUnconsumedTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
@BMRules(rules = { @BMRule(name = "set no return response and stop the broker", targetClreplaced = "org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection$CommandProcessor", targetMethod = "processAddConsumer", targetLocation = "ENTRY", action = "org.apache.activemq.transport.failover.FailoverConsumerUnconsumedTest.holdResponseAndStopBroker($0)") })
public void testFailoverClientAckMissingRedelivery() throws Exception {
maxConsumers = 2;
brokerStopLatch = new CountDownLatch(1);
broker = createBroker();
broker.start();
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.sereplacedchTopicAdvisories(false);
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?jms.consumer.prefetch=" + prefetch);
doByteman.set(true);
final Vector<TestConsumer> testConsumers = new Vector<>();
TestConsumer testConsumer = new TestConsumer(consumerSession, destination, connection);
testConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
LOG.info("onMessage:" + message.getJMSMessageID());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
testConsumers.add(testConsumer);
produceMessage(consumerSession, destination, maxConsumers * prefetch);
replacedertTrue("add messages are delivered", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int totalDelivered = 0;
for (TestConsumer testConsumer : testConsumers) {
long delivered = testConsumer.deliveredSize();
LOG.info(testConsumer.getConsumerId() + " delivered: " + delivered);
totalDelivered += delivered;
}
return totalDelivered == maxConsumers * prefetch;
}
}));
final CountDownLatch shutdownConsumerAdded = new CountDownLatch(1);
new Thread() {
@Override
public void run() {
try {
LOG.info("add last consumer...");
TestConsumer testConsumer = new TestConsumer(consumerSession, destination, connection);
testConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
try {
LOG.info("onMessage:" + message.getJMSMessageID());
} catch (JMSException e) {
e.printStackTrace();
}
}
});
testConsumers.add(testConsumer);
shutdownConsumerAdded.countDown();
LOG.info("done add last consumer");
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
brokerStopLatch.await();
doByteman.set(false);
broker = createBroker();
broker.start();
replacedertTrue("consumer added through failover", shutdownConsumerAdded.await(30, TimeUnit.SECONDS));
// each should again get prefetch messages - all unacked deliveries should be rolledback
replacedertTrue("after restart all messages are re dispatched", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int totalDelivered = 0;
for (TestConsumer testConsumer : testConsumers) {
long delivered = testConsumer.deliveredSize();
LOG.info(testConsumer.getConsumerId() + " delivered: " + delivered);
totalDelivered += delivered;
}
return totalDelivered == maxConsumers * prefetch;
}
}));
connection.close();
}
16
View Complete Implementation : FailoverClusterTestSupport.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@SuppressWarnings("unused")
protected void createClients(int numOfClients) throws Exception {
ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(clientUrl);
for (int i = 0; i < numOfClients; i++) {
ActiveMQConnection c = (ActiveMQConnection) factory.createConnection();
c.start();
Session s = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = s.createQueue(getClreplaced().getName());
MessageConsumer consumer = s.createConsumer(queue);
connections.add(c);
}
}
16
View Complete Implementation : FailoverConsumerUnconsumedTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception {
maxConsumers = 4;
broker = createBroker();
broker.start();
brokerStopLatch = new CountDownLatch(1);
doByteman.set(true);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.sereplacedchTopicAdvisories(watchTopicAdvisories);
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?jms.consumer.prefetch=" + prefetch);
final Vector<TestConsumer> testConsumers = new Vector<>();
for (int i = 0; i < maxConsumers - 1; i++) {
testConsumers.add(new TestConsumer(consumerSession, destination, connection));
}
replacedureQueueMessages(0, new SimpleString(QUEUE_NAME));
produceMessage(consumerSession, destination, maxConsumers * prefetch);
replacedertTrue("add messages are dispatched", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int totalUnconsumed = 0;
for (TestConsumer testConsumer : testConsumers) {
long unconsumed = testConsumer.unconsumedSize();
LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed);
totalUnconsumed += unconsumed;
}
return totalUnconsumed == (maxConsumers - 1) * prefetch;
}
}));
final CountDownLatch shutdownConsumerAdded = new CountDownLatch(1);
new Thread() {
@Override
public void run() {
try {
LOG.info("add last consumer...");
testConsumers.add(new TestConsumer(consumerSession, destination, connection));
shutdownConsumerAdded.countDown();
LOG.info("done add last consumer");
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
// verify interrupt
replacedertTrue("add messages dispatched and unconsumed are cleaned up", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int totalUnconsumed = 0;
for (TestConsumer testConsumer : testConsumers) {
long unconsumed = testConsumer.unconsumedSize();
LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed);
totalUnconsumed += unconsumed;
}
return totalUnconsumed == 0;
}
}));
brokerStopLatch.await();
doByteman.set(false);
broker = createBroker();
broker.start();
replacedertTrue("consumer added through failover", shutdownConsumerAdded.await(30, TimeUnit.SECONDS));
// each should again get prefetch messages - all unconsumed deliveries should be rolledback
replacedertTrue("after start all messages are re dispatched", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
int totalUnconsumed = 0;
for (TestConsumer testConsumer : testConsumers) {
long unconsumed = testConsumer.unconsumedSize();
LOG.info(testConsumer.getConsumerId() + " after restart: unconsumed: " + unconsumed);
totalUnconsumed += unconsumed;
}
return totalUnconsumed == (maxConsumers) * prefetch;
}
}));
connection.close();
}
16
View Complete Implementation : FailoverPrefetchZeroTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
@BMRules(rules = { @BMRule(name = "set no return response and stop the broker", targetClreplaced = "org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection$CommandProcessor", targetMethod = "processMessagePull", targetLocation = "ENTRY", action = "org.apache.activemq.transport.failover.FailoverPrefetchZeroTest.holdResponseAndStopBroker($0)") })
public void testPrefetchZeroConsumerThroughRestart() throws Exception {
broker = createBroker();
broker.start();
doByteman.set(true);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.sereplacedchTopicAdvisories(false);
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);
final MessageConsumer consumer = consumerSession.createConsumer(destination);
produceMessage(consumerSession, destination, 1);
final CountDownLatch receiveDone = new CountDownLatch(1);
final Vector<Message> received = new Vector<>();
new Thread() {
@Override
public void run() {
try {
LOG.info("receive one...");
Message msg = consumer.receive(30000);
if (msg != null) {
received.add(msg);
}
receiveDone.countDown();
LOG.info("done receive");
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
// will be stopped by the plugin
replacedertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS));
brokerStopLatch.await();
doByteman.set(false);
broker = createBroker();
broker.start();
replacedertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS));
replacedertTrue("we got our message:", !received.isEmpty());
connection.close();
}
16
View Complete Implementation : DestinationListenerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testConsumerForcesNotificationOfNewDestination() throws Exception {
// now lets cause a destination to be created
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
ActiveMQQueue newQueue = new ActiveMQQueue("Test.Cheese");
session.createConsumer(newQueue);
Thread.sleep(3000);
replacedertThat(newQueue, isIn(newDestinations));
LOG.info("New destinations are: " + newDestinations);
}
16
View Complete Implementation : BrokerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private void sendMessage(int timeToLive) throws Exception {
ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection();
producerConnection.start();
Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = producerSession.createProducer(destination);
if (timeToLive > 0) {
producer.setTimeToLive(timeToLive);
}
Message message = producerSession.createMessage();
message.setStringProperty("data", data);
producer.send(message);
producerConnection.close();
}
16
View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@org.junit.Test
public void testValidateRedeliveryFlagAfterRestart() throws Exception {
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")?jms.prefetchPolicy.all=0");
connection = (ActiveMQConnection) connectionFactory.createConnection();
connection.start();
Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
Destination destination = session.createQueue(queueName);
populateDestination(10, destination, connection);
MessageConsumer consumer = session.createConsumer(destination);
TextMessage msg = null;
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(20000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
session.rollback();
consumer.close();
restartBroker();
// make failover aware of the restarted auto replacedigned port
connection.getTransport().narrow(FailoverTransport.clreplaced).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
consumer = session.createConsumer(destination);
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(4000);
LOG.info("redelivered? got: " + msg);
replacedertNotNull("got the message again", msg);
replacedertEquals("redelivery count survives restart", 2, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("re delivery flag", true, msg.getJMSRedelivered());
}
session.commit();
// consume the rest that were not redeliveries
for (int i = 0; i < 5; i++) {
msg = (TextMessage) consumer.receive(20000);
LOG.info("not redelivered? got: " + msg);
replacedertNotNull("got the message", msg);
replacedertEquals("first delivery", 1, msg.getLongProperty("JMSXDeliveryCount"));
replacedertEquals("not a redelivery", false, msg.getJMSRedelivered());
}
session.commit();
connection.close();
}
16
View Complete Implementation : SimpleAuthenticationPluginTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testSecurityContextClearedOnPurge() throws Exception {
connection.close();
ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString());
ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "preplacedword");
Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
conn.start();
final int numDests = broker.getRegionBroker().getDestinations().length;
for (int i = 0; i < 10; i++) {
MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i));
p.close();
}
replacedertTrue("dests are purged", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisified() throws Exception {
LOG.info("dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length);
return (numDests + 1) == broker.getRegionBroker().getDestinations().length;
}
}));
// verify removed from connection security context
TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0);
TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId());
replacedertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size());
}
15
View Complete Implementation : ProducerFlowControlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
// re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
public void ignore2ndPubisherWithSyncSendConnectionThatIsBlocked() throws Exception {
ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory();
factory.setAlwaysSyncSend(true);
connection = (ActiveMQConnection) factory.createConnection();
connections.add(connection);
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueB);
// Test sending to Queue A
// 1st send should not block. But the rest will.
fillQueue(queueA);
// Test sending to Queue B it should not block.
CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1");
replacedertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
replacedertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2");
replacedertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
replacedertEquals("Message 2", msg.getText());
msg.acknowledge();
}
15
View Complete Implementation : ProducerFlowControlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testSimpleSendReceive() throws Exception {
ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory();
factory.setAlwaysSyncSend(true);
connection = (ActiveMQConnection) factory.createConnection();
connections.add(connection);
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueA);
// Test sending to Queue B it should not block.
CountDownLatch pubishDoneToQeueuA = asyncSendTo(queueA, "Message 1");
replacedertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
replacedertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuA = asyncSendTo(queueA, "Message 2");
replacedertTrue(pubishDoneToQeueuA.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
replacedertEquals("Message 2", msg.getText());
msg.acknowledge();
}
15
View Complete Implementation : ProducerFlowControlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void test2ndPubisherWithProducerWindowSendConnectionThatIsBlocked() throws Exception {
ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory();
factory.setProducerWindowSize(1024 * 64);
connection = (ActiveMQConnection) factory.createConnection();
connections.add(connection);
connection.start();
Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
MessageConsumer consumer = session.createConsumer(queueB);
// Test sending to Queue A
// 1 few sends should not block until the producer window is used up.
fillQueue(queueA);
// Test sending to Queue B it should not block since the connection
// should not be blocked.
CountDownLatch pubishDoneToQeueuB = asyncSendTo(queueB, "Message 1");
replacedertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
TextMessage msg = (TextMessage) consumer.receive();
replacedertEquals("Message 1", msg.getText());
msg.acknowledge();
pubishDoneToQeueuB = asyncSendTo(queueB, "Message 2");
replacedertTrue(pubishDoneToQeueuB.await(2, TimeUnit.SECONDS));
msg = (TextMessage) consumer.receive();
replacedertEquals("Message 2", msg.getText());
msg.acknowledge();
}
15
View Complete Implementation : ProducerFlowControlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
// re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
public void ignorePubisherRecoverAfterBlock() throws Exception {
ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory();
connection = (ActiveMQConnection) factory.createConnection();
connections.add(connection);
connection.start();
final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageProducer producer = session.createProducer(queueA);
final AtomicBoolean done = new AtomicBoolean(true);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
Thread thread = new Thread("Filler") {
int i;
@Override
public void run() {
while (keepGoing.get()) {
done.set(false);
try {
producer.send(session.createTextMessage("Test message " + ++i));
LOG.info("sent: " + i);
} catch (JMSException e) {
}
}
}
};
thread.start();
waitForBlockedOrResourceLimit(done);
// after receiveing messges, producer should continue sending messages
// (done == false)
MessageConsumer consumer = session.createConsumer(queueA);
TextMessage msg;
for (int idx = 0; idx < 5; ++idx) {
msg = (TextMessage) consumer.receive(1000);
LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID());
msg.acknowledge();
}
Thread.sleep(1000);
keepGoing.set(false);
replacedertFalse("producer has resumed", done.get());
}
15
View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private void populateDestination(final int nbMessages, final Destination destination, javax.jms.Connection connection) throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
for (int i = 1; i <= nbMessages; i++) {
producer.send(session.createTextMessage("<hello id='" + i + "'/>"));
}
producer.close();
session.close();
}
15
View Complete Implementation : RedeliveryRestartWithExceptionTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
private void populateDestination(final int nbMessages, final Destination destination, javax.jms.Connection connection, boolean persistent) throws JMSException {
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = session.createProducer(destination);
producer.setDeliveryMode(persistent ? DeliveryMode.PERSISTENT : DeliveryMode.NON_PERSISTENT);
for (int i = 1; i <= nbMessages; i++) {
producer.send(session.createTextMessage("<hello id='" + i + "'/>"));
}
producer.close();
session.close();
}
15
View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testRollbackFailoverConsumerTx() throws Exception {
server = createBroker();
server.start();
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.setConsumerFailoverRedeliveryWaitPeriod(10000);
final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
connection.start();
final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final Queue destination = producerSession.createQueue(QUEUE_NAME);
final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
replacedertNull("no message yet", testConsumer.receiveNoWait());
produceMessage(producerSession, destination, 1);
producerSession.close();
// consume then rollback after restart
Message msg = testConsumer.receive(5000);
replacedertNotNull(msg);
// restart with outstanding delivered message
server.stop();
server = createBroker();
server.start();
consumerSession.rollback();
// receive again
msg = testConsumer.receive(10000);
replacedertNotNull("got message again after rollback", msg);
consumerSession.commit();
// close before sweep
consumerSession.close();
msg = receiveMessage(cf, destination);
replacedertNull("should be nothing left after commit", msg);
connection.close();
}
15
View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception {
server = createBroker();
server.start();
brokerStopLatch = new CountDownLatch(1);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.sereplacedchTopicAdvisories(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 Session consumerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
final CountDownLatch commitDoneLatch = new CountDownLatch(1);
final CountDownLatch messagesReceived = new CountDownLatch(2);
final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
doByteman.set(true);
testConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
LOG.info("consume one and commit");
replacedertNotNull("got message", message);
try {
consumerSession.commit();
} catch (JMSException e) {
e.printStackTrace();
}
commitDoneLatch.countDown();
messagesReceived.countDown();
LOG.info("done commit");
}
});
// may block if broker shutodwn happens quickly
new Thread() {
@Override
public void run() {
LOG.info("producer started");
try {
produceMessage(producerSession, destination, prefetch * 2);
} catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) {
} catch (JMSException e) {
e.printStackTrace();
fail("unexpceted ex on producer: " + e);
}
LOG.info("producer done");
}
}.start();
// will be stopped by the plugin
brokerStopLatch.await();
server.stop();
server = createBroker();
doByteman.set(false);
server.start();
replacedertTrue("consumer added through failover", commitDoneLatch.await(20, TimeUnit.SECONDS));
replacedertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS));
connection.close();
}
15
View Complete Implementation : MQTTOpenwireTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestSendMQTTReceiveJMS(String mqttTopic, String jmsDestination) throws Exception {
final MQTTClientProvider provider = getMQTTClientProvider();
initializeConnection(provider);
ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection();
try {
// MUST set to true to receive retained messages
activeMQConnection.setUseRetroactiveConsumer(true);
activeMQConnection.start();
Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Topic jmsTopic = s.createTopic(jmsDestination);
MessageConsumer consumer = s.createConsumer(jmsTopic);
// send retained message
final String RETAINED = "RETAINED";
provider.publish(mqttTopic, RETAINED.getBytes(), AT_LEAST_ONCE, true);
// check whether we received retained message on JMS subscribe
ActiveMQMessage message = (ActiveMQMessage) consumer.receive(2000);
replacedertNotNull("Should get retained message " + mqttTopic + "->" + jmsDestination, message);
ByteSequence bs = message.getContent();
replacedertEquals(RETAINED, new String(bs.data, bs.offset, bs.length));
for (int i = 0; i < 1; i++) {
String payload = "Test Message: " + i;
provider.publish(mqttTopic, payload.getBytes(), AT_LEAST_ONCE);
message = (ActiveMQMessage) consumer.receive(1000);
replacedertNotNull("Should get a message " + mqttTopic + "->" + jmsDestination, message);
bs = message.getContent();
replacedertEquals(payload, new String(bs.data, bs.offset, bs.length));
}
} finally {
activeMQConnection.close();
provider.disconnect();
}
}
15
View Complete Implementation : ProducerBlockingTtlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
@Test
public void testProducerBlockWontGetTimeout() throws Exception {
flowControlConnection = (ActiveMQConnection) factory.createConnection();
Connection consumerConnection = factory.createConnection();
Thread fillThread = null;
AtomicBoolean keepGoing = new AtomicBoolean(true);
try {
flowControlConnection.start();
final Session session = flowControlConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
final MessageProducer producer = session.createProducer(queueA);
producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
final String text = "Hello World";
final int num = 10;
fillThread = new Thread("Fill thread.") {
@Override
public void run() {
try {
for (int i = 0; i < num && keepGoing.get(); i++) {
producer.send(session.createTextMessage(text + i));
}
} catch (JMSException e) {
}
}
};
fillThread.start();
// longer enough than TTL (1000)
Thread.sleep(4000);
// receive messages and unblock the producer
consumerConnection.start();
Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(queueA);
for (int i = 0; i < num; i++) {
TextMessage m = (TextMessage) consumer.receive(5000);
replacedertNotNull(m);
replacedertEquals("Hello World" + i, m.getText());
}
replacedertNull(consumer.receive(3));
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fillThread != null) {
keepGoing.set(false);
fillThread.interrupt();
fillThread.join();
}
try {
flowControlConnection.close();
flowControlConnection = null;
} catch (Throwable t) {
}
try {
consumerConnection.close();
} catch (Throwable t) {
}
}
}
14
View Complete Implementation : ProducerFlowControlTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
// re-enable once https://issues.apache.org/jira/browse/APLO-225 is fixed
public void ignoreAsyncPubisherRecoverAfterBlock() throws Exception {
ActiveMQConnectionFactory factory = (ActiveMQConnectionFactory) createConnectionFactory();
factory.setProducerWindowSize(1024 * 5);
factory.setUseAsyncSend(true);
connection = (ActiveMQConnection) factory.createConnection();
connections.add(connection);
connection.start();
final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
final MessageProducer producer = session.createProducer(queueA);
final AtomicBoolean done = new AtomicBoolean(true);
final AtomicBoolean keepGoing = new AtomicBoolean(true);
Thread thread = new Thread("Filler") {
int i;
@Override
public void run() {
while (keepGoing.get()) {
done.set(false);
try {
producer.send(session.createTextMessage("Test message " + ++i));
LOG.info("sent: " + i);
} catch (JMSException e) {
}
}
}
};
thread.start();
waitForBlockedOrResourceLimit(done);
// after receiveing messges, producer should continue sending messages
// (done == false)
MessageConsumer consumer = session.createConsumer(queueA);
TextMessage msg;
for (int idx = 0; idx < 5; ++idx) {
msg = (TextMessage) consumer.receive(1000);
replacedertNotNull("Got a message", msg);
LOG.info("received: " + idx + ", msg: " + msg.getJMSMessageID());
msg.acknowledge();
}
Thread.sleep(1000);
keepGoing.set(false);
replacedertFalse("producer has resumed", done.get());
}
14
View Complete Implementation : BrokerRedeliveryTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ) throws Exception {
startBroker(true);
sendMessage(0);
ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
redeliveryPolicy.setInitialRedeliveryDelay(0);
redeliveryPolicy.setMaximumRedeliveries(0);
consumerConnection.setRedeliveryPolicy(redeliveryPolicy);
consumerConnection.start();
Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED);
MessageConsumer consumer = consumerSession.createConsumer(destination);
Message message = consumer.receive(1000);
replacedertNotNull("got message", message);
LOG.info("got: " + message);
consumerSession.rollback();
for (int i = 0; i < maxBrokerRedeliveriesToValidate; i++) {
Message shouldBeNull = consumer.receive(500);
replacedertNull("did not get message after redelivery count exceeded: " + shouldBeNull, shouldBeNull);
TimeUnit.SECONDS.sleep(3);
Message brokerRedeliveryMessage = consumer.receive(500);
LOG.info("got: " + brokerRedeliveryMessage);
replacedertNotNull("got message via broker redelivery after delay", brokerRedeliveryMessage);
replacedertEquals("message matches", message.getStringProperty("data"), brokerRedeliveryMessage.getStringProperty("data"));
replacedertEquals("has expiryDelay specified", i == 0 ? initialRedeliveryDelayMillis : redeliveryDelayMillis, brokerRedeliveryMessage.getLongProperty(RedeliveryPlugin.REDELIVERY_DELAY));
consumerSession.rollback();
}
if (validateDLQ) {
MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
Message dlqMessage = dlqConsumer.receive(2000);
replacedertNotNull("Got message from dql", dlqMessage);
replacedertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
consumerSession.commit();
} else {
// consume/commit ok
message = consumer.receive(3000);
replacedertNotNull("got message", message);
replacedertEquals("redeliveries accounted for", maxBrokerRedeliveriesToValidate + 2, message.getLongProperty("JMSXDeliveryCount"));
consumerSession.commit();
}
consumerConnection.close();
}
14
View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestFailoverConsumerOutstandingSendTx(final boolean doActualBrokerCommit) throws Exception {
final boolean watchTopicAdvisories = true;
server = createBroker();
server.start();
brokerStopLatch = new CountDownLatch(1);
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
cf.sereplacedchTopicAdvisories(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<>();
final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
doByteman.set(true);
testConsumer.setMessageListener(new MessageListener() {
@Override
public void onMessage(Message message) {
LOG.info("consume one: " + message);
replacedertNotNull("got message", message);
receivedMessages.add((TextMessage) message);
try {
LOG.info("send one");
produceMessage(consumerSession, signalDestination, 1);
LOG.info("commit session");
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
new Thread() {
@Override
public void run() {
LOG.info("producer started");
try {
produceMessage(producerSession, destination, prefetch * 2);
} catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) {
} catch (JMSException e) {
e.printStackTrace();
fail("unexpceted ex on producer: " + e);
}
LOG.info("producer done");
}
}.start();
// will be stopped by the plugin
brokerStopLatch.await();
doByteman.set(false);
server.stop();
server = createBroker();
server.start();
replacedertTrue("commit done through failover", commitDoneLatch.await(20, TimeUnit.SECONDS));
replacedertTrue("commit failed", gotCommitException.get());
replacedertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS));
int receivedIndex = 0;
replacedertEquals("get message 0 first", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText());
if (!doActualBrokerCommit) {
// it will be redelivered and not tracked as a duplicate
replacedertEquals("get message 0 second", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText());
}
replacedertTrue("another message was received", messagesReceived.await(20, TimeUnit.SECONDS));
replacedertEquals("get message 1 eventually", MESSAGE_TEXT + "1", receivedMessages.get(receivedIndex++).getText());
connection.close();
server.stop();
}
14
View Complete Implementation : MQTTOpenwireTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void doTestSendJMSReceiveMQTT(String jmsDestination, String mqttTopic) throws Exception {
final MQTTClientProvider provider = getMQTTClientProvider();
initializeConnection(provider);
ActiveMQConnection activeMQConnection = (ActiveMQConnection) cf.createConnection();
try {
activeMQConnection.setUseRetroactiveConsumer(true);
activeMQConnection.start();
Session s = activeMQConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
javax.jms.Topic jmsTopic = s.createTopic(jmsDestination);
MessageProducer producer = s.createProducer(jmsTopic);
final String RETAINED = "RETAINED";
provider.subscribe(mqttTopic, AT_MOST_ONCE);
// send retained message from JMS
TextMessage sendMessage = s.createTextMessage(RETAINED);
// mark the message to be retained
sendMessage.setBooleanProperty("ActiveMQ.Retain", true);
// MQTT QoS can be set using MQTTProtocolConverter.QOS_PROPERTY_NAME property
sendMessage.setIntProperty("ActiveMQ.MQTT.QoS", 0);
producer.send(sendMessage);
byte[] message = provider.receive(2000);
replacedertNotNull("Should get retained message " + jmsDestination + "->" + mqttTopic, message);
replacedertEquals(RETAINED, new String(message));
for (int i = 0; i < 1; i++) {
String payload = "This is Test Message: " + i;
sendMessage = s.createTextMessage(payload);
producer.send(sendMessage);
message = provider.receive(1000);
replacedertNotNull("Should get a message " + jmsDestination + "->" + mqttTopic, message);
replacedertEquals(payload, new String(message));
}
} finally {
activeMQConnection.close();
provider.disconnect();
}
}
13
View Complete Implementation : JmsProxyImplTest.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
Copyright GNU Lesser General Public License v3.0
Author : c2mon
/**
* Test sendRequest with null request object - should throw exception.
* Also calls the lifecycle start() method and checks connection and session
* calls.
* @throws JMSException
* @throws InterruptedException
*/
@Test(expected = NullPointerException.clreplaced)
public void testStartAndSendRequestNullRequest() throws JMSException, InterruptedException {
// need to simulate start
EasyMock.expect(connectionFactory.createConnection()).andReturn(connection).times(2);
EasyMock.expect(connection.createSession(false, Session.AUTO_ACKNOWLEDGE)).andReturn(session).times(3);
connection.setExceptionListener(EasyMock.isA(ExceptionListener.clreplaced));
connection.start();
MessageConsumer messageConsumer = EasyMock.createMock(MessageConsumer.clreplaced);
EasyMock.expect(session.createConsumer(EasyMock.isA(Destination.clreplaced))).andReturn(messageConsumer).times(2);
messageConsumer.setMessageListener(EasyMock.isA(MessageListener.clreplaced));
messageConsumer.setMessageListener(EasyMock.isA(MessageListener.clreplaced));
session.close();
EasyMock.replay(connectionFactory);
EasyMock.replay(connection);
EasyMock.replay(session);
EasyMock.replay(messageConsumer);
((JmsProxyImpl) jmsProxy).init();
// leave time for connection thread to run (and set connected flag to true)
Thread.sleep(2000);
jmsProxy.sendRequest(null, "test.queue", 1000);
EasyMock.verify(connectionFactory);
EasyMock.verify(connection);
EasyMock.verify(session);
EasyMock.verify(messageConsumer);
}
12
View Complete Implementation : DestinationListenerTest.java
Copyright Apache License 2.0
Author : apache
Copyright Apache License 2.0
Author : apache
public void testProducerForcesNotificationOfNewDestination() throws Exception {
// now lets cause a destination to be created
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
ActiveMQQueue newQueue = new ActiveMQQueue("Test.Beer");
MessageProducer producer = session.createProducer(newQueue);
TextMessage message = session.createTextMessage("<hello>world</hello>");
producer.send(message);
Thread.sleep(3000);
replacedertThat(newQueue, isIn(newDestinations));
LOG.info("New destinations are: " + newDestinations);
}