Search in sources :

Example 51 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class JmsConsumerTest method testClearExceptionListener.

@Test
public void testClearExceptionListener() throws Exception {
    conn = cf.createConnection();
    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    jBossQueue = ActiveMQJMSClient.createQueue(JmsConsumerTest.Q_NAME);
    MessageConsumer consumer = session.createConsumer(jBossQueue);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(final Message msg) {
        }
    });
    consumer.setMessageListener(null);
    consumer.receiveNoWait();
}
Also used : MessageConsumer(javax.jms.MessageConsumer) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) MessageListener(javax.jms.MessageListener) Session(javax.jms.Session) Test(org.junit.Test)

Example 52 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class ManagementNotificationExample method main.

public static void main(final String[] args) throws Exception {
    Connection connection = null;
    InitialContext initialContext = null;
    try {
        // Step 1. Create an initial context to perform the JNDI lookup.
        initialContext = new InitialContext();
        // Step 2. Perform a lookup on the queue
        Queue queue = (Queue) initialContext.lookup("queue/exampleQueue");
        // Step 3. Perform a lookup on the Connection Factory
        ConnectionFactory cf = (ConnectionFactory) initialContext.lookup("ConnectionFactory");
        // Step 4.Create a JMS connection, a session and a producer for the queue
        connection = cf.createConnection();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageProducer producer = session.createProducer(queue);
        // Step 5. Perform a lookup on the notifications topic
        Topic notificationsTopic = (Topic) initialContext.lookup("topic/notificationsTopic");
        // Step 6. Create a JMS message consumer for the notification queue and set its message listener
        // It will display all the properties of the JMS Message
        MessageConsumer notificationConsumer = session.createConsumer(notificationsTopic);
        notificationConsumer.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(final Message notif) {
                System.out.println("------------------------");
                System.out.println("Received notification:");
                try {
                    Enumeration propertyNames = notif.getPropertyNames();
                    while (propertyNames.hasMoreElements()) {
                        String propertyName = (String) propertyNames.nextElement();
                        System.out.format("  %s: %s%n", propertyName, notif.getObjectProperty(propertyName));
                    }
                } catch (JMSException e) {
                }
                System.out.println("------------------------");
            }
        });
        // Step 7. Start the Connection to allow the consumers to receive messages
        connection.start();
        // Step 8. Create a JMS Message Consumer on the queue
        MessageConsumer consumer = session.createConsumer(queue);
        // Step 9. Close the consumer
        consumer.close();
        // Step 10. Try to create a connection with unknown user
        try {
            cf.createConnection("not.a.valid.user", "not.a.valid.password");
        } catch (JMSException e) {
        }
        // sleep a little bit to be sure to receive the notification for the security
        // authentication violation before leaving the example
        Thread.sleep(2000);
    } finally {
        // Step 11. Be sure to close the resources!
        if (initialContext != null) {
            initialContext.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
}
Also used : MessageConsumer(javax.jms.MessageConsumer) Enumeration(java.util.Enumeration) Message(javax.jms.Message) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) InitialContext(javax.naming.InitialContext) ConnectionFactory(javax.jms.ConnectionFactory) MessageProducer(javax.jms.MessageProducer) Topic(javax.jms.Topic) Queue(javax.jms.Queue) Session(javax.jms.Session)

Example 53 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class NetworkLoadTest method testRequestReply.

public void testRequestReply() throws Exception {
    // Send to the first broker
    final int to = 0;
    // consume from the last broker..
    int from = brokers.length - 1;
    LOG.info("Staring Final Consumer");
    Connection fromConnection = createConnection(from);
    fromConnection.start();
    Session fromSession = fromConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = fromSession.createConsumer(new ActiveMQQueue("Q" + from));
    final AtomicReference<ActiveMQTextMessage> lastMessageReceived = new AtomicReference<>();
    final AtomicLong producedMessages = new AtomicLong();
    final AtomicLong receivedMessages = new AtomicLong();
    final AtomicBoolean done = new AtomicBoolean();
    // Setup the consumer..
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message msg) {
            ActiveMQTextMessage m = (ActiveMQTextMessage) msg;
            ActiveMQTextMessage last = lastMessageReceived.get();
            if (last != null) {
                // Some order checking...
                if (last.getMessageId().getProducerSequenceId() > m.getMessageId().getProducerSequenceId()) {
                    System.out.println("Received an out of order message. Got " + m.getMessageId() + ", expected something after " + last.getMessageId());
                }
            }
            lastMessageReceived.set(m);
            receivedMessages.incrementAndGet();
        }
    });
    LOG.info("Staring Initial Producer");
    final Connection toConnection = createConnection(to);
    Thread producer = new Thread("Producer") {

        @Override
        public void run() {
            try {
                toConnection.start();
                Session toSession = toConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
                final MessageProducer producer = toSession.createProducer(new ActiveMQQueue("Q" + to));
                producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
                producer.setDisableMessageID(true);
                for (int i = 0; !done.get(); i++) {
                    TextMessage msg = toSession.createTextMessage(createMessageText(i));
                    producer.send(msg);
                    producedMessages.incrementAndGet();
                }
            } catch (JMSException e) {
                e.printStackTrace();
            }
        }

        private String createMessageText(int index) {
            StringBuffer buffer = new StringBuffer(MESSAGE_SIZE);
            buffer.append(index + " on " + new Date() + " ...");
            if (buffer.length() > MESSAGE_SIZE) {
                return buffer.substring(0, MESSAGE_SIZE);
            }
            for (int i = buffer.length(); i < MESSAGE_SIZE; i++) {
                buffer.append(' ');
            }
            return buffer.toString();
        }
    };
    producer.start();
    // Give the forwarding clients a chance to get going and fill the down
    // stream broker queues..
    Thread.sleep(BROKER_COUNT * 200);
    for (int i = 0; i < SAMPLES; i++) {
        long start = System.currentTimeMillis();
        producedMessages.set(0);
        receivedMessages.set(0);
        for (int j = 0; j < forwardingClients.length; j++) {
            forwardingClients[j].forwardCounter.set(0);
        }
        Thread.sleep(SAMPLE_DURATION);
        long end = System.currentTimeMillis();
        long r = receivedMessages.get();
        long p = producedMessages.get();
        LOG.info("published: " + p + " msgs at " + (p * 1000f / (end - start)) + " msgs/sec, " + "consumed: " + r + " msgs at " + (r * 1000f / (end - start)) + " msgs/sec");
        StringBuffer fwdingmsg = new StringBuffer(500);
        fwdingmsg.append("  forwarding counters: ");
        for (int j = 0; j < forwardingClients.length; j++) {
            if (j != 0) {
                fwdingmsg.append(", ");
            }
            fwdingmsg.append(forwardingClients[j].forwardCounter.get());
        }
        LOG.info(fwdingmsg.toString());
        // The test is just checking to make sure thaat the producer and consumer does not hang
        // due to the network hops take to route the message form the producer to the consumer.
        assertTrue("Received some messages since last sample", r > 0);
        assertTrue("Produced some messages since last sample", p > 0);
    }
    LOG.info("Sample done.");
    done.set(true);
    // Wait for the producer to finish.
    producer.join(1000 * 5);
    toConnection.close();
    fromConnection.close();
}
Also used : MessageConsumer(javax.jms.MessageConsumer) ActiveMQTextMessage(org.apache.activemq.command.ActiveMQTextMessage) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) AtomicReference(java.util.concurrent.atomic.AtomicReference) JMSException(javax.jms.JMSException) Date(java.util.Date) ActiveMQTextMessage(org.apache.activemq.command.ActiveMQTextMessage) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) AtomicLong(java.util.concurrent.atomic.AtomicLong) ActiveMQQueue(org.apache.activemq.command.ActiveMQQueue) MessageProducer(javax.jms.MessageProducer) ActiveMQTextMessage(org.apache.activemq.command.ActiveMQTextMessage) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session)

Example 54 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class ConnectionTest method testStopConsumerConnection.

/**
 * Test that delivery of message is stopped if the message consumer connection is stopped
 */
@Test
public void testStopConsumerConnection() {
    try {
        receiverConnection.stop();
        receiver.setMessageListener(new MessageListener() {

            @Override
            public void onMessage(final Message m) {
                try {
                    Assert.fail("The message must not be received, the consumer connection is stopped");
                    Assert.assertEquals("test", ((TextMessage) m).getText());
                } catch (JMSException e) {
                    fail(e);
                }
            }
        });
        TextMessage message = senderSession.createTextMessage();
        message.setText("test");
        sender.send(message);
        synchronized (this) {
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                fail(e);
            }
        }
    } catch (JMSException e) {
        fail(e);
    }
}
Also used : TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) TextMessage(javax.jms.TextMessage) JMSException(javax.jms.JMSException) Test(org.junit.Test)

Example 55 with MessageListener

use of javax.jms.MessageListener in project activemq-artemis by apache.

the class FailoverConsumerUnconsumedTest method testFailoverClientAckMissingRedelivery.

@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();
}
Also used : Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) ActiveMQConnection(org.apache.activemq.ActiveMQConnection) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) CountDownLatch(java.util.concurrent.CountDownLatch) JMSException(javax.jms.JMSException) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) Queue(javax.jms.Queue) Vector(java.util.Vector) Session(javax.jms.Session) ActiveMQSession(org.apache.activemq.ActiveMQSession) Test(org.junit.Test) OpenwireArtemisBaseTest(org.apache.activemq.broker.artemiswrapper.OpenwireArtemisBaseTest) BMRules(org.jboss.byteman.contrib.bmunit.BMRules)

Aggregations

MessageListener (javax.jms.MessageListener)146 Message (javax.jms.Message)128 MessageConsumer (javax.jms.MessageConsumer)103 Session (javax.jms.Session)97 TextMessage (javax.jms.TextMessage)95 CountDownLatch (java.util.concurrent.CountDownLatch)72 Test (org.junit.Test)71 Connection (javax.jms.Connection)60 MessageProducer (javax.jms.MessageProducer)58 JMSException (javax.jms.JMSException)57 Destination (javax.jms.Destination)32 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)31 ActiveMQConnectionFactory (org.apache.activemq.ActiveMQConnectionFactory)26 BytesMessage (javax.jms.BytesMessage)22 Queue (javax.jms.Queue)21 ConnectionFactory (javax.jms.ConnectionFactory)16 ScheduledMessage (org.apache.activemq.ScheduledMessage)15 ArrayList (java.util.ArrayList)14 Topic (javax.jms.Topic)13 ActiveMQQueue (org.apache.activemq.command.ActiveMQQueue)13