// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package jcademo.ejb;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.EJB;
import javax.ejb.MessageDriven;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

// MDB Test2Service is called with messages from message queue test2inqueue
@MessageDriven(name="Test2Service",
               activationConfig={@ActivationConfigProperty(propertyName="destinationType", propertyValue="javax.jms.Queue"),
                                 @ActivationConfigProperty(propertyName="destination", propertyValue="java:jboss/exported/jms/queue/test2inqueue")})
public class Test2MDB implements MessageListener {
	@EJB
	private TestSLSB slsb;
    @Resource(mappedName="java:/JmsXA")
    private ConnectionFactory cf;
    @Resource(mappedName="java:jboss/exported/jms/queue/test2outqueue")
    private Queue q;
	@Override
	public void onMessage(Message msg) {
		try {
			// parse id and numbers to add from message
			String text = ((TextMessage)msg).getText();
			String[] textparts = text.split("\r\n");
			String id = textparts[0];
			String line = textparts[1];
			String[] lineparts = line.split(" ");
			int a = Integer.parseInt(lineparts[0]);
			int b = Integer.parseInt(lineparts[1]);
			// apply business logic
			int c = slsb.add(a, b);
			// send response to message queue test2outqueue
			Connection con = cf.createConnection();
			Session ses = con.createSession(false,  Session.AUTO_ACKNOWLEDGE);
			MessageProducer sender = ses.createProducer(q);
			sender.send(ses.createTextMessage(id + "\r\n" + Integer.toString(c)));
			con.close();
		} catch (JMSException e) {
			e.printStackTrace();
		}
	}
}
