/**
 *
 * Copyright 2004 Hiram Chirino
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 **/
package org.codehaus.activemq.itest.ejb;

import javax.ejb.SessionBean;
import javax.ejb.SessionContext;
import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
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;

/**
 * This is a SSB that uses an outbound JMS Resource Adapter.
 *
 * @version $Revision: 1.3 $
 */
public class MessengerBean implements SessionBean {
    private static final Log log = LogFactory.getLog(MessengerBean.class);

    private SessionContext sessionContext;

    public void ejbCreate() {
    }

    public void ejbRemove() {
    }

    public void ejbActivate() {
    }

    public void ejbPassivate() {
    }

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

    /**
     * Sends a message to queue.
     *
     * @param text
     * @throws java.rmi.RemoteException
     * @throws NamingException
     * @throws JMSException
     */
    public void sendMessage(String text, int reps)
            throws java.rmi.RemoteException, NamingException, JMSException {
    	
    	log.info("sendMessage start");
        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/SendQueue");
            MessageProducer producer = session.createProducer(q);
            for (int i = 0; i < reps; i++) {
            	log.info("Sending message: "+i);
                producer.send(session.createTextMessage(text+":"+i));
            }
        } finally {
        	log.info("sendMessage end");
            con.close();
        }
    }

    /**
     * Sends a message to a named queue.
     *
     * @param text
     * @throws java.rmi.RemoteException
     * @throws NamingException
     * @throws JMSException
     */
    public void sendMessage(Destination dest, String text, int reps)
            throws java.rmi.RemoteException, NamingException, JMSException {
    	log.info("sendMessage start");
        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);
            MessageProducer producer = session.createProducer(dest);
            for (int i = 0; i < reps; i++) {
            	log.info("Sending message: "+i);
                producer.send(session.createTextMessage(text+":"+i));
            }
        } finally {
        	log.info("sendMessage end");
            con.close();
        }
    }

    /**
     * Sends a message to a named queue.
     *
     * @param text
     * @throws java.rmi.RemoteException
     * @throws NamingException
     * @throws JMSException
     */
    public void sendMessage(Destination dest, String text)
            throws java.rmi.RemoteException, NamingException, JMSException {
    	log.info("sendMessage start");
        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);
            MessageProducer producer = session.createProducer(dest);
            producer.send(session.createTextMessage(text));
        } finally {
        	log.info("sendMessage end");
            con.close();
        }
    }

    /**
     * Receives a message from a queue.
     *
     * @param timeout
     * @return @throws
     *         java.rmi.RemoteException
     * @throws NamingException
     * @throws JMSException
     */
    public String receiveMessage(Destination dest, long timeout)
            throws java.rmi.RemoteException, NamingException, JMSException {
    	log.info("receiveMessage start");
        InitialContext jndiContext = new InitialContext();
        ConnectionFactory cf = (ConnectionFactory) jndiContext
                .lookup("java:comp/env/jms/Default");
        Connection con = cf.createConnection();
        con.start();
        int received = 0;
        try {
            Session session = con.createSession(true, 0);
            MessageConsumer consumer = session.createConsumer(dest);
            TextMessage message = null;
            message = (TextMessage) consumer.receive(timeout);
            return message.getText();
        } finally {
        	log.info("receiveMessage end");
            con.close();
        }
    }


    /**
     *
     */
    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; }
             */
        }
    }

}
