KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > example > MessageSenderServlet


1 package example;
2
3 import java.io.IOException;
4 import java.io.PrintWriter;
5
6 import java.util.logging.Logger;
7
8 import javax.jms.Message;
9 import javax.jms.Queue;
10 import javax.jms.Connection;
11 import javax.jms.ConnectionFactory;
12 import javax.jms.MessageProducer;
13 import javax.jms.Session;
14
15 import javax.naming.Context;
16 import javax.naming.InitialContext;
17
18 import javax.servlet.GenericServlet;
19 import javax.servlet.ServletException;
20 import javax.servlet.ServletRequest;
21 import javax.servlet.ServletResponse;
22 import javax.naming.NamingException;
23 import javax.jms.JMSException;
24
25 public class MessageSenderServlet extends GenericServlet {
26   static protected final Logger log =
27     Logger.getLogger(MessageSenderServlet.class.getName());
28
29   Queue _queue;
30   ConnectionFactory _factory;
31   
32   public void init()
33     throws ServletException
34   {
35     super.init();
36
37     // look up the objects.
38
try {
39       Context env = (Context) new InitialContext().lookup("java:comp/env");
40       _queue = (Queue) env.lookup("jms/queue");
41       if (_queue == null)
42         throw new ServletException("`java:comp/env/jms/queue' lookup failed");
43
44       _factory = (ConnectionFactory) env.lookup("jms/queue-connection-factory");
45       if (_factory == null)
46         throw new ServletException("`java:comp/env/jms/queue-connection-factory' lookup failed");
47
48     } catch (NamingException ex) {
49       throw new ServletException(ex);
50     }
51   }
52
53   public void service(ServletRequest request, ServletResponse response)
54     throws ServletException, IOException
55   {
56     int count = 5;
57
58     try {
59       Connection connection = _factory.createConnection();
60       int ackMode = Session.AUTO_ACKNOWLEDGE;
61       Session jmsSession = connection.createSession(false, ackMode);
62
63       MessageProducer producer = jmsSession.createProducer(_queue);
64
65       for (int i = 1; i <= count; i++) {
66         String text = "hello, world: message #" + String.valueOf(i);
67         sendMessage(jmsSession,producer,text);
68       }
69     } catch (JMSException ex) {
70       throw new ServletException(ex);
71     }
72
73     PrintWriter out = response.getWriter();
74     out.print("Sent " + String.valueOf(count) + " messages.");
75   }
76
77   protected void sendMessage(Session jmsSession,
78                  MessageProducer producer,
79                  String text)
80     throws JMSException
81   {
82     // create the message
83
Message message = jmsSession.createTextMessage(text);
84
85     // send the message
86
producer.send(message);
87
88     log.info("Sent message: " + text);
89   }
90 }
91
92
Popular Tags