package org.codehaus.activemq.itest.ejb;

import javax.ejb.MessageDrivenBean;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenContext;
import javax.jms.MessageListener;
import javax.jms.Message;
import javax.jms.ConnectionFactory;
import javax.jms.Connection;
import javax.jms.Session;
import javax.jms.Queue;
import javax.jms.MessageProducer;
import javax.jms.JMSException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NameClassPair;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 *
 * @version $Revision: 1.1 $ $Date: 2004/10/14 18:44:16 $
 *
 * */
public class MDBTransferBean implements MessageDrivenBean, MessageListener {
    private static final Log log = LogFactory.getLog(MDBTransferBean.class);

    public void ejbCreate() {

    }

    public void ejbRemove() throws EJBException {
    }

    public void setMessageDrivenContext(MessageDrivenContext messageDrivenContext) throws EJBException {
    }

    public void onMessage(Message message) {
        System.out.println("entering onMessage");
        try {
            printCompEnv();
            InitialContext jndiContext = new InitialContext();
            ConnectionFactory cf = (ConnectionFactory) jndiContext
                    .lookup("java:comp/env/jms/Default");
            Connection con = cf.createConnection();
            try {
                Session session = con.createSession(true, 0);
                Queue q = (Queue) jndiContext.lookup("java:comp/env/jms/OutQueue");
                MessageProducer producer = session.createProducer(q);
                producer.send(message);
            } finally {
                con.close();
            }
        } catch (NamingException e) {
            log.info(e);
        } catch (JMSException e) {
            log.info(e);
        }
        System.out.println("leaving onMessage");
    }

   /**
    *
    */
   private void printCompEnv() throws NamingException {
       log.warn("Printing java:comp/env/jms context: ");
       Context c = (Context) new InitialContext().lookup("java:comp/env/jms");
       NamingEnumeration iter = c.list("");
       while (iter.hasMoreElements()) {
           NameClassPair pair = (NameClassPair) iter.next();
           log.warn("'" + pair.getName() + "'");
           /*
            * Object obj = ctx.lookup(node.getName()); if ( obj instanceof
            * Context ){ node.type = Node.CONTEXT;
            * buildNode(node,(Context)obj); } else if (obj instanceof
            * java.rmi.Remote) { node.type = Node.BEAN; } else { node.type =
            * Node.OTHER; }
            */
       }
   }

}


