List of usage examples for javax.jms MessageListener MessageListener
MessageListener
From source file:org.dawnsci.commandserver.ui.view.StatusQueueView.java
/** * Listens to a topic/*from w w w . j a v a2 s . c o m*/ */ private void createTopicListener(final URI uri) throws Exception { // Use job because connection might timeout. final Job topicJob = new Job("Create topic listener") { @Override protected IStatus run(IProgressMonitor monitor) { try { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); StatusQueueView.this.topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); Topic topic = session.createTopic(getTopicName()); MessageConsumer consumer = session.createConsumer(topic); final Class clazz = getBeanClass(); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final StatusBean bean = mapper.readValue(t.getText(), clazz); mergeBean(bean); } } catch (Exception e) { logger.error("Updating changed bean from topic", e); } } }; consumer.setMessageListener(listener); // Create a listener for administrator broadcast messages. topic = session.createTopic(Constants.ADMIN_MESSAGE_TOPIC); consumer = session.createConsumer(topic); listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { // AdministratorMessage shows a message to the user. final Class msgClass = AdministratorMessage.class; TextMessage t = (TextMessage) message; final AdministratorMessage bean = mapper.readValue(t.getText(), msgClass); getSite().getShell().getDisplay().syncExec(new Runnable() { public void run() { MessageDialog.openError(getViewSite().getShell(), bean.getTitle(), bean.getMessage()); viewer.refresh(); } }); } } catch (Exception e) { // Not a big deal if they do not get admin messages. } } }; consumer.setMessageListener(listener); return Status.OK_STATUS; } catch (Exception ne) { logger.error("Cannot listen to topic changes because command server is not there", ne); return Status.CANCEL_STATUS; } } }; topicJob.setPriority(Job.INTERACTIVE); topicJob.setSystem(true); topicJob.setUser(false); topicJob.schedule(); }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addMatchScanListener() throws JMSException { addMessageListener("matchRequest", new MessageListener() { @Override/* w ww . ja va 2 s . co m*/ public void onMessage(Message msg) { BytesMessage o = (BytesMessage) msg; byte[] body; try { body = new byte[(int) o.getBodyLength()]; o.readBytes(body); BCSAPIMessage.ExactMatchRequest request = BCSAPIMessage.ExactMatchRequest.parseFrom(body); final List<byte[]> match = new ArrayList<byte[]>(); for (ByteString bs : request.getMatchList()) { match.add(bs.toByteArray()); } final UpdateMode mode = UpdateMode.values()[request.getMode()]; final MessageProducer producer = session.createProducer(msg.getJMSReplyTo()); final long after = request.hasAfter() ? request.getAfter() : 0; requestProcessor.execute(new Runnable() { @Override public void run() { try { store.filterTransactions(match, mode, after, new TransactionProcessor() { @Override public void process(Tx tx) { if (tx != null) { Transaction transaction = toBCSAPITransaction(tx); BytesMessage m; try { m = session.createBytesMessage(); m.writeBytes(transaction.toProtobuf().toByteArray()); producer.send(m); } catch (JMSException e) { } } else { try { BytesMessage m = session.createBytesMessage(); producer.send(m); // indicate EOF producer.close(); } catch (JMSException e) { } } } }); } catch (ValidationException e) { log.error("Error while scanning", e); } } }); } catch (JMSException e) { log.error("invalid filter request", e); } catch (InvalidProtocolBufferException e) { log.error("invalid filter request", e); } } }); }
From source file:org.wso2.mb.integration.tests.amqp.functional.JMSRoutingKeyPropertyTestCase.java
/** * Publishes few messages to a queue with setting "AndesSetRoutingKey" system property set to null value and check * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message. * * @throws AndesClientConfigurationException * @throws XPathExpressionException/*ww w .j a v a2s . c o m*/ * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void queueRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY); long sendCount = 10; final List<Message> messages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "RoutingKeyPropertyQueue"); 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) { messages.add(message); } }); 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); for (Message message : messages) { Assert.assertEquals( message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null, "Invalid value received for routing key property."); } }
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 w w w . j a va 2s. c o 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.JMSRoutingKeyPropertyTestCase.java
/** * Publishes few messages to a topic with setting "AndesSetRoutingKey" system property set to null value and check * null comes as a JMS property "JMS_ANDES_ROUTING_KEY" for each message. * * @throws AndesClientConfigurationException * @throws XPathExpressionException//from w w w . j a v a 2s . c o m * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "topic" }) public void topicRoutingKeyPropertyNullTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { System.clearProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY); long sendCount = 10; final List<Message> messages = new ArrayList<>(); // Creating a consumer client configuration AndesJMSConsumerClientConfiguration consumerConfig = new AndesJMSConsumerClientConfiguration(getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.AUTO_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.TOPIC, "RoutingKeyPropertyTopic"); 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) { messages.add(message); } }); 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); for (Message message : messages) { Assert.assertEquals( message.getStringProperty(AndesClientConstants.JMS_ANDES_ROUTING_KEY_MESSAGE_PROPERTY), null, "Invalid value received for routing key property."); } }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addNewColorListener() throws JMSException { addMessageListener("newColor", new MessageListener() { @Override/* www. j a v a 2s . c o m*/ public void onMessage(Message arg0) { BytesMessage o = (BytesMessage) arg0; try { byte[] body = new byte[(int) o.getBodyLength()]; o.readBytes(body); Color color = Color.fromProtobuf(BCSAPIMessage.Color.parseFrom(body)); StoredColor sc = new StoredColor(); sc.setFungibleName(color.getFungibleName()); sc.setExpiryHeight(color.getExpiryHeight()); sc.setPubkey(color.getPubkey()); sc.setSignature(color.getSignature()); sc.setTerms(color.getTerms()); sc.setUnit(color.getUnit()); sc.setTxHash(color.getTransaction()); store.issueColor(sc); reply(o.getJMSReplyTo(), null); } catch (Exception e) { BCSAPIMessage.ExceptionMessage.Builder builder = BCSAPIMessage.ExceptionMessage.newBuilder(); builder.setBcsapiversion(1); builder.addMessage(e.getMessage()); try { reply(o.getJMSReplyTo(), builder.build().toByteArray()); } catch (JMSException e1) { log.error("Can not send reply ", e1); } } } }); }
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 a2 s.c o 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:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addColorRequestListener() throws JMSException { addMessageListener("colorRequest", new MessageListener() { @Override//from w ww . jav a 2 s. co m public void onMessage(Message message) { BytesMessage o = (BytesMessage) message; try { byte[] body = new byte[(int) o.getBodyLength()]; o.readBytes(body); String hash = new Hash(BCSAPIMessage.Hash.parseFrom(body).getHash(0).toByteArray()).toString(); Color c = getColor(hash); if (c != null) { reply(o.getJMSReplyTo(), c.toProtobuf().toByteArray()); } else { reply(o.getJMSReplyTo(), null); } } catch (Exception e) { log.trace("Rejected invalid color request ", e); } } }); }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addTransactionRequestListener() throws JMSException { addMessageListener("transactionRequest", new MessageListener() { @Override/*from w w w . j av a 2s . c o m*/ public void onMessage(Message arg0) { BytesMessage o = (BytesMessage) arg0; try { byte[] body = new byte[(int) o.getBodyLength()]; o.readBytes(body); String hash = new Hash(BCSAPIMessage.Hash.parseFrom(body).getHash(0).toByteArray()).toString(); Transaction t = getTransaction(hash); if (t != null) { reply(o.getJMSReplyTo(), t.toProtobuf().toByteArray()); } else { reply(o.getJMSReplyTo(), null); } } catch (Exception e) { log.trace("Rejected invalid transaction request ", e); } } }); }
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 w w . j av a2s . 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. * * @throws AndesClientConfigurationException * @throws XPathExpressionException * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void allUnacknowledgeMessageListenerTestCase() 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, "multipleUnacknowledgeQueue"); consumerConfig.setAcknowledgeMode(JMSAcknowledgeMode.PER_MESSAGE_ACKNOWLEDGE); consumerConfig.setAsync(false); // Creating a publisher client configuration AndesJMSPublisherClientConfiguration publisherConfig = new AndesJMSPublisherClientConfiguration( getAMQPPort(), ExchangeType.QUEUE, "multipleUnacknowledgeQueue"); 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 (getMessageList(receivedMessages).contains(textMessage.getText())) { message.acknowledge(); } receivedMessages.add(ImmutablePair.of(textMessage.getText(), Calendar.getInstance())); andesJMSConsumer.getReceivedMessageCount().incrementAndGet(); } catch (JMSException e) { throw new RuntimeException("Exception occurred when receiving messages.", e); } } }); 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."); }