List of usage examples for javax.jms MessageListener MessageListener
MessageListener
From source file:org.dawnsci.commandserver.core.producer.AliveConsumer.java
protected void createTerminateListener() throws Exception { ConnectionFactory connectionFactory = ConnectionFactoryFacade.createConnectionFactory(uri); this.terminateConnection = connectionFactory.createConnection(); terminateConnection.start();//from ww w . jav a 2s . co m Session session = terminateConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(Constants.TERMINATE_CONSUMER_TOPIC); final MessageConsumer consumer = session.createConsumer(topic); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class); if (bean.getStatus().isFinal()) { // Something else already happened terminateConnection.close(); return; } if (consumerId.equals(bean.getConsumerId())) { if (bean.getStatus() == ConsumerStatus.REQUEST_TERMINATE) { System.out.println(getName() + " has been requested to terminate and will exit."); cbean.setStatus(ConsumerStatus.REQUEST_TERMINATE); Thread.currentThread().sleep(2500); System.exit(0); } } } } catch (Exception e) { e.printStackTrace(); } } }; consumer.setMessageListener(listener); }
From source file:org.aludratest.service.jms.JmsActionImplTest.java
/** * Check nondurable topic messaging.// w ww.j av a 2s . c om * <ul> * <li>subscribe to topic (non-durable) and connect a {@link }MessageListener} to that subscription</li> * <li>send a message with a unique textcontent to that topic</li> * <li>check if a message containing the unique textcontent was received</li> * <li>unregister from the topic</li> * <li>send another message with a new unique textcontent to the same topic</li> * <li>verify that no more messages where recieved</li> * </ul> */ @Test public void testTopicSubscriber() { LOGGER.info("Begin testTopicSubscriber"); final List<Message> received = new ArrayList<Message>(); MessageListener listener = new MessageListener() { @Override public void onMessage(Message message) { LOGGER.info("Got Message! "); received.add(message); } }; final String topicName = topics[0]; final String subscriptionName = "testTopicSubscriber@" + topicName; final String expectedText1 = UUID.randomUUID().toString(); final String expectedText2 = UUID.randomUUID().toString(); try { LOGGER.info("Subscribing to topic " + topicName); this.perform.subscribeTopic(listener, topicName, null, subscriptionName, true); // If anything distracting is in there received.clear(); LOGGER.info("Sending message to topic " + topicName); this.perform.sendTextMessage(expectedText1, topicName); LOGGER.info("Waiting a bit to receive message(s) from " + topicName); Thread.sleep(100); LOGGER.info("Checking if message(s) where received on " + topicName); Assert.assertTrue(containtsTextMessage(received, expectedText1)); received.clear(); LOGGER.info("Unsubscribing from topic " + topicName); this.perform.unsubscribeTopic(subscriptionName); LOGGER.info("Sending message to topic " + topicName); this.perform.sendTextMessage(expectedText1, topicName); LOGGER.info("Waiting a bit to receive message(s) from " + topicName); Thread.sleep(100); LOGGER.info("Assert than NO message(s) where received on " + topicName); Assert.assertTrue(received.isEmpty()); } catch (Exception e) { Assert.fail("Unexpected excpetion on testTopicSubscriber " + " : " + e.getMessage()); } LOGGER.info("End testTopicSubscriber"); }
From source file:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addBloomFilterListener() throws JMSException { addMessageListener("filterRequest", new MessageListener() { @Override// w ww . j a v a 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.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body); byte[] data = request.getFilter().toByteArray(); long hashFunctions = request.getHashFunctions(); long tweak = request.getTweak(); UpdateMode updateMode = UpdateMode.values()[request.getMode()]; BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode); synchronized (correlationBloomFilter) { if (!correlationProducer.containsKey(o.getJMSCorrelationID())) { MessageProducer producer = session.createProducer(msg.getJMSReplyTo()); correlationProducer.put(o.getJMSCorrelationID(), producer); } correlationBloomFilter.put(o.getJMSCorrelationID(), filter); } } catch (JMSException e) { log.error("invalid filter request", e); } catch (InvalidProtocolBufferException e) { log.error("invalid filter request", e); } } }); }
From source file:org.dawnsci.commandserver.ui.view.ConsumerView.java
/** * Listens to a topic/*from www.j av a2 s .com*/ */ 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); topicConnection = connectionFactory.createConnection(); topicConnection.start(); Session session = topicConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); final Topic topic = session.createTopic(Constants.ALIVE_TOPIC); final MessageConsumer consumer = session.createConsumer(topic); final ObjectMapper mapper = new ObjectMapper(); MessageListener listener = new MessageListener() { public void onMessage(Message message) { try { if (message instanceof TextMessage) { TextMessage t = (TextMessage) message; final ConsumerBean bean = mapper.readValue(t.getText(), ConsumerBean.class); bean.setLastAlive(System.currentTimeMillis()); consumers.put(bean.getConsumerId(), bean); } } catch (Exception e) { logger.error("Updating changed bean from topic", e); } } }; 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:tools.ConsumerTool.java
@Override public void run() { Connection connection = null; Session session = null;//from ww w . j av a2 s . c o m try { connection = connectionFactory.createConnection(); if (clientId != null) { connection.setClientID(clientId); } connection.start(); session = connection.createSession(transacted, acknowledgeMode); Destination destination = null; if (jndiLookupDestinations) { destination = (Destination) context.lookup(destinationName); } else { if (useQueueDestinations) { if (useTemporaryDestinations) { destination = session.createTemporaryQueue(); } else { destination = session.createQueue(destinationName); } } else { if (useTemporaryDestinations) { destination = session.createTemporaryTopic(); } else { destination = session.createTopic(destinationName); } } } if (useQueueBrowser) { runQueueBrowser(session, (Queue) destination); } else { MessageConsumer consumer = null; if (useQueueDestinations) { //Queues if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } else { //Queues if (durable) { //Durable Subscribers if (selector != null) { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName, selector, false); } else { consumer = session.createDurableSubscriber((Topic) destination, subscriptionName); } } else { //Non-Durable Subscribers if (selector != null) { consumer = session.createConsumer(destination, selector); } else { consumer = session.createConsumer(destination); } } } if (useAsyncListener) { final Session consumerSession = session; final AtomicInteger perConsumerReceivedMessages = new AtomicInteger(0); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { perConsumerReceivedMessages.incrementAndGet(); handleMessage(consumerSession, message, perConsumerReceivedMessages.get()); } }); while (perConsumerReceivedMessages.get() < numMessages) { Thread.sleep(100); } } else { int perConsumerReceivedMessages = 0; while (perConsumerReceivedMessages < numMessages) { Message message = null; if (receiveTimeoutMS > -1) { message = consumer.receive(receiveTimeoutMS); } else { message = consumer.receive(); } if (message != null) { perConsumerReceivedMessages++; handleMessage(session, message, perConsumerReceivedMessages); } } } consumer.close(); } } catch (Exception ex) { LOGGER.error("ConsumerTool hit exception: " + ex.getMessage(), ex); } finally { if (session != null) { try { session.close(); } catch (JMSException e) { LOGGER.error("JMSException closing session", e); } } if (connection != null) { try { connection.close(); } catch (JMSException e) { LOGGER.error("JMSException closing connection", e); } } } }
From source file:com.zotoh.maedr.device.JmsIO.java
private void inizFac(Context ctx, Object obj) throws Exception { ConnectionFactory f = (ConnectionFactory) obj; final JmsIO me = this; Connection conn;/*from ww w . j a v a 2 s. c o m*/ Object c = ctx.lookup(_dest); if (!isEmpty(_jmsUser)) { conn = f.createConnection(_jmsUser, _jmsPwd); } else { conn = f.createConnection(); } _conn = conn; if (c instanceof Destination) { //TODO ? ack always ? Session s = conn.createSession(false, Session.CLIENT_ACKNOWLEDGE); MessageConsumer u = s.createConsumer((Destination) c); u.setMessageListener(new MessageListener() { public void onMessage(Message msg) { me.onMessage(msg); } }); } else { throw new Exception("JmsIO: Object not of Destination type"); } }
From source file:org.apache.activemq.network.MQTTNetworkOfBrokersFailoverTest.java
private CountDownLatch listenForConsumersOn(BrokerService broker) throws Exception { final CountDownLatch latch = new CountDownLatch(1); URI brokerUri = broker.getVmConnectorURI(); final ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory(brokerUri.toASCIIString()); final Connection connection = cf.createConnection(); connection.start();//from ww w. j a va 2s . co m final Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); Destination dest = session .createTopic("ActiveMQ.Advisory.Consumer.Queue.Consumer.foo:AT_LEAST_ONCE.VirtualTopic.foo.bar"); MessageConsumer consumer = session.createConsumer(dest); consumer.setMessageListener(new MessageListener() { @Override public void onMessage(Message message) { latch.countDown(); // shutdown this connection Dispatch.getGlobalQueue().execute(new Runnable() { @Override public void run() { try { session.close(); connection.close(); } catch (JMSException e) { e.printStackTrace(); } } }); } }); return latch; }
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 w ww. j a 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 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:com.bitsofproof.supernode.core.ImplementBCSAPI.java
private void addBloomScanListener() throws JMSException { addMessageListener("scanRequest", new MessageListener() { @Override/*from w w w . j a va2 s . c o m*/ public void onMessage(Message msg) { BytesMessage o = (BytesMessage) msg; byte[] body; try { body = new byte[(int) o.getBodyLength()]; o.readBytes(body); BCSAPIMessage.FilterRequest request = BCSAPIMessage.FilterRequest.parseFrom(body); byte[] data = request.getFilter().toByteArray(); long hashFunctions = request.getHashFunctions(); long tweak = request.getTweak(); UpdateMode updateMode = UpdateMode.values()[request.getMode()]; final BloomFilter filter = new BloomFilter(data, hashFunctions, tweak, updateMode); final MessageProducer producer = session.createProducer(msg.getJMSReplyTo()); requestProcessor.execute(new Runnable() { @Override public void run() { try { store.scan(filter, 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:com.zotoh.maedr.device.JmsIO.java
private void inizTopic(Context ctx, Object obj) throws Exception { TopicConnectionFactory f = (TopicConnectionFactory) obj; final JmsIO me = this; TopicConnection conn;/* www .java 2 s.c o m*/ Topic t = (Topic) ctx.lookup(_dest); if (!isEmpty(_jmsUser)) { conn = f.createTopicConnection(_jmsUser, _jmsPwd); } else { conn = f.createTopicConnection(); } _conn = conn; TopicSession s = conn.createTopicSession(false, Session.CLIENT_ACKNOWLEDGE); TopicSubscriber b; if (_durable) { b = s.createDurableSubscriber(t, GUID.generate()); } else { b = s.createSubscriber(t); } b.setMessageListener(new MessageListener() { public void onMessage(Message msg) { me.onMessage(msg); } }); }