/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2007 Bull S.A.S.
 * Contact: jonas-team@ow2.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: JServiceEndpoint.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.lib.ejb21;

import java.rmi.Remote;
import java.rmi.RemoteException;

import javax.rmi.PortableRemoteObject;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.handler.MessageContext;
import javax.xml.rpc.server.ServiceLifecycle;

import org.ow2.jonas.deployment.ejb.MethodDesc;
import org.ow2.jonas.lib.util.Log;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * Implementation of the Service Endpoint Interface.
 * The lifeCycle of this object is managed by the JOnASEJBProvider.
 * Although this object implements Remote, it is accessed locally today.
 * @author Guillaume Sauthier, Philippe Durieux
 */
public class JServiceEndpoint extends PortableRemoteObject implements Remote, ServiceLifecycle {

    /**
     * Logger, used also in the generated part.
     */
    protected static Logger logger = null;

    /**
     * switch instance to use
     */
    protected JSessionSwitch bs;

    /**
     * bean factory
     */
    protected JStatelessFactory bf;

    private MessageContext messageContext = null;

    /**
     * @throws java.rmi.RemoteException
     */
    public JServiceEndpoint(JStatelessFactory sf) throws RemoteException {
        super();
        logger = Log.getLogger("org.ow2.jonas.lib.ejb21.endpoint");
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        bf = sf;
    }

    // ---------------------------------------------------------------
    // other public methods
    // ---------------------------------------------------------------

    /**
     * Set the MessageContext in the StatelessContext
     * @param msgctx Axis MessageContext
     */
    public void setMessageContext(MessageContext msgctx) {
        messageContext = msgctx;
    }

    /**
     * Get the messageContext
     * @param mc JAX-RPC MessageContext
     */
    public MessageContext getMessageContext() {
        return messageContext;
    }

    /**
     * finish initialization
     * @param bs The Session Switch
     */
    public void setSessionSwitch(JSessionSwitch bs) {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        this.bs = bs;
    }

    /**
     * preInvoke is called before any request.
     * @param txa Transaction Attribute (Supports, Required, ...)
     * @return A RequestCtx object
     * @throws RemoteException preInvoke fail
     */
    public RequestCtx preInvoke(int txa) throws RemoteException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        return bf.preInvokeRemote(txa);
    }

    /**
     * Check if the access to the bean is authorized
     * @param ejbInv object containing security signature of the method, args of
     *        method, etc
     */
    public void checkSecurity(EJBInvocation ejbInv) {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        bf.checkSecurity(ejbInv);
    }

    /**
     * postInvoke is called after any request.
     * @param rctx The RequestCtx that was returned at preInvoke()
     * @throws RemoteException postInvoke fail
     */
    public void postInvoke(RequestCtx rctx) throws RemoteException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        try {
            bf.postInvokeRemote(rctx);
        } finally {
            // put instance in the pool for future reuse.
            bs.releaseICtx(rctx, false);
        }
    }

    // --------------------------------------------------------------------
    // ServiceLifeCycle implementation
    // --------------------------------------------------------------------

    /**
     * Nothing to do here.
     */
    public void init(Object arg0) throws ServiceException {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
    }

    /**
     * remove the bean instance.
     */
    public void destroy() {
        if (logger.isLoggable(BasicLevel.DEBUG)) {
            logger.log(BasicLevel.DEBUG, "");
        }
        RequestCtx rctx = null;
        try {
            rctx = bf.preInvoke(MethodDesc.TX_NOT_SET);
            bf.checkSecurity(null);
        } catch (Exception e) {
            logger.log(BasicLevel.ERROR, "preInvoke failed: ", e);
            return;
        }
        try {
            JSessionContext bctx = bs.getICtx(rctx.currTx);
            bctx.setRemoved();
        } catch (Exception e) {
            rctx.sysExc = e;
            logger.log(BasicLevel.ERROR, "EJB exception thrown:", e);
        } catch (Error e) {
            rctx.sysExc = e;
            logger.log(BasicLevel.ERROR, "error thrown:", e);
        } finally {
            try {
                bf.postInvoke(rctx);
            } catch (Exception e) {
                logger.log(BasicLevel.ERROR, "exception on postInvoke: ", e);
            }
        }

    }

}