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:org.wso2.mb.integration.tests.amqp.functional.RedeliveryDelayTestCase.java

/**
 * This test publishes 1000 messages and the subscriber reject each 100th message and then wait for the redelivered
 * message./*from   w ww .j a  v  a2 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 oneByOneUnacknowledgeMessageReceiverForMultipleMessagesTestCase()
        throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException,
        AndesClientException, NamingException {
    long sendCount = 1000;
    final List<ImmutablePair<String, Calendar>> receivedMessages = new ArrayList<>();

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

    // Creating a publisher client configuration
    AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration(
            getAMQPPort(), ExchangeType.QUEUE, "oneByOneUnacknowledgeMessageReceiverForMultipleQueue");
    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]) % 100 != 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 * 2);
    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, 1000, "#0");
    validateMessageContentAndDelay(receivedMessages, 99, 1001, "#100");
    validateMessageContentAndDelay(receivedMessages, 199, 1002, "#200");
    validateMessageContentAndDelay(receivedMessages, 299, 1003, "#300");
    validateMessageContentAndDelay(receivedMessages, 399, 1004, "#400");
    validateMessageContentAndDelay(receivedMessages, 499, 1005, "#500");
    validateMessageContentAndDelay(receivedMessages, 599, 1006, "#600");
    validateMessageContentAndDelay(receivedMessages, 699, 1007, "#700");
    validateMessageContentAndDelay(receivedMessages, 799, 1008, "#800");
    validateMessageContentAndDelay(receivedMessages, 899, 1009, "#900");

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

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

/**
 * This test publishes 10 messages and the subscriber rejects the first message and then wait for the redelivered
 * message.//from   w w  w.  j ava 2 s  .  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 firstMessageInvalidOnlyQueueMessageReceiverTestCase() 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, "firstMessageInvalidOnlyReceiverQueue");
    consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE);
    consumerConfig.setAsync(false);

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    final MessageConsumer receiver = andesJMSConsumer.getReceiver();
    Thread messageReceivingThread = new Thread() {
        private boolean receivedFirstMessage = false;

        public void run() {
            while (receiver != null) {
                try {
                    TextMessage textMessage = (TextMessage) receiver.receive();
                    if (!receivedFirstMessage && "#0".equals(textMessage.getText())) {
                        receivedFirstMessage = true;
                    } else {
                        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");

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

}

From source file:Vendor.java

public void run() {
    ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
    Session session = null;/*from w  w  w .j a v a2s  .c om*/
    Destination orderQueue;
    Destination monitorOrderQueue;
    Destination storageOrderQueue;
    TemporaryQueue vendorConfirmQueue;
    MessageConsumer orderConsumer = null;
    MessageProducer monitorProducer = null;
    MessageProducer storageProducer = null;

    try {
        Connection connection = connectionFactory.createConnection();

        session = connection.createSession(true, Session.SESSION_TRANSACTED);
        orderQueue = session.createQueue("VendorOrderQueue");
        monitorOrderQueue = session.createQueue("MonitorOrderQueue");
        storageOrderQueue = session.createQueue("StorageOrderQueue");

        orderConsumer = session.createConsumer(orderQueue);
        monitorProducer = session.createProducer(monitorOrderQueue);
        storageProducer = session.createProducer(storageOrderQueue);

        Connection asyncconnection = connectionFactory.createConnection();
        asyncSession = asyncconnection.createSession(true, Session.SESSION_TRANSACTED);

        vendorConfirmQueue = asyncSession.createTemporaryQueue();
        MessageConsumer confirmConsumer = asyncSession.createConsumer(vendorConfirmQueue);
        confirmConsumer.setMessageListener(this);

        asyncconnection.start();

        connection.start();

        while (true) {
            Order order = null;
            try {
                Message inMessage = orderConsumer.receive();
                MapMessage message;
                if (inMessage instanceof MapMessage) {
                    message = (MapMessage) inMessage;

                } else {
                    // end of stream
                    Message outMessage = session.createMessage();
                    outMessage.setJMSReplyTo(vendorConfirmQueue);
                    monitorProducer.send(outMessage);
                    storageProducer.send(outMessage);
                    session.commit();
                    break;
                }

                // Randomly throw an exception in here to simulate a Database error
                // and trigger a rollback of the transaction
                if (new Random().nextInt(3) == 0) {
                    throw new JMSException("Simulated Database Error.");
                }

                order = new Order(message);

                MapMessage orderMessage = session.createMapMessage();
                orderMessage.setJMSReplyTo(vendorConfirmQueue);
                orderMessage.setInt("VendorOrderNumber", order.getOrderNumber());
                int quantity = message.getInt("Quantity");
                System.out.println("Vendor: Retailer ordered " + quantity + " " + message.getString("Item"));

                orderMessage.setInt("Quantity", quantity);
                orderMessage.setString("Item", "Monitor");
                monitorProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Monitor(s)");

                orderMessage.setString("Item", "HardDrive");
                storageProducer.send(orderMessage);
                System.out.println("Vendor: ordered " + quantity + " Hard Drive(s)");

                session.commit();
                System.out.println("Vendor: Comitted Transaction 1");

            } catch (JMSException e) {
                System.out.println("Vendor: JMSException Occured: " + e.getMessage());
                e.printStackTrace();
                session.rollback();
                System.out.println("Vendor: Rolled Back Transaction.");
            }
        }

        synchronized (supplierLock) {
            while (numSuppliers > 0) {
                try {
                    supplierLock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        connection.close();
        asyncconnection.close();

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

}