01: package com.mockrunner.example.jms;
02:
03: import java.util.Hashtable;
04:
05: import javax.jms.JMSException;
06: import javax.jms.Message;
07: import javax.jms.MessageListener;
08: import javax.jms.Session;
09: import javax.jms.TextMessage;
10: import javax.jms.Topic;
11: import javax.jms.TopicConnection;
12: import javax.jms.TopicConnectionFactory;
13: import javax.jms.TopicSession;
14: import javax.jms.TopicSubscriber;
15: import javax.naming.Context;
16: import javax.naming.InitialContext;
17: import javax.naming.NamingException;
18:
19: /**
20: * Simple class that connects to a message server and dumps all
21: * messages to stdout. The first command line parameter is
22: * the INITIAL_CONTEXT_FACTORY of the server, the second one
23: * is the PROVIDER_URL. With the third parameter, received messages
24: * can be limited to those, that match a specified subject (i.e.
25: * a string property with the name <code>subject</code>).
26: */
27: public class NewsSubscriber {
28: private InitialContext context;
29: private String subject;
30:
31: public static void main(String[] args) {
32: if (args.length < 3) {
33: throw new RuntimeException(
34: "Please specify INITIAL_CONTEXT_FACTORY (first parameter) "
35: + "PROVIDER_URL (second parameter) "
36: + "subject (third parameter)");
37: }
38: try {
39: new NewsSubscriber(args[0], args[1], args[2]).init();
40: } catch (Exception exc) {
41: throw new RuntimeException(exc.getMessage());
42: }
43: }
44:
45: public NewsSubscriber(String contextFactory, String providerURL,
46: String subject) throws NamingException {
47: this .subject = subject;
48: Hashtable env = new Hashtable();
49: env.put(Context.INITIAL_CONTEXT_FACTORY, contextFactory);
50: env.put(Context.PROVIDER_URL, subject);
51: context = new InitialContext(env);
52: }
53:
54: public void init() throws Exception {
55: TopicConnectionFactory topicFactory = (TopicConnectionFactory) context
56: .lookup("ConnectionFactory");
57: TopicConnection topicConnection = topicFactory
58: .createTopicConnection();
59: TopicSession topicSession = topicConnection.createTopicSession(
60: false, Session.AUTO_ACKNOWLEDGE);
61: Topic topic = (Topic) context.lookup("topic/newsTopic");
62: TopicSubscriber subscriber = topicSession.createSubscriber(
63: topic, "subject = '" + subject + "'", false);
64: subscriber.setMessageListener(new InternalSubscriber());
65: topicConnection.start();
66: Thread.currentThread().join();
67: }
68:
69: private static class InternalSubscriber implements MessageListener {
70: public void onMessage(Message message) {
71: if (message instanceof TextMessage) {
72: try {
73: System.out.println(((TextMessage) message)
74: .getText());
75: } catch (JMSException exc) {
76: exc.printStackTrace();
77: }
78: }
79: }
80: }
81: }
|