1 18 19 28 package org.apache.activemq.demo; 29 30 32 33 import javax.jms.JMSException ; 34 import javax.jms.Queue ; 35 import javax.jms.QueueConnection ; 36 import javax.jms.QueueConnectionFactory ; 37 import javax.jms.QueueSender ; 38 import javax.jms.QueueSession ; 39 import javax.jms.Session ; 40 import javax.jms.TextMessage ; 41 import javax.naming.Context ; 42 import javax.naming.InitialContext ; 43 import javax.naming.NamingException ; 44 45 public class SimpleQueueSender { 46 47 private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory 48 .getLog(SimpleQueueSender.class); 49 50 56 public static void main(String [] args) { 57 String queueName = null; 58 Context jndiContext = null; 59 QueueConnectionFactory queueConnectionFactory = null; 60 QueueConnection queueConnection = null; 61 QueueSession queueSession = null; 62 Queue queue = null; 63 QueueSender queueSender = null; 64 TextMessage message = null; 65 final int NUM_MSGS; 66 67 if ((args.length < 1) || (args.length > 2)) { 68 log.info("Usage: java SimpleQueueSender " + 69 "<queue-name> [<number-of-messages>]"); 70 System.exit(1); 71 } 72 queueName = args[0]; 73 log.info("Queue name is " + queueName); 74 if (args.length == 2) { 75 NUM_MSGS = (new Integer (args[1])).intValue(); 76 } 77 else { 78 NUM_MSGS = 1; 79 } 80 81 85 try { 86 jndiContext = new InitialContext (); 87 } 88 catch (NamingException e) { 89 log.info("Could not create JNDI API context: " + e.toString()); 90 System.exit(1); 91 } 92 93 97 try { 98 queueConnectionFactory = (QueueConnectionFactory ) jndiContext.lookup("QueueConnectionFactory"); 99 queue = (Queue ) jndiContext.lookup(queueName); 100 } 101 catch (NamingException e) { 102 log.info("JNDI API lookup failed: " + e); 103 System.exit(1); 104 } 105 106 115 try { 116 queueConnection = queueConnectionFactory.createQueueConnection(); 117 queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); 118 queueSender = queueSession.createSender(queue); 119 message = queueSession.createTextMessage(); 120 for (int i = 0; i < NUM_MSGS; i++) { 121 message.setText("This is message " + (i + 1)); 122 log.info("Sending message: " + 123 message.getText()); 124 queueSender.send(message); 125 } 126 127 131 queueSender.send(queueSession.createMessage()); 132 } 133 catch (JMSException e) { 134 log.info("Exception occurred: " + 135 e.toString()); 136 } 137 finally { 138 if (queueConnection != null) { 139 try { 140 queueConnection.close(); 141 } 142 catch (JMSException e) { 143 } 144 } 145 } 146 } 147 } 148 149 | Popular Tags |