Search in sources :

Example 41 with MessageListener

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

the class JMSConsumer2Test method testMessageListenerWithConsumerCanBeStoppedConcurently.

@Test
public void testMessageListenerWithConsumerCanBeStoppedConcurently() throws Exception {
    final AtomicInteger counter = new AtomicInteger(0);
    final CountDownLatch closeDone = new CountDownLatch(1);
    connection.start();
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQDestination destination = createDestination(session, ActiveMQDestination.QUEUE_TYPE);
    // preload the queue
    sendMessages(session, destination, 2000);
    final ActiveMQMessageConsumer consumer = (ActiveMQMessageConsumer) session.createConsumer(destination);
    final Map<Thread, Throwable> exceptions = Collections.synchronizedMap(new HashMap<Thread, Throwable>());
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override
        public void uncaughtException(Thread t, Throwable e) {
            exceptions.put(t, e);
        }
    });
    final class AckAndClose implements Runnable {

        private final Message message;

        AckAndClose(Message m) {
            this.message = m;
        }

        @Override
        public void run() {
            try {
                int count = counter.incrementAndGet();
                if (count == 590) {
                    // close in a separate thread is ok by jms
                    consumer.close();
                    closeDone.countDown();
                }
                if (count % 200 == 0) {
                    // ensure there are some outstanding messages
                    // ack every 200
                    message.acknowledge();
                }
            } catch (Exception e) {
                exceptions.put(Thread.currentThread(), e);
            }
        }
    }
    final ExecutorService executor = Executors.newCachedThreadPool(ActiveMQThreadFactory.defaultThreadFactory());
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message m) {
            // ack and close eventually in separate thread
            executor.execute(new AckAndClose(m));
        }
    });
    assertTrue(closeDone.await(20, TimeUnit.SECONDS));
    // await possible exceptions
    Thread.sleep(1000);
    assertTrue("no exceptions: " + exceptions, exceptions.isEmpty());
}
Also used : Message(javax.jms.Message) ActiveMQMessageConsumer(org.apache.activemq.ActiveMQMessageConsumer) MessageListener(javax.jms.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch) ActiveMQDestination(org.apache.activemq.command.ActiveMQDestination) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ExecutorService(java.util.concurrent.ExecutorService) UncaughtExceptionHandler(java.lang.Thread.UncaughtExceptionHandler) Session(javax.jms.Session) BasicOpenWireTest(org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest) Test(org.junit.Test)

Example 42 with MessageListener

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

the class JmsConsumerResetActiveListenerTest method testNewConsumerSetListenerFromListener.

/**
 * and a listener on a new consumer, just in case.
 *
 * @throws Exception
 */
@Test
public void testNewConsumerSetListenerFromListener() throws Exception {
    final Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    final Destination dest = session.createQueue(queueName);
    final MessageConsumer consumer = session.createConsumer(dest);
    final CountDownLatch latch = new CountDownLatch(2);
    final AtomicBoolean first = new AtomicBoolean(true);
    final Vector<Object> results = new Vector<>();
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            if (first.compareAndSet(true, false)) {
                try {
                    MessageConsumer anotherConsumer = session.createConsumer(dest);
                    anotherConsumer.setMessageListener(this);
                    results.add(message);
                } catch (JMSException e) {
                    results.add(e);
                }
            } else {
                results.add(message);
            }
            latch.countDown();
        }
    });
    connection.start();
    MessageProducer producer = session.createProducer(dest);
    producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
    producer.send(session.createTextMessage("First"));
    producer.send(session.createTextMessage("Second"));
    assertTrue("we did not timeout", latch.await(5, TimeUnit.SECONDS));
    assertEquals("we have a result", 2, results.size());
    Object result = results.get(0);
    assertTrue(result instanceof TextMessage);
    assertEquals("result is first", "First", ((TextMessage) result).getText());
    result = results.get(1);
    assertTrue(result instanceof TextMessage);
    assertEquals("result is first", "Second", ((TextMessage) result).getText());
}
Also used : Destination(javax.jms.Destination) MessageConsumer(javax.jms.MessageConsumer) TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) CountDownLatch(java.util.concurrent.CountDownLatch) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MessageProducer(javax.jms.MessageProducer) Vector(java.util.Vector) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session) BasicOpenWireTest(org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest) Test(org.junit.Test)

Example 43 with MessageListener

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

the class JMSConsumer6Test method testPassMessageListenerIntoCreateConsumer.

@Test
public void testPassMessageListenerIntoCreateConsumer() throws Exception {
    final AtomicInteger counter = new AtomicInteger(0);
    final CountDownLatch done = new CountDownLatch(1);
    // Receive a message with the JMS API
    connection.start();
    ActiveMQSession session = (ActiveMQSession) connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQDestination destination = createDestination(session, destinationType);
    MessageConsumer consumer = session.createConsumer(destination, new MessageListener() {

        @Override
        public void onMessage(Message m) {
            counter.incrementAndGet();
            if (counter.get() == 4) {
                done.countDown();
            }
        }
    });
    assertNotNull(consumer);
    // Send the messages
    sendMessages(session, destination, 4);
    assertTrue(done.await(1000, TimeUnit.MILLISECONDS));
    Thread.sleep(200);
    // Make sure only 4 messages were delivered.
    assertEquals(4, counter.get());
}
Also used : ActiveMQMessageConsumer(org.apache.activemq.ActiveMQMessageConsumer) MessageConsumer(javax.jms.MessageConsumer) ActiveMQSession(org.apache.activemq.ActiveMQSession) TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) MessageListener(javax.jms.MessageListener) CountDownLatch(java.util.concurrent.CountDownLatch) ActiveMQDestination(org.apache.activemq.command.ActiveMQDestination) BasicOpenWireTest(org.apache.activemq.artemis.tests.integration.openwire.BasicOpenWireTest) Test(org.junit.Test)

Example 44 with MessageListener

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

the class ThreeBrokerTempDestDemandSubscriptionCleanupTest method installEchoClientOnBrokerC.

private void installEchoClientOnBrokerC() throws Exception {
    BrokerItem brokerC = brokers.get(BROKER_C);
    Connection conn = brokerC.createConnection();
    conn.start();
    final Session sess = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = sess.createQueue(ECHO_QUEUE_NAME);
    MessageConsumer consumer = sess.createConsumer(destination);
    consumer.setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            TextMessage textMessage = (TextMessage) message;
            try {
                Destination replyTo = message.getJMSReplyTo();
                MessageProducer producer = sess.createProducer(replyTo);
                Message response = sess.createTextMessage(textMessage.getText());
                LOG.info("Replying to this request: " + textMessage.getText());
                producer.send(response);
                producer.close();
            } catch (JMSException e) {
                e.printStackTrace();
                fail("Could not respond to an echo request");
            }
        }
    });
}
Also used : Destination(javax.jms.Destination) MessageConsumer(javax.jms.MessageConsumer) TextMessage(javax.jms.TextMessage) Message(javax.jms.Message) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) JMSException(javax.jms.JMSException) MessageProducer(javax.jms.MessageProducer) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session)

Example 45 with MessageListener

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

the class TopicProducerFlowControlTest method testTopicProducerFlowControl.

public void testTopicProducerFlowControl() throws Exception {
    // Create the connection factory
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUrl);
    connectionFactory.setAlwaysSyncSend(true);
    connectionFactory.setProducerWindowSize(1024);
    ActiveMQPrefetchPolicy prefetchPolicy = new ActiveMQPrefetchPolicy();
    prefetchPolicy.setAll(5000);
    connectionFactory.setPrefetchPolicy(prefetchPolicy);
    // Start the test destination listener
    Connection c = connectionFactory.createConnection();
    c.start();
    Session listenerSession = c.createSession(false, 1);
    Destination destination = createDestination(listenerSession);
    listenerSession.createConsumer(destination).setMessageListener(new TopicProducerFlowControlTest());
    final AtomicInteger blockedCounter = new AtomicInteger(0);
    listenerSession.createConsumer(new ActiveMQTopic(AdvisorySupport.FULL_TOPIC_PREFIX + ">")).setMessageListener(new MessageListener() {

        @Override
        public void onMessage(Message message) {
            LOG.info("Got full advisory, blockedCounter: " + blockedCounter.get());
            blockedCounter.incrementAndGet();
        }
    });
    // Start producing the test messages
    final Session session = connectionFactory.createConnection().createSession(false, Session.AUTO_ACKNOWLEDGE);
    final MessageProducer producer = session.createProducer(destination);
    Thread producingThread = new Thread("Producing Thread") {

        @Override
        public void run() {
            try {
                for (long i = 0; i < numMessagesToSend; i++) {
                    producer.send(session.createTextMessage("test"));
                    long count = produced.incrementAndGet();
                    if (count % 10000 == 0) {
                        LOG.info("Produced " + count + " messages");
                    }
                }
            } catch (Throwable ex) {
                ex.printStackTrace();
            } finally {
                try {
                    producer.close();
                    session.close();
                } catch (Exception e) {
                }
            }
        }
    };
    producingThread.start();
    Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return consumed.get() == numMessagesToSend;
        }
    }, // give it plenty of time before failing
    5 * 60 * 1000);
    assertEquals("Didn't produce all messages", numMessagesToSend, produced.get());
    assertEquals("Didn't consume all messages", numMessagesToSend, consumed.get());
    assertTrue("Producer got blocked", Wait.waitFor(new Wait.Condition() {

        @Override
        public boolean isSatisified() throws Exception {
            return blockedCounter.get() > 0;
        }
    }, 5 * 1000));
}
Also used : Destination(javax.jms.Destination) ActiveMQTopic(org.apache.activemq.command.ActiveMQTopic) Message(javax.jms.Message) Connection(javax.jms.Connection) MessageListener(javax.jms.MessageListener) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ActiveMQPrefetchPolicy(org.apache.activemq.ActiveMQPrefetchPolicy) MessageProducer(javax.jms.MessageProducer) Wait(org.apache.activemq.util.Wait) Session(javax.jms.Session)

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