1 45 46 import javax.naming.Context ; 47 import javax.naming.InitialContext ; 48 import javax.naming.NamingException ; 49 import javax.jms.ConnectionFactory ; 50 import javax.jms.Connection ; 51 import javax.jms.Topic ; 52 import javax.jms.TopicSubscriber ; 53 import javax.jms.Session ; 54 import javax.jms.Message ; 55 import javax.jms.TextMessage ; 56 import javax.jms.JMSException ; 57 58 59 65 public class DurableSubscriber { 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 topicName = null; 78 Topic topic = null; 79 int count = 1; 80 Session session = null; 81 TopicSubscriber subscriber = null; 82 String subscriptionName = "rubADubSub"; 83 84 if (args.length < 1 || args.length > 2) { 85 System.out.println("usage: DurableSubscriber <topic> [count]"); 86 System.exit(1); 87 } 88 89 topicName = 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 topic = (Topic ) context.lookup(topicName); 115 } catch (NamingException exception) { 116 System.err.println("Failed to look up topic: " + 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 subscriber = session.createDurableSubscriber( 130 topic, subscriptionName); 131 132 connection.start(); 134 135 for (int i = 0; i < count; ++i) { 136 Message message = subscriber.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 } 162 | Popular Tags |