Example usage for javax.jms MessageConsumer receive

List of usage examples for javax.jms MessageConsumer receive

Introduction

In this page you can find the example usage for javax.jms MessageConsumer receive.

Prototype


Message receive(long timeout) throws JMSException;

Source Link

Document

Receives the next message that arrives within the specified timeout interval.

Usage

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private void tryConsumeExpectNone(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();//from   ww w.j  a va 2s  .  c o m
    if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) != null) {
        fail("Should be no messages for this durable.");
    }
    consumer.close();
    connection.close();
}

From source file:org.apache.activemq.store.kahadb.SubscriptionRecoveryTest.java

private int consumeFromInactiveDurableSub(Topic topic) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    connection.start();//from   www .  j av a  2  s .com
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");

    int count = 0;

    while (consumer.receive(10000) != null) {
        count++;
    }

    consumer.close();
    connection.close();

    return count;
}

From source file:org.apache.activemq.store.jdbc.JmsTransactionCommitFailureTest.java

private Message receiveMessage(String queueName, long receiveTimeout) throws JMSException {
    Message message = null;/*from   www .j a  va2  s  .c  o  m*/
    Connection con = connectionFactory.createConnection();
    try {
        con.start();
        try {
            Session session = con.createSession(true, Session.SESSION_TRANSACTED);
            try {
                Queue destination = session.createQueue(queueName);
                MessageConsumer consumer = session.createConsumer(destination);
                try {
                    message = consumer.receive(receiveTimeout);
                    session.commit();
                } finally {
                    consumer.close();
                }
            } finally {
                session.close();
            }
        } finally {
            con.stop();
        }
    } finally {
        con.close();
    }
    return message;
}

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

public void deleteMessage(String messageId) throws ListenerException {
    Session session = null;//w w w  .ja v a2 s  .c  o m
    MessageConsumer mc = null;
    try {
        session = createSession();
        log.debug("retrieving message [" + messageId + "] in order to delete it");
        mc = getMessageConsumer(session, getDestination(), getCombinedSelector(messageId));
        mc.receive(getTimeOut());
    } catch (Exception e) {
        throw new ListenerException(e);
    } finally {
        try {
            if (mc != null) {
                mc.close();
            }
        } catch (JMSException e1) {
            throw new ListenerException("exception closing message consumer", e1);
        }
        closeSession(session);
    }
}

From source file:org.codehaus.stomp.jms.StompSession.java

public Message receiveFromJms(String destinationName, Map headers)
        throws JMSException, ProtocolException, NamingException {
    long ttl = getTimeToLive(headers);
    log.trace("Consuming message - ttl=" + ttl);
    Destination destination = convertDestination(destinationName, true);
    MessageConsumer consumer = session.createConsumer(destination);
    Message message;/*from   w w  w.j  a  v a2  s  .co  m*/
    if (ttl > 0) {
        message = consumer.receive(ttl);
    } else {
        message = consumer.receive();
    }
    if (message != null) {
        // As this is a dequeue, automatically acknowledge the message
        message.acknowledge();
    }
    consumer.close();
    log.trace("Received message: " + message);
    return message;
}

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  www  .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.store.kahadb.SubscriptionRecoveryTest.java

private void consumeDurableMessages(Topic topic, int count) throws Exception {
    Connection connection = cf.createConnection();
    connection.setClientID("Inactive");
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    MessageConsumer consumer = session.createDurableSubscriber(topic, "Inactive");
    connection.start();// w  ww.  ja v a2 s.  com
    for (int i = 0; i < count; ++i) {
        if (consumer.receive(TimeUnit.SECONDS.toMillis(10)) == null) {
            fail("should have received a message");
        }
    }
    consumer.close();
    connection.close();
}

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

/**
 * Retrieves messages from queue or other channel under transaction control, but does no processing on it.
 *///from  w ww. ja  v  a2  s  .  c  o m
private Object getRawMessageFromDestination(String correlationId, Map threadContext) throws ListenerException {
    Session session = null;
    Object msg = null;
    try {
        session = getSession(threadContext);
        MessageConsumer mc = null;
        try {
            mc = getReceiver(threadContext, session, correlationId);
            msg = mc.receive(getTimeOut());
            while (msg == null && correlationId == null && canGoOn() && !isTransacted()) {
                msg = mc.receive(getTimeOut());
            }
        } catch (JMSException e) {
            throw new ListenerException(getLogPrefix() + "exception retrieving message", e);
        } finally {
            releaseReceiver(mc, correlationId);
        }
    } finally {
        if (sessionNeedsToBeSavedForAfterProcessMessage(msg)) {
            threadContext.put(THREAD_CONTEXT_SESSION_KEY, session);
        } else {
            releaseSession(session);
        }
    }
    return msg;
}

From source file:org.apache.activemq.bugs.AMQ7118Test.java

@Test
public void testCompaction() throws Exception {
    CountDownLatch latch = new CountDownLatch(1);

    setupProducerConnection();//from   w  w w.j a  v  a 2  s . com
    setupConsumerConnection();

    Topic topic = pSession.createTopic("test");

    MessageConsumer consumer = cSession.createDurableSubscriber(topic, "clientId1");

    LOG.info("Produce message to test topic");
    produce(pSession, topic, 1, 512); // just one message

    LOG.info("Consume message from test topic");
    Message msg = consumer.receive(5000);
    assertNotNull(msg);

    LOG.info("Produce more messages to test topic and get into PFC");
    boolean sent = produce(cSession, topic, 20, 512 * 1024); // Fill the store

    assertFalse("Never got to PFC condition", sent);

    LOG.info("PFC hit");

    //We hit PFC, so shut down the producer
    producerConnection.close();

    //Lets check the db-*.log file count before checkpointUpdate
    checkFiles(false, 21, "db-21.log");

    // Force checkFiles update
    checkFiles(true, 23, "db-23.log");

    //The ackMessageFileMap should be clean, so no more writing
    checkFiles(true, 23, "db-23.log");

    //One more time just to be sure - The ackMessageFileMap should be clean, so no more writing
    checkFiles(true, 23, "db-23.log");

    //Read out the rest of the messages
    LOG.info("Consuming the rest of the files...");
    for (int i = 0; i < 20; i++) {
        msg = consumer.receive(5000);
    }
    LOG.info("All messages Consumed.");

    //Clean up the log files and be sure its stable
    checkFiles(true, 2, "db-33.log");
    checkFiles(true, 3, "db-34.log");
    checkFiles(true, 2, "db-34.log");
    checkFiles(true, 2, "db-34.log");
    checkFiles(true, 2, "db-34.log");

    broker.stop();
    broker.waitUntilStopped();
}

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  . ja  v a 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();
    }

}