Example usage for javax.jms QueueBrowser getEnumeration

List of usage examples for javax.jms QueueBrowser getEnumeration

Introduction

In this page you can find the example usage for javax.jms QueueBrowser getEnumeration.

Prototype


Enumeration getEnumeration() throws JMSException;

Source Link

Document

Gets an enumeration for browsing the current queue messages in the order they would be received.

Usage

From source file:nl.nn.adapterframework.jms.JmsMessageBrowser.java

protected Message doBrowse(Map selectors) throws ListenerException {
    QueueSession session = null;//from   w w  w . ja  v a  2s.  c  om
    Message msg = null;
    QueueBrowser queueBrowser = null;
    try {
        session = (QueueSession) createSession();
        queueBrowser = session.createBrowser((Queue) getDestination(), getCombinedSelector(selectors));
        Enumeration msgenum = queueBrowser.getEnumeration();
        if (msgenum.hasMoreElements()) {
            msg = (Message) msgenum.nextElement();
        }
        return msg;
    } catch (Exception e) {
        throw new ListenerException(e);
    } finally {
        try {
            if (queueBrowser != null) {
                queueBrowser.close();
            }
        } catch (JMSException e1) {
            throw new ListenerException("exception closing queueBrowser", e1);
        }
        closeSession(session);
    }
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

/**
 * Tests the queue browser. Browses the messages then the consumer tries to receive them. The messages should still
 * be in the queue even when it was browsed.
 *
 * Re-enable once https://issues.apache.org/jira/browse/APLO-226 is fixed.
 *
 * @throws Exception/*ww  w.j av a  2  s  . c o  m*/
 */
public void testReceiveBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    MessageProducer producer = session.createProducer(destination);
    MessageConsumer consumer = session.createConsumer(destination);
    connection.start();

    Message[] outbound = new Message[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

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

    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // Get the first.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    //Thread.sleep(200);

    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse the second
    assertTrue("should have received the second message", enumeration.hasMoreElements());
    assertEquals(outbound[1], (Message) enumeration.nextElement());

    // browse the third.
    assertTrue("Should have received the third message", enumeration.hasMoreElements());
    assertEquals(outbound[2], (Message) enumeration.nextElement());

    // There should be no more.
    boolean tooMany = false;
    while (enumeration.hasMoreElements()) {
        LOG.info("Got extra message: " + ((TextMessage) enumeration.nextElement()).getText());
        tooMany = true;
    }
    assertFalse(tooMany);
    browser.close();

    // Re-open the consumer.
    consumer = session.createConsumer(destination);
    // Receive the second.
    assertEquals(outbound[1], consumer.receive(1000));
    // Receive the third.
    assertEquals(outbound[2], consumer.receive(1000));
    consumer.close();

}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseReceive() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();//from   w w w .  ja v a  2s  .  c  o m

    Message[] outbound = new Message[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // browse the first message
    assertTrue("should have received the first message", enumeration.hasMoreElements());
    assertEquals(outbound[0], (Message) enumeration.nextElement());

    // Receive the first message.
    assertEquals(outbound[0], consumer.receive(1000));
    consumer.close();
    browser.close();
    producer.close();

}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testQueueBrowserWith2Consumers() throws Exception {
    final int numMessages = 1000;
    //        connection.setAlwaysSyncSend(false);
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");
    ActiveMQQueue destinationPrefetch10 = new ActiveMQQueue("TEST?jms.prefetchSize=10");
    ActiveMQQueue destinationPrefetch1 = new ActiveMQQueue("TEST?jms.prefetchsize=1");
    connection.start();/*  w ww  .  j ava2s .  c o  m*/

    Connection connection2 = factory.createConnection(userName, password);
    connection2.start();
    connections.add(connection2);
    Session session2 = connection2.createSession(false, Session.AUTO_ACKNOWLEDGE);

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

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

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

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

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

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

    assertFalse("nothing left in the browser", browserView.hasMoreElements());
    assertNull("consumer finished", consumer.receiveNoWait());
}

From source file:org.apache.activemq.apollo.JmsQueueBrowserTest.java

public void testBrowseClose() throws Exception {
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    ActiveMQQueue destination = new ActiveMQQueue("TEST");

    connection.start();/*from   ww  w.j  a  va  2 s. c  o m*/

    TextMessage[] outbound = new TextMessage[] { session.createTextMessage("First Message"),
            session.createTextMessage("Second Message"), session.createTextMessage("Third Message") };

    MessageProducer producer = session.createProducer(destination);
    producer.send(outbound[0]);
    producer.send(outbound[1]);
    producer.send(outbound[2]);

    // create browser first
    QueueBrowser browser = session.createBrowser((Queue) destination);
    Enumeration enumeration = browser.getEnumeration();

    // browse some messages
    assertEquals(outbound[0], (Message) enumeration.nextElement());
    assertEquals(outbound[1], (Message) enumeration.nextElement());
    //assertEquals(outbound[2], (Message) enumeration.nextElement());

    browser.close();

    // create consumer
    MessageConsumer consumer = session.createConsumer(destination);

    // Receive the first message.
    TextMessage msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[0].getText() + " but received " + msg.getText(), outbound[0], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[1].getText() + " but received " + msg.getText(), outbound[1], msg);
    msg = (TextMessage) consumer.receive(1000);
    assertEquals("Expected " + outbound[2].getText() + " but received " + msg.getText(), outbound[2], msg);

    consumer.close();
    producer.close();

}

From source file:org.apache.activemq.leveldb.test.ReplicatedLevelDBBrokerTest.java

private ArrayList<String> browseMessagesViaJMS(BrokerService brokerService) throws Exception {
    ArrayList<String> rc = new ArrayList<String>();
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(
            "tcp://localhost:" + connectPort(brokerService));
    Connection connection = factory.createConnection();
    try {//from www . j a v  a  2 s .  c o  m
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        QueueBrowser browser = session.createBrowser(session.createQueue("FOO"));
        Enumeration enumeration = browser.getEnumeration();
        while (enumeration.hasMoreElements()) {
            TextMessage textMessage = (TextMessage) enumeration.nextElement();
            rc.add(textMessage.getText());
        }
    } finally {
        connection.close();
    }
    return rc;
}

From source file:org.apache.activemq.network.BrokerNetworkWithStuckMessagesTest.java

@SuppressWarnings({ "unchecked", "unused" })
private Object[] browseQueueWithJms(BrokerService broker) throws Exception {
    Object[] messages = null;//  w  ww . j a  va2s .c  o  m
    Connection connection = null;
    Session session = null;

    try {
        URI brokerUri = connector.getUri();
        ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(brokerUri.toString());
        connection = connectionFactory.createConnection();
        connection.start();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue(queueName);
        QueueBrowser browser = session.createBrowser(destination);
        List<Message> list = new ArrayList<Message>();
        for (Enumeration<Message> enumn = browser.getEnumeration(); enumn.hasMoreElements();) {
            list.add(enumn.nextElement());
        }
        messages = list.toArray();
    } finally {
        if (session != null) {
            session.close();
        }
        if (connection != null) {
            connection.close();
        }
    }
    LOG.info("+Browsed with JMS: " + messages.length);

    return messages;
}

From source file:org.apache.james.queue.jms.JMSMailQueue.java

@Override
@SuppressWarnings("unchecked")
public MailQueueIterator browse() throws MailQueueException {
    QueueBrowser browser = null;
    try {/*  w  w w.j  a  v a2 s. co m*/
        browser = session.createBrowser(queue);

        Enumeration<Message> messages = browser.getEnumeration();
        QueueBrowser myBrowser = browser;

        return new MailQueueIterator() {

            @Override
            public void remove() {
                throw new UnsupportedOperationException("Read-only");
            }

            @Override
            public MailQueueItemView next() {
                while (hasNext()) {
                    try {
                        Message m = messages.nextElement();
                        return new MailQueueItemView(createMail(m), nextDeliveryDate(m));
                    } catch (MessagingException | JMSException e) {
                        LOGGER.error("Unable to browse queue", e);
                    }
                }

                throw new NoSuchElementException();
            }

            private ZonedDateTime nextDeliveryDate(Message m) throws JMSException {
                long nextDeliveryTimestamp = m.getLongProperty(JAMES_NEXT_DELIVERY);
                return Instant.ofEpochMilli(nextDeliveryTimestamp).atZone(ZoneId.systemDefault());
            }

            @Override
            public boolean hasNext() {
                return messages.hasMoreElements();
            }

            @Override
            public void close() {
                closeBrowser(myBrowser);
            }
        };

    } catch (Exception e) {
        closeBrowser(browser);

        LOGGER.error("Unable to browse queue {}", queueName, e);
        throw new MailQueueException("Unable to browse queue " + queueName, e);
    }
}

From source file:org.dhatim.routing.jms.JMSRouter.java

private int getQueueLength(QueueBrowser queueBrowser) throws JMSException {
    int length = 0;
    Enumeration queueEnum = queueBrowser.getEnumeration();
    while (queueEnum.hasMoreElements()) {
        length++;// www  .  j a  va 2  s.  co  m
        queueEnum.nextElement();
    }
    return length;
}

From source file:org.easybatch.jms.JmsIntegrationTest.java

@Test
public void testJmsRecordWriter() throws Exception {
    Context jndiContext = getJndiContext();
    Queue queue = (Queue) jndiContext.lookup("q");
    QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) jndiContext
            .lookup("QueueConnectionFactory");
    QueueConnection queueConnection = queueConnectionFactory.createQueueConnection();
    QueueSession queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    queueConnection.start();//from  w ww  .j a va 2 s.c o  m

    String dataSource = "foo" + LINE_SEPARATOR + "bar";

    aNewJob().reader(new StringRecordReader(dataSource)).processor(new JmsMessageTransformer(queueSession))
            .writer(new JmsQueueRecordWriter(queueConnectionFactory, queue)).call();

    // Assert that queue contains 2 messages: "foo" and "bar"
    QueueBrowser queueBrowser = queueSession.createBrowser(queue);
    Enumeration enumeration = queueBrowser.getEnumeration();

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message1 = (TextMessage) enumeration.nextElement();
    assertThat(message1.getText()).isEqualTo("foo");

    assertThat(enumeration.hasMoreElements()).isTrue();
    TextMessage message2 = (TextMessage) enumeration.nextElement();
    assertThat(message2.getText()).isEqualTo("bar");

    assertThat(enumeration.hasMoreElements()).isFalse();

    queueSession.close();
    queueConnection.close();
}