Example usage for javax.jms QueueSession createBrowser

List of usage examples for javax.jms QueueSession createBrowser

Introduction

In this page you can find the example usage for javax.jms QueueSession 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:org.dawnsci.commandserver.mx.example.ActiveMQProducer.java

public static void main(String[] args) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade
            .createConnectionFactory("tcp://ws097.diamond.ac.uk:61616");
    Connection send = connectionFactory.createConnection();

    Session session = send.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue("testQ");

    final MessageProducer producer = session.createProducer(queue);
    producer.setDeliveryMode(DeliveryMode.PERSISTENT);

    Message message = session.createTextMessage("Hello World");
    producer.send(message);/*from ww w. ja  va  2  s  . co  m*/

    message = session.createTextMessage("...and another message");
    producer.send(message);

    message = session.createObjectMessage(new TestObjectBean("this could be", "anything"));
    producer.send(message);

    // Test JSON
    SweepBean col = new SweepBean("fred", "d0000000001", 0, 100);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(col);

    message = session.createTextMessage(jsonString);
    producer.send(message);

    producer.close();
    session.close();
    send.close();

    // Now we peak at the queue
    // If the consumer is not going, the messages should still be there
    if (REQUIRE_PEAK) {
        QueueConnection qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        queue = qSes.createQueue("testQ");
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);
        Enumeration e = qb.getEnumeration();
        if (e.hasMoreElements())
            System.out.println("Peak at queue:");
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;
                System.out.println(t.getText());
            } else if (m instanceof ObjectMessage) {
                ObjectMessage o = (ObjectMessage) m;
                System.out.println(o.getObject());
            }
        }

        qb.close();
        qSes.close();
        qCon.close();
    }

}

From source file:org.dawnsci.commandserver.core.consumer.RemoteSubmission.java

/**
 * Monitors a given bean in the status queue. 
 * If the bean is not there throws exception.
 * If the bean is in a final state, returns the bean straight away.
 * /* ww  w.  j  a v a 2  s  . c o m*/
 * Polls the queue for the unique id of the bean we want until it
 * encounters a final state of that bean.
 * 
 * Polling rate is less than 1s
 * 
 * NOTE this class can poll forever if the job it is looking at never finishes.
 * 
 * @param obean
 * @param string
 * @return the bean once it is in a final state.
 * @throws exception if broker or queue absent
 */
public StatusBean monitor(StatusBean obean) throws Exception {

    if (getQueueName() == null || "".equals(getQueueName()))
        throw new Exception("Please specify a queue name!");

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);

    Class clazz = obean.getClass();
    ObjectMapper mapper = new ObjectMapper();

    try {
        POLL: while (true) {

            Thread.sleep(500);

            @SuppressWarnings("rawtypes")
            Enumeration e = qb.getEnumeration();

            while (e.hasMoreElements()) { // We must final the bean somewhere.
                Message m = (Message) e.nextElement();
                if (m == null)
                    continue;
                if (m instanceof TextMessage) {
                    TextMessage t = (TextMessage) m;
                    final StatusBean bean = mapper.readValue(t.getText(), clazz);
                    if (bean.getUniqueId().equals(obean.getUniqueId())) {
                        if (bean.getStatus().isFinal())
                            return bean;
                        System.out.println(bean.getPercentComplete());
                        continue POLL;
                    }
                }
            }

            throw new Exception(
                    "The bean with id " + obean.getUniqueId() + " does not exist in " + getQueueName() + "!");

        }
    } finally {
        qCon.close();
    }
}

From source file:org.dawnsci.commandserver.core.producer.ProcessConsumer.java

/**
 * Parse the queue for stale jobs and things that should be rerun.
 * @param bean/* w w  w.j  a  va  2 s .co  m*/
 * @throws Exception 
 */
private void processStatusQueue(URI uri, String statusQName) throws Exception {

    QueueConnection qCon = null;

    try {
        QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
        qCon = connectionFactory.createQueueConnection();
        QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Queue queue = qSes.createQueue(statusQName);
        qCon.start();

        QueueBrowser qb = qSes.createBrowser(queue);

        @SuppressWarnings("rawtypes")
        Enumeration e = qb.getEnumeration();

        ObjectMapper mapper = new ObjectMapper();

        Map<String, StatusBean> failIds = new LinkedHashMap<String, StatusBean>(7);
        List<String> removeIds = new ArrayList<String>(7);
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                try {
                    @SuppressWarnings("unchecked")
                    final StatusBean qbean = mapper.readValue(t.getText(), getBeanClass());
                    if (qbean == null)
                        continue;
                    if (qbean.getStatus() == null)
                        continue;
                    if (!qbean.getStatus().isStarted()) {
                        failIds.put(t.getJMSMessageID(), qbean);
                        continue;
                    }

                    // If it has failed, we clear it up
                    if (qbean.getStatus() == Status.FAILED) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }
                    if (qbean.getStatus() == Status.NONE) {
                        removeIds.add(t.getJMSMessageID());
                        continue;
                    }

                    // If it is running and older than a certain time, we clear it up
                    if (qbean.getStatus() == Status.RUNNING) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumRunningAge()) {
                            removeIds.add(t.getJMSMessageID());
                            continue;
                        }
                    }

                    if (qbean.getStatus().isFinal()) {
                        final long submitted = qbean.getSubmissionTime();
                        final long current = System.currentTimeMillis();
                        if (current - submitted > getMaximumCompleteAge()) {
                            removeIds.add(t.getJMSMessageID());
                        }
                    }

                } catch (Exception ne) {
                    System.out.println("Message " + t.getText() + " is not legal and will be removed.");
                    removeIds.add(t.getJMSMessageID());
                }
            }
        }

        // We fail the non-started jobs now - otherwise we could
        // actually start them late. TODO check this
        final List<String> ids = new ArrayList<String>();
        ids.addAll(failIds.keySet());
        ids.addAll(removeIds);

        if (ids.size() > 0) {

            for (String jMSMessageID : ids) {
                MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
                Message m = consumer.receive(1000);
                if (removeIds.contains(jMSMessageID))
                    continue; // We are done

                if (m != null && m instanceof TextMessage) {
                    MessageProducer producer = qSes.createProducer(queue);
                    final StatusBean bean = failIds.get(jMSMessageID);
                    bean.setStatus(Status.FAILED);
                    producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));

                    System.out.println("Failed job " + bean.getName() + " messageid(" + jMSMessageID + ")");

                }
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java

protected Collection<StatusBean> getStatusBeans(final URI uri, final String queueName,
        final IProgressMonitor monitor) throws Exception {

    QueueConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    monitor.worked(1);/*  w  ww .  java  2s  .  c  o m*/
    QueueConnection qCon = connectionFactory.createQueueConnection(); // This times out when the server is not there.
    QueueSession qSes = qCon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = qSes.createQueue(queueName);
    qCon.start();

    QueueBrowser qb = qSes.createBrowser(queue);
    monitor.worked(1);

    @SuppressWarnings("rawtypes")
    Enumeration e = qb.getEnumeration();

    Class clazz = getBeanClass();
    ObjectMapper mapper = new ObjectMapper();

    final Collection<StatusBean> list = new TreeSet<StatusBean>(new Comparator<StatusBean>() {
        @Override
        public int compare(StatusBean o1, StatusBean o2) {
            // Newest first!
            long t1 = o2.getSubmissionTime();
            long t2 = o1.getSubmissionTime();
            return (t1 < t2 ? -1 : (t1 == t2 ? 0 : 1));
        }
    });

    while (e.hasMoreElements()) {
        Message m = (Message) e.nextElement();
        if (m == null)
            continue;
        if (m instanceof TextMessage) {
            TextMessage t = (TextMessage) m;
            final StatusBean bean = mapper.readValue(t.getText(), clazz);
            list.add(bean);
        }
    }
    return list;
}

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

private void waitWhileAboveHighWaterMark() throws JMSException, SmooksRoutingException {
    if (highWaterMark == -1) {
        return;//  www.  j  a v a2  s  .co m
    }

    if (session instanceof QueueSession) {
        QueueSession queueSession = (QueueSession) session;
        QueueBrowser queueBrowser = queueSession.createBrowser((Queue) destination);

        try {
            int length = getQueueLength(queueBrowser);
            long start = System.currentTimeMillis();

            if (logger.isDebugEnabled() && length >= highWaterMark) {
                logger.debug("Length of JMS destination Queue '" + jmsProperties.getDestinationName()
                        + "' has reached " + length + ".  High Water Mark is " + highWaterMark
                        + ".  Waiting for Queue length to drop.");
            }

            while (length >= highWaterMark && (System.currentTimeMillis() < start + highWaterMarkTimeout)) {
                try {
                    Thread.sleep(highWaterMarkPollFrequency);
                } catch (InterruptedException e) {
                    logger.error("Interrupted", e);
                    return;
                }
                length = getQueueLength(queueBrowser);
            }

            // Check did the queue length drop below the HWM...
            if (length >= highWaterMark) {
                throw new SmooksRoutingException("Failed to route JMS message to Queue destination '"
                        + ((Queue) destination).getQueueName() + "'. Timed out (" + highWaterMarkTimeout
                        + " ms) waiting for queue length to drop below High Water Mark (" + highWaterMark
                        + ").  Consider increasing 'highWaterMark' and/or 'highWaterMarkTimeout' param values.");
            }
        } finally {
            queueBrowser.close();
        }
    }
}

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  w  w  .  jav  a2 s . c  om*/

    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();
}