package com.ensode.jms;

import javax.annotation.Resource;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;

public class Main {

//  @Resource(mappedName = "jms/myQueue")
    @Resource(name = "jms/myQueue")
    private static Queue myQueue;
    @Resource(name = "jms/myQueueConnectionFactory")
//  @Resource(mappedName = "jms/myQueueConnectionFactory")
    private static ConnectionFactory myQueueConnectionFactory;

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws JMSException {
        new Main().sendJMSMessageToMyQueue("NetBeans makes JMS trivial!");
    }

    private Message createJMSMessageForjmsMyQueue(Session session,
            Object messageData) throws JMSException {
        TextMessage textMessage = session.createTextMessage();
        textMessage.setText((String) messageData);

        return textMessage;
    }

    private void sendJMSMessageToMyQueue(Object messageData) throws
            JMSException {
        Connection connection = null;
        Session session = null;
        try {
            connection = myQueueConnectionFactory.createConnection();
            session = connection.createSession(false,
                    javax.jms.Session.AUTO_ACKNOWLEDGE);
            MessageProducer messageProducer = session.createProducer(myQueue);
            messageProducer.send(createJMSMessageForjmsMyQueue(session,
                    messageData));
        } finally {
            if (session != null) {
                session.close();
            }
            if (connection != null) {
                connection.close();
            }
        }
    }
}