1 18 19 28 package org.apache.activemq.demo; 29 30 32 import javax.jms.Connection ; 33 import javax.jms.ConnectionFactory ; 34 import javax.jms.Destination ; 35 import javax.jms.JMSException ; 36 import javax.jms.MessageProducer ; 37 import javax.jms.Session ; 38 import javax.jms.TextMessage ; 39 import javax.naming.Context ; 40 import javax.naming.InitialContext ; 41 import javax.naming.NamingException ; 42 43 49 public class SimpleProducer { 50 51 private static final org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory 52 .getLog(SimpleProducer.class); 53 54 57 public static void main(String [] args) { 58 Context jndiContext = null; 59 ConnectionFactory connectionFactory = null; 60 Connection connection = null; 61 Session session = null; 62 Destination destination = null; 63 MessageProducer producer = null; 64 String destinationName = null; 65 final int NUM_MSGS; 66 67 if ((args.length < 1) || (args.length > 2)) { 68 log.info("Usage: java SimpleProducer <destination-name> [<number-of-messages>]"); 69 System.exit(1); 70 } 71 destinationName = args[0]; 72 log.info("Destination name is " + destinationName); 73 if (args.length == 2) { 74 NUM_MSGS = (new Integer (args[1])).intValue(); 75 } 76 else { 77 NUM_MSGS = 1; 78 } 79 80 83 try { 84 jndiContext = new InitialContext (); 85 } 86 catch (NamingException e) { 87 log.info("Could not create JNDI API context: " + e.toString()); 88 System.exit(1); 89 } 90 91 94 try { 95 connectionFactory = (ConnectionFactory ) jndiContext.lookup("ConnectionFactory"); 96 destination = (Destination ) jndiContext.lookup(destinationName); 97 } 98 catch (NamingException e) { 99 log.info("JNDI API lookup failed: " + e); 100 System.exit(1); 101 } 102 103 111 try { 112 connection = connectionFactory.createConnection(); 113 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 114 producer = session.createProducer(destination); 115 TextMessage message = session.createTextMessage(); 116 for (int i = 0; i < NUM_MSGS; i++) { 117 message.setText("This is message " + (i + 1)); 118 log.info("Sending message: " + message.getText()); 119 producer.send(message); 120 } 121 122 125 producer.send(session.createMessage()); 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 142 | Popular Tags |