org.apache.activemq.command.ActiveMQQueue

Here are the examples of the java api class org.apache.activemq.command.ActiveMQQueue taken from open source projects.

1. QueueBridgeStandaloneReconnectTest#setUp()

View license
@Before
public void setUp() throws Exception {
    localConnectionFactory = createLocalConnectionFactory();
    foreignConnectionFactory = createForeignConnectionFactory();
    outbound = new ActiveMQQueue("RECONNECT.TEST.OUT.QUEUE");
    inbound = new ActiveMQQueue("RECONNECT.TEST.IN.QUEUE");
    jmsQueueConnector = new SimpleJmsQueueConnector();
    // Wire the bridges.
    jmsQueueConnector.setOutboundQueueBridges(new OutboundQueueBridge[] { new OutboundQueueBridge("RECONNECT.TEST.OUT.QUEUE") });
    jmsQueueConnector.setInboundQueueBridges(new InboundQueueBridge[] { new InboundQueueBridge("RECONNECT.TEST.IN.QUEUE") });
    // Tell it how to reach the two brokers.
    jmsQueueConnector.setOutboundQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61617"));
    jmsQueueConnector.setLocalQueueConnectionFactory(new ActiveMQConnectionFactory("tcp://localhost:61616"));
}

2. JMSExclusiveConsumerTest#testMixExclusiveWithNonExclusive()

View license
public void testMixExclusiveWithNonExclusive() throws Exception {
    ActiveMQQueue exclusiveQueue = new ActiveMQQueue("TEST.FOO?consumer.exclusive=true");
    ActiveMQQueue nonExclusiveQueue = new ActiveMQQueue("TEST.FOO?consumer.exclusive=false");
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer nonExCon = session.createConsumer(nonExclusiveQueue);
    MessageConsumer exCon = session.createConsumer(exclusiveQueue);
    MessageProducer prod = session.createProducer(exclusiveQueue);
    prod.send(session.createMessage());
    prod.send(session.createMessage());
    prod.send(session.createMessage());
    Message m;
    for (int i = 0; i < 3; i++) {
        m = exCon.receive(1000);
        assertNotNull(m);
        m = nonExCon.receive(1000);
        assertNull(m);
    }
}

3. DestinationListenerTest#testProducerForcesNotificationOfNewDestination()

View license
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);
    assertThat(newQueue, isIn(newDestinations));
    LOG.info("New destinations are: " + newDestinations);
}

4. DispatchMultipleConsumersTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    super.setUp();
    broker = new BrokerService();
    broker.setPersistent(true);
    broker.setUseJmx(true);
    broker.deleteAllMessages();
    broker.addConnector("tcp://localhost:0");
    broker.start();
    broker.waitUntilStarted();
    dest = new ActiveMQQueue(destinationName);
    resetCounters();
    brokerURL = broker.getTransportConnectors().get(0).getPublishableConnectString();
}

5. SimpleSecurityBrokerSystemTest#testPopulateJMSXUserID()

View license
/**
    * @throws javax.jms.JMSException
    */
public void testPopulateJMSXUserID() throws Exception {
    destination = new ActiveMQQueue("TEST");
    Connection connection = factory.createConnection("system", "manager");
    connections.add(connection);
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    sendMessages(session, destination, 1);
    // make sure that the JMSXUserID is exposed over JMX
    MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
    CompositeData[] browse = (CompositeData[]) mbs.invoke(new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST"), "browse", null, null);
    assertEquals("system", browse[0].get("JMSXUserID"));
    // And also via JMS.
    MessageConsumer consumer = session.createConsumer(destination);
    Message m = consumer.receive(1000);
    assertTrue(m.propertyExists("JMSXUserID"));
    assertEquals("system", m.getStringProperty("JMSXUserID"));
}

6. NewConsumerCreatesDestinationTest#testNewConsumerCausesNewDestinationToBeAutoCreated()

View license
public void testNewConsumerCausesNewDestinationToBeAutoCreated() throws Exception {
    // lets create a wildcard thats kinda like those used by Virtual Topics
    String wildcardText = "org.*" + getDestinationString().substring("org.apache".length());
    wildcard = new ActiveMQQueue(wildcardText);
    LOG.info("Using wildcard: " + wildcard);
    LOG.info("on destination: " + destination);
    assertDestinationCreated(destination, false);
    assertDestinationCreated(wildcard, false);
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    session.createConsumer(destination);
    assertDestinationCreated(destination, true);
    assertDestinationCreated(wildcard, true);
}

7. NetworkReconnectTest#setUp()

View license
@Override
protected void setUp() throws Exception {
    LOG.info("===============================================================================");
    LOG.info("Running Test Case: " + getName());
    LOG.info("===============================================================================");
    producerConnectionFactory = createProducerConnectionFactory();
    consumerConnectionFactory = createConsumerConnectionFactory();
    destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE");
}

8. ActiveMQInitialContextFactoryTest#testDynamicallyGrowing()

View license
public void testDynamicallyGrowing() throws Exception {
    Object answer = context.lookup("dynamicQueues/FOO.BAR");
    assertTrue("Should have found a queue but found: " + answer, answer instanceof ActiveMQQueue);
    ActiveMQQueue queue = (ActiveMQQueue) answer;
    assertEquals("queue name", "FOO.BAR", queue.getPhysicalName());
    answer = context.lookup("dynamicTopics/A.B.C");
    assertTrue("Should have found a topic but found: " + answer, answer instanceof ActiveMQTopic);
    ActiveMQTopic topic = (ActiveMQTopic) answer;
    assertEquals("topic name", "A.B.C", topic.getPhysicalName());
}

9. DestinationListenerTest#testConsumerForcesNotificationOfNewDestination()

View license
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);
    assertThat(newQueue, isIn(newDestinations));
    LOG.info("New destinations are: " + newDestinations);
}

10. ConfigUsingDestinationOptions#testValidSelectorConfig()

View license
public void testValidSelectorConfig() throws JMSException {
    ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test=1");
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
    Connection conn = factory.createConnection();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQMessageConsumer cons;
    // JMS selector should be priority
    cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test=2");
    assertEquals("test=2", cons.getMessageSelector());
    // Test setting using JMS destinations
    cons = (ActiveMQMessageConsumer) sess.createConsumer(queue);
    assertEquals("test=1", cons.getMessageSelector());
}

11. ActiveMQClientITBase#testQueuePull()

Project: pinpoint
Source File: ActiveMQClientITBase.java
View license
@Test
public void testQueuePull() throws Exception {
    // Given
    final String testQueueName = "TestPullQueue";
    final ActiveMQQueue testQueue = new ActiveMQQueue(testQueueName);
    final String testMessage = "Hello World for Queue!";
    // create producer
    ActiveMQSession producerSession = ActiveMQClientITHelper.createSession(getProducerBrokerName(), getProducerBrokerUrl());
    MessageProducer producer = producerSession.createProducer(testQueue);
    final TextMessage expectedTextMessage = producerSession.createTextMessage(testMessage);
    // When
    ActiveMQSession consumerSession = ActiveMQClientITHelper.createSession(getConsumerBrokerName(), getConsumerBrokerUrl());
    MessageConsumer consumer = consumerSession.createConsumer(testQueue);
    // Then
    producer.send(expectedTextMessage);
    Message message = consumer.receive(1000L);
    Assert.assertEquals(testMessage, ((TextMessage) message).getText());
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(5, 5000L);
    // trace count : 1
    verifyProducerSendEvent(testQueue);
    // trace count : 4
    verifyConsumerPullEvent(testQueue, consumer, expectedTextMessage);
}

12. JmsEndpointWithCustomDestinationTest#testMessageSentToCustomEndpoint()

View license
@Test
public void testMessageSentToCustomEndpoint() throws Exception {
    ActiveMQQueue jmsQueue = context.getRegistry().lookupByNameAndType("jmsQueue", ActiveMQQueue.class);
    assertNotNull("jmsQueue", jmsQueue);
    assertEquals("jmsqueue.getPhysicalName()", "Test.Camel.CustomEndpoint", jmsQueue.getPhysicalName());
    getMockEndpoint("mock:result").expectedBodiesReceived(expectedBody);
    template.sendBody("direct:start", expectedBody);
    assertMockEndpointsSatisfied();
}

13. QueueProducerQoSTest#configureBroker()

Project: camel
Source File: QueueProducerQoSTest.java
View license
@Override
protected void configureBroker(BrokerService broker) throws Exception {
    broker.setUseJmx(true);
    broker.setPersistent(true);
    broker.setDataDirectory("target/activemq-data");
    broker.deleteAllMessages();
    broker.setAdvisorySupport(true);
    broker.addConnector(brokerUri);
    // configure expiration rate
    ActiveMQQueue queueName = new ActiveMQQueue(">");
    PolicyEntry entry = new PolicyEntry();
    entry.setDestination(queueName);
    entry.setExpireMessagesPeriod(1000);
    PolicyMap policyMap = new PolicyMap();
    policyMap.put(queueName, entry);
    broker.setDestinationPolicy(policyMap);
}

14. JmsQueueBrowserTest#testQueueBrowserWith2Consumers()

View license
public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();
    ActiveMQConnection connection2 = (ActiveMQConnection) factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destinationPrefetch10);
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    for (int i = 0; i < numMessages; i++) {
        TextMessage message = session.createTextMessage("Message: " + i);
        producer.send(message);
    }
    QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
    Enumeration<Message> browserView = browser.getEnumeration();
    List<Message> messages = new ArrayList<>();
    for (int i = 0; i < numMessages; i++) {
        Message m1 = consumer.receive(5000);
        assertNotNull("m1 is null for index: " + i, m1);
        messages.add(m1);
    }
    int i = 0;
    for (; i < numMessages && browserView.hasMoreElements(); i++) {
        Message m1 = messages.get(i);
        Message m2 = browserView.nextElement();
        assertNotNull("m2 is null for index: " + i, m2);
        assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
    }
    // currently browse max page size is ignored for a queue browser consumer
    // only guarantee is a page size - but a snapshot of pagedinpending is
    // used so it is most likely more
    assertTrue("got at least our expected minimum in the browser: ", i > BaseDestination.MAX_PAGE_SIZE);
    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

15. TwoBrokerVirtualTopicForwardingTest#testBridgeVirtualTopicQueues()

View license
public void testBridgeVirtualTopicQueues() throws Exception {
    bridgeAndConfigureBrokers("BrokerA", "BrokerB");
    startAllBrokers();
    waitForBridgeFormation();
    MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false));
    MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false));
    // give a sec to let advisories propagate
    Thread.sleep(500);
    ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic");
    Destination destination = getDestination(brokers.get("BrokerA").broker, queueA);
    assertEquals(1, destination.getConsumers().size());
    ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic");
    destination = getDestination(brokers.get("BrokerA").broker, queueB);
    assertEquals(1, destination.getConsumers().size());
    ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic");
    assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic));
    assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic));
    // send some messages
    sendMessages("BrokerA", virtualTopic, 1);
    MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
    MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
    msgsA.waitForMessagesToArrive(1);
    msgsB.waitForMessagesToArrive(1);
    // ensure we don't get any more messages
    Thread.sleep(2000);
    assertEquals(1, msgsA.getMessageCount());
    assertEquals(1, msgsB.getMessageCount());
}

16. TwoBrokerVirtualTopicForwardingTest#testDontBridgeQueuesWithOnlyQueueConsumers()

View license
public void testDontBridgeQueuesWithOnlyQueueConsumers() throws Exception {
    dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB");
    startAllBrokers();
    waitForBridgeFormation();
    MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false));
    MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false));
    // give a sec to let advisories propagate
    Thread.sleep(500);
    ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic");
    Destination destination = getDestination(brokers.get("BrokerA").broker, queueA);
    assertEquals(1, destination.getConsumers().size());
    ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic");
    destination = getDestination(brokers.get("BrokerA").broker, queueB);
    assertNull(destination);
    ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic");
    assertNull(getDestination(brokers.get("BrokerA").broker, virtualTopic));
    assertNull(getDestination(brokers.get("BrokerB").broker, virtualTopic));
    // send some messages
    sendMessages("BrokerA", virtualTopic, 1);
    MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
    MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
    msgsA.waitForMessagesToArrive(1);
    msgsB.waitForMessagesToArrive(0);
    // ensure we don't get any more messages
    Thread.sleep(2000);
    assertEquals(1, msgsA.getMessageCount());
    assertEquals(0, msgsB.getMessageCount());
}

17. TwoBrokerVirtualTopicForwardingTest#testDontBridgeQueuesWithBothTypesConsumers()

View license
public void testDontBridgeQueuesWithBothTypesConsumers() throws Exception {
    dontBridgeVirtualTopicConsumerQueues("BrokerA", "BrokerB");
    startAllBrokers();
    waitForBridgeFormation();
    MessageConsumer clientA = createConsumer("BrokerA", createDestination("Consumer.A.VirtualTopic.tempTopic", false));
    MessageConsumer clientB = createConsumer("BrokerB", createDestination("Consumer.B.VirtualTopic.tempTopic", false));
    MessageConsumer clientC = createConsumer("BrokerB", createDestination("VirtualTopic.tempTopic", true));
    // give a sec to let advisories propagate
    Thread.sleep(500);
    ActiveMQQueue queueA = new ActiveMQQueue("Consumer.A.VirtualTopic.tempTopic");
    Destination destination = getDestination(brokers.get("BrokerA").broker, queueA);
    assertEquals(1, destination.getConsumers().size());
    ActiveMQQueue queueB = new ActiveMQQueue("Consumer.B.VirtualTopic.tempTopic");
    destination = getDestination(brokers.get("BrokerA").broker, queueB);
    assertNull(destination);
    ActiveMQTopic virtualTopic = new ActiveMQTopic("VirtualTopic.tempTopic");
    assertNotNull(getDestination(brokers.get("BrokerA").broker, virtualTopic));
    assertNotNull(getDestination(brokers.get("BrokerB").broker, virtualTopic));
    // send some messages
    sendMessages("BrokerA", virtualTopic, 1);
    MessageIdList msgsA = getConsumerMessages("BrokerA", clientA);
    MessageIdList msgsB = getConsumerMessages("BrokerB", clientB);
    msgsA.waitForMessagesToArrive(1);
    msgsB.waitForMessagesToArrive(1);
    // ensure we don't get any more messages
    Thread.sleep(2000);
    assertEquals(1, msgsA.getMessageCount());
    assertEquals(1, msgsB.getMessageCount());
}

18. NetworkBridgeProducerFlowControlTest#testFastAndSlowRemoteConsumers()

View license
/**
    * This test is parameterized by {@link #persistentTestMessages}, which
    * determines whether the producer on broker0 sends persistent or
    * non-persistent messages, and {@link #networkIsAlwaysSendSync}, which
    * determines how the bridge will forward both persistent and non-persistent
    * messages to broker1.
    *
    * @see #initCombosForTestFastAndSlowRemoteConsumers()
    */
public void testFastAndSlowRemoteConsumers() throws Exception {
    final int NUM_MESSAGES = 100;
    final long TEST_MESSAGE_SIZE = 1024;
    final long SLOW_CONSUMER_DELAY_MILLIS = 100;
    // Consumer prefetch is disabled for broker1's consumers.
    final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1");
    final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1");
    // Start a local and a remote broker.
    createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker0&persistent=false&useJmx=true"));
    BrokerService remoteBroker = createBroker(new URI("broker:(tcp://localhost:0" + ")?brokerName=broker1&persistent=false&useJmx=true"));
    // Set a policy on the remote broker that limits the maximum size of the
    // slow shared queue.
    PolicyEntry policyEntry = new PolicyEntry();
    policyEntry.setMemoryLimit(5 * TEST_MESSAGE_SIZE);
    PolicyMap policyMap = new PolicyMap();
    policyMap.put(SLOW_SHARED_QUEUE, policyEntry);
    remoteBroker.setDestinationPolicy(policyMap);
    // Create an outbound bridge from the local broker to the remote broker.
    // The bridge is configured with the remoteDispatchType enhancement.
    NetworkConnector nc = bridgeBrokers("broker0", "broker1");
    nc.setAlwaysSyncSend(networkIsAlwaysSendSync);
    nc.setPrefetchSize(1);
    startAllBrokers();
    waitForBridgeFormation();
    // Send the test messages to the local broker's shared queues. The
    // messages are either persistent or non-persistent to demonstrate the
    // difference between synchronous and asynchronous dispatch.
    persistentDelivery = persistentTestMessages;
    sendMessages("broker0", FAST_SHARED_QUEUE, NUM_MESSAGES);
    sendMessages("broker0", SLOW_SHARED_QUEUE, NUM_MESSAGES);
    // Start two asynchronous consumers on the remote broker, one for each
    // of the two shared queues, and keep track of how long it takes for
    // each of the consumers to receive all the messages.
    final CountDownLatch fastConsumerLatch = new CountDownLatch(NUM_MESSAGES);
    final CountDownLatch slowConsumerLatch = new CountDownLatch(NUM_MESSAGES);
    final long startTimeMillis = System.currentTimeMillis();
    final AtomicLong fastConsumerTime = new AtomicLong();
    final AtomicLong slowConsumerTime = new AtomicLong();
    Thread fastWaitThread = new Thread() {

        @Override
        public void run() {
            try {
                fastConsumerLatch.await();
                fastConsumerTime.set(System.currentTimeMillis() - startTimeMillis);
            } catch (InterruptedException ex) {
                exceptions.add(ex);
                Assert.fail(ex.getMessage());
            }
        }
    };
    Thread slowWaitThread = new Thread() {

        @Override
        public void run() {
            try {
                slowConsumerLatch.await();
                slowConsumerTime.set(System.currentTimeMillis() - startTimeMillis);
            } catch (InterruptedException ex) {
                exceptions.add(ex);
                Assert.fail(ex.getMessage());
            }
        }
    };
    fastWaitThread.start();
    slowWaitThread.start();
    createConsumer("broker1", FAST_SHARED_QUEUE, fastConsumerLatch);
    MessageConsumer slowConsumer = createConsumer("broker1", SLOW_SHARED_QUEUE, slowConsumerLatch);
    MessageIdList messageIdList = brokers.get("broker1").consumers.get(slowConsumer);
    messageIdList.setProcessingDelay(SLOW_CONSUMER_DELAY_MILLIS);
    fastWaitThread.join();
    slowWaitThread.join();
    assertTrue("no exceptions on the wait threads:" + exceptions, exceptions.isEmpty());
    LOG.info("Fast consumer duration (ms): " + fastConsumerTime.get());
    LOG.info("Slow consumer duration (ms): " + slowConsumerTime.get());
    // Verify the behaviour as described in the description of this class.
    if (networkIsAlwaysSendSync) {
        Assert.assertTrue(fastConsumerTime.get() < slowConsumerTime.get() / 10);
    } else {
        Assert.assertEquals(persistentTestMessages, fastConsumerTime.get() < slowConsumerTime.get() / 10);
    }
}

19. NetworkBridgeProducerFlowControlTest#testSendFailIfNoSpaceDoesNotBlockQueueNetwork()

View license
public void testSendFailIfNoSpaceDoesNotBlockQueueNetwork() throws Exception {
    // Consumer prefetch is disabled for broker1's consumers.
    final ActiveMQQueue SLOW_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".slow.shared?consumer.prefetchSize=1");
    final ActiveMQQueue FAST_SHARED_QUEUE = new ActiveMQQueue(NetworkBridgeProducerFlowControlTest.class.getSimpleName() + ".fast.shared?consumer.prefetchSize=1");
    doTestSendFailIfNoSpaceDoesNotBlockNetwork(SLOW_SHARED_QUEUE, FAST_SHARED_QUEUE);
}

20. QueueBrowsingTest#testBrowseConcurrent()

View license
@Test
public void testBrowseConcurrent() throws Exception {
    final int messageToSend = 370;
    final ActiveMQQueue queue = new ActiveMQQueue("TEST");
    Connection connection = factory.createConnection();
    connection.start();
    final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    String data = "";
    for (int i = 0; i < 1024 * 2; i++) {
        data += "x";
    }
    for (int i = 0; i < messageToSend; i++) {
        producer.send(session.createTextMessage(data));
    }
    Thread browserThread = new Thread() {

        @Override
        public void run() {
            try {
                QueueBrowser browser = session.createBrowser(queue);
                Enumeration<?> enumeration = browser.getEnumeration();
                int received = 0;
                while (enumeration.hasMoreElements()) {
                    Message m = (Message) enumeration.nextElement();
                    received++;
                    LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
                }
                assertEquals("Browsed all messages", messageToSend, received);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    browserThread.start();
    Thread consumerThread = new Thread() {

        @Override
        public void run() {
            try {
                MessageConsumer consumer = session.createConsumer(queue);
                int received = 0;
                while (true) {
                    Message m = consumer.receive(1000);
                    if (m == null)
                        break;
                    received++;
                }
                assertEquals("Consumed all messages", messageToSend, received);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };
    consumerThread.start();
    browserThread.join();
    consumerThread.join();
}

21. TwoBrokerTempQueueAdvisoryTest#testSendToRemovedTemp()

View license
public void testSendToRemovedTemp() throws Exception {
    ActiveMQQueue requestReplyDest = new ActiveMQQueue("RequestReply");
    NetworkConnector nc = bridgeBrokers("BrokerA", "BrokerB");
    if (useDuplex) {
        nc.setDuplex(true);
    } else {
        bridgeBrokers("BrokerB", "BrokerA");
    }
    // way
    if (!useDuplex) {
        brokers.get("BrokerB").broker.setAllowTempAutoCreationOnSend(true);
    }
    TransportConnector forClient = brokers.get("BrokerA").broker.addConnector("tcp://localhost:0");
    startAllBrokers();
    waitForBridgeFormation();
    waitForMinTopicRegionConsumerCount("BrokerB", 1);
    waitForMinTopicRegionConsumerCount("BrokerA", 1);
    ConnectionFactory factory = new ActiveMQConnectionFactory(forClient.getConnectUri());
    ActiveMQConnection conn = (ActiveMQConnection) factory.createConnection();
    conn.setWatchTopicAdvisories(false);
    conn.start();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ConnectionFactory replyFactory = getConnectionFactory("BrokerB");
    for (int i = 0; i < 500; 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();
        replyConnection.setWatchTopicAdvisories(false);
        replyConnection.start();
        Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest);
        javax.jms.Message msg = replyConsumer.receive(10000);
        assertNotNull("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);
        assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply);
        consumer.close();
        tempDest.delete();
    }
}

22. TransactionTest#testTransaction()

View license
public void testTransaction() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    connection = factory.createConnection();
    queue = new ActiveMQQueue(getClass().getName() + "." + getName());
    producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    consumerSession = connection.createSession(true, 0);
    producer = producerSession.createProducer(queue);
    consumer = consumerSession.createConsumer(queue);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message m) {
            try {
                TextMessage tm = (TextMessage) m;
                receivedText = tm.getText();
                latch.countDown();
                LOG.info("consumer received message :" + receivedText);
                consumerSession.commit();
                LOG.info("committed transaction");
            } catch (JMSException e) {
                try {
                    consumerSession.rollback();
                    LOG.info("rolled back transaction");
                } catch (JMSException e1) {
                    LOG.info(e1.toString());
                    e1.printStackTrace();
                }
                LOG.info(e.toString());
                e.printStackTrace();
            }
        }
    });
    connection.start();
    TextMessage tm = null;
    try {
        tm = producerSession.createTextMessage();
        tm.setText("Hello, " + new Date());
        producer.send(tm);
        LOG.info("producer sent message :" + tm.getText());
    } catch (JMSException e) {
        e.printStackTrace();
    }
    LOG.info("Waiting for latch");
    latch.await(2, TimeUnit.SECONDS);
    assertNotNull(receivedText);
    LOG.info("test completed, destination=" + receivedText);
}

23. TransactionRollbackOrderTest#testTransaction()

View license
public void testTransaction() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    connection = factory.createConnection();
    queue = new ActiveMQQueue(getClass().getName() + "." + getName());
    producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    consumerSession = connection.createSession(true, 0);
    producer = producerSession.createProducer(queue);
    consumer = consumerSession.createConsumer(queue);
    consumer.setMessageListener(new MessageListener() {

        int msgCount;

        int msgCommittedCount;

        @Override
        public void onMessage(Message m) {
            try {
                msgCount++;
                TextMessage tm = (TextMessage) m;
                receivedText = tm.getText();
                if (tm.getJMSRedelivered()) {
                    msgRedelivered.add(receivedText);
                }
                LOG.info("consumer received message: " + receivedText + (tm.getJMSRedelivered() ? " ** Redelivered **" : ""));
                if (msgCount == 3) {
                    msgRolledBack.add(receivedText);
                    consumerSession.rollback();
                    LOG.info("[msg: " + receivedText + "] ** rolled back **");
                } else {
                    msgCommittedCount++;
                    msgCommitted.add(receivedText);
                    consumerSession.commit();
                    LOG.info("[msg: " + receivedText + "] committed transaction ");
                }
                if (msgCommittedCount == numMessages) {
                    latch.countDown();
                }
            } catch (JMSException e) {
                try {
                    consumerSession.rollback();
                    LOG.info("rolled back transaction");
                } catch (JMSException e1) {
                    LOG.info(e1.toString());
                    e1.printStackTrace();
                }
                LOG.info(e.toString());
                e.printStackTrace();
            }
        }
    });
    connection.start();
    TextMessage tm = null;
    try {
        for (int i = 1; i <= numMessages; i++) {
            tm = producerSession.createTextMessage();
            tm.setText("Hello " + i);
            msgSent.add(tm.getText());
            producer.send(tm);
            LOG.info("producer sent message: " + tm.getText());
        }
    } catch (JMSException e) {
        e.printStackTrace();
    }
    LOG.info("Waiting for latch");
    latch.await();
    assertEquals(1, msgRolledBack.size());
    assertEquals(1, msgRedelivered.size());
    LOG.info("msg RolledBack = " + msgRolledBack.get(0));
    LOG.info("msg Redelivered = " + msgRedelivered.get(0));
    assertEquals(msgRolledBack.get(0), msgRedelivered.get(0));
    assertEquals(numMessages, msgSent.size());
    assertEquals(numMessages, msgCommitted.size());
    assertEquals(msgSent, msgCommitted);
}

24. QueueRepeaterTest#testTransaction()

View license
public void testTransaction() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost?broker.persistent=false");
    connection = factory.createConnection();
    queue = new ActiveMQQueue(getClass().getName() + "." + getName());
    producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    consumerSession = connection.createSession(true, 0);
    producer = producerSession.createProducer(queue);
    consumer = consumerSession.createConsumer(queue);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message m) {
            try {
                TextMessage tm = (TextMessage) m;
                receivedText = tm.getText();
                latch.countDown();
                LOG.info("consumer received message :" + receivedText);
                consumerSession.commit();
                LOG.info("committed transaction");
            } catch (JMSException e) {
                try {
                    consumerSession.rollback();
                    LOG.info("rolled back transaction");
                } catch (JMSException e1) {
                    LOG.info(e1.toString());
                    e1.printStackTrace();
                }
                LOG.info(e.toString());
                e.printStackTrace();
            }
        }
    });
    connection.start();
    TextMessage tm = null;
    try {
        tm = producerSession.createTextMessage();
        tm.setText("Hello, " + new Date());
        producer.send(tm);
        LOG.info("producer sent message :" + tm.getText());
    } catch (JMSException e) {
        e.printStackTrace();
    }
    LOG.info("Waiting for latch");
    latch.await(2, TimeUnit.SECONDS);
    assertNotNull(receivedText);
    LOG.info("test completed, destination=" + receivedText);
}

25. QueueBrowsingTest#testMemoryLimit()

View license
@Test
public void testMemoryLimit() throws Exception {
    broker.getSystemUsage().getMemoryUsage().setLimit(16 * 1024);
    int messageToSend = 370;
    ActiveMQQueue queue = new ActiveMQQueue("TEST");
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    String data = "";
    for (int i = 0; i < 1024 * 2; i++) {
        data += "x";
    }
    for (int i = 0; i < messageToSend; i++) {
        producer.send(session.createTextMessage(data));
    }
    QueueBrowser browser = session.createBrowser(queue);
    Enumeration<?> enumeration = browser.getEnumeration();
    int received = 0;
    while (enumeration.hasMoreElements()) {
        Message m = (Message) enumeration.nextElement();
        received++;
        LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
    }
    browser.close();
    assertTrue("got at least maxPageSize", received >= maxPageSize);
}

26. TwoSecureBrokerRequestReplyTest#testRequestReply()

View license
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.setWatchTopicAdvisories(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.setWatchTopicAdvisories(false);
        replyConnection.start();
        Session replySession = replyConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        ActiveMQMessageConsumer replyConsumer = (ActiveMQMessageConsumer) replySession.createConsumer(requestReplyDest);
        javax.jms.Message msg = replyConsumer.receive(10000);
        assertNotNull("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);
        assertNotNull("reply message : " + i + ", to: " + tempDest + ", by consumer:" + consumer.getConsumerId(), reply);
        consumer.close();
        tempDest.delete();
        LOG.info("message #" + i + " processed");
    }
}

27. QueueBrowsingTest#testBrowsing()

View license
@Test
public void testBrowsing() throws JMSException {
    int messageToSend = 370;
    ActiveMQQueue queue = new ActiveMQQueue("TEST");
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    String data = "";
    for (int i = 0; i < 1024 * 2; i++) {
        data += "x";
    }
    for (int i = 0; i < messageToSend; i++) {
        producer.send(session.createTextMessage(data));
    }
    QueueBrowser browser = session.createBrowser(queue);
    Enumeration<?> enumeration = browser.getEnumeration();
    int received = 0;
    while (enumeration.hasMoreElements()) {
        Message m = (Message) enumeration.nextElement();
        received++;
        LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
    }
    browser.close();
    assertEquals(messageToSend, received);
}

28. QueueBrowsingLimitTest#testBrowsingLimited()

View license
@Test
public void testBrowsingLimited() throws Exception {
    int messageToSend = 470;
    ActiveMQQueue queue = new ActiveMQQueue("TEST");
    Connection connection = factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    String data = "";
    for (int i = 0; i < 1024 * 2; i++) {
        data += "x";
    }
    for (int i = 0; i < messageToSend; i++) {
        producer.send(session.createTextMessage(data));
    }
    QueueBrowser browser = session.createBrowser(queue);
    Enumeration<?> enumeration = browser.getEnumeration();
    int received = 0;
    while (enumeration.hasMoreElements()) {
        Message m = (Message) enumeration.nextElement();
        received++;
        LOG.info("Browsed message " + received + ": " + m.getJMSMessageID());
    }
    browser.close();
    assertEquals(browserLimit, received);
}

29. MessageGroupLateArrivalsTest#setUp()

View license
@Before
public void setUp() throws Exception {
    broker = createBroker();
    broker.start();
    ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1000");
    connection = connFactory.createConnection();
    session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    destination = new ActiveMQQueue("test-queue2");
    producer = session.createProducer(destination);
    connection.start();
}

30. MessageGroupDelayedTest#setUp()

View license
@Override
public void setUp() throws Exception {
    broker = createBroker();
    broker.start();
    ActiveMQConnectionFactory connFactory = new ActiveMQConnectionFactory(connector.getConnectUri() + "?jms.prefetchPolicy.all=1");
    connection = connFactory.createConnection();
    session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    destination = new ActiveMQQueue("test-queue2");
    producer = session.createProducer(destination);
    connection.start();
}

31. ActiveMQClientITBase#testQueuePush()

Project: pinpoint
Source File: ActiveMQClientITBase.java
View license
@Test
public void testQueuePush() throws Exception {
    // Given
    final String testQueueName = "TestPushQueue";
    final ActiveMQQueue testQueue = new ActiveMQQueue(testQueueName);
    final String testMessage = "Hello World for Queue!";
    final CountDownLatch consumerLatch = new CountDownLatch(1);
    final Collection<Throwable> consumerThrowables = new CopyOnWriteArrayList<Throwable>();
    // create producer
    ActiveMQSession producerSession = ActiveMQClientITHelper.createSession(getProducerBrokerName(), getProducerBrokerUrl());
    MessageProducer producer = producerSession.createProducer(testQueue);
    final TextMessage expectedTextMessage = producerSession.createTextMessage(testMessage);
    // create consumer
    ActiveMQSession consumerSession = ActiveMQClientITHelper.createSession(getConsumerBrokerName(), getConsumerBrokerUrl());
    MessageConsumer consumer = consumerSession.createConsumer(testQueue);
    consumer.setMessageListener(new AssertTextMessageListener(consumerLatch, consumerThrowables, expectedTextMessage));
    // When
    producer.send(expectedTextMessage);
    consumerLatch.await(1L, TimeUnit.SECONDS);
    // Then
    assertNoConsumerError(consumerThrowables);
    // Wait till all traces are recorded (consumer traces are recorded from another thread)
    awaitAndVerifyTraceCount(2, 5000L);
    // trace count : 1
    verifyProducerSendEvent(testQueue);
    // trace count : 1
    verifyConsumerPushEvent(testQueue);
}

32. RedeliveryPolicyTest#testRedeliveryDelayOne()

View license
@Test
public void testRedeliveryDelayOne() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(1000);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(2);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

33. JmsQueueBrowserTest#testReceiveBrowseReceive()

View license
/**
    * Tests the queue browser. Browses the messages then the consumer tries to
    * receive them. The messages should still be in the queue even when it was
    * browsed.
    *
    * @throws Exception
    */
@Test
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();
    Message[] outbound = new Message[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);
    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    System.out.println("creating browser...");
    QueueBrowser browser = session.createBrowser(destination);
    System.out.println("browser created");
    Enumeration<?> enumeration = browser.getEnumeration();
    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], enumeration.nextElement());
    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], enumeration.nextElement());
    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        System.out.println("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();
    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();
}

34. JmsQueueBrowserTest#testBatchSendBrowseReceive()

View license
@Test
public void testBatchSendBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();
    TextMessage[] outbound = new TextMessage[10];
    for (int i = 0; i < 10; i++) {
        outbound[i] = session.createTextMessage(i + " Message");
    }
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    consumer.close();
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    for (int i = 0; i < outbound.length; i++) {
        assertTrue("should have a", enumeration.hasMoreElements());
        assertEquals(outbound[i], enumeration.nextElement());
    }
    browser.close();
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    // verify second batch is visible to browse
    browser = session.createBrowser(destination);
    enumeration = browser.getEnumeration();
    for (int j = 0; j < 2; j++) {
        for (int i = 0; i < outbound.length; i++) {
            assertTrue("should have a", enumeration.hasMoreElements());
            assertEquals("j=" + j + ", i=" + i, outbound[i].getText(), ((TextMessage) enumeration.nextElement()).getText());
        }
    }
    browser.close();
    consumer = session.createConsumer(destination);
    for (int i = 0; i < outbound.length * 2; i++) {
        assertNotNull("Got message: " + i, consumer.receive(2000));
    }
    consumer.close();
}

35. JmsQueueBrowserTest#testBrowseReceive()

View license
/* disable this test because it uses management mbeans which we don't implement yet.
   @Test
   public void testBatchSendJmxBrowseReceive() throws Exception
   {
      Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);
      ActiveMQQueue destination = new ActiveMQQueue("TEST");
      MessageProducer producer = session.createProducer(destination);
      MessageConsumer consumer = session.createConsumer(destination);
      connection.start();

      TextMessage[] outbound = new TextMessage[10];
      for (int i = 0; i < 10; i++)
      {
         outbound[i] = session.createTextMessage(i + " Message");
      }
      ;

      // lets consume any outstanding messages from previous test runs
      while (consumer.receive(1000) != null)
      {
      }
      consumer.close();

      for (int i = 0; i < outbound.length; i++)
      {
         producer.send(outbound[i]);
      }

      ObjectName queueViewMBeanName = new ObjectName(
            "org.apache.activemq.artemis:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST");

      System.out.println("Create QueueView MBean...");
      QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext()
            .newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);

      long concount = proxy.getConsumerCount();
      System.out.println("Consumer Count :" + concount);
      long messcount = proxy.getQueueSize();
      System.out.println("current number of messages in the queue :"
            + messcount);

      // lets browse
      CompositeData[] compdatalist = proxy.browse();
      if (compdatalist.length == 0)
      {
         fail("There is no message in the queue:");
      }
      String[] messageIDs = new String[compdatalist.length];

      for (int i = 0; i < compdatalist.length; i++)
      {
         CompositeData cdata = compdatalist[i];

         if (i == 0)
         {
            System.out.println("Columns: " + cdata.getCompositeType().keySet());
         }
         messageIDs[i] = (String) cdata.get("JMSMessageID");
         System.out.println("message " + i + " : " + cdata.values());
      }

      TabularData table = proxy.browseAsTable();
      System.out.println("Found tabular data: " + table);
      assertTrue("Table should not be empty!", table.size() > 0);

      assertEquals("Queue size", outbound.length, proxy.getQueueSize());
      assertEquals("Queue size", outbound.length, compdatalist.length);
      assertEquals("Queue size", outbound.length, table.size());

      System.out.println("Send another 10");
      for (int i = 0; i < outbound.length; i++)
      {
         producer.send(outbound[i]);
      }

      System.out.println("Browse again");

      messcount = proxy.getQueueSize();
      System.out.println("current number of messages in the queue :"
            + messcount);

      compdatalist = proxy.browse();
      if (compdatalist.length == 0)
      {
         fail("There is no message in the queue:");
      }
      messageIDs = new String[compdatalist.length];

      for (int i = 0; i < compdatalist.length; i++)
      {
         CompositeData cdata = compdatalist[i];

         if (i == 0)
         {
            System.out.println("Columns: " + cdata.getCompositeType().keySet());
         }
         messageIDs[i] = (String) cdata.get("JMSMessageID");
         System.out.println("message " + i + " : " + cdata.values());
      }

      table = proxy.browseAsTable();
      System.out.println("Found tabular data: " + table);
      assertTrue("Table should not be empty!", table.size() > 0);

      assertEquals("Queue size", outbound.length * 2, proxy.getQueueSize());
      assertEquals("Queue size", outbound.length * 2, compdatalist.length);
      assertEquals("Queue size", outbound.length * 2, table.size());

      consumer = session.createConsumer(destination);
      for (int i = 0; i < outbound.length * 2; i++)
      {
         assertNotNull("Got message: " + i, consumer.receive(2000));
      }
      consumer.close();
   }

*/
@Test
public void testBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    connection.start();
    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);
    System.out.println("created consumer ... ");
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    consumer.close();
    Message[] outbound = new Message[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    // create browser first
    System.out.println("creating browser...");
    QueueBrowser browser = session.createBrowser(destination);
    System.out.println("created " + browser);
    Enumeration<?> enumeration = browser.getEnumeration();
    System.out.println("browsing first");
    // browse the first message
    assertTrue("should have received the first message", enumeration.hasMoreElements());
    System.out.println("we have more");
    assertEquals(outbound[0], enumeration.nextElement());
    System.out.println("ok");
    consumer = session.createConsumer(destination);
    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();
    System.out.println("test done.");
}

36. JmsQueueBrowserTest#testLargeNumberOfMessages()

View license
@Test
public void testLargeNumberOfMessages() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    connection.start();
    MessageProducer producer = session.createProducer(destination);
    int numberOfMessages = 4096;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(session.createTextMessage("Message: " + i));
    }
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    assertTrue(enumeration.hasMoreElements());
    int numberBrowsed = 0;
    while (enumeration.hasMoreElements()) {
        Message browsed = (Message) enumeration.nextElement();
        System.out.println("Browsed Message [{}]" + browsed.getJMSMessageID());
        numberBrowsed++;
    }
    System.out.println("Number browsed:  " + numberBrowsed);
    assertEquals(numberOfMessages, numberBrowsed);
    browser.close();
    producer.close();
}

37. JmsQueueBrowserTest#testBrowseClose()

View license
/*
   @Test
   public void testQueueBrowserWith2Consumers() throws Exception
   {
      final int numMessages = 1000;
      connection.setAlwaysSyncSend(false);
      Session session = connection.createSession(false,
            Session.CLIENT_ACKNOWLEDGE);
      ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
      ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue(
            "TEST?jms.prefetchSize=10");
      ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue(
            "TEST?jms.prefetchsize=1");
      connection.start();

      ActiveMQConnection connection2 = (ActiveMQConnection) factory
            .createConnection();
      connection2.start();

      Session session2 = connection2.createSession(false,
            Session.AUTO_ACKNOWLEDGE);

      MessageProducer producer = session.createProducer(destination);
      MessageConsumer consumer = session.createConsumer(destinationPrefetch10);

      // lets consume any outstanding messages from previous test runs
      while (consumer.receive(1000) != null)
      {
      }
      consumer.close();

      for (int i = 0; i < numMessages; i++)
      {
         TextMessage message = session.createTextMessage("Message: " + i);
         producer.send(message);
      }

      QueueBrowser browser = session2.createBrowser(destinationPrefetch1);
      @SuppressWarnings("unchecked")
      Enumeration<Message> browserView = browser.getEnumeration();

      List<Message> messages = new ArrayList<Message>();
      for (int i = 0; i < numMessages; i++)
      {
         Message m1 = consumer.receive(5000);
         assertNotNull("m1 is null for index: " + i, m1);
         messages.add(m1);
      }

      int i = 0;
      for (; i < numMessages && browserView.hasMoreElements(); i++)
      {
         Message m1 = messages.get(i);
         Message m2 = browserView.nextElement();
         assertNotNull("m2 is null for index: " + i, m2);
         assertEquals(m1.getJMSMessageID(), m2.getJMSMessageID());
      }

      // currently browse max page size is ignored for a queue browser consumer
      // only guarantee is a page size - but a snapshot of pagedinpending is
      // used so it is most likely more
      assertTrue("got at least our expected minimum in the browser: ", i > 200);

      assertFalse("nothing left in the browser", browserView.hasMoreElements());
      assertNull("consumer finished", consumer.receiveNoWait());
      connection2.close();
   }
   */
@Test
public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = (ActiveMQQueue) this.createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    connection.start();
    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    consumer.close();
    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);
    // create browser first
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    // browse some messages
    assertEquals(outbound[0], enumeration.nextElement());
    assertEquals(outbound[1], enumeration.nextElement());
    // assertEquals(outbound[2], (Message) enumeration.nextElement());
    browser.close();
    consumer = session.createConsumer(destination);
    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);
    consumer.close();
    producer.close();
}

38. RedeliveryPolicyTest#testExponentialRedeliveryPolicyDelaysDeliveryOnRollback()

View license
/**
    * @throws Exception
    */
@Test
public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(500);
    policy.setBackOffMultiplier((short) 2);
    policy.setUseExponentialBackOff(true);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("testExponentialRedeliveryPolicyDelaysDeliveryOnRollback");
    this.makeSureCoreQueueExist("testExponentialRedeliveryPolicyDelaysDeliveryOnRollback");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // No delay on first rollback..
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    session.rollback();
    // Show subsequent re-delivery delay is incrementing.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // Show re-delivery delay is incrementing exponentially
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(500);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
}

39. RedeliveryPolicyTest#testNornalRedeliveryPolicyDelaysDeliveryOnRollback()

View license
/**
    * @throws Exception
    */
@Test
public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(500);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("testNornalRedeliveryPolicyDelaysDeliveryOnRollback");
    this.makeSureCoreQueueExist("testNornalRedeliveryPolicyDelaysDeliveryOnRollback");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // No delay on first rollback..
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    session.rollback();
    // Show subsequent re-delivery delay is incrementing.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // The message gets redelivered after 500 ms every time since
    // we are not using exponential backoff.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
}

40. RedeliveryPolicyTest#testDLQHandling()

View license
/**
    * @throws Exception
    */
@Test
public void testDLQHandling() throws Exception {
    this.makeSureCoreQueueExist("ActiveMQ.DLQ");
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(2);
    connection.start();
    Session session = connection.createSession(true, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ"));
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // The last rollback should cause the 1st message to get sent to the DLQ
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    // We should be able to get the message off the DLQ now.
    m = (TextMessage) dlqConsumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy"));
    session.commit();
}

41. RedeliveryPolicyTest#testInfiniteMaximumNumberOfRedeliveries()

View license
/**
    * @throws Exception
    */
@Test
public void testInfiniteMaximumNumberOfRedeliveries() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    // let's set the maximum redeliveries to no maximum (ie. infinite)
    policy.setMaximumRedeliveries(-1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // we should be able to get the 1st message redelivered until a
    // session.commit is called
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.commit();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

42. RedeliveryPolicyTest#testMaximumRedeliveryDelay()

View license
/**
    * @throws Exception
    */
@Test
public void testMaximumRedeliveryDelay() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(10);
    policy.setUseExponentialBackOff(true);
    policy.setMaximumRedeliveries(-1);
    policy.setRedeliveryDelay(50);
    policy.setMaximumRedeliveryDelay(1000);
    policy.setBackOffMultiplier((short) 2);
    policy.setUseExponentialBackOff(true);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    for (int i = 0; i < 10; ++i) {
        // we should be able to get the 1st message redelivered until a
        // session.commit is called
        m = (TextMessage) consumer.receive(2000);
        assertNotNull(m);
        assertEquals("1st", m.getText());
        session.rollback();
    }
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.commit();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    assertTrue(policy.getNextRedeliveryDelay(Long.MAX_VALUE) == 1000);
}

43. RedeliveryPolicyTest#testZeroMaximumNumberOfRedeliveries()

View license
/**
    * @throws Exception
    */
@Test
public void testZeroMaximumNumberOfRedeliveries() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    // let's set the maximum redeliveries to 0
    policy.setMaximumRedeliveries(0);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // the 1st message should not be redelivered since maximumRedeliveries is
    // set to 0
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

44. RedeliveryPolicyTest#testInitialRedeliveryDelayZero()

View license
@Test
public void testInitialRedeliveryDelayZero() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    session.commit();
}

45. RedeliveryPolicyTest#testInitialRedeliveryDelayOne()

View license
@Test
public void testInitialRedeliveryDelayOne() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(1000);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

46. RedeliveryPolicyTest#testRedeliveryPolicyPerDestination()

View license
@Test
public void testRedeliveryPolicyPerDestination() throws Exception {
    RedeliveryPolicy queuePolicy = new RedeliveryPolicy();
    queuePolicy.setInitialRedeliveryDelay(0);
    queuePolicy.setRedeliveryDelay(1000);
    queuePolicy.setUseExponentialBackOff(false);
    queuePolicy.setMaximumRedeliveries(2);
    RedeliveryPolicy topicPolicy = new RedeliveryPolicy();
    topicPolicy.setInitialRedeliveryDelay(0);
    topicPolicy.setRedeliveryDelay(1000);
    topicPolicy.setUseExponentialBackOff(false);
    topicPolicy.setMaximumRedeliveries(3);
    // Receive a message with the JMS API
    RedeliveryPolicyMap map = connection.getRedeliveryPolicyMap();
    map.put(new ActiveMQTopic(">"), topicPolicy);
    map.put(new ActiveMQQueue(">"), queuePolicy);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue queue = new ActiveMQQueue("TEST");
    ActiveMQTopic topic = new ActiveMQTopic("TEST");
    this.makeSureCoreQueueExist("TEST");
    MessageProducer producer = session.createProducer(null);
    MessageConsumer queueConsumer = session.createConsumer(queue);
    MessageConsumer topicConsumer = session.createConsumer(topic);
    // Send the messages
    producer.send(queue, session.createTextMessage("1st"));
    producer.send(queue, session.createTextMessage("2nd"));
    producer.send(topic, session.createTextMessage("1st"));
    producer.send(topic, session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    session.rollback();
    m = (TextMessage) queueConsumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) queueConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    m = (TextMessage) queueConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    // No third attempt for the Queue consumer
    m = (TextMessage) queueConsumer.receive(2000);
    assertNull(m);
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNull(m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

47. JmsQueueBrowserTest#testBatchSendJmxBrowseReceive()

View license
public void testBatchSendJmxBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();
    TextMessage[] outbound = new TextMessage[10];
    for (int i = 0; i < 10; i++) {
        outbound[i] = session.createTextMessage(i + " Message");
    }
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    consumer.close();
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    ObjectName queueViewMBeanName = new ObjectName("org.apache.activemq:type=Broker,brokerName=localhost,destinationType=Queue,destinationName=TEST");
    LOG.info("Create QueueView MBean...");
    QueueViewMBean proxy = (QueueViewMBean) broker.getManagementContext().newProxyInstance(queueViewMBeanName, QueueViewMBean.class, true);
    long concount = proxy.getConsumerCount();
    LOG.info("Consumer Count :" + concount);
    long messcount = proxy.getQueueSize();
    LOG.info("current number of messages in the queue :" + messcount);
    // lets browse
    CompositeData[] compdatalist = proxy.browse();
    if (compdatalist.length == 0) {
        fail("There is no message in the queue:");
    }
    String[] messageIDs = new String[compdatalist.length];
    for (int i = 0; i < compdatalist.length; i++) {
        CompositeData cdata = compdatalist[i];
        if (i == 0) {
            LOG.info("Columns: " + cdata.getCompositeType().keySet());
        }
        messageIDs[i] = (String) cdata.get("JMSMessageID");
        LOG.info("message " + i + " : " + cdata.values());
    }
    TabularData table = proxy.browseAsTable();
    LOG.info("Found tabular data: " + table);
    assertTrue("Table should not be empty!", table.size() > 0);
    assertEquals("Queue size", outbound.length, proxy.getQueueSize());
    assertEquals("Queue size", outbound.length, compdatalist.length);
    assertEquals("Queue size", outbound.length, table.size());
    LOG.info("Send another 10");
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    LOG.info("Browse again");
    messcount = proxy.getQueueSize();
    LOG.info("current number of messages in the queue :" + messcount);
    compdatalist = proxy.browse();
    if (compdatalist.length == 0) {
        fail("There is no message in the queue:");
    }
    messageIDs = new String[compdatalist.length];
    for (int i = 0; i < compdatalist.length; i++) {
        CompositeData cdata = compdatalist[i];
        if (i == 0) {
            LOG.info("Columns: " + cdata.getCompositeType().keySet());
        }
        messageIDs[i] = (String) cdata.get("JMSMessageID");
        LOG.info("message " + i + " : " + cdata.values());
    }
    table = proxy.browseAsTable();
    LOG.info("Found tabular data: " + table);
    assertTrue("Table should not be empty!", table.size() > 0);
    assertEquals("Queue size", outbound.length * 2, proxy.getQueueSize());
    assertEquals("Queue size", outbound.length * 2, compdatalist.length);
    assertEquals("Queue size", outbound.length * 2, table.size());
    consumer = session.createConsumer(destination);
    for (int i = 0; i < outbound.length * 2; i++) {
        assertNotNull("Got message: " + i, consumer.receive(2000));
    }
    consumer.close();
}

48. NetworkConnectionsTest#testNetworkConnectionReAddURI()

View license
@Test
public void testNetworkConnectionReAddURI() throws Exception {
    LOG.info("testNetworkConnectionReAddURI is starting...");
    LOG.info("Adding network connector 'NC1'...");
    NetworkConnector nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")");
    nc.setName("NC1");
    nc.start();
    assertTrue(nc.isStarted());
    LOG.info("Looking up network connector by name...");
    NetworkConnector nc1 = localBroker.getNetworkConnectorByName("NC1");
    assertNotNull("Should find network connector 'NC1'", nc1);
    assertTrue(nc1.isStarted());
    assertEquals(nc, nc1);
    LOG.info("Setting up producer and consumer...");
    ActiveMQQueue destination = new ActiveMQQueue(DESTINATION_NAME);
    ActiveMQConnectionFactory localFactory = new ActiveMQConnectionFactory(LOCAL_BROKER_TRANSPORT_URI);
    Connection localConnection = localFactory.createConnection();
    localConnection.start();
    Session localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer localProducer = localSession.createProducer(destination);
    ActiveMQConnectionFactory remoteFactory = new ActiveMQConnectionFactory(REMOTE_BROKER_TRANSPORT_URI);
    Connection remoteConnection = remoteFactory.createConnection();
    remoteConnection.start();
    Session remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer remoteConsumer = remoteSession.createConsumer(destination);
    Message message = localSession.createTextMessage("test");
    localProducer.send(message);
    LOG.info("Testing initial network connection...");
    message = remoteConsumer.receive(10000);
    assertNotNull(message);
    LOG.info("Stopping network connector 'NC1'...");
    nc.stop();
    assertFalse(nc.isStarted());
    LOG.info("Removing network connector...");
    assertTrue(localBroker.removeNetworkConnector(nc));
    nc1 = localBroker.getNetworkConnectorByName("NC1");
    assertNull("Should not find network connector 'NC1'", nc1);
    LOG.info("Re-adding network connector 'NC2'...");
    nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")");
    nc.setName("NC2");
    nc.start();
    assertTrue(nc.isStarted());
    LOG.info("Looking up network connector by name...");
    NetworkConnector nc2 = localBroker.getNetworkConnectorByName("NC2");
    assertNotNull(nc2);
    assertTrue(nc2.isStarted());
    assertEquals(nc, nc2);
    LOG.info("Testing re-added network connection...");
    message = localSession.createTextMessage("test");
    localProducer.send(message);
    message = remoteConsumer.receive(10000);
    assertNotNull(message);
    LOG.info("Stopping network connector...");
    nc.stop();
    assertFalse(nc.isStarted());
    LOG.info("Removing network connection 'NC2'");
    assertTrue(localBroker.removeNetworkConnector(nc));
    nc2 = localBroker.getNetworkConnectorByName("NC2");
    assertNull("Should not find network connector 'NC2'", nc2);
}

49. NetworkConnectionsTest#testNetworkConnectionRestart()

View license
@Test
public void testNetworkConnectionRestart() throws Exception {
    LOG.info("testNetworkConnectionRestart is starting...");
    LOG.info("Adding network connector...");
    NetworkConnector nc = localBroker.addNetworkConnector("static:(" + REMOTE_BROKER_TRANSPORT_URI + ")");
    nc.setName("NC1");
    nc.start();
    assertTrue(nc.isStarted());
    LOG.info("Setting up Message Producer and Consumer");
    ActiveMQQueue destination = new ActiveMQQueue(DESTINATION_NAME);
    ActiveMQConnectionFactory localFactory = new ActiveMQConnectionFactory(LOCAL_BROKER_TRANSPORT_URI);
    Connection localConnection = localFactory.createConnection();
    localConnection.start();
    Session localSession = localConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer localProducer = localSession.createProducer(destination);
    ActiveMQConnectionFactory remoteFactory = new ActiveMQConnectionFactory(REMOTE_BROKER_TRANSPORT_URI);
    Connection remoteConnection = remoteFactory.createConnection();
    remoteConnection.start();
    Session remoteSession = remoteConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer remoteConsumer = remoteSession.createConsumer(destination);
    Message message = localSession.createTextMessage("test");
    localProducer.send(message);
    LOG.info("Testing initial network connection...");
    message = remoteConsumer.receive(10000);
    assertNotNull(message);
    LOG.info("Stopping network connection...");
    nc.stop();
    assertFalse(nc.isStarted());
    LOG.info("Sending 2nd message...");
    message = localSession.createTextMessage("test stop");
    localProducer.send(message);
    message = remoteConsumer.receive(1000);
    assertNull("Message should not have been delivered since NetworkConnector was stopped", message);
    LOG.info("(Re)starting network connection...");
    nc.start();
    assertTrue(nc.isStarted());
    LOG.info("Wait for 2nd message to get forwarded and received...");
    message = remoteConsumer.receive(10000);
    assertNotNull("Should have received 2nd message", message);
}

50. QueueOutboundBridgeReconnectTest#setUp()

View license
@Before
public void setUp() throws Exception {
    producerConnectionFactory = createProducerConnectionFactory();
    consumerConnectionFactory = createConsumerConnectionFactory();
    destination = new ActiveMQQueue("RECONNECT.TEST.QUEUE");
}

51. JmsSessionRecoverTest#testQueueAsynchRecoverWithAutoAck()

View license
/**
    * @throws JMSException
    * @throws InterruptedException
    */
public void testQueueAsynchRecoverWithAutoAck() throws JMSException, InterruptedException {
    dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis());
    doTestAsynchRecoverWithAutoAck();
}

52. JmsSessionRecoverTest#testQueueAsynchRecover()

View license
/**
    * @throws JMSException
    * @throws InterruptedException
    */
public void testQueueAsynchRecover() throws JMSException, InterruptedException {
    dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis());
    doTestAsynchRecover();
}

53. JmsSessionRecoverTest#testQueueSynchRecover()

View license
/**
    * @throws JMSException
    * @throws InterruptedException
    */
public void testQueueSynchRecover() throws JMSException, InterruptedException {
    dest = new ActiveMQQueue("Queue-" + System.currentTimeMillis());
    doTestSynchRecover();
}

54. JmsQueueBrowserTest#testBrowseClose()

View license
public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    connection.start();
    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);
    // create browser first
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    // browse some messages
    assertEquals(outbound[0], enumeration.nextElement());
    assertEquals(outbound[1], enumeration.nextElement());
    //assertEquals(outbound[2], (Message) enumeration.nextElement());
    browser.close();
    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);
    consumer.close();
    producer.close();
}

55. JmsQueueBrowserTest#testLargeNumberOfMessages()

View license
public void testLargeNumberOfMessages() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    connection.start();
    MessageProducer producer = session.createProducer(destination);
    int numberOfMessages = 4096;
    for (int i = 0; i < numberOfMessages; i++) {
        producer.send(session.createTextMessage("Message: " + i));
    }
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    assertTrue(enumeration.hasMoreElements());
    int numberBrowsed = 0;
    while (enumeration.hasMoreElements()) {
        Message browsed = (Message) enumeration.nextElement();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Browsed Message [{}]", browsed.getJMSMessageID());
        }
        numberBrowsed++;
    }
    System.out.println("Number browsed:  " + numberBrowsed);
    assertEquals(numberOfMessages, numberBrowsed);
    browser.close();
    producer.close();
}

56. JmsQueueBrowserTest#testBrowseReceive()

View license
//ref: https://issues.apache.org/jira/browse/ARTEMIS-384
public void testBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    connection.start();
    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    Message[] outbound = new Message[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    // create browser first
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    // browse the first message
    assertTrue("should have received the first message", enumeration.hasMoreElements());
    assertEquals(outbound[0], enumeration.nextElement());
    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();
}

57. ActiveMQQueueTest#createObject()

View license
@Override
public Object createObject() throws Exception {
    ActiveMQQueue info = new ActiveMQQueue();
    populateObject(info);
    return info;
}

58. JmsQueueBrowserTest#testBatchSendBrowseReceive()

View license
public void testBatchSendBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();
    TextMessage[] outbound = new TextMessage[10];
    for (int i = 0; i < 10; i++) {
        outbound[i] = session.createTextMessage(i + " Message");
    }
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    consumer.close();
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    for (int i = 0; i < outbound.length; i++) {
        assertTrue("should have a", enumeration.hasMoreElements());
        assertEquals(outbound[i], enumeration.nextElement());
    }
    browser.close();
    for (int i = 0; i < outbound.length; i++) {
        producer.send(outbound[i]);
    }
    // verify second batch is visible to browse
    browser = session.createBrowser(destination);
    enumeration = browser.getEnumeration();
    for (int j = 0; j < 2; j++) {
        for (int i = 0; i < outbound.length; i++) {
            assertTrue("should have a", enumeration.hasMoreElements());
            assertEquals("j=" + j + ", i=" + i, outbound[i].getText(), ((TextMessage) enumeration.nextElement()).getText());
        }
    }
    browser.close();
    consumer = session.createConsumer(destination);
    for (int i = 0; i < outbound.length * 2; i++) {
        assertNotNull("Got message: " + i, consumer.receive(2000));
    }
    consumer.close();
}

59. JmsQueueBrowserTest#testReceiveBrowseReceive()

View license
/**
    * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still
    * be in the queue even when it was browsed.
    *
    * @throws Exception
    */
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();
    Message[] outbound = new Message[] { session.createTextMessage("First Message"), session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };
    // lets consume any outstanding messages from previous test runs
    while (consumer.receive(1000) != null) {
    }
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);
    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    QueueBrowser browser = session.createBrowser(destination);
    Enumeration<?> enumeration = browser.getEnumeration();
    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], enumeration.nextElement());
    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], enumeration.nextElement());
    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();
    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();
}

60. JMSExclusiveConsumerTest#testDispatchExclusive()

View license
/**
    * Shows that if the "?consumer.exclusive=true" option is added to
    * destination, then all messages are routed to 1 consumer.
    *
    * @throws Exception
    */
public void testDispatchExclusive() throws Exception {
    // Receive a message with the JMS API
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST?consumer.exclusive=true");
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);
    MessageConsumer consumer1 = session.createConsumer(destination);
    MessageConsumer consumer2 = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    producer.send(session.createTextMessage("3nd"));
    Message m;
    m = consumer2.receive(1000);
    if (m != null) {
        // Consumer 2 should get all the messages.
        for (int i = 0; i < 2; i++) {
            m = consumer2.receive(1000);
            assertNotNull(m);
        }
    } else {
        // Consumer 1 should get all the messages.
        for (int i = 0; i < 3; i++) {
            m = consumer1.receive(1000);
            assertNotNull(m);
        }
    }
    assertNull(consumer1.receiveNoWait());
    assertNull(consumer2.receiveNoWait());
}

61. JMSExclusiveConsumerTest#testRoundRobinDispatchOnNonExclusive()

View license
/**
    * Shows that by default messages are round robined across a set of
    * consumers.
    *
    * @throws Exception
    */
public void testRoundRobinDispatchOnNonExclusive() throws Exception {
    // Receive a message with the JMS API
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    producer.setDeliveryMode(deliveryMode);
    MessageConsumer consumer1 = session.createConsumer(destination);
    MessageConsumer consumer2 = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    Message m;
    m = consumer2.receive(1000);
    assertNotNull(m);
    m = consumer1.receive(1000);
    assertNotNull(m);
    assertNull(consumer1.receiveNoWait());
    assertNull(consumer2.receiveNoWait());
}

62. JMSConsumerTest#testPrefetch1MessageNotDispatched()

View license
public void testPrefetch1MessageNotDispatched() throws Exception {
    // Set prefetch to 1
    connection.getPrefetchPolicy().setAll(1);
    connection.start();
    Session session = connection.createSession(true, 0);
    destination = new ActiveMQQueue("TEST");
    MessageConsumer consumer = 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();
    connections.add(connection2);
    Session session2 = connection2.createSession(true, 0);
    MessageConsumer consumer2 = session2.createConsumer(destination);
    // Pick up the first message.
    Message message1 = consumer.receive(1000);
    assertNotNull(message1);
    // Pick up the 2nd messages.
    Message message2 = consumer2.receive(5000);
    assertNotNull(message2);
    session.commit();
    session2.commit();
    assertNull(consumer.receiveNoWait());
}

63. DestinationMapTest#testQueueAndTopicWithSameName()

View license
public void testQueueAndTopicWithSameName() throws Exception {
    ActiveMQQueue q1 = new ActiveMQQueue("foo");
    ActiveMQTopic t1 = new ActiveMQTopic("foo");
    map.put(q1, v1);
    map.put(t1, v2);
    assertMapValue(q1, v1);
    assertMapValue(t1, v2);
}

64. ConfigUsingDestinationOptions#testInvalidSelectorConfig()

View license
public void testInvalidSelectorConfig() throws JMSException {
    ActiveMQQueue queue = new ActiveMQQueue("TEST.FOO?consumer.selector=test||1");
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory("vm://localhost");
    Connection conn = factory.createConnection();
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQMessageConsumer cons;
    // JMS selector should be priority
    try {
        cons = (ActiveMQMessageConsumer) sess.createConsumer(queue, "test||1");
        fail("Selector should be invalid" + cons);
    } catch (InvalidSelectorException e) {
    }
    // Test setting using JMS destinations
    try {
        cons = (ActiveMQMessageConsumer) sess.createConsumer(queue);
        fail("Selector should be invalid" + cons);
    } catch (InvalidSelectorException e) {
    }
}

65. JobSchedulerTestSupport#setUp()

View license
@Before
public void setUp() throws Exception {
    connectionUri = "vm://localhost";
    destination = new ActiveMQQueue(name.getMethodName());
    broker = createBroker();
    broker.start();
    broker.waitUntilStarted();
    jobScheduler = broker.getJobSchedulerStore().getJobScheduler("JMS");
}

66. RedeliveryPolicyTest#testZeroMaximumNumberOfRedeliveries()

View license
/**
    * @throws Exception
    */
public void testZeroMaximumNumberOfRedeliveries() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    //let's set the maximum redeliveries to 0
    policy.setMaximumRedeliveries(0);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    //the 1st  message should not be redelivered since maximumRedeliveries is set to 0
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

67. SoWriteTimeoutClientTest#testSendWithClientWriteTimeout()

View license
@Test
public void testSendWithClientWriteTimeout() throws Exception {
    final ActiveMQQueue dest = new ActiveMQQueue("testClientWriteTimeout");
    messageTextPrefix = initMessagePrefix(80 * 1024);
    URI tcpBrokerUri = new URI(newURI(0));
    LOG.info("consuming using uri: " + tcpBrokerUri);
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(tcpBrokerUri);
    Connection c = factory.createConnection();
    c.start();
    Session session = c.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(dest);
    SocketProxy proxy = new SocketProxy();
    try {
        proxy.setTarget(tcpBrokerUri);
        proxy.open();
        ActiveMQConnectionFactory pFactory = new ActiveMQConnectionFactory("failover:(" + proxy.getUrl() + "?soWriteTimeout=4000&sleep=500)?jms.useAsyncSend=true&trackMessages=true&maxCacheSize=6638400");
        final Connection pc = pFactory.createConnection();
        try {
            pc.start();
            proxy.pause();
            final int messageCount = 20;
            ExecutorService executorService = Executors.newCachedThreadPool();
            executorService.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        sendMessages(pc, dest, messageCount);
                    } catch (Exception ignored) {
                        ignored.printStackTrace();
                    }
                }
            });
            // wait for timeout and reconnect
            TimeUnit.SECONDS.sleep(8);
            proxy.goOn();
            for (int i = 0; i < messageCount; i++) {
                TextMessage m = (TextMessage) consumer.receive(10000);
                Assert.assertNotNull("Got message " + i + " after reconnect", m);
            }
            Assert.assertNull(consumer.receive(5000));
        } finally {
            pc.close();
        }
    } finally {
        proxy.close();
        c.close();
    }
}

68. RedeliveryPolicyTest#testRedeliveryPolicyPerDestination()

View license
public void testRedeliveryPolicyPerDestination() throws Exception {
    RedeliveryPolicy queuePolicy = new RedeliveryPolicy();
    queuePolicy.setInitialRedeliveryDelay(0);
    queuePolicy.setRedeliveryDelay(1000);
    queuePolicy.setUseExponentialBackOff(false);
    queuePolicy.setMaximumRedeliveries(2);
    RedeliveryPolicy topicPolicy = new RedeliveryPolicy();
    topicPolicy.setInitialRedeliveryDelay(0);
    topicPolicy.setRedeliveryDelay(1000);
    topicPolicy.setUseExponentialBackOff(false);
    topicPolicy.setMaximumRedeliveries(3);
    // Receive a message with the JMS API
    RedeliveryPolicyMap map = connection.getRedeliveryPolicyMap();
    map.put(new ActiveMQTopic(">"), topicPolicy);
    map.put(new ActiveMQQueue(">"), queuePolicy);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue queue = new ActiveMQQueue("TEST");
    ActiveMQTopic topic = new ActiveMQTopic("TEST");
    MessageProducer producer = session.createProducer(null);
    MessageConsumer queueConsumer = session.createConsumer(queue);
    MessageConsumer topicConsumer = session.createConsumer(topic);
    // Send the messages
    producer.send(queue, session.createTextMessage("1st"));
    producer.send(queue, session.createTextMessage("2nd"));
    producer.send(topic, session.createTextMessage("1st"));
    producer.send(topic, session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    session.rollback();
    m = (TextMessage) queueConsumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) queueConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    m = (TextMessage) queueConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.rollback();
    // No third attempt for the Queue consumer
    m = (TextMessage) queueConsumer.receive(2000);
    assertNull(m);
    m = (TextMessage) topicConsumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) queueConsumer.receive(100);
    assertNull(m);
    m = (TextMessage) topicConsumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

69. RedeliveryPolicyTest#testRedeliveryDelayOne()

View license
public void testRedeliveryDelayOne() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(1000);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(2);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNotNull("first immediate redelivery", m);
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNull("second delivery delayed: " + m, m);
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

70. RedeliveryPolicyTest#testInitialRedeliveryDelayOne()

View license
public void testInitialRedeliveryDelayOne() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(1000);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

71. RedeliveryPolicyTest#testInitialRedeliveryDelayZero()

View license
public void testInitialRedeliveryDelayZero() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    session.commit();
}

72. RedeliveryPolicyTest#testRepeatedRedeliveryServerSessionNoCommit()

View license
public void testRepeatedRedeliveryServerSessionNoCommit() throws Exception {
    connection.start();
    Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = dlqSession.createProducer(destination);
    // Send the messages
    producer.send(dlqSession.createTextMessage("1st"));
    dlqSession.commit();
    MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ"));
    final int maxRedeliveries = 4;
    final AtomicInteger receivedCount = new AtomicInteger(0);
    for (int i = 0; i <= maxRedeliveries + 1; i++) {
        connection = (ActiveMQConnection) factory.createConnection(userName, password);
        connections.add(connection);
        RedeliveryPolicy policy = connection.getRedeliveryPolicy();
        policy.setInitialRedeliveryDelay(0);
        policy.setUseExponentialBackOff(false);
        policy.setMaximumRedeliveries(maxRedeliveries);
        connection.start();
        final CountDownLatch done = new CountDownLatch(1);
        final ActiveMQSession session = (ActiveMQSession) connection.createSession(true, Session.SESSION_TRANSACTED);
        session.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                try {
                    ActiveMQTextMessage m = (ActiveMQTextMessage) message;
                    assertEquals("1st", m.getText());
                    assertEquals(receivedCount.get(), m.getRedeliveryCounter());
                    receivedCount.incrementAndGet();
                    done.countDown();
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        });
        connection.createConnectionConsumer(destination, null, new ServerSessionPool() {

            @Override
            public ServerSession getServerSession() throws JMSException {
                return new ServerSession() {

                    @Override
                    public Session getSession() throws JMSException {
                        return session;
                    }

                    @Override
                    public void start() throws JMSException {
                    }
                };
            }
        }, 100, false);
        Wait.waitFor(new Wait.Condition() {

            @Override
            public boolean isSatisified() throws Exception {
                session.run();
                return done.await(10, TimeUnit.MILLISECONDS);
            }
        });
        if (i <= maxRedeliveries) {
            assertTrue("listener done @" + i, done.await(5, TimeUnit.SECONDS));
        } else {
            // final redlivery gets poisoned before dispatch
            assertFalse("listener not done @" + i, done.await(1, TimeUnit.SECONDS));
        }
        connection.close();
        connections.remove(connection);
    }
    // We should be able to get the message off the DLQ now.
    TextMessage m = (TextMessage) dlqConsumer.receive(1000);
    assertNotNull("Got message from DLQ", m);
    assertEquals("1st", m.getText());
    String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy"));
    dlqSession.commit();
}

73. RedeliveryPolicyTest#testRepeatedRedeliveryOnMessageNoCommit()

View license
public void testRepeatedRedeliveryOnMessageNoCommit() throws Exception {
    connection.start();
    Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = dlqSession.createProducer(destination);
    // Send the messages
    producer.send(dlqSession.createTextMessage("1st"));
    dlqSession.commit();
    MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ"));
    final int maxRedeliveries = 4;
    final AtomicInteger receivedCount = new AtomicInteger(0);
    for (int i = 0; i <= maxRedeliveries + 1; i++) {
        connection = (ActiveMQConnection) factory.createConnection(userName, password);
        connections.add(connection);
        RedeliveryPolicy policy = connection.getRedeliveryPolicy();
        policy.setInitialRedeliveryDelay(0);
        policy.setUseExponentialBackOff(false);
        policy.setMaximumRedeliveries(maxRedeliveries);
        connection.start();
        final Session session = connection.createSession(true, Session.SESSION_TRANSACTED);
        MessageConsumer consumer = session.createConsumer(destination);
        final CountDownLatch done = new CountDownLatch(1);
        consumer.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(Message message) {
                try {
                    ActiveMQTextMessage m = (ActiveMQTextMessage) message;
                    assertEquals("1st", m.getText());
                    assertEquals(receivedCount.get(), m.getRedeliveryCounter());
                    receivedCount.incrementAndGet();
                    done.countDown();
                } catch (Exception ignored) {
                    ignored.printStackTrace();
                }
            }
        });
        if (i <= maxRedeliveries) {
            assertTrue("listener done", done.await(5, TimeUnit.SECONDS));
        } else {
            // final redlivery gets poisoned before dispatch
            assertFalse("listener done", done.await(1, TimeUnit.SECONDS));
        }
        connection.close();
        connections.remove(connection);
    }
    // We should be able to get the message off the DLQ now.
    TextMessage m = (TextMessage) dlqConsumer.receive(1000);
    assertNotNull("Got message from DLQ", m);
    assertEquals("1st", m.getText());
    String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy"));
    dlqSession.commit();
}

74. RedeliveryPolicyTest#testRepeatedRedeliveryReceiveNoCommit()

View license
public void testRepeatedRedeliveryReceiveNoCommit() throws Exception {
    connection.start();
    Session dlqSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = dlqSession.createProducer(destination);
    // Send the messages
    producer.send(dlqSession.createTextMessage("1st"));
    dlqSession.commit();
    MessageConsumer dlqConsumer = dlqSession.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ"));
    final int maxRedeliveries = 4;
    for (int i = 0; i <= maxRedeliveries + 1; i++) {
        connection = (ActiveMQConnection) factory.createConnection(userName, password);
        connections.add(connection);
        // Receive a message with the JMS API
        RedeliveryPolicy policy = connection.getRedeliveryPolicy();
        policy.setInitialRedeliveryDelay(0);
        policy.setUseExponentialBackOff(false);
        policy.setMaximumRedeliveries(maxRedeliveries);
        connection.start();
        Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(destination);
        ActiveMQTextMessage m = ((ActiveMQTextMessage) consumer.receive(4000));
        if (i <= maxRedeliveries) {
            assertEquals("1st", m.getText());
            assertEquals(i, m.getRedeliveryCounter());
        } else {
            assertNull("null on exceeding redelivery count", m);
        }
        connection.close();
        connections.remove(connection);
    }
    // We should be able to get the message off the DLQ now.
    TextMessage m = (TextMessage) dlqConsumer.receive(1000);
    assertNotNull("Got message from DLQ", m);
    assertEquals("1st", m.getText());
    String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy"));
    dlqSession.commit();
}

75. SoWriteTimeoutTest#testWriteTimeoutStompNio()

View license
public void testWriteTimeoutStompNio() throws Exception {
    ActiveMQQueue dest = new ActiveMQQueue("testWriteTimeout");
    messageTextPrefix = initMessagePrefix(8 * 1024);
    sendMessages(dest, 500);
    URI stompBrokerUri = URISupport.removeQuery(broker.getTransportConnectors().get(2).getConnectUri());
    LOG.info("consuming using uri: " + stompBrokerUri);
    SocketProxy proxy = new SocketProxy();
    proxy.setTarget(new URI("tcp://localhost:" + stompBrokerUri.getPort()));
    proxy.setReceiveBufferSize(receiveBufferSize);
    proxy.open();
    StompConnection stompConnection = new StompConnection();
    stompConnection.open(new Socket("localhost", proxy.getUrl().getPort()));
    stompConnection.getStompSocket().setTcpNoDelay(true);
    String frame = "CONNECT\n" + "login:system\n" + "passcode:manager\n\n" + Stomp.NULL;
    stompConnection.sendFrame(frame);
    frame = stompConnection.receiveFrame();
    assertTrue(frame.startsWith("CONNECTED"));
    frame = "SUBSCRIBE\n" + "destination:jms.queue." + dest.getQueueName() + "\n" + "ack:client\n\n" + Stomp.NULL;
    stompConnection.sendFrame(frame);
    // ensure dispatch has started before pause
    frame = stompConnection.receiveFrame();
    System.out.println("frame: " + frame);
    assertTrue(frame.startsWith("MESSAGE"));
    proxy.pause();
    // writes should back up... writeTimeout will kick in and abort the connection
    TimeUnit.SECONDS.sleep(1);
    // see the blocked threads
    //dumpAllThreads("blocked on write");
    // abort should be done after this
    TimeUnit.SECONDS.sleep(10);
    proxy.goOn();
    // get a buffered message
    frame = stompConnection.receiveFrame();
    assertTrue(frame.startsWith("MESSAGE"));
    // verify connection is dead
    try {
        for (int i = 0; i < 200; i++) {
            stompConnection.send("jms.queue." + dest.getPhysicalName(), "ShouldBeDeadConnectionText" + i);
        }
        fail("expected send to fail with timeout out connection");
    } catch (SocketException expected) {
        LOG.info("got exception on send after timeout: " + expected);
    }
}

76. RedeliveryPolicyTest#testMaximumRedeliveryDelay()

View license
/**
    * @throws Exception
    */
public void testMaximumRedeliveryDelay() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(10);
    policy.setUseExponentialBackOff(true);
    policy.setMaximumRedeliveries(-1);
    policy.setRedeliveryDelay(50);
    policy.setMaximumRedeliveryDelay(1000);
    policy.setBackOffMultiplier((short) 2);
    policy.setUseExponentialBackOff(true);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    for (int i = 0; i < 10; ++i) {
        // we should be able to get the 1st message redelivered until a session.commit is called
        m = (TextMessage) consumer.receive(2000);
        assertNotNull(m);
        assertEquals("1st", m.getText());
        session.rollback();
    }
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.commit();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    assertTrue(policy.getNextRedeliveryDelay(Long.MAX_VALUE) == 1000);
}

77. RedeliveryPolicyTest#testInfiniteMaximumNumberOfRedeliveries()

View license
/**
    * @throws Exception
    */
public void testInfiniteMaximumNumberOfRedeliveries() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    //  let's set the maximum redeliveries to no maximum (ie. infinite)
    policy.setMaximumRedeliveries(-1);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    //we should be able to get the 1st message redelivered until a session.commit is called
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.commit();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
}

78. RedeliveryPolicyTest#testDLQHandling()

View license
/**
    * @throws Exception
    */
public void testDLQHandling() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(100);
    policy.setUseExponentialBackOff(false);
    policy.setMaximumRedeliveries(2);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    MessageConsumer dlqConsumer = session.createConsumer(new ActiveMQQueue("ActiveMQ.DLQ"));
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    m = (TextMessage) consumer.receive(2000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // The last rollback should cause the 1st message to get sent to the DLQ
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("2nd", m.getText());
    session.commit();
    // We should be able to get the message off the DLQ now.
    m = (TextMessage) dlqConsumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    String cause = m.getStringProperty(ActiveMQMessage.DLQ_DELIVERY_FAILURE_CAUSE_PROPERTY);
    assertTrue("cause exception has policy ref", cause.contains("RedeliveryPolicy"));
    session.commit();
}

79. RedeliveryPolicyTest#testNornalRedeliveryPolicyDelaysDeliveryOnRollback()

View license
/**
    * @throws Exception
    */
public void testNornalRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(500);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue(getName());
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // No delay on first rollback..
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    session.rollback();
    // Show subsequent re-delivery delay is incrementing.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // The message gets redelivered after 500 ms every time since
    // we are not using exponential backoff.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
}

80. RedeliveryPolicyTest#testExponentialRedeliveryPolicyDelaysDeliveryOnRollback()

View license
/**
    * @throws Exception
    */
public void testExponentialRedeliveryPolicyDelaysDeliveryOnRollback() throws Exception {
    // Receive a message with the JMS API
    RedeliveryPolicy policy = connection.getRedeliveryPolicy();
    policy.setInitialRedeliveryDelay(0);
    policy.setRedeliveryDelay(500);
    policy.setBackOffMultiplier((short) 2);
    policy.setUseExponentialBackOff(true);
    connection.start();
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue(getName());
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    // Send the messages
    producer.send(session.createTextMessage("1st"));
    producer.send(session.createTextMessage("2nd"));
    session.commit();
    TextMessage m;
    m = (TextMessage) consumer.receive(1000);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // No delay on first rollback..
    m = (TextMessage) consumer.receive(100);
    assertNotNull(m);
    session.rollback();
    // Show subsequent re-delivery delay is incrementing.
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
    session.rollback();
    // Show re-delivery delay is incrementing exponentially
    m = (TextMessage) consumer.receive(100);
    assertNull(m);
    m = (TextMessage) consumer.receive(500);
    assertNull(m);
    m = (TextMessage) consumer.receive(700);
    assertNotNull(m);
    assertEquals("1st", m.getText());
}

81. ActiveMQQueueTest#populateObject()

View license
@Override
protected void populateObject(Object object) throws Exception {
    super.populateObject(object);
    ActiveMQQueue info = (ActiveMQQueue) object;
}

82. ActiveMQQueueTest#createObject()

View license
@Override
public Object createObject() throws Exception {
    ActiveMQQueue info = new ActiveMQQueue();
    populateObject(info);
    return info;
}

83. ActiveMQQueueTest#populateObject()

View license
@Override
protected void populateObject(Object object) throws Exception {
    super.populateObject(object);
    ActiveMQQueue info = (ActiveMQQueue) object;
}