org.apache.activemq.ActiveMQConnection

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

1. DurablePersistentFalseRestartTest#testValidateNoPersistenceForDurableAfterRestart()

Project: activemq-artemis
File: DurablePersistentFalseRestartTest.java
public void testValidateNoPersistenceForDurableAfterRestart() throws Exception {
    ConnectionFactory connectionFactory = new ActiveMQConnectionFactory("failover:(" + broker.getTransportConnectors().get(0).getPublishableConnectString() + ")");
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.setClientID("clientId");
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Topic destination = session.createTopic(queueName);
    MessageConsumer consumer = session.createDurableSubscriber(destination, "subscriberName");
    populateDestination(10, destination, connection);
    restartBroker();
    // make failover aware of the restarted auto assigned port
    connection.getTransport().narrow(FailoverTransport.class).add(true, broker.getTransportConnectors().get(0).getPublishableConnectString());
    TextMessage msg = (TextMessage) consumer.receive(4000);
    assertNull("did not get a message when persistent=false, message: " + msg, msg);
    connection.close();
}

2. FailoverRandomTest#testRandomConnections()

Project: activemq-artemis
File: FailoverRandomTest.java
@Test
public void testRandomConnections() throws Exception {
    String failoverUrl = "failover:(" + newURI(0) + "," + newURI(1) + ")";
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(failoverUrl);
    ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final String brokerName1 = connection.getBrokerName();
    Assert.assertNotNull(brokerName1);
    connection.close();
    String brokerName2 = brokerName1;
    int attempts = 40;
    while (brokerName1.equals(brokerName2) && attempts-- > 0) {
        connection = (ActiveMQConnection) cf.createConnection();
        connection.start();
        brokerName2 = connection.getBrokerName();
        Assert.assertNotNull(brokerName2);
        connection.close();
    }
    Assert.assertTrue(brokerName1 + "!=" + brokerName2, !brokerName1.equals(brokerName2));
}

3. BrokerRedeliveryTest#sendMessage()

Project: activemq-artemis
File: BrokerRedeliveryTest.java
private void sendMessage(int timeToLive) throws Exception {
    ActiveMQConnection producerConnection = (ActiveMQConnection) createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = producerSession.createProducer(destination);
    if (timeToLive > 0) {
        producer.setTimeToLive(timeToLive);
    }
    Message message = producerSession.createMessage();
    message.setStringProperty("data", data);
    producer.send(message);
    producerConnection.close();
}

4. ConnectionFactoryResourceTest#testRoundRobbin()

Project: camel
File: ConnectionFactoryResourceTest.java
@Test
public void testRoundRobbin() throws Exception {
    ConnectionFactoryResource pool = new ConnectionFactoryResource(2, connectionFactory);
    pool.fillPool();
    assertNotNull(pool);
    ActiveMQConnection connection = (ActiveMQConnection) pool.borrowConnection();
    assertNotNull(connection);
    assertTrue(connection.isStarted());
    pool.returnConnection(connection);
    ActiveMQConnection connection2 = (ActiveMQConnection) pool.borrowConnection();
    assertNotNull(connection2);
    assertNotEquals(connection, connection2);
    pool.drainPool();
}

5. ConnectionFactoryResourceTest#testReturnObject()

Project: camel
File: ConnectionFactoryResourceTest.java
@Test
public void testReturnObject() throws Exception {
    ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
    pool.fillPool();
    assertNotNull(pool);
    ActiveMQConnection connection = (ActiveMQConnection) pool.borrowConnection();
    assertNotNull(connection);
    assertTrue(connection.isStarted());
    pool.returnConnection(connection);
    ActiveMQConnection connection2 = (ActiveMQConnection) pool.borrowConnection();
    assertNotNull(connection2);
    pool.drainPool();
}

6. SimpleNetworkTest#testMessageCompression()

Project: activemq-artemis
File: SimpleNetworkTest.java
// works b/c of non marshaling vm transport, the connection
// ref from the client is used during the forward
@Test(timeout = 60 * 1000)
public void testMessageCompression() throws Exception {
    ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection;
    localAmqConnection.setUseCompression(true);
    MessageConsumer consumer1 = remoteSession.createConsumer(included);
    MessageProducer producer = localSession.createProducer(included);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    waitForConsumerRegistration(localBroker, 1, included);
    for (int i = 0; i < MESSAGE_COUNT; i++) {
        Message test = localSession.createTextMessage("test-" + i);
        producer.send(test);
        Message msg = consumer1.receive(3000);
        assertNotNull(msg);
        ActiveMQMessage amqMessage = (ActiveMQMessage) msg;
        assertTrue(amqMessage.isCompressed());
    }
    // ensure no more messages received
    assertNull(consumer1.receive(1000));
}

7. CompressionOverNetworkTest#testCompressedOverCompressedNetwork()

Project: activemq-artemis
File: CompressionOverNetworkTest.java
@Test
public void testCompressedOverCompressedNetwork() throws Exception {
    ActiveMQConnection localAmqConnection = (ActiveMQConnection) localConnection;
    localAmqConnection.setUseCompression(true);
    MessageConsumer consumer1 = remoteSession.createConsumer(included);
    MessageProducer producer = localSession.createProducer(included);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    waitForConsumerRegistration(localBroker, 1, included);
    StringBuilder payload = new StringBuilder("test-");
    for (int i = 0; i < 100; ++i) {
        payload.append(UUID.randomUUID().toString());
    }
    Message test = localSession.createTextMessage(payload.toString());
    producer.send(test);
    Message msg = consumer1.receive(RECEIVE_TIMEOUT_MILLS);
    assertNotNull(msg);
    ActiveMQTextMessage message = (ActiveMQTextMessage) msg;
    assertTrue(message.isCompressed());
    assertEquals(payload.toString(), message.getText());
}

8. MessageCompressionTest#sendTestMapMessage()

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

9. MessageCompressionTest#sendTestStreamMessage()

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

10. BrokerRedeliveryTest#testNoScheduledRedeliveryOfExpired()

Project: activemq-artemis
File: BrokerRedeliveryTest.java
public void testNoScheduledRedeliveryOfExpired() throws Exception {
    startBroker(true);
    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    sendMessage(1500);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);
    // ensure there is another consumer to redispatch to
    MessageConsumer redeliverConsumer = consumerSession.createConsumer(destination);
    // allow consumed to expire so it gets redelivered
    TimeUnit.SECONDS.sleep(2);
    consumer.close();
    // should go to dlq as it has expired
    // validate DLQ
    MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
    Message dlqMessage = dlqConsumer.receive(2000);
    assertNotNull("Got message from dql", dlqMessage);
    assertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
}

11. ActiveMQMessageProducerSendInterceptor#validateTransport()

Project: pinpoint
File: ActiveMQMessageProducerSendInterceptor.java
private boolean validateTransport(ActiveMQSession session) {
    if (session == null) {
        return false;
    }
    ActiveMQConnection connection = session.getConnection();
    if (!(connection instanceof TransportGetter)) {
        if (isDebug) {
            logger.debug("Invalid connection object. Need field accessor({}).", TransportGetter.class.getName());
        }
        return false;
    }
    Transport transport = getRootTransport(((TransportGetter) connection)._$PINPOINT$_getTransport());
    if (!(transport instanceof SocketGetter)) {
        if (isDebug) {
            logger.debug("Transport not traceable({}).", transport.getClass().getName());
        }
        return false;
    }
    return true;
}

12. ActiveMQMessageConsumerDispatchInterceptor#validateTransport()

Project: pinpoint
File: ActiveMQMessageConsumerDispatchInterceptor.java
private boolean validateTransport(ActiveMQSession session) {
    if (session == null) {
        return false;
    }
    ActiveMQConnection connection = session.getConnection();
    if (!(connection instanceof TransportGetter)) {
        if (isDebug) {
            logger.debug("Invalid connection object. Need field accessor({}).", TransportGetter.class.getName());
        }
        return false;
    }
    Transport transport = getRootTransport(((TransportGetter) connection)._$PINPOINT$_getTransport());
    if (!(transport instanceof SocketGetter)) {
        if (isDebug) {
            logger.debug("Transport not traceable({}).", transport.getClass().getName());
        }
        return false;
    }
    return true;
}

13. ActiveMQJmsService#getActiveMQConnection()

Project: Karaf-Tutorial
File: ActiveMQJmsService.java
private ActiveMQConnection getActiveMQConnection(final Connection connection) {
    Connection physConnection = connection;
    if (connection instanceof PooledConnection) {
        try {
            physConnection = ((PooledConnection) connection).getConnection();
        } catch (JMSException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
    ActiveMQConnection aConnection = (ActiveMQConnection) physConnection;
    return aConnection;
}

14. TwoBrokerFailoverClusterTest#assertClientsConnectionsEvenlyDistributed()

Project: activemq-artemis
File: TwoBrokerFailoverClusterTest.java
protected void assertClientsConnectionsEvenlyDistributed(double minimumPercentage) {
    Map<String, Double> clientConnectionCounts = new HashMap<>();
    int total = 0;
    for (ActiveMQConnection c : connections) {
        String key = c.getTransportChannel().getRemoteAddress();
        if (key != null) {
            total++;
            if (clientConnectionCounts.containsKey(key)) {
                double count = clientConnectionCounts.get(key);
                count += 1.0;
                clientConnectionCounts.put(key, count);
            } else {
                clientConnectionCounts.put(key, 1.0);
            }
        }
    }
    Set<String> keys = clientConnectionCounts.keySet();
    for (String key : keys) {
        double count = clientConnectionCounts.get(key);
        double percentage = count / total;
        System.out.println(count + " of " + total + " connections for " + key + " = " + percentage);
        Assert.assertTrue("Connections distribution expected to be >= than " + minimumPercentage + ".  Actuall distribution was " + percentage + " for connection " + key, percentage >= minimumPercentage);
    }
}

15. FailoverTimeoutTest#testUpdateUris()

Project: activemq-artemis
File: FailoverTimeoutTest.java
@Test
public void testUpdateUris() throws Exception {
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + tcpUri + ")?useExponentialBackOff=false");
    ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    try {
        connection.start();
        FailoverTransport failoverTransport = connection.getTransport().narrow(FailoverTransport.class);
        URI[] bunchOfUnknownAndOneKnown = new URI[] { new URI("tcp://unknownHost:" + tcpUri.getPort()), new URI("tcp://unknownHost2:" + tcpUri.getPort()), new URI("tcp://localhost:2222") };
        failoverTransport.add(false, bunchOfUnknownAndOneKnown);
    } finally {
        if (connection != null) {
            connection.close();
        }
    }
}

16. FailoverClusterTestSupport#assertClientsConnectionsEvenlyDistributed()

Project: activemq-artemis
File: FailoverClusterTestSupport.java
protected void assertClientsConnectionsEvenlyDistributed(double minimumPercentage) {
    Map<String, Double> clientConnectionCounts = new HashMap<>();
    int total = 0;
    for (ActiveMQConnection c : connections) {
        String key = c.getTransportChannel().getRemoteAddress();
        if (key != null) {
            total++;
            if (clientConnectionCounts.containsKey(key)) {
                double count = clientConnectionCounts.get(key);
                count += 1.0;
                clientConnectionCounts.put(key, count);
            } else {
                clientConnectionCounts.put(key, 1.0);
            }
        }
    }
    Set<String> keys = clientConnectionCounts.keySet();
    for (String key : keys) {
        double count = clientConnectionCounts.get(key);
        double percentage = count / total;
        logger.info(count + " of " + total + " connections for " + key + " = " + percentage);
        assertTrue("Connections distribution expected to be >= than " + minimumPercentage + ".  Actuall distribution was " + percentage + " for connection " + key, percentage >= minimumPercentage);
    }
}

17. FailoverClusterTest#testClusterConnectedBeforeClients()

Project: activemq-artemis
File: FailoverClusterTest.java
@Test
public void testClusterConnectedBeforeClients() throws Exception {
    server1.start();
    server2.start();
    Assert.assertTrue(server1.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    Assert.assertTrue(server2.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    createClients();
    server1.stop();
    Thread.sleep(1000);
    URI brokerBURI = new URI(newURI(2));
    for (ActiveMQConnection c : connections) {
        String addr = c.getTransportChannel().getRemoteAddress();
        Assert.assertTrue(addr.indexOf("" + brokerBURI.getPort()) > 0);
    }
}

18. FailoverClusterTest#testClusterURIOptionsStrip()

Project: activemq-artemis
File: FailoverClusterTest.java
//this test seems the same as the above one as long as artemis broker
//is concerned.
@Test
public void testClusterURIOptionsStrip() throws Exception {
    server1.start();
    createClients();
    server2.start();
    Assert.assertTrue(server1.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    Assert.assertTrue(server2.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    Thread.sleep(3000);
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        set.add(c.getTransportChannel().getRemoteAddress());
    }
    Assert.assertTrue(set.size() > 1);
}

19. FailoverClusterTest#testClusterConnectedAfterClients()

Project: activemq-artemis
File: FailoverClusterTest.java
@Test
public void testClusterConnectedAfterClients() throws Exception {
    server1.start();
    createClients();
    Set<String> set = new HashSet<>();
    server2.start();
    Assert.assertTrue(server1.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    Assert.assertTrue(server2.waitClusterForming(100, TimeUnit.MILLISECONDS, 20, 2));
    Thread.sleep(3000);
    for (ActiveMQConnection c : connections) {
        System.out.println("======> adding address: " + c.getTransportChannel().getRemoteAddress());
        set.add(c.getTransportChannel().getRemoteAddress());
    }
    System.out.println("============final size: " + set.size());
    Assert.assertTrue(set.size() > 1);
}

20. DiscardingDeadLetterPolicyTest#doTest()

Project: activemq-artemis
File: DiscardingDeadLetterPolicyTest.java
@Override
protected void doTest() throws Exception {
    connection.start();
    ActiveMQConnection amqConnection = (ActiveMQConnection) connection;
    rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1;
    LOG.info("Will redeliver messages: " + rollbackCount + " times");
    makeConsumer();
    makeDlqConsumer();
    sendMessages();
    // now lets receive and rollback N times
    for (int i = 0; i < messageCount; i++) {
        consumeAndRollback(i);
    }
    for (int i = 0; i < messageCount; i++) {
        Message msg = dlqConsumer.receive(1000);
        assertNull("Should not be a DLQ message for loop: " + i, msg);
    }
    session.commit();
}

21. DeadLetterTest#doTest()

Project: activemq-artemis
File: DeadLetterTest.java
@Override
protected void doTest() throws Exception {
    connection.start();
    ActiveMQConnection amqConnection = (ActiveMQConnection) connection;
    rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1;
    LOG.info("Will redeliver messages: " + rollbackCount + " times");
    makeConsumer();
    makeDlqConsumer();
    sendMessages();
    // now lets receive and rollback N times
    for (int i = 0; i < messageCount; i++) {
        consumeAndRollback(i);
    }
    for (int i = 0; i < messageCount; i++) {
        Message msg = dlqConsumer.receive(1000);
        assertMessage(msg, i);
        assertNotNull("Should be a DLQ message for loop: " + i, msg);
    }
    session.commit();
}

22. RequestReplyNoAdvisoryNetworkTest#doTestNonAdvisoryNetworkRequestReply()

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

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

23. BrokerRedeliveryTest#doTestScheduledRedelivery()

Project: activemq-artemis
File: BrokerRedeliveryTest.java
public void doTestScheduledRedelivery(int maxBrokerRedeliveriesToValidate, boolean validateDLQ) throws Exception {
    startBroker(true);
    sendMessage(0);
    ActiveMQConnection consumerConnection = (ActiveMQConnection) createConnection();
    RedeliveryPolicy redeliveryPolicy = new RedeliveryPolicy();
    redeliveryPolicy.setInitialRedeliveryDelay(0);
    redeliveryPolicy.setMaximumRedeliveries(0);
    consumerConnection.setRedeliveryPolicy(redeliveryPolicy);
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(true, Session.SESSION_TRANSACTED);
    MessageConsumer consumer = consumerSession.createConsumer(destination);
    Message message = consumer.receive(1000);
    assertNotNull("got message", message);
    LOG.info("got: " + message);
    consumerSession.rollback();
    for (int i = 0; i < maxBrokerRedeliveriesToValidate; i++) {
        Message shouldBeNull = consumer.receive(500);
        assertNull("did not get message after redelivery count exceeded: " + shouldBeNull, shouldBeNull);
        TimeUnit.SECONDS.sleep(3);
        Message brokerRedeliveryMessage = consumer.receive(500);
        LOG.info("got: " + brokerRedeliveryMessage);
        assertNotNull("got message via broker redelivery after delay", brokerRedeliveryMessage);
        assertEquals("message matches", message.getStringProperty("data"), brokerRedeliveryMessage.getStringProperty("data"));
        assertEquals("has expiryDelay specified", i == 0 ? initialRedeliveryDelayMillis : redeliveryDelayMillis, brokerRedeliveryMessage.getLongProperty(RedeliveryPlugin.REDELIVERY_DELAY));
        consumerSession.rollback();
    }
    if (validateDLQ) {
        MessageConsumer dlqConsumer = consumerSession.createConsumer(new ActiveMQQueue(SharedDeadLetterStrategy.DEFAULT_DEAD_LETTER_QUEUE_NAME));
        Message dlqMessage = dlqConsumer.receive(2000);
        assertNotNull("Got message from dql", dlqMessage);
        assertEquals("message matches", message.getStringProperty("data"), dlqMessage.getStringProperty("data"));
        consumerSession.commit();
    } else {
        // consume/commit ok
        message = consumer.receive(3000);
        assertNotNull("got message", message);
        assertEquals("redeliveries accounted for", maxBrokerRedeliveriesToValidate + 2, message.getLongProperty("JMSXDeliveryCount"));
        consumerSession.commit();
    }
    consumerConnection.close();
}

24. MessageCompressionTest#receiveAMQBytesMessage()

Project: activemq-openwire
File: MessageCompressionTest.java
private ActiveMQBytesMessage receiveAMQBytesMessage() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(getActiveMQQueue());
    ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive();
    connection.close();
    return rc;
}

25. MessageCompressionTest#receiveAMQTextMessage()

Project: activemq-openwire
File: MessageCompressionTest.java
private ActiveMQTextMessage receiveAMQTextMessage() throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(getActiveMQQueue());
    ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive();
    connection.close();
    return rc;
}

26. TwoSecureBrokerRequestReplyTest#testRequestReply()

Project: activemq-artemis
File: TwoSecureBrokerRequestReplyTest.java
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. TwoBrokerTempQueueAdvisoryTest#testSendToRemovedTemp()

Project: activemq-artemis
File: TwoBrokerTempQueueAdvisoryTest.java
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();
    }
}

28. FailoverPrefetchZeroTest#testPrefetchZeroConsumerThroughRestart()

Project: activemq-artemis
File: FailoverPrefetchZeroTest.java
@SuppressWarnings("unchecked")
@Test
@BMRules(rules = { @BMRule(name = "set no return response and stop the broker", targetClass = "org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection$CommandProcessor", targetMethod = "processMessagePull", targetLocation = "ENTRY", action = "org.apache.activemq.transport.failover.FailoverPrefetchZeroTest.holdResponseAndStopBroker($0)") })
public void testPrefetchZeroConsumerThroughRestart() throws Exception {
    broker = createBroker();
    broker.start();
    doByteman.set(true);
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(false);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);
    final MessageConsumer consumer = consumerSession.createConsumer(destination);
    produceMessage(consumerSession, destination, 1);
    final CountDownLatch receiveDone = new CountDownLatch(1);
    final Vector<Message> received = new Vector<>();
    new Thread() {

        @Override
        public void run() {
            try {
                LOG.info("receive one...");
                Message msg = consumer.receive(30000);
                if (msg != null) {
                    received.add(msg);
                }
                receiveDone.countDown();
                LOG.info("done receive");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    // will be stopped by the plugin
    assertTrue("pull completed on broker", pullDone.await(30, TimeUnit.SECONDS));
    brokerStopLatch.await();
    doByteman.set(false);
    broker = createBroker();
    broker.start();
    assertTrue("receive completed through failover", receiveDone.await(30, TimeUnit.SECONDS));
    assertTrue("we got our message:", !received.isEmpty());
    connection.close();
}

29. FailoverConsumerUnconsumedTest#doTestFailoverConsumerDups()

Project: activemq-artemis
File: FailoverConsumerUnconsumedTest.java
@SuppressWarnings("unchecked")
public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception {
    maxConsumers = 4;
    broker = createBroker();
    broker.start();
    brokerStopLatch = new CountDownLatch(1);
    doByteman.set(true);
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(watchTopicAdvisories);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session consumerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?jms.consumer.prefetch=" + prefetch);
    final Vector<TestConsumer> testConsumers = new Vector<>();
    for (int i = 0; i < maxConsumers - 1; i++) {
        testConsumers.add(new TestConsumer(consumerSession, destination, connection));
    }
    assureQueueMessages(0, new SimpleString("jms.queue." + QUEUE_NAME));
    produceMessage(consumerSession, destination, maxConsumers * prefetch);
    assertTrue("add messages are dispatched", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            int totalUnconsumed = 0;
            for (TestConsumer testConsumer : testConsumers) {
                long unconsumed = testConsumer.unconsumedSize();
                LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed);
                totalUnconsumed += unconsumed;
            }
            return totalUnconsumed == (maxConsumers - 1) * prefetch;
        }
    }));
    final CountDownLatch shutdownConsumerAdded = new CountDownLatch(1);
    new Thread() {

        @Override
        public void run() {
            try {
                LOG.info("add last consumer...");
                testConsumers.add(new TestConsumer(consumerSession, destination, connection));
                shutdownConsumerAdded.countDown();
                LOG.info("done add last consumer");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    // verify interrupt
    assertTrue("add messages dispatched and unconsumed are cleaned up", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            int totalUnconsumed = 0;
            for (TestConsumer testConsumer : testConsumers) {
                long unconsumed = testConsumer.unconsumedSize();
                LOG.info(testConsumer.getConsumerId() + " unconsumed: " + unconsumed);
                totalUnconsumed += unconsumed;
            }
            return totalUnconsumed == 0;
        }
    }));
    brokerStopLatch.await();
    doByteman.set(false);
    broker = createBroker();
    broker.start();
    assertTrue("consumer added through failover", shutdownConsumerAdded.await(30, TimeUnit.SECONDS));
    // each should again get prefetch messages - all unconsumed deliveries should be rolledback
    assertTrue("after start all messages are re dispatched", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            int totalUnconsumed = 0;
            for (TestConsumer testConsumer : testConsumers) {
                long unconsumed = testConsumer.unconsumedSize();
                LOG.info(testConsumer.getConsumerId() + " after restart: unconsumed: " + unconsumed);
                totalUnconsumed += unconsumed;
            }
            return totalUnconsumed == (maxConsumers) * prefetch;
        }
    }));
    connection.close();
}

30. FailoverConsumerUnconsumedTest#testFailoverClientAckMissingRedelivery()

Project: activemq-artemis
File: FailoverConsumerUnconsumedTest.java
@SuppressWarnings("unchecked")
@Test
@BMRules(rules = { @BMRule(name = "set no return response and stop the broker", targetClass = "org.apache.activemq.artemis.core.protocol.openwire.OpenWireConnection$CommandProcessor", targetMethod = "processAddConsumer", targetLocation = "ENTRY", action = "org.apache.activemq.transport.failover.FailoverConsumerUnconsumedTest.holdResponseAndStopBroker($0)") })
public void testFailoverClientAckMissingRedelivery() throws Exception {
    maxConsumers = 2;
    brokerStopLatch = new CountDownLatch(1);
    broker = createBroker();
    broker.start();
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(false);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session consumerSession = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    final Queue destination = consumerSession.createQueue(QUEUE_NAME + "?jms.consumer.prefetch=" + prefetch);
    doByteman.set(true);
    final Vector<TestConsumer> testConsumers = new Vector<>();
    TestConsumer testConsumer = new TestConsumer(consumerSession, destination, connection);
    testConsumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                LOG.info("onMessage:" + message.getJMSMessageID());
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }
    });
    testConsumers.add(testConsumer);
    produceMessage(consumerSession, destination, maxConsumers * prefetch);
    assertTrue("add messages are delivered", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            int totalDelivered = 0;
            for (TestConsumer testConsumer : testConsumers) {
                long delivered = testConsumer.deliveredSize();
                LOG.info(testConsumer.getConsumerId() + " delivered: " + delivered);
                totalDelivered += delivered;
            }
            return totalDelivered == maxConsumers * prefetch;
        }
    }));
    final CountDownLatch shutdownConsumerAdded = new CountDownLatch(1);
    new Thread() {

        @Override
        public void run() {
            try {
                LOG.info("add last consumer...");
                TestConsumer testConsumer = new TestConsumer(consumerSession, destination, connection);
                testConsumer.setMessageListener(new MessageListener() {

                    @Override
                    public void onMessage(Message message) {
                        try {
                            LOG.info("onMessage:" + message.getJMSMessageID());
                        } catch (JMSException e) {
                            e.printStackTrace();
                        }
                    }
                });
                testConsumers.add(testConsumer);
                shutdownConsumerAdded.countDown();
                LOG.info("done add last consumer");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }.start();
    brokerStopLatch.await();
    doByteman.set(false);
    broker = createBroker();
    broker.start();
    assertTrue("consumer added through failover", shutdownConsumerAdded.await(30, TimeUnit.SECONDS));
    // each should again get prefetch messages - all unacked deliveries should be rolledback
    assertTrue("after restart all messages are re dispatched", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            int totalDelivered = 0;
            for (TestConsumer testConsumer : testConsumers) {
                long delivered = testConsumer.deliveredSize();
                LOG.info(testConsumer.getConsumerId() + " delivered: " + delivered);
                totalDelivered += delivered;
            }
            return totalDelivered == maxConsumers * prefetch;
        }
    }));
    connection.close();
}

31. FailoverConsumerOutstandingCommitTest#receiveMessage()

Project: activemq-artemis
File: FailoverConsumerOutstandingCommitTest.java
private Message receiveMessage(ActiveMQConnectionFactory cf, Queue destination) throws Exception {
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    final MessageConsumer consumer = consumerSession.createConsumer(destination);
    Message msg = consumer.receive(5000);
    consumerSession.commit();
    connection.close();
    return msg;
}

32. FailoverConsumerOutstandingCommitTest#testRollbackFailoverConsumerTx()

Project: activemq-artemis
File: FailoverConsumerOutstandingCommitTest.java
@Test
public void testRollbackFailoverConsumerTx() throws Exception {
    server = createBroker();
    server.start();
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setConsumerFailoverRedeliveryWaitPeriod(10000);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination = producerSession.createQueue(QUEUE_NAME);
    final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
    assertNull("no message yet", testConsumer.receiveNoWait());
    produceMessage(producerSession, destination, 1);
    producerSession.close();
    // consume then rollback after restart
    Message msg = testConsumer.receive(5000);
    assertNotNull(msg);
    // restart with outstanding delivered message
    server.stop();
    server = createBroker();
    server.start();
    consumerSession.rollback();
    // receive again
    msg = testConsumer.receive(10000);
    assertNotNull("got message again after rollback", msg);
    consumerSession.commit();
    // close before sweep
    consumerSession.close();
    msg = receiveMessage(cf, destination);
    assertNull("should be nothing left after commit", msg);
    connection.close();
}

33. FailoverConsumerOutstandingCommitTest#doTestFailoverConsumerOutstandingSendTx()

Project: activemq-artemis
File: FailoverConsumerOutstandingCommitTest.java
@SuppressWarnings("unchecked")
public void doTestFailoverConsumerOutstandingSendTx(final boolean doActualBrokerCommit) throws Exception {
    final boolean watchTopicAdvisories = true;
    server = createBroker();
    server.start();
    brokerStopLatch = new CountDownLatch(1);
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(watchTopicAdvisories);
    cf.setDispatchAsync(false);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);
    final Queue signalDestination = producerSession.createQueue(QUEUE_NAME + ".signal" + "?consumer.prefetchSize=" + prefetch);
    final Session consumerSession = connection.createSession(true, Session.SESSION_TRANSACTED);
    final CountDownLatch commitDoneLatch = new CountDownLatch(1);
    final CountDownLatch messagesReceived = new CountDownLatch(3);
    final AtomicBoolean gotCommitException = new AtomicBoolean(false);
    final ArrayList<TextMessage> receivedMessages = new ArrayList<>();
    final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
    doByteman.set(true);
    testConsumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            LOG.info("consume one: " + message);
            assertNotNull("got message", message);
            receivedMessages.add((TextMessage) message);
            try {
                LOG.info("send one");
                produceMessage(consumerSession, signalDestination, 1);
                LOG.info("commit session");
                consumerSession.commit();
            } catch (JMSException e) {
                LOG.info("commit exception", e);
                gotCommitException.set(true);
            }
            commitDoneLatch.countDown();
            messagesReceived.countDown();
            LOG.info("done commit");
        }
    });
    // may block if broker shutdown happens quickly
    new Thread() {

        @Override
        public void run() {
            LOG.info("producer started");
            try {
                produceMessage(producerSession, destination, prefetch * 2);
            } catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) {
            } catch (JMSException e) {
                e.printStackTrace();
                fail("unexpceted ex on producer: " + e);
            }
            LOG.info("producer done");
        }
    }.start();
    // will be stopped by the plugin
    brokerStopLatch.await();
    doByteman.set(false);
    server.stop();
    server = createBroker();
    server.start();
    assertTrue("commit done through failover", commitDoneLatch.await(20, TimeUnit.SECONDS));
    assertTrue("commit failed", gotCommitException.get());
    assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS));
    int receivedIndex = 0;
    assertEquals("get message 0 first", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText());
    if (!doActualBrokerCommit) {
        // it will be redelivered and not tracked as a duplicate
        assertEquals("get message 0 second", MESSAGE_TEXT + "0", receivedMessages.get(receivedIndex++).getText());
    }
    assertTrue("another message was received", messagesReceived.await(20, TimeUnit.SECONDS));
    assertEquals("get message 1 eventually", MESSAGE_TEXT + "1", receivedMessages.get(receivedIndex++).getText());
    connection.close();
    server.stop();
}

34. FailoverConsumerOutstandingCommitTest#doTestFailoverConsumerDups()

Project: activemq-artemis
File: FailoverConsumerOutstandingCommitTest.java
@SuppressWarnings("unchecked")
public void doTestFailoverConsumerDups(final boolean watchTopicAdvisories) throws Exception {
    server = createBroker();
    server.start();
    brokerStopLatch = new CountDownLatch(1);
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("failover:(" + url + ")");
    cf.setWatchTopicAdvisories(watchTopicAdvisories);
    cf.setDispatchAsync(false);
    final ActiveMQConnection connection = (ActiveMQConnection) cf.createConnection();
    connection.start();
    final Session producerSession = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    final Queue destination = producerSession.createQueue(QUEUE_NAME + "?consumer.prefetchSize=" + prefetch);
    final Session consumerSession = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    final CountDownLatch commitDoneLatch = new CountDownLatch(1);
    final CountDownLatch messagesReceived = new CountDownLatch(2);
    final MessageConsumer testConsumer = consumerSession.createConsumer(destination);
    doByteman.set(true);
    testConsumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            LOG.info("consume one and commit");
            assertNotNull("got message", message);
            try {
                consumerSession.commit();
            } catch (JMSException e) {
                e.printStackTrace();
            }
            commitDoneLatch.countDown();
            messagesReceived.countDown();
            LOG.info("done commit");
        }
    });
    // may block if broker shutodwn happens quickly
    new Thread() {

        @Override
        public void run() {
            LOG.info("producer started");
            try {
                produceMessage(producerSession, destination, prefetch * 2);
            } catch (javax.jms.IllegalStateException SessionClosedExpectedOnShutdown) {
            } catch (JMSException e) {
                e.printStackTrace();
                fail("unexpceted ex on producer: " + e);
            }
            LOG.info("producer done");
        }
    }.start();
    // will be stopped by the plugin
    brokerStopLatch.await();
    server.stop();
    server = createBroker();
    doByteman.set(false);
    server.start();
    assertTrue("consumer added through failover", commitDoneLatch.await(20, TimeUnit.SECONDS));
    assertTrue("another message was received after failover", messagesReceived.await(20, TimeUnit.SECONDS));
    connection.close();
}

35. MessageCompressionTest#receiveTestBytesMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private ActiveMQBytesMessage receiveTestBytesMessage(ActiveMQConnectionFactory factory) throws JMSException, UnsupportedEncodingException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQBytesMessage rc = (ActiveMQBytesMessage) consumer.receive();
    connection.close();
    return rc;
}

36. MessageCompressionTest#receiveTestMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private ActiveMQTextMessage receiveTestMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQTextMessage rc = (ActiveMQTextMessage) consumer.receive();
    connection.close();
    return rc;
}

37. MessageCompressionTest#receiveTestMapMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private ActiveMQMapMessage receiveTestMapMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQMapMessage rc = (ActiveMQMapMessage) consumer.receive();
    connection.close();
    return rc;
}

38. MessageCompressionTest#receiveTestStreamMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private ActiveMQStreamMessage receiveTestStreamMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQStreamMessage rc = (ActiveMQStreamMessage) consumer.receive();
    connection.close();
    return rc;
}

39. MessageCompressionTest#receiveTestObjectMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private ActiveMQObjectMessage receiveTestObjectMessage(ActiveMQConnectionFactory factory) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    connection.start();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createConsumer(queue);
    ActiveMQObjectMessage rc = (ActiveMQObjectMessage) consumer.receive();
    connection.close();
    return rc;
}

40. AbortSlowAckConsumer0Test#testIdleConsumerCanBeAborted()

Project: activemq-artemis
File: AbortSlowAckConsumer0Test.java
@Test
public void testIdleConsumerCanBeAborted() throws Exception {
    strategy.setIgnoreIdleConsumers(false);
    // Make it shorter
    strategy.setMaxTimeSinceLastAck(2000);
    ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
    conn.setExceptionListener(this);
    connections.add(conn);
    Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    final MessageConsumer consumer = sess.createConsumer(destination);
    assertNotNull(consumer);
    conn.start();
    startProducers(destination, 1);
    Message message = consumer.receive(5000);
    assertNotNull(message);
    message.acknowledge();
    // Consumer needs to be closed before the reeive call.
    TimeUnit.SECONDS.sleep(15);
    try {
        consumer.receive(5000);
        fail("Idle consumer not aborted.");
    } catch (Exception ex) {
    }
}

41. AbortSlowAckConsumer0Test#testIdleConsumerCanBeAbortedNoMessages()

Project: activemq-artemis
File: AbortSlowAckConsumer0Test.java
@Test
public void testIdleConsumerCanBeAbortedNoMessages() throws Exception {
    strategy.setIgnoreIdleConsumers(false);
    // Make it shorter
    strategy.setMaxTimeSinceLastAck(2000);
    ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
    conn.setExceptionListener(this);
    connections.add(conn);
    Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    final MessageConsumer consumer = sess.createConsumer(destination);
    assertNotNull(consumer);
    conn.start();
    startProducers(destination, 1);
    Message message = consumer.receive(5000);
    assertNotNull(message);
    // Consumer needs to be closed before the reeive call.
    TimeUnit.SECONDS.sleep(15);
    try {
        consumer.receive(5000);
        fail("Idle consumer not aborted.");
    } catch (Exception ex) {
    }
}

42. AbortSlowAckConsumer0Test#testZeroPrefetchConsumerIsAborted()

Project: activemq-artemis
File: AbortSlowAckConsumer0Test.java
@Test
public void testZeroPrefetchConsumerIsAborted() throws Exception {
    // Make it shorter
    strategy.setMaxTimeSinceLastAck(2000);
    ActiveMQConnection conn = (ActiveMQConnection) createConnectionFactory().createConnection();
    conn.setExceptionListener(this);
    connections.add(conn);
    Session sess = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    final MessageConsumer consumer = sess.createConsumer(destination);
    assertNotNull(consumer);
    conn.start();
    startProducers(destination, 20);
    Message message = consumer.receive(5000);
    assertNotNull(message);
    TimeUnit.SECONDS.sleep(15);
    try {
        consumer.receive(5000);
        fail("Slow consumer not aborted.");
    } catch (Exception ex) {
    }
}

43. MessageCompressionTest#sendAMQBytesMessage()

Project: activemq-openwire
File: MessageCompressionTest.java
private void sendAMQBytesMessage(String message, boolean useCompression) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
    factory.setUseCompression(useCompression);
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(getActiveMQQueue());
    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(message.getBytes("UTF8"));
    producer.send(bytesMessage);
    connection.close();
}

44. MessageCompressionTest#sendAMQTextMessage()

Project: activemq-openwire
File: MessageCompressionTest.java
private void sendAMQTextMessage(String message, boolean useCompression) throws Exception {
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(connectionURI);
    factory.setUseCompression(useCompression);
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(getActiveMQQueue());
    producer.send(session.createTextMessage(message));
    connection.close();
}

45. JMSConsumer11Test#testPrefetch1MessageNotDispatched()

Project: activemq-artemis
File: JMSConsumer11Test.java
@Test
public void testPrefetch1MessageNotDispatched() throws Exception {
    // Set prefetch to 1
    connection.getPrefetchPolicy().setAll(1);
    connection.start();
    Session session = connection.createSession(true, 0);
    ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    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();
    Session session2 = connection2.createSession(true, 0);
    MessageConsumer consumer2 = session2.createConsumer(destination);
    System.out.println("consumer receiving ...");
    // Pick up the first message.
    Message message1 = consumer.receive(1000);
    System.out.println("received1: " + message1);
    assertNotNull(message1);
    System.out.println("consumer 2 receiving...");
    // Pick up the 2nd messages.
    Message message2 = consumer2.receive(5000);
    System.out.println("received2: " + message2);
    assertNotNull(message2);
    System.out.println("committing sessions !! " + session.getClass().getName());
    session.commit();
    System.out.println("committed session, now 2");
    session2.commit();
    System.out.println("all committed");
    Message m = consumer.receiveNoWait();
    System.out.println("received 3: " + m);
    assertNull(m);
    try {
        connection2.close();
    } catch (Throwable e) {
        System.err.println("exception e: " + e);
        e.printStackTrace();
    }
    System.out.println("Test finished!!");
}

46. RequestReplyNoAdvisoryNetworkTest#createConnection()

Project: activemq-artemis
File: RequestReplyNoAdvisoryNetworkTest.java
private ActiveMQConnection createConnection(ActiveMQConnectionFactory factory) throws Exception {
    ActiveMQConnection c = (ActiveMQConnection) factory.createConnection();
    c.start();
    return c;
}

47. NonBlockingConsumerRedeliveryTest#testNonBlockingMessageDeleiveryWithAllRolledBack()

Project: activemq-artemis
File: NonBlockingConsumerRedeliveryTest.java
@Test
public void testNonBlockingMessageDeleiveryWithAllRolledBack() throws Exception {
    final LinkedHashSet<Message> received = new LinkedHashSet<>();
    final LinkedHashSet<Message> dlqed = new LinkedHashSet<>();
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.getRedeliveryPolicy().setMaximumRedeliveries(5);
    final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue(destinationName);
    final Destination dlq = session.createQueue("ActiveMQ.DLQ");
    final MessageConsumer consumer = session.createConsumer(destination);
    final MessageConsumer dlqConsumer = session.createConsumer(dlq);
    dlqConsumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            dlqed.add(message);
        }
    });
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            received.add(message);
        }
    });
    sendMessages();
    connection.start();
    assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Consumer has received " + received.size() + " messages.");
            return received.size() == MSG_COUNT;
        }
    }));
    session.rollback();
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            try {
                session.rollback();
            } catch (JMSException e) {
                LOG.warn("Caught an unexcepted exception: " + e.getMessage());
            }
        }
    });
    assertTrue("Post-Rollback expects to DLQ: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Consumer has received " + dlqed.size() + " messages in DLQ.");
            return dlqed.size() == MSG_COUNT;
        }
    }));
    session.commit();
}

48. NonBlockingConsumerRedeliveryTest#testNonBlockingMessageDeleiveryWithRollbacks()

Project: activemq-artemis
File: NonBlockingConsumerRedeliveryTest.java
@Test
public void testNonBlockingMessageDeleiveryWithRollbacks() throws Exception {
    final LinkedHashSet<Message> received = new LinkedHashSet<>();
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    final Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    final Destination destination = session.createQueue(destinationName);
    final MessageConsumer consumer = session.createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            received.add(message);
        }
    });
    sendMessages();
    connection.start();
    assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Consumer has received " + received.size() + " messages.");
            return received.size() == MSG_COUNT;
        }
    }));
    received.clear();
    consumer.setMessageListener(new MessageListener() {

        int count = 0;

        @Override
        public void onMessage(Message message) {
            if (++count > 10) {
                try {
                    session.rollback();
                    LOG.info("Rolling back session.");
                    count = 0;
                } catch (JMSException e) {
                    LOG.warn("Caught an unexcepted exception: " + e.getMessage());
                }
            } else {
                received.add(message);
                try {
                    session.commit();
                } catch (JMSException e) {
                    LOG.warn("Caught an unexcepted exception: " + e.getMessage());
                }
            }
        }
    });
    session.rollback();
    assertTrue("Post-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Consumer has received " + received.size() + " messages since rollback.");
            return received.size() == MSG_COUNT;
        }
    }));
    assertEquals(MSG_COUNT, received.size());
    session.commit();
}

49. NonBlockingConsumerRedeliveryTest#testNonBlockingMessageDeleiveryIsDelayed()

Project: activemq-artemis
File: NonBlockingConsumerRedeliveryTest.java
@Test
public void testNonBlockingMessageDeleiveryIsDelayed() throws Exception {
    final LinkedHashSet<Message> received = new LinkedHashSet<>();
    ActiveMQConnection connection = (ActiveMQConnection) connectionFactory.createConnection();
    connection.getRedeliveryPolicy().setInitialRedeliveryDelay(TimeUnit.SECONDS.toMillis(6));
    Session session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
    Destination destination = session.createQueue(destinationName);
    MessageConsumer consumer = session.createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            received.add(message);
        }
    });
    sendMessages();
    connection.start();
    assertTrue("Pre-Rollback expects to receive: " + MSG_COUNT + " messages.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("Consumer has received " + received.size() + " messages.");
            return received.size() == MSG_COUNT;
        }
    }));
    received.clear();
    session.rollback();
    assertFalse("Delayed redelivery test not expecting any messages yet.", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return received.size() > 0;
        }
    }, TimeUnit.SECONDS.toMillis(4)));
    session.commit();
    session.close();
}

50. SimpleAuthenticationPluginTest#testSecurityContextClearedOnPurge()

Project: activemq-artemis
File: SimpleAuthenticationPluginTest.java
public void testSecurityContextClearedOnPurge() throws Exception {
    connection.close();
    ActiveMQConnectionFactory tcpFactory = new ActiveMQConnectionFactory(broker.getTransportConnectors().get(0).getPublishableConnectString());
    ActiveMQConnection conn = (ActiveMQConnection) tcpFactory.createConnection("user", "password");
    Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    conn.start();
    final int numDests = broker.getRegionBroker().getDestinations().length;
    for (int i = 0; i < 10; i++) {
        MessageProducer p = sess.createProducer(new ActiveMQQueue("USERS.PURGE." + i));
        p.close();
    }
    assertTrue("dests are purged", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            LOG.info("dests, orig: " + numDests + ", now: " + broker.getRegionBroker().getDestinations().length);
            return (numDests + 1) == broker.getRegionBroker().getDestinations().length;
        }
    }));
    // verify removed from connection security context
    TransportConnection brokerConnection = broker.getTransportConnectors().get(0).getConnections().get(0);
    TransportConnectionState transportConnectionState = brokerConnection.lookupConnectionState(conn.getConnectionInfo().getConnectionId());
    assertEquals("no destinations", 0, transportConnectionState.getContext().getSecurityContext().getAuthorizedWriteDests().size());
}

51. MessageCompressionTest#sendTestBytesMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private void sendTestBytesMessage(ActiveMQConnectionFactory factory, String message) throws JMSException, UnsupportedEncodingException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    BytesMessage bytesMessage = session.createBytesMessage();
    bytesMessage.writeBytes(message.getBytes(StandardCharsets.UTF_8));
    producer.send(bytesMessage);
    connection.close();
}

52. MessageCompressionTest#sendTestMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private void sendTestMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    producer.send(session.createTextMessage(message));
    connection.close();
}

53. MessageCompressionTest#sendTestObjectMessage()

Project: activemq-artemis
File: MessageCompressionTest.java
private void sendTestObjectMessage(ActiveMQConnectionFactory factory, String message) throws JMSException {
    ActiveMQConnection connection = (ActiveMQConnection) factory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(queue);
    ObjectMessage objectMessage = session.createObjectMessage();
    objectMessage.setObject(TEXT);
    producer.send(objectMessage);
    connection.close();
}

54. ActiveMQMessageConsumerDispatchInterceptor#doInBeforeTrace()

Project: pinpoint
File: ActiveMQMessageConsumerDispatchInterceptor.java
@Override
protected void doInBeforeTrace(SpanRecorder recorder, Object target, Object[] args) {
    recorder.recordServiceType(ActiveMQClientConstants.ACTIVEMQ_CLIENT);
    ActiveMQSession session = ((ActiveMQSessionGetter) target)._$PINPOINT$_getActiveMQSession();
    ActiveMQConnection connection = session.getConnection();
    Transport transport = getRootTransport(((TransportGetter) connection)._$PINPOINT$_getTransport());
    Socket socket = ((SocketGetter) transport)._$PINPOINT$_getSocket();
    SocketAddress localSocketAddress = socket.getLocalSocketAddress();
    String endPoint = ActiveMQClientUtils.getEndPoint(localSocketAddress);
    // Endpoint should be the local socket address of the consumer.
    recorder.recordEndPoint(endPoint);
    SocketAddress remoteSocketAddress = socket.getRemoteSocketAddress();
    String remoteAddress = ActiveMQClientUtils.getEndPoint(remoteSocketAddress);
    // Remote address is the socket address of where the consumer is connected to.
    recorder.recordRemoteAddress(remoteAddress);
    MessageDispatch md = (MessageDispatch) args[0];
    ActiveMQMessage message = (ActiveMQMessage) md.getMessage();
    ActiveMQDestination destination = message.getDestination();
    // Rpc name is the URI of the queue/topic we're consuming from.
    recorder.recordRpcName(destination.getQualifiedName());
    // Record acceptor host as the queue/topic name in order to generate virtual queue node.
    recorder.recordAcceptorHost(destination.getPhysicalName());
    String parentApplicationName = ActiveMQClientHeader.getParentApplicationName(message, null);
    if (!recorder.isRoot() && parentApplicationName != null) {
        short parentApplicationType = ActiveMQClientHeader.getParentApplicationType(message, ServiceType.UNDEFINED.getCode());
        recorder.recordParentApplication(parentApplicationName, parentApplicationType);
    }
}

55. ActiveMQClientITHelper#createSession()

Project: pinpoint
File: ActiveMQClientITHelper.java
public static final ActiveMQSession createSession(String brokerName, String brokerUrl, boolean transacted, int acknowledgeMode) throws JMSException {
    ActiveMQConnection connection = BROKER_SERVICE.getConnection(brokerName, brokerUrl);
    return (ActiveMQSession) connection.createSession(transacted, acknowledgeMode);
}

56. ConnectionFactoryResourceTest#testBorrowObject()

Project: camel
File: ConnectionFactoryResourceTest.java
@Test(expected = NoSuchElementException.class)
public void testBorrowObject() throws Exception {
    ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
    pool.fillPool();
    assertNotNull(pool);
    ActiveMQConnection connection = (ActiveMQConnection) pool.borrowConnection();
    assertNotNull(connection);
    assertTrue(connection.isStarted());
    pool.borrowConnection();
}

57. ConnectionFactoryResourceTest#testDestroyObject()

Project: camel
File: ConnectionFactoryResourceTest.java
@Test
public void testDestroyObject() throws Exception {
    ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
    pool.fillPool();
    assertNotNull(pool);
    ActiveMQConnection connection = (ActiveMQConnection) pool.makeObject();
    assertNotNull(connection);
    assertTrue(connection.isStarted());
    pool.drainPool();
    assertTrue(pool.size() == 0);
}

58. ConnectionFactoryResourceTest#testCreateObject()

Project: camel
File: ConnectionFactoryResourceTest.java
@Test
public void testCreateObject() throws Exception {
    ConnectionFactoryResource pool = new ConnectionFactoryResource(1, connectionFactory);
    pool.fillPool();
    assertNotNull(pool);
    ActiveMQConnection connection = (ActiveMQConnection) pool.makeObject();
    assertNotNull(connection);
    assertTrue(connection.isStarted());
    pool.drainPool();
}

59. ConsumeTopicPrefetchTest#createConnection()

Project: activemq-artemis
File: ConsumeTopicPrefetchTest.java
@Override
protected Connection createConnection() throws Exception {
    ActiveMQConnection connection = (ActiveMQConnection) super.createConnection();
    connection.getPrefetchPolicy().setQueuePrefetch(prefetchSize);
    connection.getPrefetchPolicy().setTopicPrefetch(prefetchSize);
    return connection;
}

60. TwoBrokerFailoverClusterTest#assertAllConnectedTo()

Project: activemq-artemis
File: TwoBrokerFailoverClusterTest.java
protected void assertAllConnectedTo(String url) throws Exception {
    for (ActiveMQConnection c : connections) {
        Assert.assertEquals(url, c.getTransportChannel().getRemoteAddress());
    }
}

61. TwoBrokerFailoverClusterTest#assertClientsConnectedToTwoBrokers()

Project: activemq-artemis
File: TwoBrokerFailoverClusterTest.java
protected void assertClientsConnectedToTwoBrokers() {
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        if (c.getTransportChannel().getRemoteAddress() != null) {
            set.add(c.getTransportChannel().getRemoteAddress());
        }
    }
    Assert.assertTrue("Only 2 connections should be found: " + set, set.size() == 2);
}

62. TwoBrokerFailoverClusterTest#tearDown()

Project: activemq-artemis
File: TwoBrokerFailoverClusterTest.java
@After
public void tearDown() throws Exception {
    for (ActiveMQConnection conn : connections) {
        conn.close();
    }
    server0.stop();
    server1.stop();
}

63. FailoverPriorityTest#assertAllConnectedTo()

Project: activemq-artemis
File: FailoverPriorityTest.java
protected void assertAllConnectedTo(String url) throws Exception {
    for (ActiveMQConnection c : connections) {
        Assert.assertEquals(url, c.getTransportChannel().getRemoteAddress());
    }
}

64. FailoverComplexClusterTest#assertAllConnectedTo()

Project: activemq-artemis
File: FailoverComplexClusterTest.java
protected void assertAllConnectedTo(String url) throws Exception {
    for (ActiveMQConnection c : connections) {
        Assert.assertEquals(url, c.getTransportChannel().getRemoteAddress());
    }
}

65. FailoverComplexClusterTest#assertClientsConnectionsEvenlyDistributed()

Project: activemq-artemis
File: FailoverComplexClusterTest.java
protected void assertClientsConnectionsEvenlyDistributed(double minimumPercentage, double maximumPercentage) {
    Map<String, Double> clientConnectionCounts = new HashMap<>();
    int total = 0;
    for (ActiveMQConnection c : connections) {
        String key = c.getTransportChannel().getRemoteAddress();
        if (key != null) {
            total++;
            if (clientConnectionCounts.containsKey(key)) {
                double count = clientConnectionCounts.get(key);
                count += 1.0;
                clientConnectionCounts.put(key, count);
            } else {
                clientConnectionCounts.put(key, 1.0);
            }
        }
    }
    Set<String> keys = clientConnectionCounts.keySet();
    List<String> errorMsgs = new ArrayList<>();
    for (String key : keys) {
        double count = clientConnectionCounts.get(key);
        double percentage = count / total;
        if (percentage < minimumPercentage || percentage > maximumPercentage) {
            errorMsgs.add("Connections distribution expected to be within range [ " + minimumPercentage + ", " + maximumPercentage + "].  Actuall distribution was " + percentage + " for connection " + key);
        }
        if (errorMsgs.size() > 0) {
            for (String err : errorMsgs) {
                System.err.println(err);
            }
            Assert.fail("Test failed. Please see the log message for details");
        }
    }
}

66. FailoverComplexClusterTest#assertClientsConnectedToTwoBrokers()

Project: activemq-artemis
File: FailoverComplexClusterTest.java
protected void assertClientsConnectedToTwoBrokers() {
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        if (c.getTransportChannel().getRemoteAddress() != null) {
            set.add(c.getTransportChannel().getRemoteAddress());
        }
    }
    Assert.assertTrue("Only 2 connections should be found: " + set, set.size() == 2);
}

67. FailoverComplexClusterTest#assertClientsConnectedToThreeBrokers()

Project: activemq-artemis
File: FailoverComplexClusterTest.java
protected void assertClientsConnectedToThreeBrokers() {
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        if (c.getTransportChannel().getRemoteAddress() != null) {
            set.add(c.getTransportChannel().getRemoteAddress());
        }
    }
    Assert.assertTrue("Only 3 connections should be found: " + set, set.size() == 3);
}

68. FailoverClusterTestSupport#assertAllConnectedTo()

Project: activemq-artemis
File: FailoverClusterTestSupport.java
protected void assertAllConnectedTo(String url) throws Exception {
    for (ActiveMQConnection c : connections) {
        assertEquals(url, c.getTransportChannel().getRemoteAddress());
    }
}

69. FailoverClusterTestSupport#assertClientsConnectedToThreeBrokers()

Project: activemq-artemis
File: FailoverClusterTestSupport.java
protected void assertClientsConnectedToThreeBrokers() {
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        if (c.getTransportChannel().getRemoteAddress() != null) {
            set.add(c.getTransportChannel().getRemoteAddress());
        }
    }
    assertTrue("Only 3 connections should be found: " + set, set.size() == 3);
}

70. FailoverClusterTestSupport#assertClientsConnectedToTwoBrokers()

Project: activemq-artemis
File: FailoverClusterTestSupport.java
protected void assertClientsConnectedToTwoBrokers() {
    Set<String> set = new HashSet<>();
    for (ActiveMQConnection c : connections) {
        if (c.getTransportChannel().getRemoteAddress() != null) {
            set.add(c.getTransportChannel().getRemoteAddress());
        }
    }
    assertTrue("Only 2 connections should be found: " + set, set.size() == 2);
}

71. MessageListenerDeadLetterTest#doTest()

Project: activemq-artemis
File: MessageListenerDeadLetterTest.java
@Override
protected void doTest() throws Exception {
    messageCount = 200;
    connection.start();
    ActiveMQConnection amqConnection = (ActiveMQConnection) connection;
    rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1;
    LOG.info("Will redeliver messages: " + rollbackCount + " times");
    makeConsumer();
    makeDlqConsumer();
    sendMessages();
    // now lets receive and rollback N times
    int maxRollbacks = messageCount * rollbackCount;
    consumer.setMessageListener(new RollbackMessageListener(maxRollbacks, rollbackCount));
    for (int i = 0; i < messageCount; i++) {
        Message msg = dlqConsumer.receive(4000);
        if (error[0] != null) {
            // error from message listener
            throw error[0];
        }
        assertMessage(msg, i);
        assertNotNull("Should be a DLQ message for loop: " + i, msg);
    }
    if (error[0] != null) {
        throw error[0];
    }
}

72. IndividualDeadLetterTest#testDLQBrowsing()

Project: activemq-artemis
File: IndividualDeadLetterTest.java
public void testDLQBrowsing() throws Exception {
    super.topic = false;
    deliveryMode = DeliveryMode.PERSISTENT;
    durableSubscriber = false;
    messageCount = 1;
    connection.start();
    ActiveMQConnection amqConnection = (ActiveMQConnection) connection;
    rollbackCount = amqConnection.getRedeliveryPolicy().getMaximumRedeliveries() + 1;
    LOG.info("Will redeliver messages: " + rollbackCount + " times");
    sendMessages();
    // now lets receive and rollback N times
    for (int i = 0; i < rollbackCount; i++) {
        makeConsumer();
        Message message = consumer.receive(5000);
        assertNotNull("No message received: ", message);
        session.rollback();
        LOG.info("Rolled back: " + rollbackCount + " times");
        consumer.close();
    }
    makeDlqBrowser();
    browseDlq();
    dlqBrowser.close();
    session.close();
    Thread.sleep(1000);
    session = connection.createSession(transactedMode, acknowledgeMode);
    Queue testQueue = new ActiveMQQueue("ActiveMQ.DLQ.Queue.ActiveMQ.DLQ.Queue." + getClass().getName() + "." + getName());
    MessageConsumer testConsumer = session.createConsumer(testQueue);
    assertNull("The message shouldn't be sent to another DLQ", testConsumer.receive(1000));
}