1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 /***
41 * The SimpleQueueReceiver class consists only of a main method,
42 * which fetches one or more messages from a queue using
43 * synchronous message delivery. Run this program in conjunction
44 * with SimpleQueueSender. Specify a queue name on the command
45 * line when you run the program.
46 */
47 package org.codehaus.activemq.demo;
48
49 import javax.jms.Connection;
50 import javax.jms.ConnectionFactory;
51 import javax.jms.Destination;
52 import javax.jms.JMSException;
53 import javax.jms.Message;
54 import javax.jms.MessageConsumer;
55 import javax.jms.Session;
56 import javax.jms.TextMessage;
57 import javax.naming.Context;
58 import javax.naming.InitialContext;
59 import javax.naming.NamingException;
60
61 /***
62 * A simple polymorphic JMS consumer which can work with Queues or Topics
63 * which uses JNDI to lookup the JMS connection factory and destination
64 *
65 * @version $Revision: 1.1 $
66 */
67 public class SimpleConsumer {
68
69 /***
70 * @param args the queue used by the example
71 */
72 public static void main(String[] args) {
73 String destinationName = null;
74 Context jndiContext = null;
75 ConnectionFactory connectionFactory = null;
76 Connection connection = null;
77 Session session = null;
78 Destination destination = null;
79 MessageConsumer consumer = null;
80
81
82
83
84 if (args.length != 1) {
85 System.out.println("Usage: java SimpleConsumer <destination-name>");
86 System.exit(1);
87 }
88 destinationName = new String(args[0]);
89 System.out.println("Destination name is " + destinationName);
90
91
92
93
94 try {
95 jndiContext = new InitialContext();
96 }
97 catch (NamingException e) {
98 System.out.println("Could not create JNDI API " +
99 "context: " + e.toString());
100 System.exit(1);
101 }
102
103
104
105
106 try {
107 connectionFactory = (ConnectionFactory)
108 jndiContext.lookup("ConnectionFactory");
109 destination = (Destination) jndiContext.lookup(destinationName);
110 }
111 catch (NamingException e) {
112 System.out.println("JNDI API lookup failed: " +
113 e.toString());
114 System.exit(1);
115 }
116
117
118
119
120
121
122
123
124
125
126
127 try {
128 connection = connectionFactory.createConnection();
129 session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
130 consumer = session.createConsumer(destination);
131 connection.start();
132 while (true) {
133 Message m = consumer.receive(1);
134 if (m != null) {
135 if (m instanceof TextMessage) {
136 TextMessage message = (TextMessage) m;
137 System.out.println("Reading message: " + message.getText());
138 }
139 else {
140 break;
141 }
142 }
143 }
144 }
145 catch (JMSException e) {
146 System.out.println("Exception occurred: " + e);
147 }
148 finally {
149 if (connection != null) {
150 try {
151 connection.close();
152 }
153 catch (JMSException e) {
154 }
155 }
156 }
157 }
158 }