1 18 19 26 package org.apache.activemq.demo; 27 28 import javax.jms.Connection ; 29 import javax.jms.ConnectionFactory ; 30 import javax.jms.Destination ; 31 import javax.jms.JMSException ; 32 import javax.jms.Message ; 33 import javax.jms.MessageConsumer ; 34 import javax.jms.Session ; 35 import javax.jms.TextMessage ; 36 import javax.naming.Context ; 37 import javax.naming.InitialContext ; 38 import javax.naming.NamingException ; 39 40 46 public class SimpleConsumer { 47 48 private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory 49 .getLog(SimpleConsumer.class); 50 51 54 public static void main(String [] args) { 55 String destinationName = null; 56 Context jndiContext = null; 57 ConnectionFactory connectionFactory = null; 58 Connection connection = null; 59 Session session = null; 60 Destination destination = null; 61 MessageConsumer consumer = null; 62 63 66 if (args.length != 1) { 67 log.info("Usage: java SimpleConsumer <destination-name>"); 68 System.exit(1); 69 } 70 destinationName = args[0]; 71 log.info("Destination name is " + destinationName); 72 73 76 try { 77 jndiContext = new InitialContext (); 78 } 79 catch (NamingException e) { 80 log.info("Could not create JNDI API " + 81 "context: " + e.toString()); 82 System.exit(1); 83 } 84 85 88 try { 89 connectionFactory = (ConnectionFactory ) 90 jndiContext.lookup("ConnectionFactory"); 91 destination = (Destination ) jndiContext.lookup(destinationName); 92 } 93 catch (NamingException e) { 94 log.info("JNDI API lookup failed: " + 95 e.toString()); 96 System.exit(1); 97 } 98 99 109 try { 110 connection = connectionFactory.createConnection(); 111 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 112 consumer = session.createConsumer(destination); 113 connection.start(); 114 while (true) { 115 Message m = consumer.receive(1); 116 if (m != null) { 117 if (m instanceof TextMessage ) { 118 TextMessage message = (TextMessage ) m; 119 log.info("Reading message: " + message.getText()); 120 } 121 else { 122 break; 123 } 124 } 125 } 126 } 127 catch (JMSException e) { 128 log.info("Exception occurred: " + e); 129 } 130 finally { 131 if (connection != null) { 132 try { 133 connection.close(); 134 } 135 catch (JMSException e) { 136 } 137 } 138 } 139 } 140 } 141 | Popular Tags |