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:ConsumerTool.java

protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer,
        long timeout) throws JMSException, IOException {
    System.out.println(/*www  .  j  av  a  2 s  .  c o  m*/
            "[" + this.getName() + "] We will consume messages while they continue to be delivered within: "
                    + timeout + " ms, and then we will shutdown");

    Message message;
    while ((message = consumer.receive(timeout)) != null) {
        onMessage(message);
    }

    System.out.println("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
    if (pauseBeforeShutdown) {
        System.out.println("[" + this.getName() + "] Press return to shut down");
        System.in.read();
    }
}

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  w  ww.j a v  a2s  .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:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Comsume messages and close the connection. */
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer,
        long timeout) throws JMSException, IOException {
    LOG.info("[" + this.getName() + "] consume messages while continue to be delivered within: " + timeout
            + " ms, and then we will shutdown");
    Message message;//from  w  w  w.j av a  2  s.c o  m
    while ((message = consumer.receive(timeout)) != null) {
        onMessage(message);
    }
    LOG.info("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
}

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

public String sendMessage(String correlationID, String message, ParameterResolutionContext prc,
        String soapHeader) throws SenderException, TimeOutException {
    Session s = null;/*from  w  w  w  .j  a  v a 2s  .  c o m*/
    MessageProducer mp = null;

    ParameterValueList pvl = null;
    if (prc != null && paramList != null) {
        try {
            pvl = prc.getValues(paramList);
        } catch (ParameterException e) {
            throw new SenderException(getLogPrefix() + "cannot extract parameters", e);
        }
    }

    if (isSoap()) {
        if (soapHeader == null) {
            if (pvl != null && StringUtils.isNotEmpty(getSoapHeaderParam())) {
                ParameterValue soapHeaderParamValue = pvl.getParameterValue(getSoapHeaderParam());
                if (soapHeaderParamValue == null) {
                    log.warn("no SoapHeader found using parameter [" + getSoapHeaderParam() + "]");
                } else {
                    soapHeader = soapHeaderParamValue.asStringValue("");
                }
            }
        }
        message = soapWrapper.putInEnvelope(message, getEncodingStyleURI(), getServiceNamespaceURI(),
                soapHeader);
        if (log.isDebugEnabled())
            log.debug(getLogPrefix() + "correlationId [" + correlationID + "] soap message [" + message + "]");
    }
    try {
        s = createSession();
        mp = getMessageProducer(s, getDestination(prc));
        Destination replyQueue = null;

        // create message
        Message msg = createTextMessage(s, correlationID, message);

        if (getMessageType() != null) {
            msg.setJMSType(getMessageType());
        }
        if (getDeliveryModeInt() > 0) {
            msg.setJMSDeliveryMode(getDeliveryModeInt());
            mp.setDeliveryMode(getDeliveryModeInt());
        }
        if (getPriority() >= 0) {
            msg.setJMSPriority(getPriority());
            mp.setPriority(getPriority());
        }

        // set properties
        if (pvl != null) {
            setProperties(msg, pvl);
        }
        if (replyToName != null) {
            replyQueue = getDestination(replyToName);
        } else {
            if (isSynchronous()) {
                replyQueue = getMessagingSource().getDynamicReplyQueue(s);
            }
        }
        if (replyQueue != null) {
            msg.setJMSReplyTo(replyQueue);
            if (log.isDebugEnabled())
                log.debug("replyTo set to queue [" + replyQueue.toString() + "]");
        }

        // send message   
        send(mp, msg);
        if (log.isDebugEnabled()) {
            log.debug("[" + getName() + "] " + "sent message [" + message + "] " + "to [" + mp.getDestination()
                    + "] " + "msgID [" + msg.getJMSMessageID() + "] " + "correlationID ["
                    + msg.getJMSCorrelationID() + "] " + "using deliveryMode [" + getDeliveryMode() + "] "
                    + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
        } else {
            if (log.isInfoEnabled()) {
                log.info("[" + getName() + "] " + "sent message to [" + mp.getDestination() + "] " + "msgID ["
                        + msg.getJMSMessageID() + "] " + "correlationID [" + msg.getJMSCorrelationID() + "] "
                        + "using deliveryMode [" + getDeliveryMode() + "] "
                        + ((replyToName != null) ? "replyTo [" + replyToName + "]" : ""));
            }
        }
        if (isSynchronous()) {
            String replyCorrelationId = null;
            if (replyToName != null) {
                if ("CORRELATIONID".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = correlationID;
                } else if ("CORRELATIONID_FROM_MESSAGE".equalsIgnoreCase(getLinkMethod())) {
                    replyCorrelationId = msg.getJMSCorrelationID();
                } else {
                    replyCorrelationId = msg.getJMSMessageID();
                }
            }
            if (log.isDebugEnabled())
                log.debug("[" + getName() + "] start waiting for reply on [" + replyQueue + "] requestMsgId ["
                        + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId + "] for ["
                        + getReplyTimeout() + "] ms");
            MessageConsumer mc = getMessageConsumerForCorrelationId(s, replyQueue, replyCorrelationId);
            try {
                Message rawReplyMsg = mc.receive(getReplyTimeout());
                if (rawReplyMsg == null) {
                    throw new TimeOutException("did not receive reply on [" + replyQueue + "] requestMsgId ["
                            + msg.getJMSMessageID() + "] replyCorrelationId [" + replyCorrelationId
                            + "] within [" + getReplyTimeout() + "] ms");
                }
                return getStringFromRawMessage(rawReplyMsg, prc != null ? prc.getSession() : null, isSoap(),
                        getReplySoapHeaderSessionKey(), soapWrapper);
            } finally {
                if (mc != null) {
                    try {
                        mc.close();
                    } catch (JMSException e) {
                        log.warn("JmsSender [" + getName()
                                + "] got exception closing message consumer for reply", e);
                    }
                }
            }
        }
        return msg.getJMSMessageID();
    } catch (JMSException e) {
        throw new SenderException(e);
    } catch (IOException e) {
        throw new SenderException(e);
    } catch (NamingException e) {
        throw new SenderException(e);
    } catch (DomBuilderException e) {
        throw new SenderException(e);
    } catch (TransformerException e) {
        throw new SenderException(e);
    } catch (JmsException e) {
        throw new SenderException(e);
    } finally {
        if (mp != null) {
            try {
                mp.close();
            } catch (JMSException e) {
                log.warn("JmsSender [" + getName() + "] got exception closing message producer", e);
            }
        }
        closeSession(s);
    }
}

From source file:com.chinamobile.bcbsp.comm.ConsumerTool.java

/** Comsumer messages and close the connection.
 * @throws IOException,JMSException/*from  w w w . j av  a 2s  .c  om*/
 */
protected void consumeMessagesAndClose(Connection connection, Session session, MessageConsumer consumer)
        throws JMSException, IOException {
    LOG.info("[" + this.getName() + "] We are about to wait until we consume: " + maxiumMessages
            + " message(s) then we will shutdown");
    for (int i = 0; i < maxiumMessages && isRunning();) {
        Message message = consumer.receive(1000);
        if (message != null) {
            i++;
            onMessage(message);
        }
    }
    LOG.info("[" + this.getName() + "] Closing connection");
    consumer.close();
    session.close();
    connection.close();
    if (pauseBeforeShutdown) {
        LOG.info("[" + this.getName() + "] Press return to shut down");
        // System.in.read();
    }
}

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

/**
 * WARNING - starts infinite loop - you have to kill 
 * @param uri//from ww  w  .  ja  v a 2s  . com
 * @param submitQName
 * @param statusTName
 * @param statusQName
 * @throws Exception
 */
private void monitorSubmissionQueue(URI uri, String submitQName, String statusTName, String statusQName)
        throws Exception {

    ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri);
    Connection connection = connectionFactory.createConnection();
    Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Queue queue = session.createQueue(submitQName);

    final MessageConsumer consumer = session.createConsumer(queue);
    connection.start();

    System.out.println("Starting consumer for submissions to queue " + submitQName);
    while (isActive()) { // You have to kill it or call stop() to stop it!

        try {

            // Consumes messages from the queue.
            Message m = consumer.receive(1000);
            if (m != null) {

                // TODO FIXME Check if we have the max number of processes
                // exceeded and wait until we dont...

                TextMessage t = (TextMessage) m;
                ObjectMapper mapper = new ObjectMapper();

                final StatusBean bean = mapper.readValue(t.getText(), getBeanClass());

                if (bean != null) { // We add this to the status list so that it can be rendered in the UI

                    if (!isHandled(bean))
                        continue; // Consume it and move on

                    // Now we put the bean in the status queue and we 
                    // start the process
                    RemoteSubmission factory = new RemoteSubmission(uri);
                    factory.setLifeTime(t.getJMSExpiration());
                    factory.setPriority(t.getJMSPriority());
                    factory.setTimestamp(t.getJMSTimestamp());
                    factory.setQueueName(statusQName); // Move the message over to a status queue.

                    factory.submit(bean, false);

                    final ProgressableProcess process = createProcess(uri, statusTName, statusQName, bean);
                    if (process != null) {
                        if (process.isBlocking()) {
                            System.out.println("About to run job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                        processCount++;
                        process.start();
                        if (process.isBlocking()) {
                            System.out.println(
                                    "Ran job " + bean.getName() + " messageid(" + t.getJMSMessageID() + ")");
                        } else {
                            System.out.println("Started job " + bean.getName() + " messageid("
                                    + t.getJMSMessageID() + ")");
                        }
                    }

                }
            }

        } catch (Throwable ne) {
            // Really basic error reporting, they have to pipe to file.
            ne.printStackTrace();
            setActive(false);
        }
    }

}

From source file:com.linagora.obm.sync.TestQueueManager.java

@Test
public void testDurableSubscription2() throws Exception {
    String testText = "test text";
    String clientId = "c1";

    Connection connection = createManagedConnection();
    connection.setClientID(clientId);/* w  w w . j  a va 2s.c  o m*/
    connection.start();
    Session consumerSession = createManagedSession(connection);
    MessageConsumer consumer = queueManager.createDurableConsumerOnTopic(consumerSession, TOPIC, clientId);

    writeMessageOnTopic(testText, TOPIC, queueManager);
    shutdownQueueManager();
    startQueueManager();

    Connection connection2 = createManagedConnection();
    connection2.setClientID(clientId);
    connection2.start();

    consumerSession = createManagedSession(connection2);
    consumer = queueManager.createDurableConsumerOnTopic(consumerSession, TOPIC, clientId);

    TextMessage messageReceived = (TextMessage) consumer.receive(TIMEOUT);
    Assert.assertEquals(testText, messageReceived.getText());
}

From source file:com.linagora.obm.sync.TestQueueManager.java

@Test
public void testDurableSubscription() throws Exception {
    String testText = "test text";
    String clientId = "c1";

    Connection connection = queueManager.createConnection();
    connection.setClientID(clientId);/*from   ww  w . j a  v a2s .c o  m*/
    connection.start();
    Session consumerSession = queueManager.createSession(connection);
    MessageConsumer consumer = queueManager.createDurableConsumerOnTopic(consumerSession, TOPIC, clientId);
    consumerSession.close();
    connection.close();

    writeMessageOnTopic(testText, TOPIC, queueManager);

    Connection connection2 = createManagedConnection();
    connection2.setClientID(clientId);
    connection2.start();

    consumerSession = queueManager.createSession(connection2);
    consumer = queueManager.createDurableConsumerOnTopic(consumerSession, TOPIC, clientId);

    TextMessage messageReceived = (TextMessage) consumer.receive(TIMEOUT);
    Assert.assertEquals(testText, messageReceived.getText());
}

From source file:com.adaptris.core.jms.JmsProducer.java

@Override
protected AdaptrisMessage doRequest(AdaptrisMessage msg, ProduceDestination dest, long timeout)
        throws ProduceException {

    AdaptrisMessage translatedReply = defaultIfNull(getMessageFactory()).newMessage();
    Destination replyTo = null;/*  w ww . j  a  v a 2  s.  c  o  m*/
    MessageConsumer receiver = null;
    try {
        setupSession(msg);
        VendorImplementation vendorImp = retrieveConnection(JmsConnection.class)
                .configuredVendorImplementation();
        String destString = dest.getDestination(msg);
        MyJmsDestination target = new MyJmsDestination(vendorImp.createDestination(destString, this));
        replyTo = createReplyTo(msg, target, true);
        target.setReplyTo(replyTo);
        receiver = currentSession().createConsumer(replyTo);
        produce(msg, target);
        Message jmsReply = receiver.receive(timeout);

        if (jmsReply != null) {
            translatedReply = MessageTypeTranslatorImp.translate(getMessageTranslator(), jmsReply);
        } else {
            throw new JMSException("No Reply Received within " + timeout + "ms");
        }
        acknowledge(jmsReply);
        // BUG#915
        commit();
    } catch (Exception e) {
        logLinkedException("", e);
        rollback();
        throw ExceptionHelper.wrapProduceException(e);
    } finally {
        JmsUtils.closeQuietly(receiver);
        JmsUtils.deleteTemporaryDestination(replyTo);
    }
    return translatedReply;
}

From source file:io.fabric8.msg.gateway.TestGateway.java

/**
 * TODO - lets figure out a way of mocking kubernetes, running a ZK ensemble, an Artemis broker and testing it!
 * @throws Exception// w  w w.  j a  v a2s  . c o m
 */
@Ignore
public void simpleTest() throws Exception {
    int numberOfMessages = 10;
    String destinationName = "jms.queue.test.foo";
    String brokerURL = "tcp://0.0.0.0:61616";
    ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(brokerURL);

    Connection consumerConnection = factory.createConnection();
    consumerConnection.start();
    Session consumerSession = consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination consumerDestination = consumerSession.createQueue(destinationName);
    MessageConsumer messageConsumer = consumerSession.createConsumer(consumerDestination);

    Connection producerConnection = factory.createConnection();
    producerConnection.start();
    Session producerSession = producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
    Destination destination = producerSession.createQueue(destinationName);
    MessageProducer producer = producerSession.createProducer(destination);

    for (int i = 0; i < numberOfMessages; i++) {
        Message message = producerSession.createTextMessage("test message: " + i);
        producer.send(message);
        //System.err.println("Sent message " + message);

    }

    Message message;

    for (int i = 0; i < numberOfMessages; i++) {
        message = messageConsumer.receive(5000);
        Assert.assertNotNull(message);
        //System.err.println("Got Message " + message);

    }
    messageConsumer.close();

}