List of usage examples for javax.jms MessageConsumer setMessageListener
void setMessageListener(MessageListener listener) throws JMSException;
From source file:hermes.ext.imq.ImqAdmin.java
private MessageConsumer subscribeToDestMetricTopic(String destName, int domain) throws JMSException { LOG.debug("Subscribing to " + destName); String topicName = null;/*ww w . j a va2 s .c om*/ if (domain == Domain.QUEUE.getId()) { topicName = QUEUE_METRICS_TOPIC_PREFIX + destName; } else if (domain == Domain.TOPIC.getId()) { topicName = TOPIC_METRICS_TOPIC_PREFIX + destName; } Topic destListTopic = session.createTopic(topicName); MessageConsumer subscriber = session.createConsumer(destListTopic); subscriber.setMessageListener(this); LOG.debug("Created subscriber " + subscriber + " listening to " + topicName); return subscriber; }
From source file:HierarchicalChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password, String pubTopicname, String subTopicname) {//from w ww. j a v a 2s .c o m // Create a connection. try { javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); pubSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); subSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics // Note that the publish and subscribe topics are different. try { javax.jms.Topic subscriberTopic = pubSession.createTopic(subTopicname); javax.jms.MessageConsumer subscriber = subSession.createConsumer(subscriberTopic, null, false); subscriber.setMessageListener(this); javax.jms.Topic publisherTopic = pubSession.createTopic(pubTopicname); publisher = pubSession.createProducer(publisherTopic); // Now that setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); System.out.println("\nHierarchicalChat application:\n" + "============================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will publish messages to the " + DEFAULT_PUBLISHER_TOPIC + " topic." + ".\n" + "The application also subscribes to topics using the wildcard syntax " + DEFAULT_SUBSCRIBER_TOPIC + " so that it can receive all messages to " + DEFAULT_SUBSCRIBER_ROOT + " and its subtopics.\n\n" + "Type some text, and then press Enter to publish a TextMesssage from " + username + ".\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0) { javax.jms.TextMessage msg = pubSession.createTextMessage(); msg.setText(username + ": " + s); publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:Replier.java
/** Create JMS client for sending and receiving messages. */ private void start(String broker, String username, String password, String rQueue, String mode) { // Set the operation mode imode = (mode.equals("uppercase")) ? UPPERCASE : LOWERCASE; // Create a connection. try {/* w w w.j av a2 s .c o m*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); session = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Receivers to application queues as well as a Sender // to use for JMS replies. try { javax.jms.Queue queue = session.createQueue(rQueue); javax.jms.MessageConsumer receiver = session.createConsumer(queue); receiver.setMessageListener(this); replier = session.createProducer(null); // Queue will be set for each reply // Now that all setup is complete, start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { // Read standard input waiting for "EXIT" command. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.println("\nReplier application:\n" + "============================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application gets requests with JMSReplyTo set on the " + DEFAULT_QUEUE + " queue." + "The message is transformed to all uppercase or all lowercase, and then returned to the requestor." + "The Requestor application displays the result.\n\n" + "Enter EXIT or press Ctrl+C to close the Replier.\n"); String s = stdin.readLine(); if (s == null || s.equalsIgnoreCase("EXIT")) { System.out.println("\nStopping Replier. Please wait..\n>"); exit(); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } }
From source file:TransactedChat.java
/** Create JMS client for publishing and subscribing to messages. */ private void chatter(String broker, String username, String password) { // Create a connection. try {/*from www. j av a 2 s .com*/ javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); // We want to be able up commit/rollback messages published, // but not affect messages consumed. Therefore, we need two sessions. publishSession = connect.createSession(true, javax.jms.Session.AUTO_ACKNOWLEDGE); subscribeSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Publisher and Subscriber to 'chat' topics try { javax.jms.Topic topic = subscribeSession.createTopic(APP_TOPIC); javax.jms.MessageConsumer subscriber = subscribeSession.createConsumer(topic); subscriber.setMessageListener(this); publisher = publishSession.createProducer(topic); // Now start the Connection connect.start(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } try { // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); boolean showMessage = true; while (true) { if (showMessage) { System.out.println("TransactedChat application:"); System.out.println("==========================="); System.out.println("The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + "."); System.out.println("The application will stage messages to the " + APP_TOPIC + " topic until you either commit them or roll them back."); System.out.println( "The application also subscribes to that topic to consume any committed messages published there.\n"); System.out.println("1. Enter text to publish and then press Enter to stage the message."); System.out.println("2. Add a few messages to the transaction batch."); System.out.println("3. Then, either:"); System.out.println( " o Enter the text 'COMMIT', and press Enter to publish all the staged messages."); System.out.println( " o Enter the text 'CANCEL', and press Enter to drop the staged messages waiting to be sent."); showMessage = false; } String s = stdin.readLine(); if (s == null) exit(); else if (s.trim().equals("CANCEL")) { // Rollback the messages. A new transaction is implicitly // started for following messages. System.out.println("Cancelling messages..."); publishSession.rollback(); System.out.println("Staged messages have been cleared."); showMessage = false; // don't show the help message again. } else if (s.length() > 0) // See if we should send the messages if (s.trim().equals("COMMIT")) { // Commit (send) the messages. A new transaction is // implicitly started for following messages. System.out.println("Committing messages... "); publishSession.commit(); System.out.println("Staged messages have all been sent."); showMessage = false; // dont't show the help message again. } else { javax.jms.TextMessage msg = publishSession.createTextMessage(); msg.setText(username + ": " + s); // Publish the message persistently publisher.send(msg); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } }
From source file:org.logicblaze.lingo.jms.JmsRemotingTest.java
protected void subscribeToQueue(JmsServiceExporter exporter, String queueName) throws JMSException { Session serverSession = createSession(); Queue queue = serverSession.createQueue(queueName); MessageConsumer consumer = serverSession.createConsumer(queue); consumer.setMessageListener(exporter); }
From source file:pl.baczkowicz.mqspy.connectivity.jms.JmsConnection.java
public boolean subscribe(final BaseSubscription subscription) { try {//from w w w . j av a 2s . c om logger.info("Subscribing..."); final Destination destination = session.createTopic(subscription.getTopic()); final MessageConsumer consumer = session.createConsumer(destination); final JmsMessageDrivenBean mdb = new JmsMessageDrivenBean(scriptManager, subscription); consumer.setMessageListener(mdb); //connection.subscribe(subscription.getTopic(), new StompCallback(scriptManager, subscription)); logger.info("Subscribed to " + subscription.getTopic()); if (subscription.getDetails() != null && subscription.getDetails().getScriptFile() != null && !subscription.getDetails().getScriptFile().isEmpty()) { final Script script = scriptManager .addScript(new ScriptDetails(false, false, subscription.getDetails().getScriptFile())); subscription.setScript(script); scriptManager.runScript(script, false); if (scriptManager.invokeBefore(script)) { subscription.setScriptActive(true); } } return true; } catch (Exception e) { logger.error("JMS error", e); } return false; }
From source file:org.apache.activemq.usecases.DurableSubscriberWithNetworkDisconnectTest.java
public void testSendOnAReceiveOnBWithTransportDisconnect() throws Exception { bridgeBrokers(SPOKE, HUB);//from w w w . ja va 2 s . c o m startAllBrokers(); // Setup connection URI hubURI = brokers.get(HUB).broker.getVmConnectorURI(); URI spokeURI = brokers.get(SPOKE).broker.getVmConnectorURI(); ActiveMQConnectionFactory facHub = new ActiveMQConnectionFactory(hubURI); ActiveMQConnectionFactory facSpoke = new ActiveMQConnectionFactory(spokeURI); Connection conHub = facHub.createConnection(); Connection conSpoke = facSpoke.createConnection(); conHub.setClientID("clientHUB"); conSpoke.setClientID("clientSPOKE"); conHub.start(); conSpoke.start(); Session sesHub = conHub.createSession(false, Session.AUTO_ACKNOWLEDGE); Session sesSpoke = conSpoke.createSession(false, Session.AUTO_ACKNOWLEDGE); ActiveMQTopic topic = new ActiveMQTopic("TEST.FOO"); String consumerName = "consumerName"; // Setup consumers MessageConsumer remoteConsumer = sesSpoke.createDurableSubscriber(topic, consumerName); remoteConsumer.setMessageListener(new MessageListener() { public void onMessage(Message msg) { try { TextMessage textMsg = (TextMessage) msg; receivedMsgs++; LOG.info("Received messages (" + receivedMsgs + "): " + textMsg.getText()); } catch (JMSException e) { e.printStackTrace(); } } }); // allow subscription information to flow back to Spoke sleep(1000); // Setup producer MessageProducer localProducer = sesHub.createProducer(topic); localProducer.setDeliveryMode(DeliveryMode.PERSISTENT); // Send messages for (int i = 0; i < MESSAGE_COUNT; i++) { sleep(50); if (i == 50 || i == 150) { if (simulateStalledNetwork) { socketProxy.pause(); } else { socketProxy.close(); } networkDownTimeStart = System.currentTimeMillis(); } else if (networkDownTimeStart > 0) { // restart after NETWORK_DOWN_TIME seconds sleep(NETWORK_DOWN_TIME); networkDownTimeStart = 0; if (simulateStalledNetwork) { socketProxy.goOn(); } else { socketProxy.reopen(); } } else { // slow message production to allow bridge to recover and limit message duplication sleep(500); } Message test = sesHub.createTextMessage("test-" + i); localProducer.send(test); } LOG.info("waiting for messages to flow"); Wait.waitFor(new Wait.Condition() { @Override public boolean isSatisified() throws Exception { return receivedMsgs >= MESSAGE_COUNT; } }); assertTrue("At least message " + MESSAGE_COUNT + " must be received, count=" + receivedMsgs, MESSAGE_COUNT <= receivedMsgs); brokers.get(HUB).broker.deleteAllMessages(); brokers.get(SPOKE).broker.deleteAllMessages(); conHub.close(); conSpoke.close(); }
From source file:Talk.java
/** Create JMS client for sending and receiving messages. */ private void talker(String broker, String username, String password, String rQueue, String sQueue) { // Create a connection. try {//from ww w. j ava 2 s . c om javax.jms.ConnectionFactory factory; factory = new ActiveMQConnectionFactory(username, password, broker); connect = factory.createConnection(username, password); sendSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); receiveSession = connect.createSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE); } catch (javax.jms.JMSException jmse) { System.err.println("error: Cannot connect to Broker - " + broker); jmse.printStackTrace(); System.exit(1); } // Create Sender and Receiver 'Talk' queues try { if (sQueue != null) { javax.jms.Queue sendQueue = sendSession.createQueue(sQueue); sender = sendSession.createProducer(sendQueue); } if (rQueue != null) { javax.jms.Queue receiveQueue = receiveSession.createQueue(rQueue); javax.jms.MessageConsumer qReceiver = receiveSession.createConsumer(receiveQueue); qReceiver.setMessageListener(this); // Now that 'receive' setup is complete, start the Connection connect.start(); } } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); exit(); } try { if (rQueue != null) System.out.println(""); else System.out.println("\nNo receiving queue specified.\n"); // Read all standard input and send it as a message. java.io.BufferedReader stdin = new java.io.BufferedReader(new java.io.InputStreamReader(System.in)); if (sQueue != null) System.out.println("\nTalk application:\n" + "=================\n" + "The application user " + username + " connects to the broker at " + DEFAULT_BROKER_NAME + ".\n" + "The application will send messages to the " + sQueue + " queue.\n" + "The application creates a receiver on the " + rQueue + " queue to consume any messages allocated to it.\n\n" + "Type some text, and then press Enter to send it as a TextMesssage from " + username + ".\n"); else System.out.println("\nPress CTRL-C to exit.\n"); while (true) { String s = stdin.readLine(); if (s == null) exit(); else if (s.length() > 0 && sQueue != null) { javax.jms.TextMessage msg = sendSession.createTextMessage(); msg.setText(username + ": " + s); // Queues usually are used for PERSISTENT messages. // Hold messages for 30 minutes (1,800,000 millisecs). sender.send(msg, javax.jms.DeliveryMode.PERSISTENT, javax.jms.Message.DEFAULT_PRIORITY, MESSAGE_LIFESPAN); } } } catch (java.io.IOException ioe) { ioe.printStackTrace(); } catch (javax.jms.JMSException jmse) { jmse.printStackTrace(); } // Close the connection. exit(); }
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 non-null value and * check the correct routing key comes as a JMS property for each message. * * @throws AndesClientConfigurationException * @throws XPathExpressionException/* w w w . j a v a2s. com*/ * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "queue" }) public void queueRoutingKeyPropertyTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1"); 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), "RoutingKeyPropertyQueue", "Invalid value received for " + "routing key property."); } }
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 non-null value and * check the correct routing key comes as a JMS property for each message. * * @throws AndesClientConfigurationException * @throws XPathExpressionException//from w w w . j a v a 2s . c om * @throws IOException * @throws JMSException * @throws AndesClientException * @throws NamingException */ @Test(groups = { "wso2.mb", "topic" }) public void topicRoutingKeyPropertyTestCase() throws AndesClientConfigurationException, XPathExpressionException, IOException, JMSException, AndesClientException, NamingException { System.setProperty(AndesClientConstants.ANDES_SET_ROUTING_KEY, "1"); 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), "RoutingKeyPropertyTopic", "Invalid value received for " + "routing key property."); } }