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.wso2.siddhi.extension.output.transport.jms.util.QueueConsumer.java

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*ww  w .  j av a2s  .  co m*/
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueConnection.start();
    } catch (JMSException e) {
        log.error("Can not create queue connection." + e.getMessage(), e);
        return;
    }
    Session session;
    try {
        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages at " + queueName);
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message: " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message: " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message: " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        queueConnection.stop();
        queueConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:org.wso2.extension.siddhi.io.jms.sink.util.QueueConsumer.java

public void run() {
    // create queue connection
    QueueConnection queueConnection = null;
    try {/*from w  ww  . j a  va2  s. c o m*/
        queueConnection = queueConnectionFactory.createQueueConnection();
        queueConnection.start();
    } catch (JMSException e) {
        log.error("Can not create queue connection." + e.getMessage(), e);
        return;
    }
    Session session;
    try {
        session = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createQueue(queueName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages at " + queueName);
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                resultContainer.eventReceived(message);
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    log.info("Received Map Message: " + map);
                } else if (message instanceof TextMessage) {
                    log.info("Received Text Message: " + ((TextMessage) message).getText());
                } else {
                    log.info("Received message: " + message.toString());
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        queueConnection.stop();
        queueConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:endpoint.protocol.jms.JMSBrokerController.java

public Message receiveMessage(Destination destination) throws JMSException, InterruptedException {
    this.connection = this.connectionFactory.createConnection();
    this.connection.start();
    this.session = this.connection.createSession(false, 1);
    MessageConsumer consumer = this.session.createConsumer(destination);
    Message receivedMsg = consumer.receive(1);
    int count = 0;
    while (receivedMsg == null) {
        count++;//from   w  ww  . j  a  va  2s  . co m
        if (count == 10) {
            // return null to avoid hanging
            return null;
        }
        Thread.sleep(10);
        receivedMsg = consumer.receive(1);
    }
    return receivedMsg;
}

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.ja  va  2s .  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:fr.xebia.sample.springframework.jms.requestreply.RequestReplyClientInvoker.java

/**
 * Request/Reply SpringFramework sample.
 * /*from ww  w . java  2  s. c o  m*/
 * @param request
 *            sent to the remote service
 * @return reply returned by the remote service
 * @throws JMSException
 */
public String requestReply(String request) throws JMSException {

    Connection connection = connectionFactory.createConnection();
    try {
        connection.start();
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        try {
            MessageProducer messageProducer = session.createProducer(this.requestDestination);
            try {
                Message requestMessage = session.createTextMessage(request);
                requestMessage.setJMSReplyTo(this.replyToDestination);
                // requestMessage.setJMSCorrelationID(String.valueOf(random.nextLong()));

                messageProducer.send(requestMessage);
                String messageSelector = "JMSCorrelationID  LIKE '" + requestMessage.getJMSMessageID() + "'";

                MessageConsumer messageConsumer = session.createConsumer(this.replyToDestination,
                        messageSelector);
                TextMessage replyMessage = (TextMessage) messageConsumer.receive(timeoutInMillis);
                Assert.notNull(replyMessage, "Timeout waiting for jms response");
                logger.debug(
                        "requestReply " + "\r\nrequest : " + requestMessage + "\r\nreply : " + replyMessage);
                String result = replyMessage.getText();
                logger.debug("requestReply('" + request + "'): '" + result + "'");
                return result;
            } finally {
                JmsUtils.closeMessageProducer(messageProducer);
            }
        } finally {
            JmsUtils.closeSession(session);
        }
    } finally {
        JmsUtils.closeConnection(connection);
    }
}

From source file:org.wso2.carbon.integration.test.client.JMSConsumerClient.java

public void run() {
    // create topic connection
    TopicConnection topicConnection = null;
    try {//from  w w  w .j  av  a2  s.co  m
        topicConnection = topicConnectionFactory.createTopicConnection();
        topicConnection.start();
    } catch (JMSException e) {
        log.error("Can not create topic connection." + e.getMessage(), e);
        return;
    }
    Session session = null;
    try {

        session = topicConnection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination destination = session.createTopic(topicName);
        MessageConsumer consumer = session.createConsumer(destination);
        log.info("Listening for messages");
        while (active) {
            Message message = consumer.receive(1000);
            if (message != null) {
                messageCount++;
                if (message instanceof MapMessage) {
                    MapMessage mapMessage = (MapMessage) message;
                    Map<String, Object> map = new HashMap<String, Object>();
                    Enumeration enumeration = mapMessage.getMapNames();
                    while (enumeration.hasMoreElements()) {
                        String key = (String) enumeration.nextElement();
                        map.put(key, mapMessage.getObject(key));
                    }
                    preservedEventList.add(map);
                    log.info("Received Map Message : \n" + map + "\n");
                } else if (message instanceof TextMessage) {
                    String textMessage = ((TextMessage) message).getText();
                    preservedEventList.add(textMessage);
                    log.info("Received Text Message : \n" + textMessage + "\n");
                } else {
                    preservedEventList.add(message.toString());
                    log.info("Received message : \n" + message.toString() + "\n");
                }
            }
        }
        log.info("Finished listening for messages.");
        session.close();
        topicConnection.stop();
        topicConnection.close();
    } catch (JMSException e) {
        log.error("Can not subscribe." + e.getMessage(), e);
    }
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public Message receive(Channel channel, long timeout) throws Exception {
    Message ret = null;/* w w w. j  a  va 2 s  .c  o m*/
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        javax.jms.MessageConsumer consumer = m_session.createConsumer(queue);

        javax.jms.Message m = consumer.receive(timeout);

        consumer.close();

        if (m instanceof javax.jms.ObjectMessage) {
            ret = (Message) ((javax.jms.ObjectMessage) m).getObject();
        }
    } else if (m_closed == false) {
        throw new Exception("Unable to find queue for channel");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Receive (timeout " + timeout + ") on channel " + channel + " = " + ret);
    }

    return (ret);
}

From source file:org.symplify.runtime.jms.JMSContextImpl.java

public Message receiveNoWait(Channel channel) throws Exception {
    Message ret = null;//from ww  w .  j  ava 2 s . c om
    javax.jms.Queue queue = getQueue(channel);

    if (queue != null) {
        javax.jms.MessageConsumer consumer = m_session.createConsumer(queue);

        javax.jms.Message m = consumer.receive(5);

        if (m instanceof javax.jms.ObjectMessage) {
            ret = (Message) ((javax.jms.ObjectMessage) m).getObject();
        }

        consumer.close();

    } else {
        throw new Exception("Unable to find queue for channel");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Receive (no wait) on channel " + channel + " = " + ret);
    }

    return (ret);
}

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

/**
 * /*from ww  w  .j  ava  2s .  c om*/
 * @param bean
 * @throws Exception 
 */
private void updateQueue(StatusBean bean) throws Exception {

    QueueConnection qCon = null;

    try {

        QueueBrowser qb = qSes.createBrowser(queue);

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

        ObjectMapper mapper = new ObjectMapper();
        String jMSMessageID = null;
        while (e.hasMoreElements()) {
            Message m = (Message) e.nextElement();
            if (m == null)
                continue;
            if (m instanceof TextMessage) {
                TextMessage t = (TextMessage) m;

                @SuppressWarnings("unchecked")
                final StatusBean qbean = mapper.readValue(t.getText(), bean.getClass());
                if (qbean == null)
                    continue;
                if (qbean.getUniqueId() == null)
                    continue; // Definitely not our bean
                if (qbean.getUniqueId().equals(bean.getUniqueId())) {
                    jMSMessageID = t.getJMSMessageID();
                    break;
                }
            }
        }

        qb.close();

        if (jMSMessageID != null) {
            MessageConsumer consumer = qSes.createConsumer(queue, "JMSMessageID = '" + jMSMessageID + "'");
            Message m = consumer.receive(1000);
            if (m != null && m instanceof TextMessage) {
                MessageProducer producer = qSes.createProducer(queue);
                producer.send(qSes.createTextMessage(mapper.writeValueAsString(bean)));
            }
        }
    } finally {
        if (qCon != null)
            qCon.close();
    }

}

From source file:org.apache.qpid.systest.management.jmx.ConnectionManagementTest.java

public void testProducerFlowBlocked() throws Exception {
    _connection = getConnection();/*ww w . j  av  a 2  s. c o  m*/
    _connection.start();

    String queueName = getTestQueueName();
    Session session = _connection.createSession(true, Session.SESSION_TRANSACTED);
    Queue queue = session.createQueue(queueName);
    createQueueOnBroker(session, queue);

    ManagedQueue managedQueue = _jmxUtils.getManagedQueue(queueName);
    managedQueue.setFlowResumeCapacity(DEFAULT_MESSAGE_SIZE * 2l);
    managedQueue.setCapacity(DEFAULT_MESSAGE_SIZE * 3l);

    final ManagedConnection managedConnection = getConnectionMBean();

    // Check that producer flow is not block before test
    final CompositeDataSupport rowBeforeSend = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeSend, false);

    // Check that producer flow does not become block too soon
    sendMessage(session, queue, 3);
    final CompositeDataSupport rowBeforeFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowBeforeFull, false);

    // Fourth message will over-fill the queue (but as we are not sending more messages, client thread wont't block)
    sendMessage(session, queue, 1);
    final CompositeDataSupport rowAfterFull = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterFull, true);

    // Consume two to bring the queue down to the resume capacity
    MessageConsumer consumer = session.createConsumer(queue);
    assertNotNull("Could not receive first message", consumer.receive(1000));
    assertNotNull("Could not receive second message", consumer.receive(1000));
    session.commit();

    // Check that producer flow is no longer blocked
    final CompositeDataSupport rowAfterReceive = getTheOneChannelRow(managedConnection);
    assertFlowBlocked(rowAfterReceive, false);
}