/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jtests.beans.secured;

import javax.ejb.CreateException;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.QueueConnectionFactory;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueSession;
import javax.jms.QueueSender;
import javax.jms.Session;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import org.objectweb.jonas.common.Log;
import org.objectweb.util.monolog.api.Logger;
import org.objectweb.util.monolog.api.BasicLevel;

/**
 * Come from the mdb tests
 * @author Philippe Coq & Philippe Durieux
 * @author Florent Benoit (run-as test)
 */
public class Listener implements MessageDrivenBean, MessageListener {

    /**
     * Logger
     */
    private static Logger logger = null;

    /**
     * Context
     */
    private transient MessageDrivenContext mdbContext;

    /**
     * Class of the other bean
     */
    private transient DerivedLocalHome dh = null;

    
    /** 
     * Default constructor
     */
    public Listener() {
    }

    // ------------------------------------------------------------------
    // MessageDrivenBean implementation
    // ------------------------------------------------------------------

    /** 
     * Set the associated context. The container call this method
     * after the instance creation. 
     * The enterprise Bean instance should store the reference to the context
     * object in an instance variable. 
     * This method is called with no transaction context.
     *
     * @param ctx MessageDrivenContext A MessageDrivenContext interface for the instance.
     */

    public void setMessageDrivenContext(MessageDrivenContext ctx) {
        if (logger == null) {
            logger = Log.getLogger(Log.JONAS_TESTS_PREFIX);
        }
        logger.log(BasicLevel.DEBUG, "");
        mdbContext = ctx;
    } 

    /**
     * A container invokes this method before it ends the life of the message-driven object. 
     * This happens when a container decides to terminate the message-driven object. 
     *
     * This method is called with no transaction context. 
     *
     */
    public void ejbRemove() {
        logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * The Message driven  bean must define an ejbCreate methods with no args.
     */
    public void ejbCreate() {
        logger.log(BasicLevel.DEBUG, "");
    }

    /**
     * onMessage method
     * @param message receive message
     */
    public void onMessage(Message message) {
        logger.log(BasicLevel.DEBUG, "");

        String messageTest = "ok";

        try {
            // Don't test message but test run-as bean by calling another bean
            try {
                InitialContext ictx = new InitialContext();
                dh = (DerivedLocalHome) ictx.lookup("java:comp/env/ejb/derivednorunaslocal");
            } catch (NamingException e) {
                logger.log(BasicLevel.ERROR, "Listener : Cannot get DerivedHome:" + e);
                messageTest = "fail : Cannot get DerivedHome: " + e;
            }
            
            // Create a new bean for this message (with right run-as)
            try {
                dh.create();
            } catch (EJBException ejbe) {
                messageTest = "fail : EJBException : " + ejbe.getMessage();
                logger.log(BasicLevel.ERROR, "EJBException: " + ejbe.getMessage());
            } catch (CreateException e) {
                messageTest = "fail : Can not create the bean";
                logger.log(BasicLevel.ERROR, "Listener exception: " + e);
            }
        } catch (Exception ee) {
            logger.log(BasicLevel.ERROR, "exception: " + ee);
             messageTest = "fail :" + ee.getMessage();
        }

        QueueConnectionFactory qcf = null;
        Queue queue = null;
        try {
            // Send the message (ok or fail)
            try {
                InitialContext ictx = new InitialContext();
                qcf = (QueueConnectionFactory) ictx.lookup("java:comp/env/jms/RunAsFactory");
                queue = (Queue) ictx.lookup("java:comp/env/jms/testRunAs");
            } catch (NamingException e) {
                logger.log(BasicLevel.ERROR, "Listener : Cannot get DerivedHome:" + e);
            }
            
            
            QueueConnection qc = qcf.createQueueConnection();
            QueueSession qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
            Message m = qs.createMessage();
            m.setStringProperty("testRunAsJms", messageTest);
            QueueSender qsender = qs.createSender(queue);
            qsender.send(m);
            
            // close
            qsender.close();
            qs.close();
            qc.close();
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "exception:" + e);
        }
    }
}
