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() throws JMSException;

Source Link

Document

Receives the next message produced for this message consumer.

Usage

From source file:net.blogracy.controller.FileSharing.java

public String seed(File file) {
    String uri = null;//from   w  ww . j  a va 2 s. c o  m
    try {
        Destination tempDest = session.createTemporaryQueue();
        MessageConsumer responseConsumer = session.createConsumer(tempDest);

        JSONObject requestObj = new JSONObject();
        requestObj.put("file", file.getAbsolutePath());

        TextMessage request = session.createTextMessage();
        request.setText(requestObj.toString());
        request.setJMSReplyTo(tempDest);
        producer.send(seedQueue, request);

        TextMessage response = (TextMessage) responseConsumer.receive();
        String msgText = ((TextMessage) response).getText();
        JSONObject responseObj = new JSONObject(msgText);
        uri = responseObj.getString("uri");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return uri;
}

From source file:Retailer.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    try {//from  w ww. j  a  v  a 2  s .  c  o m
        Connection connection = connectionFactory.createConnection();

        // The Retailer's session is non-trasacted.
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Destination vendorOrderQueue = session.createQueue("VendorOrderQueue");
        TemporaryQueue retailerConfirmQueue = session.createTemporaryQueue();

        MessageProducer producer = session.createProducer(vendorOrderQueue);
        MessageConsumer replyConsumer = session.createConsumer(retailerConfirmQueue);

        connection.start();

        for (int i = 0; i < 5; i++) {
            MapMessage message = session.createMapMessage();
            message.setString("Item", "Computer(s)");
            int quantity = (int) (Math.random() * 4) + 1;
            message.setInt("Quantity", quantity);
            message.setJMSReplyTo(retailerConfirmQueue);
            producer.send(message);
            System.out.println("Retailer: Ordered " + quantity + " computers.");

            MapMessage reply = (MapMessage) replyConsumer.receive();
            if (reply.getBoolean("OrderAccepted")) {
                System.out.println("Retailer: Order Filled");
            } else {
                System.out.println("Retailer: Order Not Filled");
            }
        }

        // Send a non-MapMessage to signal the end
        producer.send(session.createMessage());

        replyConsumer.close();
        connection.close();

    } catch (JMSException e) {
        e.printStackTrace();
    }
}

From source file:org.aludratest.service.jms.impl.JmsActionImpl.java

@Override
public Message receiveMessage(String destinationName, long timeout) {
    MessageConsumer consumer = null;
    try {//from w ww  . jav a2s  .  c  om
        Destination dest = (Destination) context.lookup(destinationName);
        consumer = getSession().createConsumer(dest);
        this.startConnection();
        Message msg;
        if (timeout == -1) {
            msg = consumer.receive();
        } else {
            msg = consumer.receive(timeout);
        }
        this.stopConnection();
        if (msg == null) {
            throw new PerformanceFailure(
                    "Destination " + destinationName + " did not deliver a message within timeout");
        }
        return msg;
    } catch (NamingException e) {
        throw new AutomationException("Could not lookup destination " + destinationName, e);
    } catch (ClassCastException e) {
        throw new AutomationException("JNDI object with name " + destinationName + " is no destination", e);
    } catch (JMSException e) {
        throw new AccessFailure("Could not receive JMS message", e);
    } finally {
        if (consumer != null) {
            try {
                consumer.close();
            } catch (JMSException e) {
            }
        }
    }
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

protected void consumeTestMessages(MessageConsumer consumer, int size, String topicName) throws Exception {
    for (int i = 0; i < size; i++) {
        consumer.receive();
    }/*from  w  w  w .  j  a v a  2  s  . com*/
}

From source file:org.apache.activemq.artemis.tests.integration.persistence.metrics.JournalPendingMessageTest.java

@Test
public void testDeliveringStats() throws Exception {
    AtomicLong publishedMessageSize = new AtomicLong();

    Connection connection = cf.createConnection();
    connection.start();//from  w  ww.j av a 2s.co  m
    Session session = connection.createSession(false, Session.CLIENT_ACKNOWLEDGE);
    MessageProducer producer = session.createProducer(session.createQueue(defaultQueueName));
    producer.send(session.createTextMessage("test"));

    verifyPendingStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyPendingDurableStats(defaultQueueName, 1, publishedMessageSize.get());
    verifyDeliveringStats(defaultQueueName, 0, 0);

    MessageConsumer consumer = session.createConsumer(session.createQueue(defaultQueueName));
    Message msg = consumer.receive();
    verifyDeliveringStats(defaultQueueName, 1, publishedMessageSize.get());
    msg.acknowledge();

    verifyPendingStats(defaultQueueName, 0, 0);
    verifyPendingDurableStats(defaultQueueName, 0, 0);
    verifyDeliveringStats(defaultQueueName, 0, 0);

    connection.close();
}

From source file:org.opencastproject.message.broker.impl.MessageReceiverImpl.java

/**
 * Private function to get a message or none if there is an error.
 *
 * @param destinationId/*  w w  w  .j a v a2  s.c om*/
 *          The destination queue or topic to pull the message from.
 * @param type
 *          The type of the destination either queue or topic.
 * @return A message or none if there was a problem getting the message.
 */
private Option<Message> waitForMessage(String destinationId, DestinationType type) {
    MessageConsumer consumer = null;
    try {

        // Create the destination (Topic or Queue)
        Destination destination;
        if (type.equals(DestinationType.Queue)) {
            destination = getSession().createQueue(destinationId);
        } else {
            destination = getSession().createTopic(destinationId);
        }

        // Create a MessageConsumer from the Session to the Topic or Queue
        consumer = getSession().createConsumer(destination);

        // Wait for a message
        Message message = consumer.receive();
        return Option.option(message);
    } catch (JMSException e) {
        if (e instanceof javax.jms.IllegalStateException || e.getCause() instanceof InterruptedException
                || e.getCause() instanceof InterruptedIOException) {
            // Swallowing the shutdown exception
            logger.trace("Shutting down message receiver {}", ExceptionUtils.getStackTrace(e));
        } else {
            logger.error("Unable to receive messages {}", ExceptionUtils.getStackTrace(e));
        }
        return Option.<Message>none();
    } finally {
        try {
            if (consumer != null) {
                consumer.close();
            }
        } catch (JMSException e) {
            logger.error("Unable to close connections after receipt of message {}",
                    ExceptionUtils.getStackTrace(e));
        }
    }
}

From source file:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java

/**
 * This test publishes 10 messages and the subscriber rejects the 8th message and then wait for the redelivered
 * message./*from  w w w.j  a  v  a2 s. com*/
 * <p/>
 * The redelivered message is tested against the same message content with the original message and the timestamps
 * are also checked against the original message timestamp to make sure that the message was delayed.
 * Here message receive method is used instead of the message listener to receive messages.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void unacknowledgeMiddleMessageMessageReceiverTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "unacknowledgeMiddleMessageReceiverQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "unacknowledgeMiddleMessageReceiverQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    final MessageConsumer receiver = andesJMSConsumer.getReceiver();
    Thread messageReceivingThread = new Thread() {
        public void run() {
            while (receiver != null) {
                try {
                    TextMessage textMessage = (TextMessage) receiver.receive();
                    if (!textMessage.getText().equals("#7")
                            || getMessageList(receivedMessages).contains(textMessage.getText())) {
                        textMessage.acknowledge();
                    }
                    receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance()));
                    andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
                } catch (JMSException e) {
                    throw new RuntimeException("Exception occurred when receiving messages.", e);
                }
            }
        }
    };
    messageReceivingThread.start();
    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    log.info("Received Messages : " + getMessageList(receivedMessages));

    for (int i = 0; i < sendCount; i++) {
        Assert.assertEquals(receivedMessages.get(i).getLeft(), "#" + Integer.toString(i),
                "Invalid messages received. #" + Integer.toString(i) + " expected.");
    }

    validateMessageContentAndDelay(receivedMessages, 6, 10, "#7");

    Assert.assertEquals(receivedMessages.size(), sendCount + 1, "Message receiving failed.");
}

From source file:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java

/**
 * This test publishes 10 messages and the subscriber rejects all message and then wait for the redelivered
 * message.// w  ww  .j a  v a  2  s. c  o  m
 * <p/>
 * The redelivered message is tested against the same message content with the original message and the timestamps
 * are also checked against the original message timestamp to make sure that the message was delayed.
 * Here message receive method is used instead of the message listener to receive messages.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void allUnacknowledgeMessageReceiverTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    int sendCount = 10;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "multipleUnacknowledgeReceiverQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "multipleUnacknowledgeReceiverQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    final MessageConsumer receiver = andesJMSConsumer.getReceiver();
    Thread messageReceivingThread = new Thread() {
        public void run() {
            while (receiver != null) {
                try {
                    TextMessage textMessage = (TextMessage) receiver.receive();
                    if (getMessageList(receivedMessages).contains(textMessage.getText())) {
                        textMessage.acknowledge();
                    }
                    receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance()));
                    andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
                } catch (JMSException e) {
                    throw new RuntimeException("Exception occurred when receiving messages.", e);
                }
            }
        }
    };
    messageReceivingThread.start();
    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    log.info("Received Messages : " + getMessageList(receivedMessages));

    for (int i = 0; i < sendCount * 2; i++) {
        if (i < sendCount) {
            Assert.assertEquals(receivedMessages.get(i).getLeft(), "#" + Integer.toString(i),
                    "Invalid messages received. #" + Integer.toString(i) + " expected.");
        } else {
            validateMessageContentAndDelay(receivedMessages, i - sendCount, i,
                    "#" + Integer.toString(i - sendCount));
        }
    }

    Assert.assertEquals(receivedMessages.size(), sendCount * 2, "Message receiving failed.");
}

From source file:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java

/**
 * This test publishes 10 messages and the subscriber rejects a message after each 3 received messages and then wait
 * for the redelivered message.//from w  ww . ja v  a2s  .co m
 * <p/>
 * The redelivered message is tested against the same message content with the original message and the timestamps
 * are also checked against the original message timestamp to make sure that the message was delayed.
 * Here message receive method is used instead of the message listener to receive messages.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void oneByOneUnacknowledgeMessageReceiverTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "oneByOneUnacknowledgeReceiverQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgeReceiverQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    final MessageConsumer receiver = andesJMSConsumer.getReceiver();
    Thread messageReceivingThread = new Thread() {
        public void run() {
            while (receiver != null) {
                try {
                    TextMessage textMessage = (TextMessage) receiver.receive();
                    if (Integer.parseInt(textMessage.getText().split("#")[1]) % 3 != 0
                            || getMessageList(receivedMessages).contains(textMessage.getText())) {
                        textMessage.acknowledge();
                    }
                    receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance()));
                    andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
                } catch (JMSException e) {
                    throw new RuntimeException("Exception occurred when receiving messages.", e);
                }
            }
        }
    };
    messageReceivingThread.start();
    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    log.info("Received Messages : " + getMessageList(receivedMessages));

    for (int i = 0; i < sendCount; i++) {
        Assert.assertEquals(receivedMessages.get(i).getLeft(), "#" + Integer.toString(i),
                "Invalid messages received. #" + Integer.toString(i) + " expected.");
    }

    validateMessageContentAndDelay(receivedMessages, 0, 10, "#0");
    validateMessageContentAndDelay(receivedMessages, 1, 11, "#3");
    validateMessageContentAndDelay(receivedMessages, 2, 12, "#6");
    validateMessageContentAndDelay(receivedMessages, 3, 13, "#9");

    Assert.assertEquals(receivedMessages.size(), sendCount + 4, "Message receiving failed.");
}

From source file:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java

/**
 * This test publishes 10 messages and the subscriber rejects first 4 messages and then wait for the redelivered
 * message./*from w ww  .  ja v a  2 s  . c  om*/
 * <p/>
 * The redelivered message is tested against the same message content with the original message and the timestamps
 * are also checked against the original message timestamp to make sure that the message was delayed.
 * Here message receive method is used instead of the message listener to receive messages.
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void firstFewUnacknowledgeMessageReceiverTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();

    // Creating a consumer client configuration
    AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(),
            ExchangeType.QUEUE, "firstFewUnacknowledgeReceiverQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "firstFewUnacknowledgeReceiverQueue");
    publisherConfig.setNumberOfMessagesToSend(sendCount);

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    final MessageConsumer receiver = andesJMSConsumer.getReceiver();
    Thread messageReceivingThread = new Thread() {
        public void run() {
            while (receiver != null) {
                try {
                    TextMessage textMessage = (TextMessage) receiver.receive();
                    if (Integer.parseInt(textMessage.getText().split("#")[1]) >= 4
                            || getMessageList(receivedMessages).contains(textMessage.getText())) {
                        textMessage.acknowledge();
                    }
                    receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance()));
                    andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
                } catch (JMSException e) {
                    throw new RuntimeException("Exception occurred when receiving messages.", e);
                }
            }
        }
    };
    messageReceivingThread.start();
    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    AndesJMSPublisher andesJMSPublisher = publisherClient.getPublishers().get(0);
    MessageProducer sender = andesJMSPublisher.getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = andesJMSPublisher.getSession().createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

    AndesClientUtils.waitForMessagesAndShutdown(consumerClient, AndesClientConstants.DEFAULT_RUN_TIME);
    log.info("Received Messages : " + getMessageList(receivedMessages));

    for (int i = 0; i < sendCount; i++) {
        Assert.assertEquals(receivedMessages.get(i).getLeft(), "#" + Integer.toString(i),
                "Invalid messages received. #" + Integer.toString(i) + " expected.");
    }

    validateMessageContentAndDelay(receivedMessages, 0, 10, "#0");
    validateMessageContentAndDelay(receivedMessages, 1, 11, "#1");
    validateMessageContentAndDelay(receivedMessages, 2, 12, "#2");
    validateMessageContentAndDelay(receivedMessages, 3, 13, "#3");

    Assert.assertEquals(receivedMessages.size(), sendCount + 4, "Message receiving failed.");
}