/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * 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: JSessionLocal.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

import javax.ejb.EJBException;
import javax.ejb.EJBLocalHome;
import javax.ejb.EJBLocalObject;
import javax.ejb.RemoveException;


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

/**
 * Generic part of the EJBLocalObject implementation
 * @author Philippe Durieux
 */
public abstract class JSessionLocal extends JLocal {

    protected JSessionFactory bf;

    protected JSessionSwitch bs;

    /**
     * constructor
     * @param bf The Session Factory
     */
    public JSessionLocal(JSessionFactory bf) {
        super(bf);
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        this.bf = bf;
    }

    // --------------------------------------------------------------------------
    // EJBLocalObject implementation
    // remove() is implemented in the generated part.
    // --------------------------------------------------------------------------

    public abstract void remove() throws RemoveException;

    /**
     * @return the enterprise Bean's local home interface.
     */
    public EJBLocalHome getEJBLocalHome() {
        return bf.getLocalHome();
    }

    /**
     * @return the Primary Key for this EJBObject
     * @throws EJBException Always : Session bean has no primary key
     */
    public Object getPrimaryKey() throws EJBException {
        throw new EJBException("Session bean has no primary key");
    }

    /**
     * Tests if a given EJB is identical to the invoked EJB object. This is
     * different whether the bean is stateless or stateful.
     * @param obj - An object to test for identity with the
     *        invoked object.
     * @return True if the given EJB object is identical to the invoked object.
     * @throws EJBException Thrown when the method failed due to a system-level
     *         failure.
     */
    public boolean isIdentical(EJBLocalObject obj) {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        boolean ret = false;
        JSessionFactory sf = bf;
        if (sf.isStateful()) {
            // For stateful sessions, just compare both objects.
            if (obj != null) {
                ret = obj.equals(this);
            }
        } else {
            // In case of Stateless session bean, we must compare the 2
            // factories
            if (obj != null) {
                try {
                    //a simple cast should work on a local object
                    JSessionLocal ejb2 = (JSessionLocal) obj;
                    JSessionSwitch bs2 = ejb2.getSessionSwitch();
                    JSessionFactory bf2 = bs2.getBeanFactory();
                    ret = bf2.equals(sf);
                } catch (Exception e) {
                    TraceEjb.logger.log(BasicLevel.WARN, "exception:" + e);
                    throw new EJBException("isIdentical failed", e);
                }
            }
        }
        return ret;
    }

    // ---------------------------------------------------------------
    // other public methods, for internal use.
    // ---------------------------------------------------------------

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

    /**
     * @return the JSessionSwitch for this Session
     */
    public JSessionSwitch getSessionSwitch() {
        return bs;
    }

    /**
     * preInvoke is called before any request.
     * @param txa Transaction Attribute (Supports, Required, ...)
     * @return A RequestCtx object
     * @throws EJBException
     */
    public RequestCtx preInvoke(int txa) {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        RequestCtx rctx = bf.preInvoke(txa);
        bs.setMustCommit(rctx.mustCommit); // for remove stateful session
        bs.enlistConnections(rctx.currTx); // Enlist connection list to tx
        return rctx;
    }

    /**
     * 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 (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        bf.checkSecurity(ejbInv);
    }

    /**
     * postInvoke is called after any request.
     * @param rctx The RequestCtx that was returned at preInvoke()
     * @throws EJBException
     */
    public void postInvoke(RequestCtx rctx) {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        bs.delistConnections(rctx.currTx);
        // save current tx (for Stateful Bean Managed only)
        bs.saveBeanTx();
        try {
            bf.postInvoke(rctx);
        } finally {
            bs.releaseICtx(rctx, rctx.sysExc != null);
        }
    }

}
