package com.eactive.eai.common.routing;

import javax.jms.TextMessage;
import javax.jms.ObjectMessage;
import javax.jms.JMSException;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;

import com.eactive.eai.common.util.ServiceLocator;

public class JMSQueueSender {
	private QueueConnectionFactory factory; 
	private QueueConnection con = null;
	private QueueSession ses = null;
	private QueueSender qsender;
    private Queue queue = null;
    private TextMessage msg;
    private ObjectMessage objmsg;
    
    private String jms_connectionfactory;
    private String queue_name;
    
    public void send(String queueConnectionFactory, String queueName, String message, String id) throws JMSException {
        init(queueConnectionFactory, queueName);
        msg = ses.createTextMessage();
        if(id!=null) msg.setJMSCorrelationID(id);
        msg.setText(message);
        qsender.send(msg);
        closeQueueConnection();
    }
    
    public void sendObject(String queueConnectionFactory, String queueName, java.io.Serializable message, String id) throws JMSException {

        init(queueConnectionFactory, queueName);
        objmsg = ses.createObjectMessage();
        if(id!=null) objmsg.setJMSCorrelationID(id);
        objmsg.setObject(message);
        qsender.send(objmsg);
        closeQueueConnection();
    }
    
    public void init(String queueConnectionFactory, String queueName) {
        jms_connectionfactory = queueConnectionFactory;
        queue_name = queueName;
        startQueueConnection();
    }
    
    
    public void close() {
       closeQueueConnection();    
    }
    
    private void startQueueConnection() {
        try {
			ServiceLocator locator = ServiceLocator.getInstance();            
            
			factory = locator.getQueueConnectionFactory(jms_connectionfactory);
			con = factory.createQueueConnection();
			ses = con.createQueueSession(false, QueueSession.AUTO_ACKNOWLEDGE);			
            queue = (Queue)locator.getQueue(queue_name);
			qsender = ses.createSender(queue);
        	con.start();
		} catch (Throwable e) {
            e.printStackTrace();
			closeQueueConnection();
		}
    }
    private void closeQueueConnection() {
		if (ses != null) try { ses.close(); ses = null; } catch (Throwable e) {};
		if (con != null) try { con.stop(); } catch (Throwable e) {};
		if (con != null) try { con.close(); con = null; } catch (Throwable e) {};
    }
}
