package com.eactive.eai.common.activemq;

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

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

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

public class AmqQueueProducer {

	private Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

	private String queueName = null;

	public AmqQueueProducer(String connectionUrl, String queueName) {
		this.queueName = queueName;
	}

	public void sendMessage(Serializable object, Properties prop) throws JMSException {
		Connection connection = null;
		Session session = null;
		MessageProducer producer = null;

		try {
			// Create a Connection
			connection = AmqPooledConnectionFactory.getInstance().getConnection();

			// Create a Session
			session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

			// Create the destination (Topic or Queue)
			Destination destination = session.createQueue(queueName);
			producer = session.createProducer(destination);
			producer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
			ObjectMessage message = session.createObjectMessage(object);
			if (prop != null) {
				for(Object key : prop.keySet()) {
					message.setObjectProperty(key.toString(), prop.get(key));
				}
			}
			producer.send(message);
		} catch (JMSException ex) {
			logger.error("Send Error = " + ex.getMessage(), ex);
			throw ex;
		} finally {
			if (producer != null) {
				try {
					producer.close();
				} catch (Exception e) {
					// ignored
				}
			}
			if (session != null)
				try {
					session.close();
				} catch (JMSException e) {
					// ignored
				}
			if (connection != null)
				try {
					connection.close();
				} catch (JMSException e) {
					// ignored
				}
		}
	}
}
