Example usage for javax.jms MessageProducer send

List of usage examples for javax.jms MessageProducer send

Introduction

In this page you can find the example usage for javax.jms MessageProducer send.

Prototype


void send(Message message) throws JMSException;

Source Link

Document

Sends a message using the MessageProducer 's default delivery mode, priority, and time to live.

Usage

From source file:com.mothsoft.alexis.engine.retrieval.DocumentRetrievalTaskImpl.java

private String requestParse(final Long documentId, final String content) {
    Connection connection = null;
    Session session = null;//from w w  w.j  a  va 2s  .c o  m
    MessageProducer producer = null;

    // set up JMS connection, session, consumer, producer
    try {
        connection = this.connectionFactory.createConnection();
        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        producer = session.createProducer(this.requestQueue);

        logger.info("Sending parse request, document ID: " + documentId);
        final TextMessage textMessage = session.createTextMessage(content);
        textMessage.setJMSReplyTo(this.responseQueue);
        textMessage.setLongProperty(DOCUMENT_ID, documentId);

        producer.send(textMessage);
    } catch (JMSException e) {
        throw new RuntimeException(e);
    } finally {
        try {
            if (producer != null) {
                producer.close();
            }
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (JMSException e) {
            throw new RuntimeException(e);
        }
    }

    return content;
}

From source file:com.espertech.esper.example.servershellclient.ServerShellClientMain.java

public ServerShellClientMain() throws Exception {
    log.info("Loading properties");
    Properties properties = new Properties();
    InputStream propertiesIS = ServerShellClientMain.class.getClassLoader()
            .getResourceAsStream(ServerShellConstants.CONFIG_FILENAME);
    if (propertiesIS == null) {
        throw new RuntimeException(
                "Properties file '" + ServerShellConstants.CONFIG_FILENAME + "' not found in classpath");
    }//from   w ww  .  j av  a  2 s .c om
    properties.load(propertiesIS);

    // Attached via JMX to running server
    log.info("Attach to server via JMX");
    JMXServiceURL url = new JMXServiceURL(properties.getProperty(ServerShellConstants.MGMT_SERVICE_URL));
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    ObjectName mBeanName = new ObjectName(ServerShellConstants.MGMT_MBEAN_NAME);
    EPServiceProviderJMXMBean proxy = (EPServiceProviderJMXMBean) MBeanServerInvocationHandler
            .newProxyInstance(mbsc, mBeanName, EPServiceProviderJMXMBean.class, true);

    // Connect to JMS
    log.info("Connecting to JMS server");
    String factory = properties.getProperty(ServerShellConstants.JMS_CONTEXT_FACTORY);
    String jmsurl = properties.getProperty(ServerShellConstants.JMS_PROVIDER_URL);
    String connFactoryName = properties.getProperty(ServerShellConstants.JMS_CONNECTION_FACTORY_NAME);
    String user = properties.getProperty(ServerShellConstants.JMS_USERNAME);
    String password = properties.getProperty(ServerShellConstants.JMS_PASSWORD);
    String destination = properties.getProperty(ServerShellConstants.JMS_INCOMING_DESTINATION);
    boolean isTopic = Boolean.parseBoolean(properties.getProperty(ServerShellConstants.JMS_IS_TOPIC));
    JMSContext jmsCtx = JMSContextFactory.createContext(factory, jmsurl, connFactoryName, user, password,
            destination, isTopic);

    // Create statement via JMX
    log.info("Creating a statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.createEPL("select * from SampleEvent where duration > 9.9", "filterStatement",
            new ClientSideUpdateListener());

    // Get producer
    jmsCtx.getConnection().start();
    MessageProducer producer = jmsCtx.getSession().createProducer(jmsCtx.getDestination());

    Random random = new Random();
    String[] ipAddresses = { "127.0.1.0", "127.0.2.0", "127.0.3.0", "127.0.4.0" };
    NumberFormat format = NumberFormat.getInstance();

    // Send messages
    for (int i = 0; i < 1000; i++) {
        String ipAddress = ipAddresses[random.nextInt(ipAddresses.length)];
        double duration = 10 * random.nextDouble();
        String durationStr = format.format(duration);
        String payload = ipAddress + "," + durationStr;

        BytesMessage bytesMessage = jmsCtx.getSession().createBytesMessage();
        bytesMessage.writeBytes(payload.getBytes());
        bytesMessage.setJMSDeliveryMode(DeliveryMode.NON_PERSISTENT);
        producer.send(bytesMessage);

        if (i % 100 == 0) {
            log.info("Sent " + i + " messages");
        }
    }

    // Create statement via JMX
    log.info("Destroing statement via Java Management Extensions (JMX) MBean Proxy");
    proxy.destroy("filterStatement");

    log.info("Shutting down JMS client connection");
    jmsCtx.destroy();

    log.info("Exiting");
    System.exit(-1);
}

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

/**
 * This test publishes 1000 messages and the subscriber accepts all message and then wait for the redelivered
 * message./* ww  w .ja va 2  s .  c  o  m*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void allAcknowledgeMessageListenerForMultipleMessagesTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 1000;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                message.acknowledge();
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

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

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

/**
 * This test publishes 10 messages and the subscriber rejects the 8th message and then wait for the redelivered
 * message./*from ww  w.jav a  2s. co m*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void unacknowledgeMiddleMessageMessageListenerPerAckTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (!textMessage.getText().equals("#7") || receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

    Assert.assertEquals(receivedMessages.get(10), "#7", "Invalid messages received. #7 expected.");

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

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

/**
 * This test publishes 10 messages and the subscriber rejects all message and then wait for the redelivered
 * message./*from  www. jav a 2 s  .  co m*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void allUnacknowledgeMessageListenerPerAckTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

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

From source file:org.wso2.mb.integration.tests.amqp.functional.PerMessageAcknowledgementsTestCase.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  w  w  .  ja  v a  2  s  .co m
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void oneByOneUnacknowledgeMessageListenerPerAckTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (Integer.parseInt(textMessage.getText().split("#")[1]) % 3 != 0
                        || receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

    Assert.assertEquals(receivedMessages.get(10), "#0", "Invalid messages received. #0 expected.");
    Assert.assertEquals(receivedMessages.get(11), "#3", "Invalid messages received. #3 expected.");
    Assert.assertEquals(receivedMessages.get(12), "#6", "Invalid messages received. #6 expected.");
    Assert.assertEquals(receivedMessages.get(13), "#9", "Invalid messages received. #9 expected.");

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

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

/**
 * This test publishes 10 messages and the subscriber rejects first 4 messages and then wait for the redelivered
 * message./*w  w  w .  j a  va  2  s .c  o  m*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void firstFewUnacknowledgeMessageListenerPerAckTestCase() throws AndesClientConfigurationException,
        XPathExpressionException, IOException, JMSException, AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (Integer.parseInt(textMessage.getText().split("#")[1]) >= 4
                        || receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

    Assert.assertEquals(receivedMessages.get(10), "#0", "Invalid messages received. #0 expected.");
    Assert.assertEquals(receivedMessages.get(11), "#1", "Invalid messages received. #1 expected.");
    Assert.assertEquals(receivedMessages.get(12), "#2", "Invalid messages received. #2 expected.");
    Assert.assertEquals(receivedMessages.get(13), "#3", "Invalid messages received. #3 expected.");

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

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

/**
 * This test publishes 10 messages and the subscriber rejects the first message and then wait for the redelivered
 * message./*from  ww  w  .j  a  v a  2 s.c om*/
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void firstMessageInvalidOnlyPerAckQueueMessageListenerTestCase()
        throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException,
        AndesClientException, NamingException {
    long sendCount = 10;
    final List<String> receivedMessages = new ArrayList<>();

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

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

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

        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (!receivedFirstMessage && "#0".equals(textMessage.getText())) {
                    receivedFirstMessage = true;
                } else {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

    Assert.assertEquals(receivedMessages.get(10), "#0", "Invalid messages received. #0 expected.");

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

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

/**
 * This test publishes 1000 messages and the subscriber reject each 100th message and then wait for the redelivered
 * message.//w ww .ja v  a 2  s . c  o  m
 *
 * @throws AndesClientConfigurationException
 * @throws XPathExpressionException
 * @throws IOException
 * @throws JMSException
 * @throws AndesClientException
 * @throws NamingException
 */
@Test(groups = { "wso2.mb", "queue" })
public void oneByOneUnacknowledgeMessageListenerForMultipleMessagesPerAckTestCase()
        throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException,
        AndesClientException, NamingException {
    long sendCount = 1000;
    final List<String> receivedMessages = new ArrayList<>();

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

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

    // Creating clients
    AndesClient consumerClient = new AndesClient(consumerConfig, true);
    final AndesJMSConsumer andesJMSConsumer = consumerClient.getConsumers().get(0);
    MessageConsumer receiver = andesJMSConsumer.getReceiver();
    receiver.setMessageListener(new MessageListener() {
        @Override
        public void onMessage(Message message) {
            try {
                TextMessage textMessage = (TextMessage) message;
                if (Integer.parseInt(textMessage.getText().split("#")[1]) % 100 != 0
                        || receivedMessages.contains(textMessage.getText())) {
                    message.acknowledge();
                }
                receivedMessages.add(textMessage.getText());
                andesJMSConsumer.getReceivedMessageCount().incrementAndGet();
            } catch (JMSException e) {
                throw new RuntimeException("Exception occurred when receiving messages.", e);
            }
        }
    });

    AndesClient publisherClient = new AndesClient(publisherConfig, true);
    MessageProducer sender = publisherClient.getPublishers().get(0).getSender();
    for (int i = 0; i < sendCount; i++) {
        TextMessage textMessage = publisherClient.getPublishers().get(0).getSession()
                .createTextMessage("#" + Integer.toString(i));
        sender.send(textMessage);
    }

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

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

    Assert.assertEquals(receivedMessages.get(1000), "#0", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1001), "#100", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1002), "#200", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1003), "#300", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1004), "#400", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1005), "#500", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1006), "#600", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1007), "#700", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1008), "#800", "Invalid messages received.");
    Assert.assertEquals(receivedMessages.get(1009), "#900", "Invalid messages received.");

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

From source file:com.fusesource.forge.jmstest.tests.AsyncConsumer.java

public void onMessage(Message msg) {
    if (receiveCount != null) {
        receiveCount.incrementAndGet();/*ww  w  . j  a v a  2  s  .  co m*/
    }
    MessageProducer producer = null;
    try {
        Destination replyDest = msg.getJMSReplyTo();
        if (replyDest != null) {
            Message response = getSession().createTextMessage("Response");
            response.setStringProperty("ServedBy", getName());
            response.setJMSCorrelationID(msg.getJMSCorrelationID());
            for (Enumeration<?> en = msg.getPropertyNames(); en.hasMoreElements();) {
                String key = (String) en.nextElement();
                Object value = msg.getObjectProperty(key);
                if (key.equals("BrokerStamp")) {
                    value = value.toString() + " --";
                }
                response.setObjectProperty(key, value);
            }
            producer = getSession().createProducer(replyDest);
            producer.send(response);
        }
    } catch (Exception e) {
        LOG.error(e);
    } finally {
        if (producer != null) {
            try {
                producer.close();
            } catch (Exception e) {
            }
        }
    }
}