/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 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_ejb.container;

import java.rmi.NoSuchObjectException;
import java.rmi.RemoteException;

import javax.ejb.EJBHome;
import javax.ejb.EJBMetaData;
import javax.ejb.Handle;
import javax.ejb.HomeHandle;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import org.objectweb.carol.cmi.DistributedEquiv;
import org.objectweb.carol.cmi.ServerConfigException;
import org.objectweb.carol.util.configuration.ConfigurationRepository;
import org.objectweb.carol.util.csiv2.SasHelper;

import org.objectweb.jonas_ejb.deployment.api.BeanDesc;
import org.objectweb.jonas_ejb.deployment.api.EntityDesc;
import org.objectweb.jonas_ejb.deployment.api.SessionDesc;
import org.objectweb.jonas_ejb.deployment.api.SessionStatelessDesc;
import org.objectweb.jonas_ejb.lib.EJBInvocation;
import org.objectweb.jonas_ejb.svc.JHomeHandleIIOP;
import org.objectweb.jonas_ejb.svc.JMetaData;

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

/**
 * This class represents an EJBHome Remote Interface
 * It is shared between Sessions and Entities.
 * @author Philippe Coq, Philippe Durieux
 */
public abstract class JHome extends PortableRemoteObject implements EJBHome {

    protected JMetaData ejbMetaData = null;
    protected BeanDesc dd;
    protected JFactory bf;
    protected boolean unregistered = true;

    /**
     * Constructor for the base class of the specific generated Home object.
     * @param dd The Been Deployment Descriptor
     * @param bf The Bean Factory
     * @throws RemoteException exception
     */
    public JHome(BeanDesc dd, JFactory bf) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "JHome constructor");
        }
        this.dd = dd;
        this.bf = bf;

        // For CMI needs, we have to keep the link between jndiname/classloader
        String protocol = ConfigurationRepository.getCurrentConfiguration().getProtocol().getName();
        if (protocol.equals("cmi")) {
            String key = DistributedEquiv.CL_PREFIX + dd.getJndiName();
            if (key != null) { // cluster object
                // register its classloader in the local cache
                try {
                    DistributedEquiv.putLocalCLByKey(key, bf.getContainer().getClassLoader());
                } catch (ServerConfigException e) {
                    throw new RemoteException("", e);
                }
            }

        }
    }

    // ---------------------------------------------------------------
    // EJBHome Implementation
    // ---------------------------------------------------------------

    /**
     * Obtains the EJBMetaData for the enterprise Bean.
     * @return The enterprise Bean's EJBMetaData
     * @throws RemoteException exception
     */
    public EJBMetaData getEJBMetaData() throws RemoteException {

        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "JHome getEJBMetaData");
        }

        /*
         * 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 {
         */
        if (ejbMetaData == null) {

            if (dd instanceof SessionDesc) {
                boolean isSession = true;
                boolean isStatelessSession = (dd instanceof SessionStatelessDesc);
                Class primaryKeyClass = null;
                ejbMetaData = new JMetaData(this, dd.getHomeClass(), dd.getRemoteClass(), isSession, isStatelessSession, primaryKeyClass);
          } else if (dd instanceof EntityDesc) {
              boolean isSession = false;
              boolean isStatelessSession = false;
              Class primaryKeyClass = ((EntityDesc) dd).getPrimaryKeyClass();
              ejbMetaData = new JMetaData(this, dd.getHomeClass(), dd.getRemoteClass(), isSession, isStatelessSession, primaryKeyClass);
          }
        }
        return ejbMetaData;
        /*
         * } 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;
         * }
         */
    }

    /**
     * Obtain a handle for the home object. The handle can be used at later time to re-obtain a
     * reference to the home object, possibly in a different Java Virtual Machine.
     * @return A handle for the home object.
     * @exception java.rmi.RemoteException - Thrown when the method failed due to a system-level
     * failure.
     */
    public HomeHandle getHomeHandle() throws java.rmi.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.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "Current protocol = " + protocol);
        }
        if (protocol.equals("iiop")) {
            return new JHomeHandleIIOP(this, bf.myClassLoader());
        } else {
            return new JHomeHandle(dd.getJndiName());
        }

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

    /**
     * Removes an EJB object identified by its handle.
     * @param handle The EJB Handle
     * @throws RemoteException exception
     * @throws RemoveException exception
     *
     */
    public abstract void remove(Handle handle) throws RemoteException, RemoveException;

    /**
     * Removes an EJB object identified by its primary key.
     * @param primaryKey The Primary Key
     * @throws RemoteException exception
     * @throws RemoveException exception
     */
    public abstract void remove(Object primaryKey) throws RemoteException, RemoveException;

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

    /**
     * register this bean to JNDI (rebind)
     * @throws NamingException exception
     */
    protected void register() throws NamingException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        String name = dd.getJndiName();

        // register in registry
        SasHelper.rebind(name, this, dd.getSasComponent());

        unregistered = false;
    }

    /**
     * unregister this bean in JNDI (unbind)
     * @throws NamingException exception
     */
    protected void unregister() throws NamingException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        String name = dd.getJndiName();
        // unregister in default InitialContext
        bf.getInitialContext().unbind(name);

        try {
            PortableRemoteObject.unexportObject(this);
        } catch (NoSuchObjectException e) {
            TraceEjb.interp.log(BasicLevel.ERROR, "unexportObject(JHome) failed", e);
        }
        unregistered = true;
    }

    /**
     * Get the jndi name for the bean
     * @return The jndi name
     * @throws RemoteException
     */
    public String getJndiName() {
        return dd.getJndiName();
    }

    /**
     * preInvoke is called before any request.
     * @param txa Transaction Attribute (Supports, Required, ...)
     * @return A RequestCtx object
     * @throws RemoteException unexpected exception in preinvoke
     */
    public RequestCtx preInvoke(int txa) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.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 (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 unexpected exception in postinvoke
     */
    public void postInvoke(RequestCtx rctx) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "");
        }
        bf.postInvokeRemote(rctx);
    }

    /**
     * @return Returns the dd.
     */
    public BeanDesc getDd() {
        return dd;
    }
    /**
     * @return the bean factory
     */
    public JFactory getBf() {
        return bf;
    }
}
