/*
 * JBoss, the OpenSource EJB server
 *
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 */
package org.jboss.test.jmsra.bean;

import java.rmi.RemoteException;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.ejb.EJBException;

import javax.naming.InitialContext;
import javax.naming.Context;

import javax.jms.QueueConnectionFactory;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.QueueReceiver;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.Message;
import javax.jms.JMSException;

import org.apache.log4j.Category;

/**
 * <p>QueueRec bean, get a message from the configured queue. The JMS stuff is
 * configured via the deployment descriptor.
 * 
 * <p>Test sync receive for jms ra.
 * 
 * @author <a href="mailto:peter.antman@tim.se">Peter Antman </a>
 * @version $Revision: 1.3 $
 */
public class QueueRecBean implements SessionBean
{

    private final Category log = Category.getInstance(this.getClass());

    /**
     * Name used to lookup QueueConnectionFactory
     */
    private static final String CONNECTION_JNDI = "java:comp/env/jms/MyQueueConnection";

    private QueueConnectionFactory factory = null;

    /**
     * Name used to lookup queue destination
     */
    private static final String QUEUE_JNDI = "java:comp/env/jms/QueueName";

    private SessionContext ctx = null;

    private Queue queue = null;

    public QueueRecBean()
    {
    }

    public void setSessionContext(SessionContext ctx)
    {
        this.ctx = ctx;
    }

    public void ejbCreate()
    {
        try
        {
            Context context = new InitialContext();

            // Lookup the queue
            queue = (Queue) context.lookup(QUEUE_JNDI);

            // Lookup the connection factory
            factory = (QueueConnectionFactory) context.lookup(CONNECTION_JNDI);

            // Keep both around
        }
        catch (Exception ex)
        {
            // JMSException or NamingException could be thrown
            log.debug("failed", ex);
            throw new EJBException(ex.toString());
        }
    }

    public void ejbRemove() throws RemoteException
    {
    }

    public void ejbActivate()
    {
    }

    public void ejbPassivate()
    {
    }

    /**
     * Get a message with sync rec.
     * 
     * @return int property name defined in Publisher.JMS_MESSAGE_NR, or -1 if
     *         fail.
     */
    public int getMessage()
    {
        QueueConnection queueConnection = null;
        QueueSession queueSession = null;
        int ret;
        try
        {

            // Create a session
            queueConnection = factory.createQueueConnection();
            queueConnection.start();
            queueSession = queueConnection.createQueueSession(true, Session.AUTO_ACKNOWLEDGE);
            // Get message
            QueueReceiver queueReceiver = queueSession.createReceiver(queue);
            log.info("Waiting for message");
            Message msg = queueReceiver.receive(500L);
            if (msg != null)
            {
                log.info("Recived message: " + msg);
                int nr = msg.getIntProperty(Publisher.JMS_MESSAGE_NR);
                log.debug("nr: " + nr);
                ret = nr;
            }
            else
            {
                log.info("NO message recived");
                ret = -1;
            }

        }
        catch (JMSException ex)
        {

            log.warn("failed", ex);
            ctx.setRollbackOnly();
            throw new EJBException(ex.toString());
        }
        finally
        {
            // ALWAYS close the session. It's pooled, so do not worry.
            if (queueConnection != null)
            {
                try
                {
                    queueConnection.close();
                }
                catch (Exception e)
                {
                    log.debug("failed", e);
                }
            }
        }
        return ret;
    }

}