package com.eactive.eai.common.activemq;

import java.io.Serializable;

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 org.apache.activemq.ActiveMQConnectionFactory;

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

public class AmqQueueProducer {
	
	Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);
	
	Connection connection = null;
	Session session = null;
	MessageProducer producer = null;
	String connectionUrl = null;
	String queueName = null;
	
	public AmqQueueProducer(String connectionUrl, String queueName) throws Exception {
		this.connectionUrl = connectionUrl;
		this.queueName = queueName;
	}
	
	public void sendMessage(Serializable object) throws Exception {
		try {
			ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(connectionUrl);
			connectionFactory.setTrustAllPackages(true);
			
	        // Create a Connection
	        connection = connectionFactory.createConnection();
	        connection.start();
	
	        // 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);
			producer.send(message);
		}
		catch(Exception ex) {
			logger.error("Send Error = " + ex.getMessage(), ex);
			throw ex;
		}
		finally {
			if(session != null)
				try {
					session.close();
				} catch (JMSException e) { }
        	if(connection != null)
				try {
					connection.close();
				} catch (JMSException e) { }
		}
	}	
}
