Example usage for javax.jms Session createBrowser

List of usage examples for javax.jms Session createBrowser

Introduction

In this page you can find the example usage for javax.jms Session createBrowser.

Prototype

QueueBrowser createBrowser(Queue queue) throws JMSException;

Source Link

Document

Creates a QueueBrowser object to peek at the messages on the specified queue.

Usage

From source file:example.browser.Browser.java

public static void main(String[] args) {
    String url = BROKER_URL;
    if (args.length > 0) {
        url = args[0].trim();/*from   ww  w  .  j  a  v a2  s. c o  m*/
    }
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("admin", "password", url);
    Connection connection = null;

    try {

        connection = connectionFactory.createConnection();
        connection.start();

        Session session = connection.createSession(NON_TRANSACTED, Session.AUTO_ACKNOWLEDGE);
        Queue destination = session.createQueue("test-queue");
        QueueBrowser browser = session.createBrowser(destination);
        Enumeration enumeration = browser.getEnumeration();

        while (enumeration.hasMoreElements()) {
            TextMessage message = (TextMessage) enumeration.nextElement();
            System.out.println("Browsing: " + message);
            TimeUnit.MILLISECONDS.sleep(DELAY);
        }

        session.close();

    } catch (Exception e) {
        System.out.println("Caught exception!");
    } finally {
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
                System.out.println("Could not close an open connection...");
            }
        }
    }
}

From source file:nl.nn.adapterframework.extensions.tibco.GetTibcoQueues.java

private String getQueueMessage(Session jSession, TibjmsAdmin admin, String queueName, int queueItem,
        LdapSender ldapSender) throws TibjmsAdminException, JMSException {
    QueueInfo qInfo = admin.getQueue(queueName);
    if (qInfo == null) {
        throw new JMSException(" queue [" + queueName + "] does not exist");
    }//w ww.j  av a 2 s .c o  m

    XmlBuilder qMessageXml = new XmlBuilder("qMessage");
    ServerInfo serverInfo = admin.getInfo();
    String url = serverInfo.getURL();
    qMessageXml.addAttribute("url", url);
    String resolvedUrl = getResolvedUrl(url);
    if (resolvedUrl != null) {
        qMessageXml.addAttribute("resolvedUrl", resolvedUrl);
    }
    qMessageXml.addAttribute("timestamp", DateUtils.getIsoTimeStamp());
    qMessageXml.addAttribute("startTime", DateUtils.format(serverInfo.getStartTime(), DateUtils.fullIsoFormat));
    XmlBuilder qNameXml = new XmlBuilder("qName");
    qNameXml.setCdataValue(queueName);

    Queue queue = jSession.createQueue(queueName);
    QueueBrowser queueBrowser = null;
    try {
        queueBrowser = jSession.createBrowser(queue);
        Enumeration enm = queueBrowser.getEnumeration();
        int count = 0;
        boolean found = false;
        String chompCharSizeString = AppConstants.getInstance().getString("browseQueue.chompCharSize", null);
        int chompCharSize = (int) Misc.toFileSize(chompCharSizeString, -1);

        while (enm.hasMoreElements() && !found) {
            count++;
            if (count == queueItem) {
                qNameXml.addAttribute("item", count);
                Object o = enm.nextElement();
                if (o instanceof Message) {
                    Message msg = (Message) o;
                    XmlBuilder qMessageId = new XmlBuilder("qMessageId");
                    qMessageId.setCdataValue(msg.getJMSMessageID());
                    qMessageXml.addSubElement(qMessageId);
                    XmlBuilder qTimestamp = new XmlBuilder("qTimestamp");
                    qTimestamp.setCdataValue(DateUtils.format(msg.getJMSTimestamp(), DateUtils.fullIsoFormat));
                    qMessageXml.addSubElement(qTimestamp);

                    StringBuffer sb = new StringBuffer("");
                    Enumeration propertyNames = msg.getPropertyNames();
                    while (propertyNames.hasMoreElements()) {
                        String propertyName = (String) propertyNames.nextElement();
                        Object object = msg.getObjectProperty(propertyName);
                        if (sb.length() > 0) {
                            sb.append("; ");
                        }
                        sb.append(propertyName);
                        sb.append("=");
                        sb.append(object);
                    }
                    XmlBuilder qPropsXml = new XmlBuilder("qProps");
                    qPropsXml.setCdataValue(sb.toString());

                    qMessageXml.addSubElement(qPropsXml);
                    XmlBuilder qTextXml = new XmlBuilder("qText");
                    String msgText;
                    try {
                        TextMessage textMessage = (TextMessage) msg;
                        msgText = textMessage.getText();
                    } catch (ClassCastException e) {
                        msgText = msg.toString();
                        qTextXml.addAttribute("text", false);
                    }
                    int msgSize = msgText.length();
                    if (isHideMessage()) {
                        qTextXml.setCdataValue("***HIDDEN***");
                    } else {
                        if (chompCharSize >= 0 && msgSize > chompCharSize) {
                            qTextXml.setCdataValue(msgText.substring(0, chompCharSize) + "...");
                            qTextXml.addAttribute("chomped", true);
                        } else {
                            qTextXml.setCdataValue(msgText);
                        }
                    }
                    qMessageXml.addSubElement(qTextXml);
                    XmlBuilder qTextSizeXml = new XmlBuilder("qTextSize");
                    qTextSizeXml.setValue(Misc.toFileSize(msgSize));
                    qMessageXml.addSubElement(qTextSizeXml);
                }
                found = true;
            } else {
                enm.nextElement();
            }
        }
    } finally {
        if (queueBrowser != null) {
            try {
                queueBrowser.close();
            } catch (JMSException e) {
                log.warn(getLogPrefix(null) + "exception on closing queue browser", e);
            }
        }
    }

    qMessageXml.addSubElement(qNameXml);

    Map aclMap = getAclMap(admin, ldapSender);
    XmlBuilder aclXml = new XmlBuilder("acl");
    XmlBuilder qInfoXml = qInfoToXml(qInfo);
    aclXml.setValue((String) aclMap.get(qInfo.getName()));
    qInfoXml.addSubElement(aclXml);
    qMessageXml.addSubElement(qInfoXml);

    Map consumersMap = getConnectedConsumersMap(admin);
    XmlBuilder consumerXml = new XmlBuilder("connectedConsumers");
    if (consumersMap.containsKey(qInfo.getName())) {
        LinkedList<String> consumers = (LinkedList<String>) consumersMap.get(qInfo.getName());
        String consumersString = listToString(consumers);
        if (consumersString != null) {
            consumerXml.setCdataValue(consumersString);
        }
    }
    qInfoXml.addSubElement(consumerXml);

    return qMessageXml.toXML();
}

From source file:nl.nn.adapterframework.extensions.tibco.TibcoUtils.java

protected static long getQueueFirstMessageAge(Session jSession, String queueName, String messageSelector,
        long currentTime, boolean warn) throws JMSException {
    QueueBrowser queueBrowser = null;//from   ww  w . j a  va  2  s .c om
    try {
        Queue queue = jSession.createQueue(queueName);
        if (messageSelector == null) {
            queueBrowser = jSession.createBrowser(queue);
        } else {
            queueBrowser = jSession.createBrowser(queue, messageSelector);
        }
        Enumeration enm = queueBrowser.getEnumeration();
        if (enm.hasMoreElements()) {
            Object o = enm.nextElement();
            if (o instanceof Message) {
                Message msg = (Message) o;
                long jmsTimestamp = msg.getJMSTimestamp();
                return currentTime - jmsTimestamp;
            } else {
                if (warn) {
                    log.warn("message was not of type Message, but [" + o.getClass().getName() + "]");
                }
                return -2;
            }
        } else {
            return -1;
        }
    } finally {
        if (queueBrowser != null) {
            try {
                queueBrowser.close();
            } catch (JMSException e) {
                log.warn("Exception on closing queueBrowser", e);
            }
        }
    }
}

From source file:nl.nn.adapterframework.extensions.tibco.TibcoUtils.java

protected static long getQueueMessageCount(Session jSession, String queueName, String messageSelector)
        throws JMSException {
    QueueBrowser queueBrowser = null;/*from ww w .  j  a v a2s  .c  om*/
    try {
        Queue queue = jSession.createQueue(queueName);
        if (messageSelector == null) {
            queueBrowser = jSession.createBrowser(queue);
        } else {
            queueBrowser = jSession.createBrowser(queue, messageSelector);
        }
        int count = 0;
        for (Enumeration enm = queueBrowser.getEnumeration(); enm.hasMoreElements(); enm.nextElement()) {
            count++;
        }
        return count;
    } finally {
        if (queueBrowser != null) {
            try {
                queueBrowser.close();
            } catch (JMSException e) {
                log.warn("Exception on closing queueBrowser", e);
            }
        }
    }
}

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

public int getMessageCount() throws ListenerException {
    QueueBrowser queueBrowser = null;/*www  . ja  va2 s. com*/
    Session session = null;
    try {
        session = createSession();
        if (StringUtils.isEmpty(getSelector())) {
            queueBrowser = session.createBrowser((Queue) getDestination());
        } else {
            queueBrowser = session.createBrowser((Queue) getDestination(), getSelector());
        }
        int count = 0;
        for (Enumeration enm = queueBrowser.getEnumeration(); enm.hasMoreElements(); enm.nextElement()) {
            count++;
        }
        return count;
    } catch (Exception e) {
        throw new ListenerException("cannot determin messagecount", e);
    } finally {
        try {
            if (queueBrowser != null) {
                queueBrowser.close();
            }
        } catch (JMSException e) {
            throw new ListenerException("error closing queuebrowser", e);
        }
        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 a2 s  . c  om
 */
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();/* w w w .j  a va 2 s  . co  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();/*from   ww  w  .j a  v a  2  s . co  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 w w  w.j a va2 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 {// w ww . j  a  va  2s.com
        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;
}