List of usage examples for javax.jms MessageConsumer setMessageListener
void setMessageListener(MessageListener listener) throws JMSException;
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.// w w w .j a v a 2s .c om * * @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 . 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 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 . ja v a2 s .c om*/ * * @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./* w w w . java 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./*from ww w. j av a2 s. c om*/ * * @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:ConsumerTool.java
public void run() { try {// w w w . ja v a 2 s . c om running = true; ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url); Connection connection = connectionFactory.createConnection(); if (durable && clientId != null && clientId.length() > 0 && !"null".equals(clientId)) { connection.setClientID(clientId); } connection.setExceptionListener(this); connection.start(); session = connection.createSession(transacted, ackMode); if (topic) { destination = session.createTopic(subject); } else { destination = session.createQueue(subject); } replyProducer = session.createProducer(null); replyProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT); MessageConsumer consumer = null; if (durable && topic) { consumer = session.createDurableSubscriber((Topic) destination, consumerName); } else { consumer = session.createConsumer(destination); } if (maxiumMessages > 0) { consumeMessagesAndClose(connection, session, consumer); } else { if (receiveTimeOut == 0) { consumer.setMessageListener(this); } else { consumeMessagesAndClose(connection, session, consumer, receiveTimeOut); } } } catch (Exception e) { System.out.println("[" + this.getName() + "] Caught: " + e); e.printStackTrace(); } }
From source file:org.sakaiproject.nakamura.email.outgoing.LiteOutgoingEmailMessageListener.java
@Activate @Modified//w w w .j a v a 2s.co m protected void activate(ComponentContext ctx) { @SuppressWarnings("rawtypes") Dictionary props = ctx.getProperties(); Integer _maxRetries = PropertiesUtil.toInteger(props.get(MAX_RETRIES), -1); if (_maxRetries > -1) { if (diff(maxRetries, _maxRetries)) { maxRetries = _maxRetries; } } else { LOGGER.error("Maximum times to retry messages not set."); } Integer _retryInterval = PropertiesUtil.toInteger(props.get(RETRY_INTERVAL), -1); if (_retryInterval > -1) { if (diff(_retryInterval, retryInterval)) { retryInterval = _retryInterval; } } else { LOGGER.error("SMTP retry interval not set."); } if (maxRetries * retryInterval < 4320 /* minutes in 3 days */) { LOGGER.warn("SMTP retry window is very short."); } Integer _smtpPort = PropertiesUtil.toInteger(props.get(SMTP_PORT), -1); boolean validPort = _smtpPort != null && _smtpPort >= 0 && _smtpPort <= 65535; if (validPort) { if (diff(smtpPort, _smtpPort)) { smtpPort = _smtpPort; } } else { LOGGER.error("Invalid port set for SMTP"); } String _smtpServer = PropertiesUtil.toString(props.get(SMTP_SERVER), ""); if (!StringUtils.isBlank(_smtpServer)) { if (diff(smtpServer, _smtpServer)) { smtpServer = _smtpServer; } } else { LOGGER.error("No SMTP server set"); } String _replyAsAddress = PropertiesUtil.toString(props.get(REPLY_AS_ADDRESS), ""); if (!StringUtils.isBlank(_replyAsAddress)) { if (diff(replyAsAddress, _replyAsAddress)) { replyAsAddress = _replyAsAddress; } } else { LOGGER.error("No reply-as email address set"); } String _replyAsName = PropertiesUtil.toString(props.get(REPLY_AS_NAME), ""); if (!StringUtils.isBlank(_replyAsName)) { if (diff(replyAsName, _replyAsName)) { replyAsName = _replyAsName; } } else { LOGGER.error("No reply-as email name set"); } useTls = PropertiesUtil.toBoolean(props.get(SMTP_USE_TLS), false); useSsl = PropertiesUtil.toBoolean(props.get(SMTP_USE_SSL), false); authUser = PropertiesUtil.toString(props.get(SMTP_AUTH_USER), ""); authPass = PropertiesUtil.toString(props.get(SMTP_AUTH_PASS), ""); try { connection = connFactoryService.getDefaultConnectionFactory().createConnection(); Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Queue dest = session.createQueue(QUEUE_NAME); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(this); connection.start(); } catch (JMSException e) { LOGGER.error(e.getMessage(), e); if (connection != null) { try { connection.close(); } catch (JMSException e1) { } } } }
From source file:org.apache.qpid.systest.management.jmx.QueueManagementTest.java
private void startAsyncConsumerOn(Destination queue, Connection asyncConnection, final CountDownLatch requiredNumberOfMessagesRead, final AtomicInteger totalConsumed) throws Exception { Session session = asyncConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = session.createConsumer(queue); consumer.setMessageListener(new MessageListener() { @Override//w w w .j a va2 s. c o m public void onMessage(Message arg0) { totalConsumed.incrementAndGet(); requiredNumberOfMessagesRead.countDown(); } }); }
From source file:eu.eubrazilcc.lvl.storage.activemq.ActiveMQConnector.java
public void subscribe(final String topicName, final MessageListener listener) { String topicName2 = null;//from ww w . ja v a 2 s . c om checkArgument(isNotBlank(topicName2 = trimToEmpty(topicName)), "Uninitialized or invalid topic"); checkNotNull(listener); TopicConnection conn = null; TopicSession session = null; MessageConsumer consumer = null; try { conn = broker().getConsumersConnFactory().createTopicConnection(); conn.start(); session = conn.createTopicSession(false, AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(topicName2); consumer = session.createConsumer(topic); consumer.setMessageListener(listener); register(TopicSubscriber.builder().topicName(topicName2).connection(conn).session(session) .consumer(consumer).build()); LOGGER.info("Subscribed to topic: " + topicName2); } catch (JMSException e) { if (consumer != null) { try { consumer.close(); } catch (JMSException ignore) { } } if (session != null) { try { session.close(); } catch (JMSException ignore) { } } if (conn != null) { try { conn.close(); } catch (JMSException ignore) { } } LOGGER.error("Failed to subscribe to topic: " + topicName2, e); } }
From source file:com.mirth.connect.connectors.jms.JmsReceiver.java
@Override public void onStart() throws ConnectorTaskException { jmsClient.start();/*from ww w.ja va2 s.co m*/ TemplateValueReplacer replacer = new TemplateValueReplacer(); String channelId = getChannelId(); String channelName = getChannel().getName(); String destinationName = replacer.replaceValues(connectorProperties.getDestinationName(), channelId, channelName); try { MessageConsumer consumer; Destination destination = jmsClient.getDestination(destinationName); String selector = replacer.replaceValues(connectorProperties.getSelector(), channelId, channelName); if (connectorProperties.isTopic() && connectorProperties.isDurableTopic()) { consumer = jmsClient.getSession().createDurableSubscriber((Topic) destination, connectorProperties.getClientId(), selector, true); } else { consumer = jmsClient.getSession().createConsumer(destination, selector, true); } consumer.setMessageListener(new JmsReceiverMessageListener()); logger.debug("Message consumer created"); } catch (Exception e) { try { jmsClient.stop(); } catch (Exception e1) { logger.error(e1); } throw new ConnectorTaskException( "Failed to initialize JMS message consumer for destination \"" + destinationName + "\"", e); } eventController.dispatchEvent(new ConnectionStatusEvent(getChannelId(), getMetaDataId(), getSourceName(), ConnectionStatusEventType.CONNECTED)); }