/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2008 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$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.ejb21;

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.util.monolog.api.BasicLevel;
import org.ow2.carol.util.configuration.ConfigurationRepository;
import org.ow2.carol.util.csiv2.SasHelper;
import org.ow2.jonas.deployment.ejb.BeanDesc;
import org.ow2.jonas.deployment.ejb.EntityDesc;
import org.ow2.jonas.deployment.ejb.SessionDesc;
import org.ow2.jonas.deployment.ejb.SessionStatefulDesc;
import org.ow2.jonas.deployment.ejb.SessionStatelessDesc;
import org.ow2.jonas.lib.execution.ExecutionResult;
import org.ow2.jonas.lib.execution.IExecution;
import org.ow2.jonas.lib.execution.RunnableHelper;
import org.ow2.jonas.lib.svc.JHomeHandleIIOP;
import org.ow2.jonas.lib.svc.JMetaData;
import org.ow2.util.ee.event.types.BeanRegisterEvent;
import org.ow2.util.ee.event.types.BeanUnregisterEvent;
import org.ow2.util.event.api.IEventDispatcher;

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

    protected JMetaData ejbMetaData = null;

    protected BeanDesc dd;

    protected JFactory bf;

    protected boolean unregistered = true;
    /**
     * Event filter.
     */

    private static final String EVENT_FILTER = "/beans/lifecycle/events";

    /**
     * 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(final BeanDesc dd, final JFactory bf) throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, "JHome constructor");
        }
        this.dd = dd;
        this.bf = bf;
    }

    // ---------------------------------------------------------------
    // 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, "");
        }
        final String name = dd.getJndiName();
        dispacthRegisterEvent();
        // register in registry (inside an IExecution block)
        final JHome jhome = this;
        IExecution<Void> rebinder = new IExecution<Void>() {
            public Void execute() throws Exception {
                SasHelper.rebind(name, jhome, dd.getSasComponent());
                return null;
            }
        };
        ExecutionResult<Void> result = RunnableHelper.execute(getClass().getClassLoader(), rebinder);
        // Throw an ServiceException if needed
        if (result.hasException()) {
            TraceEjb.interp.log(BasicLevel.ERROR, "Cannot register bean");
            throw new RuntimeException("Cannot register bean:", result.getException());
        }

        unregistered = false;
    }

    /**
     * Notify a session has been created.
     */
    private void dispacthRegisterEvent() {
        IEventDispatcher dispatcher = bf.cont.getLifeCycleDispatcher();
        if(dispatcher != null && dd.getCluster() != null) {
            BeanRegisterEvent beanRegisterEvent = new BeanRegisterEvent(EVENT_FILTER
                    + dd.getJndiName());
            beanRegisterEvent.setJndiName(dd.getJndiName());
            beanRegisterEvent.setClassLoader(bf.cont.getClassLoader());
            beanRegisterEvent.setClusterConfig(dd.getCluster());
            beanRegisterEvent.setHomeClass(dd.getHomeClass());
            beanRegisterEvent.setStateful((dd instanceof SessionStatefulDesc) || (dd instanceof EntityDesc));
            beanRegisterEvent.setClusterReplicated(dd.isClusterReplicated());
            beanRegisterEvent.setRemoteClass(dd.getRemoteClass());
            beanRegisterEvent.setEventProviderFilter(EVENT_FILTER);
            dispatcher.dispatch(beanRegisterEvent);
        }
    }

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

    /**
     * Dispatch unregister event.
     */
    private void dispacthUnregisterEvent() {
        IEventDispatcher dispatcher = bf.cont.getLifeCycleDispatcher();
        if(dispatcher != null && dd.getCluster() != null) {
            BeanUnregisterEvent beanUnRegisterEvent = new BeanUnregisterEvent("jonas/service/ejb2-container/bean/unregister/"
                    + dd.getJndiName());
            beanUnRegisterEvent.setJndiName(dd.getJndiName());
            beanUnRegisterEvent.setEventProviderFilter(EVENT_FILTER);
            dispatcher.dispatch(beanUnRegisterEvent);
        }
    }

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