1 45 46 import javax.naming.Context ; 47 import javax.naming.InitialContext ; 48 import javax.naming.NamingException ; 49 50 import javax.jms.JMSException ; 51 import javax.jms.Destination ; 52 import javax.jms.Connection ; 53 import javax.jms.ConnectionFactory ; 54 import javax.jms.MessageProducer ; 55 import javax.jms.Session ; 56 import javax.jms.TextMessage ; 57 58 59 65 public class Sender { 66 67 72 public static void main(String [] args) { 73 Context context = null; 74 ConnectionFactory factory = null; 75 Connection connection = null; 76 String factoryName = "ConnectionFactory"; 77 String destName = null; 78 Destination dest = null; 79 int count = 1; 80 Session session = null; 81 MessageProducer sender = null; 82 String text = "Message "; 83 84 if (args.length < 1 || args.length > 2) { 85 System.out.println("usage: Sender <destination> [count]"); 86 System.exit(1); 87 } 88 89 destName = args[0]; 90 if (args.length == 2) { 91 count = Integer.parseInt(args[1]); 92 } 93 94 try { 96 context = new InitialContext (); 97 } catch (NamingException exception) { 98 System.err.println("Failed to create initial JNDI context: " 99 + exception); 100 System.exit(1); 101 } 102 103 try { 105 factory = (ConnectionFactory ) context.lookup(factoryName); 106 } catch (NamingException exception) { 107 System.err.println("Failed to look up connection factory: " 108 + exception); 109 System.exit(1); 110 } 111 112 try { 114 dest = (Destination ) context.lookup(destName); 115 } catch (NamingException exception) { 116 System.err.println("Failed to look up destination: " + exception); 117 System.exit(1); 118 } 119 120 try { 121 connection = factory.createConnection(); 123 124 session = connection.createSession( 126 false, Session.AUTO_ACKNOWLEDGE); 127 128 sender = session.createProducer(dest); 130 131 connection.start(); 133 134 for (int i = 0; i < count; ++i) { 135 TextMessage message = session.createTextMessage(); 136 message.setText(text + (i + 1)); 137 sender.send(message); 138 } 139 } catch (JMSException exception) { 140 System.err.println("JMS exception: " + exception); 141 System.exit(1); 142 } finally { 143 if (connection != null) { 144 try { 145 connection.close(); 146 } catch (JMSException exception) { 147 System.err.println("Failed to close connection: " 148 + exception); 149 } 150 } 151 } 152 System.exit(0); 153 } 154 } 155 | Popular Tags |