org.apache.activemq.ActiveMQConnection.close() - java examples

Here are the examples of the java api org.apache.activemq.ActiveMQConnection.close() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

54 Examples 7

19 View Complete Implementation : TestBroker.java
Copyright Apache License 2.0
Author : naver
void stop() throws Exception {
    for (Map.Entry<String, ActiveMQConnection> e : this.connections.entrySet()) {
        ActiveMQConnection connection = e.getValue();
        connection.close();
    }
    this.brokerService.stop();
    this.brokerService.waitUntilStopped();
}

19 View Complete Implementation : ActiveMqMessagingService.java
Copyright Apache License 2.0
Author : gocd
@Override
public void stop() throws JMSException {
    connection.close();
    try {
        broker.stop();
    } catch (Exception e) {
    }
}

19 View Complete Implementation : ActiveMQConnector.java
Copyright MIT License
Author : dcshock
@Override
public synchronized void stop() throws ConnectorException {
    if (conn != null)
        try {
            conn.close();
        } catch (JMSException e) {
            throw new ConnectorException(e.getMessage());
        }
}

19 View Complete Implementation : ActiveMQueue.java
Copyright Apache License 2.0
Author : sriksun
@Override
public void reconnect() throws IvoryException {
    try {
        LOG.info("Attempting to close producer");
        producer.close();
        LOG.info("Producer closed successfully");
    } catch (Exception ignore) {
    }
    try {
        LOG.info("Attempting to close consumer");
        consumer.close();
        LOG.info("Consumer closed successfully");
    } catch (Exception ignore) {
    }
    try {
        LOG.info("Attempting to close connection");
        connection.close();
        LOG.info("Connection closed successfully");
    } catch (Exception ignore) {
    }
    init();
}

19 View Complete Implementation : DestinationListenerTest.java
Copyright Apache License 2.0
Author : apache
@Override
protected void tearDown() throws Exception {
    if (connection != null) {
        connection.close();
    }
    super.tearDown();
}

19 View Complete Implementation : JmsProxyImpl.java
Copyright GNU Lesser General Public License v3.0
Author : c2mon
/**
 * Stops all topic listeners and disconnects; connection listeners are not
 * notified. Used at shutdown.
 */
private synchronized void disconnectQuietly() {
    connected = false;
    // these listeners are re-created
    for (Map.Entry<String, MessageListenerWrapper> entry : topicToWrapper.entrySet()) {
        entry.getValue().stop();
    }
    if (connection != null && !connection.isClosed() && connection.isTransportFailed()) {
        try {
            // closes all consumers and sessions also
            connection.close();
        } catch (JMSException e) {
            String message = "Exception caught while attempting to disconnect from JMS: " + e.getMessage();
            log.error(message);
            log.debug(message, e);
        }
    }
}

19 View Complete Implementation : ProducerFlowControlBaseTest.java
Copyright Apache License 2.0
Author : apache
@Override
@After
public void tearDown() throws Exception {
    try {
        if (flowControlConnection != null) {
            TcpTransport t = flowControlConnection.getTransport().narrow(TcpTransport.clreplaced);
            try {
                flowControlConnection.getTransport().stop();
                flowControlConnection.close();
            } catch (Throwable ignored) {
            // sometimes the disposed up can make the test to fail
            // even worse I have seen this breaking every single test after this
            // if not caught here
            }
            t.getTransportListener().onException(new IOException("Disposed."));
        }
        if (asyncThread != null) {
            asyncThread.join();
            asyncThread = null;
        }
    } finally {
        super.tearDown();
    }
}

19 View Complete Implementation : ActiveMQSpanConsumer.java
Copyright Apache License 2.0
Author : openzipkin
@Override
public void close() {
    if (checkResult == CLOSED)
        return;
    checkResult = CLOSED;
    connection.removeTransportListener(this);
    try {
        for (Map.Entry<QueueSession, QueueReceiver> sessionReceiver : sessionToReceiver.entrySet()) {
            // deregister this
            sessionReceiver.getValue().setMessageListener(null);
            sessionReceiver.getKey().close();
        }
        connection.close();
    } catch (JMSException ignored) {
    }
}

18 View Complete Implementation : TwoBrokerFailoverClusterTest.java
Copyright Apache License 2.0
Author : apache
@After
public void tearDown() throws Exception {
    for (ActiveMQConnection conn : connections) {
        conn.close();
    }
    server0.stop();
    server1.stop();
}

18 View Complete Implementation : ConsumeUncompressedCompressedMessageTest.java
Copyright Apache License 2.0
Author : apache
@After
public void tearDown() throws Exception {
    if (connection != null) {
        connection.close();
    }
    broker.stop();
    broker.waitUntilStopped();
}

18 View Complete Implementation : LazyInit.java
Copyright Apache License 2.0
Author : openzipkin
ActiveMQSpanConsumer doInit() {
    final ActiveMQConnection connection;
    try {
        connection = (ActiveMQConnection) connectionFactory.createQueueConnection();
        connection.start();
    } catch (JMSException e) {
        throw uncheckedException("Unable to establish connection to ActiveMQ broker: ", e);
    }
    try {
        ActiveMQSpanConsumer result = new ActiveMQSpanConsumer(collector, metrics, connection);
        for (int i = 0; i < concurrency; i++) {
            result.registerInNewSession(connection, queue);
        }
        return result;
    } catch (JMSException e) {
        try {
            connection.close();
        } catch (JMSException ignored) {
        }
        throw uncheckedException("Unable to create queueReceiver(" + queue + "): ", e);
    }
}

17 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private ActiveMQTextMessage receiveTestMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive();
    connection.close();
    return rc;
}

17 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private ActiveMQMapMessage receiveTestMapMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQMapMessage rc = (ActiveMQMapMessage) consumer.receive();
    connection.close();
    return rc;
}

17 View Complete Implementation : ReconnectWithSameClientIDTest.java
Copyright Apache License 2.0
Author : apache
@Override
@After
public void tearDown() throws Exception {
    if (sameIdConnection != null) {
        sameIdConnection.close();
        sameIdConnection = null;
    }
    super.tearDown();
}

17 View Complete Implementation : ActiveMQConn.java
Copyright Apache License 2.0
Author : openzipkin
@Override
public void close() {
    if (checkResult == CLOSED)
        return;
    checkResult = CLOSED;
    connection.removeTransportListener(this);
    try {
        sender.close();
        session.close();
        connection.close();
    } catch (JMSException ignored) {
    }
}

17 View Complete Implementation : RedeliveryRestartTest.java
Copyright Apache License 2.0
Author : apache
@Override
@After
public void tearDown() throws Exception {
    if (connection != null) {
        connection.close();
    }
    broker.stop();
    super.tearDown();
}

17 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private ActiveMQStreamMessage receiveTestStreamMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQStreamMessage rc = (ActiveMQStreamMessage) consumer.receive();
    connection.close();
    return rc;
}

17 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private ActiveMQBytesMessage receiveTestBytesMessage(ActiveMQConnectionFactory factory) throws JMSException, UnsupportedEncodingException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive();
    connection.close();
    return rc;
}

17 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private ActiveMQObjectMessage receiveTestObjectMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQObjectMessage rc = (ActiveMQObjectMessage) consumer.receive();
    connection.close();
    return rc;
}

16 View Complete Implementation : DurablePersistentFalseRestartTest.java
Copyright Apache License 2.0
Author : apache
public void testValidateNoPersistenceForDurableAfterRestart() throws Exception {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")");
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("clientId");
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(queueName);
    MessageConsumer consumer = session.createDurableSubscriber(destination, "subscriberName");
    populateDestination(10, destination, connection);
    restartBroker();
    // make failover aware of the restarted auto replacedigned port
    connection.getTransport().narrow(FailoverTransport.clreplaced).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
    TextMessage msg = (TextMessage) consumer.receive(4000);
    replacedertNull("did not get a message when persistent=false, message: " + msg, msg);
    connection.close();
}

16 View Complete Implementation : FailoverRandomTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testRandomConnections() throws Exception {
    String failoverUrl = "failover:(" + newURI(0) + "," + newURI(1) + ")";
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUrl);
    ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final String brokerName1 = connection.getBrokerName();
    replacedert.replacedertNotNull(brokerName1);
    connection.close();
    String brokerName2 = brokerName1;
    int attempts = 40;
    while (brokerName1.equals(brokerName2) && attempts-- > 0) {
        connection = (ActiveMQConnection) cf.createConnection();
        connection.start();
        brokerName2 = connection.getBrokerName();
        replacedert.replacedertNotNull(brokerName2);
        connection.close();
    }
    replacedert.replacedertTrue(brokerName1 + "!=" + brokerName2, !brokerName1.equals(brokerName2));
}

16 View Complete Implementation : FailoverTimeoutTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testUpdateUris() throws Exception {
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?useExponentialBackOff=false");
    ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    try {
        connection.start();
        FailoverTransport failoverTransport = connection.getTransport().narrow(FailoverTransport.clreplaced);
        URI[] bunchOfUnknownAndOneKnown = new URI[] { new URI("tcp://unknownHost:" + tcpUri.getPort()), new URI("tcp://unknownHost2:" + tcpUri.getPort()), new URI("tcp://localhost:2222") };
        failoverTransport.add(false, bunchOfUnknownAndOneKnown);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

16 View Complete Implementation : ProducerBlockingTtlTest.java
Copyright Apache License 2.0
Author : apache
@Override
@After
public void tearDown() throws Exception {
    try {
        if (flowControlConnection != null) {
            TcpTransport t = flowControlConnection.getTransport().narrow(TcpTransport.clreplaced);
            try {
                flowControlConnection.getTransport().stop();
                flowControlConnection.close();
            } catch (Throwable ignored) {
            }
        }
    } finally {
        super.tearDown();
    }
}

16 View Complete Implementation : ReconnectWithSameClientIDTest.java
Copyright Apache License 2.0
Author : apache
@Test
public void testReconnectMultipleTimesWithSameClientID() throws Exception {
    try {
        sameIdConnection = (ActiveMQConnection) this.factory.createConnection();
        useConnection(sameIdConnection);
        // now lets create another which should fail
        for (int i = 1; i < 11; i++) {
            Connection connection2 = this.factory.createConnection();
            try {
                useConnection(connection2);
                fail("Should have thrown InvalidClientIDException on attempt" + i);
            } catch (InvalidClientIDException e) {
                System.err.println("Caught expected: " + e);
            } finally {
                connection2.close();
            }
        }
        // now lets try closing the original connection and creating a new
        // connection with the same ID
        sameIdConnection.close();
        sameIdConnection = (ActiveMQConnection) factory.createConnection();
        useConnection(connection);
    } finally {
        if (sameIdConnection != null) {
            sameIdConnection.close();
        }
    }
}

15 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private void sendTestBytesMessage(ActiveMQConnectionFactory factory, String message) throws JMSException, UnsupportedEncodingException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(message.getBytes(StandardCharsets.UTF_8));
    producer.send(bytesMessage);
    connection.close();
}

14 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private void sendTestObjectMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    ObjectMessage objectMessage = session.createObjectMessage();
    objectMessage.setObject(TEXT);
    producer.send(objectMessage);
    connection.close();
}

14 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private void sendTestMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage(message));
    connection.close();
}

14 View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
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;
}

13 View Complete Implementation : JMSConsumer11Test.java
Copyright Apache License 2.0
Author : apache
@Test
public void testPrefetch1MessageNotDispatched() throws Exception {
    // Set prefetch to 1
    connection.getPrefetchPolicy().setAll(1);
    connection.start();
    Session session = connection.createSession(true, 0);
    ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination);
    // Send 2 messages to the destination.
    sendMessages(session, destination, 2);
    session.commit();
    // The prefetch should fill up with 1 message.
    // Since prefetch is still full, the 2nd message should get dispatched
    // to another consumer.. lets create the 2nd consumer test that it does
    // make sure it does.
    ActiveMQConnection connection2 = (ActiveMQConnection) factory.createConnection();
    connection2.start();
    Session session2 = connection2.createSession(true, 0);
    ActiveMQMessageConsumer consumer2 = (ActiveMQMessageConsumer) session2.createConsumer(destination);
    // On a test race you could have a scenario where the message only arrived at the first consumer and
    // if the test is not fast enough the first consumer will receive the message againt
    // This will guarantee the test is correctly balanced.
    Wait.replacedertEquals(1, consumer::getMessageSize);
    Wait.replacedertEquals(1, consumer2::getMessageSize);
    System.out.println("consumer receiving ...");
    // Pick up the first message.
    Message message1 = consumer.receive(1000);
    System.out.println("received1: " + message1);
    replacedertNotNull(message1);
    System.out.println("consumer 2 receiving...");
    // Pick up the 2nd messages.
    Message message2 = consumer2.receive(5000);
    System.out.println("received2: " + message2);
    replacedertNotNull(message2);
    System.out.println("committing sessions !! " + session.getClreplaced().getName());
    session.commit();
    System.out.println("committed session, now 2");
    session2.commit();
    System.out.println("all committed");
    Message m = consumer.receiveNoWait();
    System.out.println("received 3: " + m);
    replacedertNull(m);
    try {
        connection2.close();
    } catch (Throwable e) {
        System.err.println("exception e: " + e);
        e.printStackTrace();
    }
    System.out.println("Test finished!!");
}

12 View Complete Implementation : LazyInit.java
Copyright Apache License 2.0
Author : openzipkin
ActiveMQConn doGet() throws IOException {
    final ActiveMQConnection connection;
    try {
        connection = (ActiveMQConnection) connectionFactory.createQueueConnection();
        connection.start();
    } catch (JMSException e) {
        throw ioException("Unable to establish connection to ActiveMQ broker: ", e);
    }
    try {
        // Preplaced redundant info as we can't use default method in activeMQ
        QueueSession session = connection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        // No need to do anything on ActiveMQ side as physical queues are created on demand
        Queue destination = session.createQueue(queue);
        QueueSender sender = session.createSender(destination);
        return new ActiveMQConn(connection, session, sender);
    } catch (JMSException e) {
        try {
            connection.close();
        } catch (JMSException ignored) {
        }
        throw ioException("Unable to create queueSender(" + queue + "): ", e);
    }
}

12 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private void sendTestMapMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    MapMessage mapMessage = session.createMapMessage();
    mapMessage.setBoolean("boolean-type", true);
    mapMessage.setByte("byte-type", (byte) 10);
    mapMessage.setBytes("bytes-type", TEXT.getBytes());
    mapMessage.setChar("char-type", 'A');
    mapMessage.setDouble("double-type", 55.3D);
    mapMessage.setFloat("float-type", 79.1F);
    mapMessage.setInt("int-type", 37);
    mapMessage.setLong("long-type", 56652L);
    mapMessage.setObject("object-type", new String("VVVV"));
    mapMessage.setShort("short-type", (short) 333);
    mapMessage.setString("string-type", TEXT);
    producer.send(mapMessage);
    connection.close();
}

12 View Complete Implementation : RequestReplyNoAdvisoryNetworkTest.java
Copyright Apache License 2.0
Author : apache
public void doTestNonAdvisoryNetworkRequestReply() throws Exception {
    waitForBridgeFormation(a, 1, 0);
    waitForBridgeFormation(b, 1, 0);
    ActiveMQConnectionFactory sendFactory = createConnectionFactory(a);
    ActiveMQConnection sendConnection = createConnection(sendFactory);
    ActiveMQSession sendSession = (ActiveMQSession) sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = sendSession.createProducer(sendQ);
    ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue();
    TextMessage message = sendSession.createTextMessage("1");
    message.setJMSReplyTo(realReplyQ);
    producer.send(message);
    LOG.info("request sent");
    // responder
    ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b);
    ActiveMQConnection consumerConnection = createConnection(consumerFactory);
    ActiveMQSession consumerSession = (ActiveMQSession) consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(sendQ);
    TextMessage received = (TextMessage) consumer.receive(receiveTimeout);
    replacedertNotNull("got request from sender ok", received);
    LOG.info("got request, sending reply");
    MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo());
    consumerProducer.send(consumerSession.createTextMessage("got " + received.getText()));
    // temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures
    // message gets delivered before destination is removed
    consumerConnection.close();
    // reply consumer
    MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ);
    TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout);
    replacedertNotNull("expected reply message", reply);
    replacedertEquals("text is as expected", "got 1", reply.getText());
    sendConnection.close();
    LOG.info("checking for dangling temp destinations");
    // ensure all temp dests get cleaned up on all brokers
    for (BrokerService brokerService : brokers) {
        final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker();
        replacedertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition() {

            @Override
            public boolean isSatisified() throws Exception {
                Map<?, ?> tempTopics = regionBroker.getTempTopicRegion().getDestinationMap();
                LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics);
                Map<?, ?> tempQ = regionBroker.getTempQueueRegion().getDestinationMap();
                LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ);
                return tempQ.isEmpty() && tempTopics.isEmpty();
            }
        }));
    }
}

11 View Complete Implementation : RedeliveryRestartTest.java
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();
}

11 View Complete Implementation : RedeliveryRestartTest.java
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();
}

11 View Complete Implementation : RedeliveryRestartWithExceptionTest.java
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();
}

11 View Complete Implementation : RedeliveryRestartWithExceptionTest.java
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();
}

11 View Complete Implementation : RedeliveryRestartWithExceptionTest.java
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();
}

11 View Complete Implementation : MessageCompressionTest.java
Copyright Apache License 2.0
Author : apache
private void sendTestStreamMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    StreamMessage streamMessage = session.createStreamMessage();
    streamMessage.writeBoolean(true);
    streamMessage.writeByte((byte) 10);
    streamMessage.writeBytes(TEXT.getBytes());
    streamMessage.writeChar('A');
    streamMessage.writeDouble(55.3D);
    streamMessage.writeFloat(79.1F);
    streamMessage.writeInt(37);
    streamMessage.writeLong(56652L);
    streamMessage.writeObject(new String("VVVV"));
    streamMessage.writeShort((short) 333);
    streamMessage.writeString(TEXT);
    producer.send(streamMessage);
    connection.close();
}

11 View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
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();
}

11 View Complete Implementation : FailoverConsumerUnconsumedTest.java
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();
}

11 View Complete Implementation : FailoverConsumerUnconsumedTest.java
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();
}

11 View Complete Implementation : MQTTOpenwireTest.java
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();
    }
}

11 View Complete Implementation : BasicOpenWireTest.java
Copyright Apache License 2.0
Author : apache
@Override
@After
public void tearDown() throws Exception {
    System.clearProperty("org.apache.activemq.transport.AbstractInactivityMonitor.keepAliveTime");
    System.out.println("tear down! " + connection);
    try {
        if (connection != null) {
            System.out.println("closing connection");
            connection.close();
            System.out.println("connection closed.");
        }
        Iterator<SimpleString> iterQueues = testQueues.values().iterator();
        while (iterQueues.hasNext()) {
            SimpleString coreQ = iterQueues.next();
            try {
                this.server.destroyQueue(coreQ, null, false, true);
            } catch (ActiveMQNonExistentQueueException idontcare) {
            // i don't care if this failed. it means it didn't find the queue
            } catch (Throwable e) {
                // just print, what else can we do?
                e.printStackTrace();
            }
            System.out.println("Destroyed queue: " + coreQ);
        }
        testQueues.clear();
    } catch (Throwable e) {
        System.out.println("Exception !! " + e);
        e.printStackTrace();
    } finally {
        super.tearDown();
        System.out.println("Super done.");
    }
}

10 View Complete Implementation : RedeliveryRestartTest.java
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();
}

10 View Complete Implementation : FailoverPrefetchZeroTest.java
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();
}

9 View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
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();
}

9 View Complete Implementation : TwoSecureBrokerRequestReplyTest.java
Copyright Apache License 2.0
Author : apache
public void testRequestReply() throws Exception {
    ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply");
    startAllBrokers();
    waitForBridgeFormation();
    waitForMinTopicRegionConsumerCount("sender", 1);
    waitForMinTopicRegionConsumerCount("receiver", 1);
    ConnectionFactory factory = getConnectionFactory("sender");
    ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection("system", "manager");
    conn.sereplacedchTopicAdvisories(false);
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ConnectionFactory replyFactory = getConnectionFactory("receiver");
    for (int i = 0; i < 2000; i++) {
        TemporaryQueue tempDest = session.createTemporaryQueue();
        MessageProducer producer = session.createProducer(requestReplyDest);
        javax.jms.Message message = session.createTextMessage("req-" + i);
        message.setJMSReplyTo(tempDest);
        ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(tempDest);
        producer.send(message);
        ActiveMQConnection replyConnection = (ActiveMQConnection) replyFactory.createConnection("system", "manager");
        replyConnection.sereplacedchTopicAdvisories(false);
        replyConnection.start();
        Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest);
        javax.jms.Message msg = replyConsumer.receive(10000);
        replacedertNotNull("request message not null: " + i, msg);
        MessageProducer replyProducer = replySession.createProducer(msg.getJMSReplyTo());
        replyProducer.send(session.createTextMessage("reply-" + i));
        replyConnection.close();
        javax.jms.Message reply = consumer.receive(10000);
        replacedertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply);
        consumer.close();
        tempDest.delete();
        LOG.info("message #" + i + " processed");
    }
}

8 View Complete Implementation : BrokerRedeliveryTest.java
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();
}

8 View Complete Implementation : FailoverConsumerOutstandingCommitTest.java
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();
}

7 View Complete Implementation : BrokerRedeliveryTest.java
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();
}