1 |
package dk.thoerup.messagedriven; |
2 |
|
3 |
import javax.ejb.ActivationConfigProperty; |
4 |
import javax.ejb.MessageDriven; |
5 |
import javax.jms.Connection; |
6 |
import javax.jms.ConnectionFactory; |
7 |
import javax.jms.Destination; |
8 |
import javax.jms.JMSException; |
9 |
import javax.jms.Message; |
10 |
import javax.jms.MessageListener; |
11 |
import javax.jms.MessageProducer; |
12 |
import javax.jms.Queue; |
13 |
import javax.jms.Session; |
14 |
import javax.jms.TextMessage; |
15 |
import javax.naming.InitialContext; |
16 |
|
17 |
|
18 |
|
19 |
|
20 |
@MessageDriven(mappedName = "jms/reverse", activationConfig = { |
21 |
@ActivationConfigProperty(propertyName = "acknowledgeMode", propertyValue = "Auto-acknowledge"), |
22 |
@ActivationConfigProperty(propertyName = "destinationType", propertyValue = "javax.jms.Queue") |
23 |
}) |
24 |
|
25 |
public class ReverserBean implements MessageListener { |
26 |
|
27 |
@Override |
28 |
public void onMessage(Message message) { |
29 |
|
30 |
try { |
31 |
if (message instanceof TextMessage) { |
32 |
TextMessage txt = (TextMessage) message; |
33 |
String msg = reverse( txt.getText() ); |
34 |
|
35 |
Destination d = txt.getJMSReplyTo(); |
36 |
Queue q = (Queue) d; |
37 |
|
38 |
|
39 |
System.out.println("got Message - sending reply to " + q.getQueueName() + " corrID=" + txt.getJMSCorrelationID()); |
40 |
|
41 |
|
42 |
|
43 |
sendReply(msg,q, txt.getJMSCorrelationID()); |
44 |
|
45 |
|
46 |
} |
47 |
|
48 |
} catch (JMSException e) { |
49 |
System.out.println("Error:" + e.getMessage() ); |
50 |
} |
51 |
|
52 |
} |
53 |
|
54 |
private void sendReply(String msg, Queue dest, String id) { |
55 |
try { |
56 |
InitialContext ic = new InitialContext(); |
57 |
|
58 |
ConnectionFactory cf = (ConnectionFactory)ic.lookup("jms/helloFactory"); |
59 |
Connection con = cf.createConnection(); |
60 |
Session session = con.createSession(false, Session.AUTO_ACKNOWLEDGE); |
61 |
MessageProducer producer = session.createProducer(dest); |
62 |
|
63 |
|
64 |
|
65 |
TextMessage reply = session.createTextMessage(); |
66 |
reply.setStringProperty("name", "reply"); |
67 |
reply.setText(msg); |
68 |
reply.setJMSCorrelationID(id); |
69 |
|
70 |
producer.setTimeToLive(5000); //message expires after 5 seconds |
71 |
producer.send(reply); |
72 |
|
73 |
System.out.println("reply send messageid=" + reply.getJMSMessageID() ); |
74 |
|
75 |
con.close(); |
76 |
|
77 |
}catch (Exception e) { |
78 |
System.out.println("Error " + e); |
79 |
} |
80 |
|
81 |
} |
82 |
|
83 |
|
84 |
private String reverse(String str) { |
85 |
StringBuilder sb = new StringBuilder(); |
86 |
|
87 |
for (int i=str.length()-1; i>=0; i--) { |
88 |
sb.append( str.charAt(i) ); |
89 |
} |
90 |
|
91 |
return sb.toString(); |
92 |
} |
93 |
} |