/**
 * 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: JSessionRemote.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.ejb.EJBHome;
import javax.ejb.EJBObject;
import javax.ejb.Handle;
import javax.ejb.RemoveException;
import javax.rmi.PortableRemoteObject;

import org.ow2.jonas.lib.svc.JHandleIIOP;

import org.ow2.carol.rmi.exception.RmiUtility;
import org.ow2.carol.util.configuration.ConfigurationRepository;


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

/**
 * Generic part of the EJBObject implementation
 * @author Philippe Coq
 * @author Philippe Durieux
 */
public abstract class JSessionRemote extends JRemote implements Remote {


    /**
     * <code>bs</code>
     */
    protected JSessionSwitch bs;

    /**
     * constructor
     * @param bf The Session Factory
     * @throws RemoteException Thrown when the method failed due to a system-level failure.
     */
    public JSessionRemote(JSessionFactory bf) throws RemoteException {
        super((JFactory) bf);
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
    }

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

    /**
     * remove is implemented in the generated part.
     * @throws RemoteException Thrown when the method failed due to a system-level failure.
     * @throws RemoveException Thrown when the method failed due to remove failure.
     */
    public abstract void remove() throws RemoteException, RemoveException;

    /**
     * @return the enterprise Bean's home interface.
     */
    public EJBHome getEJBHome() {
        /*
         * try/catch block is commented because the encapsulated code don't
         * throw a RemoteException
         * If the code changes and throws a such exception, let's think
         * to uncomment it
         *
         * try {
         */

        return bf.getHome();

        /*
         * } catch (RemoteException e) {
         * // check if rmi exception mapping is needed - if yes the method  rethrows it
         * RmiUtility.rethrowRmiException(e);
         * // if not, throws the exception just as it is
         * throw e;
         * }
         */

    }

    /**
     * @throws RemoteException Always : Session bean has never a primary key
     * @return never carried out because a exception is thrown
     */
    public Object getPrimaryKey() throws RemoteException {

        try {
            throw new RemoteException("Session bean has no primary key");
        } catch (RemoteException e) {
            // check if rmi exception mapping is needed - if yes the method rethrows it
            RmiUtility.rethrowRmiException(e);
            // if not, throws the exception just as it is
            throw e;
        }
    }

    /**
     * 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 RemoteException Thrown when the method failed due to a system-level failure.
     */
    public boolean isIdentical(EJBObject obj) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        try {
            boolean ret = false;
            JSessionFactory sf = (JSessionFactory) bf;
            if (sf.isStateful()) {
                // For stateful sessions, just compare both objects.
                if (obj != null) {
                    ret = ((obj.equals(PortableRemoteObject.toStub(this))) || (obj.equals(this)));
                }
            } else {
                // In case of Stateless session bean, we must compare the 2 Home
                // We cannot cast the remote EJBObject cbecause it's a stub.
                String myhome = getEJBHome().getEJBMetaData().getHomeInterfaceClass().getName();
                if (obj != null) {
                    ret = obj.getEJBHome().getEJBMetaData().getHomeInterfaceClass().getName().equals(myhome);
                }
            }
            return ret;
        } catch (RemoteException e) {
            // check if rmi exception mapping is needed - if yes the method
            // rethrows it
            RmiUtility.rethrowRmiException(e);
            // if not, throws the exception just as it is
            throw e;
        }
    }

    /**
     * Obtains a handle for the EJB object. The handle can be used at later time
     * to re-obtain a reference to the EJB object, possibly in a different JVM.
     * @return A handle for the EJB object.
     * @exception RemoteException Thrown when the method failed due to a
     *            system-level failure.
     */
    public Handle getHandle() throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }

        /*
         * try/catch block is commented because the encapsulated code don't
         * throw a RemoteException
         * If the code changes and throws a such exception, let's think
         * to uncomment it
         *
         * try {
         */
        // for iiop, a specific interoperable Handle is created with the use of
        // HandleDelegate
        String protocol = ConfigurationRepository.getCurrentConfiguration().getProtocol().getName();
        if (TraceEjb.interp.isLoggable(BasicLevel.DEBUG)) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "Current protocol = " + protocol);
        }

        if (protocol.equals("iiop")) {
            return new JHandleIIOP(this);
        } else {
            return new JSessionHandle(this);
        }

        /*
         * } catch (RemoteException e) {
         * // check if rmi exception mapping is needed - if yes the method  rethrows it
         * RmiUtility.rethrowRmiException(e);
         * // if not, throws the exception just as it is
         * throw e;
         * }
         */

    }

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

    /**
     * finish initialization
     * @param bs the SessionSwitch
     */
    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 RemoteException Thrown when the method failed due to a
     *            system-level failure.
     */
    public RequestCtx preInvoke(int txa) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        RequestCtx rctx = bf.preInvokeRemote(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 RemoteException Thrown when the method failed due to a
     *            system-level failure.
     */
    public void postInvoke(RequestCtx rctx) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        bs.delistConnections(rctx.currTx);
        // save current tx (for Bean Managed only)
        bs.saveBeanTx();
        try {
            bf.postInvokeRemote(rctx);
        } finally {
            bs.releaseICtx(rctx, rctx.sysExc != null);
        }
    }

}
