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