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.Message ; 52 import javax.jms.Destination ; 53 import javax.jms.Connection ; 54 import javax.jms.ConnectionFactory ; 55 import javax.jms.Session ; 56 import javax.jms.MessageConsumer ; 57 import javax.jms.Session ; 58 import javax.jms.TextMessage ; 59 60 61 67 public class Receiver { 68 69 74 public static void main(String [] args) { 75 Context context = null; 76 ConnectionFactory factory = null; 77 Connection connection = null; 78 String factoryName = "ConnectionFactory"; 79 String destName = null; 80 Destination dest = null; 81 int count = 1; 82 Session session = null; 83 MessageConsumer receiver = null; 84 85 if (args.length < 1 || args.length > 2) { 86 System.out.println("usage: Receiver <destination> [count]"); 87 System.exit(1); 88 } 89 90 destName = args[0]; 91 if (args.length == 2) { 92 count = Integer.parseInt(args[1]); 93 } 94 95 try { 97 context = new InitialContext (); 98 } catch (NamingException exception) { 99 System.err.println("Failed to create initial JNDI context: " 100 + exception); 101 System.exit(1); 102 } 103 104 try { 106 factory = (ConnectionFactory ) context.lookup(factoryName); 107 } catch (NamingException exception) { 108 System.err.println("Failed to look up connection factory: " 109 + exception); 110 System.exit(1); 111 } 112 113 try { 115 dest = (Destination ) context.lookup(destName); 116 } catch (NamingException exception) { 117 System.err.println("Failed to look up destination: " + exception); 118 System.exit(1); 119 } 120 121 try { 122 connection = factory.createConnection(); 124 125 session = connection.createSession( 127 false, Session.AUTO_ACKNOWLEDGE); 128 129 receiver = session.createConsumer(dest); 131 132 connection.start(); 134 135 for (int i = 0; i < count; ++i) { 136 Message message = receiver.receive(); 137 if (message instanceof TextMessage ) { 138 TextMessage text = (TextMessage ) message; 139 System.out.println("Received: " + text.getText()); 140 } else if (message != null) { 141 System.out.println("Received non text message"); 142 } 143 } 144 145 } catch (JMSException exception) { 146 System.err.println("JMS exception: " + exception); 147 System.exit(1); 148 } finally { 149 if (connection != null) { 150 try { 151 connection.close(); 152 } catch (JMSException exception) { 153 System.err.println("Failed to close connection: " 154 + exception); 155 } 156 } 157 } 158 System.exit(0); 159 } 160 } 161 | Popular Tags |