package com.eactive.eai.common.jeus;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Properties;

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

import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.jms.JmsServiceLocator;
import com.eactive.eai.common.util.Logger;

public class JeusQueueProducer {
	Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	QueueConnectionFactory qconFactory = null;
	
	String connectionFactory = null;
	String destination = null;

	public JeusQueueProducer(String connectionUrl, String queueName) throws Exception {
		this.connectionFactory = connectionUrl;
		this.destination = queueName;
	}

	public void sendMessage(Serializable object, Properties prop) throws Exception {
		QueueConnection qcon = null;
		QueueSession qsession = null;
		Queue queue = null;
		QueueSender qsender = null;
		try {
			JmsServiceLocator locator = JmsServiceLocator.getInstance();

			qconFactory = locator.getQueueConnectionFactory(connectionFactory);
			qcon = qconFactory.createQueueConnection();
			qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);

			queue = locator.getQueue(destination);
			qsender = qsession.createSender(queue);

			ObjectMessage msg = qsession.createObjectMessage();
			msg.setObject(object);

			// Properties setting setStringProperties();
			if (prop != null) {
				Iterator it = prop.keySet().iterator();
				while (it.hasNext()) {
					String key = (String) it.next();
					String value = prop.getProperty(key);
					msg.setStringProperty(key, value);
				}
			}

			qsender.send(msg);
		} catch (Exception e) {
			e.printStackTrace();
			// throw new JMSException("RECEAICUL001");
			throw new JMSException(ExceptionUtil.getErrorCode(e, "RECEAICUL001"));
		} finally {
			try {
				if (qsender != null)
					qsender.close();
			} catch (Exception e) {
				// nothing to do 
			}
			try {
				if (qsession != null)
					qsession.close();
			} catch (Exception e) {
				// nothing to do
			}
			try {
				if (qcon != null)
					qcon.close();
			} catch (Exception e) {
				// nothing to do
			}
		}
	}
}
