KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jms > service > ServiceAvailabilityBean


1 package jms.service;
2
3 import javax.ejb.MessageDrivenBean JavaDoc;
4 import javax.ejb.MessageDrivenContext JavaDoc;
5 import javax.ejb.EJBException JavaDoc;
6 import javax.jms.*;
7 import javax.naming.NamingException JavaDoc;
8 import javax.naming.InitialContext JavaDoc;
9
10 /**
11  * This is a simple MDB that processes a message containing an integer
12  * that represents a zip code, and returns a message containing a
13  * boolean indicating whether DSL service is available at that zip code
14  * or not.
15  * Internally the bean just returns true for zip codes < 50000 and
16  * false otherwise.
17  */

18 public class ServiceAvailabilityBean implements MessageDrivenBean JavaDoc, MessageListener {
19     MessageDrivenContext JavaDoc context = null;
20
21     public void setMessageDrivenContext(MessageDrivenContext JavaDoc context) {
22     this.context = context;
23     }
24     public void ejbCreate() throws EJBException JavaDoc { }
25
26     public void ejbRemove() {
27     context = null;
28     }
29
30     public void onMessage(Message msg) {
31     try {
32         TextMessage message = (TextMessage)msg;
33         // assume we have an integer
34
int zipCode = new Integer JavaDoc(message.getText()).intValue();
35         // return true if zip code < 50000, false otherwise
36
if (zipCode<50000)
37         sendMessage(message,"true");
38         else
39         sendMessage(message,"false");
40     } catch(Exception JavaDoc e) {
41         // aargh - this should not happen usually
42
System.out.println(e);
43         e.printStackTrace();
44     }
45     }
46
47     public void sendMessage(TextMessage requestMsg, String JavaDoc serviceAvailable)
48     throws NamingException JavaDoc, JMSException {
49     // wait for some time
50
InitialContext JavaDoc jndiContext = new InitialContext JavaDoc();
51     QueueConnectionFactory factory = (QueueConnectionFactory)
52         jndiContext.lookup("ConnectionFactory");
53     QueueConnection connect = factory.createQueueConnection();
54     QueueSession session = connect.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
55     Queue queue = (Queue)requestMsg.getJMSReplyTo();
56     QueueSender sender = session.createSender(queue);
57     TextMessage message = session.createTextMessage();
58     // set the correlation ID
59
message.setJMSCorrelationID(requestMsg.getJMSMessageID());
60     // set the text
61
message.setText(serviceAvailable);
62     sender.send(message);
63     sender.close();
64     session.close();
65     connect.close();
66     }
67 }
68
69
Popular Tags