1 18 19 26 package org.apache.activemq.demo; 27 28 import javax.jms.JMSException ; 29 import javax.jms.Message ; 30 import javax.jms.Queue ; 31 import javax.jms.QueueConnection ; 32 import javax.jms.QueueConnectionFactory ; 33 import javax.jms.QueueReceiver ; 34 import javax.jms.QueueSession ; 35 import javax.jms.Session ; 36 import javax.jms.TextMessage ; 37 import javax.naming.Context ; 38 import javax.naming.InitialContext ; 39 import javax.naming.NamingException ; 40 41 public class SimpleQueueReceiver { 42 43 private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory 44 .getLog(SimpleQueueReceiver.class); 45 46 51 public static void main(String [] args) { 52 String queueName = null; 53 Context jndiContext = null; 54 QueueConnectionFactory queueConnectionFactory = null; 55 QueueConnection queueConnection = null; 56 QueueSession queueSession = null; 57 Queue queue = null; 58 QueueReceiver queueReceiver = null; 59 TextMessage message = null; 60 61 64 if (args.length != 1) { 65 log.info("Usage: java " + 66 "SimpleQueueReceiver <queue-name>"); 67 System.exit(1); 68 } 69 queueName = args[0]; 70 log.info("Queue name is " + queueName); 71 72 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 89 try { 90 queueConnectionFactory = (QueueConnectionFactory ) 91 jndiContext.lookup("QueueConnectionFactory"); 92 queue = (Queue ) jndiContext.lookup(queueName); 93 } 94 catch (NamingException e) { 95 log.info("JNDI API lookup failed: " + 96 e.toString()); 97 System.exit(1); 98 } 99 100 110 try { 111 queueConnection = 112 queueConnectionFactory.createQueueConnection(); 113 queueSession = 114 queueConnection.createQueueSession(false, 115 Session.AUTO_ACKNOWLEDGE); 116 queueReceiver = queueSession.createReceiver(queue); 117 queueConnection.start(); 118 while (true) { 119 Message m = queueReceiver.receive(1); 120 if (m != null) { 121 if (m instanceof TextMessage ) { 122 message = (TextMessage ) m; 123 log.info("Reading message: " + 124 message.getText()); 125 } 126 else { 127 break; 128 } 129 } 130 } 131 } 132 catch (JMSException e) { 133 log.info("Exception occurred: " + 134 e.toString()); 135 } 136 finally { 137 if (queueConnection != null) { 138 try { 139 queueConnection.close(); 140 } 141 catch (JMSException e) { 142 } 143 } 144 } 145 } 146 } 147 | Popular Tags |