1 45 46 import java.util.Enumeration ; 47 import javax.jms.Connection ; 48 import javax.jms.ConnectionFactory ; 49 import javax.jms.JMSException ; 50 import javax.jms.Message ; 51 import javax.jms.Queue ; 52 import javax.jms.QueueBrowser ; 53 import javax.jms.Session ; 54 import javax.jms.TextMessage ; 55 import javax.naming.Context ; 56 import javax.naming.InitialContext ; 57 import javax.naming.NamingException ; 58 59 60 66 public class Browser { 67 68 73 public static void main(String [] args) { 74 Context context = null; 75 ConnectionFactory factory = null; 76 Connection connection = null; 77 String factoryName = "ConnectionFactory"; 78 String queueName = null; 79 Queue queue = null; 80 Session session = null; 81 QueueBrowser browser = null; 82 83 if (args.length != 1) { 84 System.out.println("usage: Browser <queue>"); 85 System.exit(1); 86 } 87 88 queueName = args[0]; 89 90 try { 92 context = new InitialContext (); 93 } catch (NamingException exception) { 94 System.err.println("Failed to create initial JNDI context: " 95 + exception); 96 System.exit(1); 97 } 98 99 try { 101 factory = (ConnectionFactory ) context.lookup(factoryName); 102 } catch (NamingException exception) { 103 System.err.println("Failed to look up connection factory: " 104 + exception); 105 System.exit(1); 106 } 107 108 try { 110 queue = (Queue ) context.lookup(queueName); 111 } catch (NamingException exception) { 112 System.err.println("Failed to look up queue: " + exception); 113 System.exit(1); 114 } 115 116 try { 117 connection = factory.createConnection(); 119 120 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE); 122 123 browser = session.createBrowser(queue); 125 126 connection.start(); 128 129 Enumeration messages = browser.getEnumeration(); 130 while (messages.hasMoreElements()) { 131 Message message = (Message ) messages.nextElement(); 132 if (message instanceof TextMessage ) { 133 TextMessage text = (TextMessage ) message; 134 System.out.println("Browsed: " + text.getText()); 135 } else if (message != null) { 136 System.out.println("Browsed non text message"); 137 } 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 |