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

package org.ow2.jonas.lib.ejb21;

import java.io.Serializable;
import java.rmi.RemoteException;

import javax.ejb.EJBHome;
import javax.ejb.HomeHandle;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

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

/**
 * This class implements javax.ejb.HomeHandle interface. A handle is an
 * abstraction of a network reference to a home object. A handle is intended to
 * be used as a "robust" persistent reference to a home object.
 * @author Philippe Durieux, Philippe Coq
 */
public class JHomeHandle implements HomeHandle, Serializable {

    /**
     * Name of the home
     */
    private String homename = null;

    /**
     * EjbHome class
     */
    private EJBHome ejbHome = null;

    /**
     * constructor
     * @param hname JNDI name of the Home
     */
    public JHomeHandle(String hname) {
        homename = hname;
    }

    // -----------------------------------------------------------------------
    // HomeHandle implementation
    // -----------------------------------------------------------------------

    /**
     * Obtains the home object represented by this handle.
     * @throws RemoteException The home object could not be obtained because of
     *         a system-level failure.
     * @return The EJBHome object
     */
    public EJBHome getEJBHome() throws RemoteException {
        if (TraceEjb.isDebugIc()) {
            TraceEjb.interp.log(BasicLevel.DEBUG, homename);
        }
        Context ic = null;
        if (ejbHome == null) {
            try {
                ic = new InitialContext();
                Object o = ic.lookup(homename);
                ejbHome = (EJBHome) PortableRemoteObject.narrow(o, EJBHome.class);
            } catch (NamingException e) {
                throw new RemoteException("getEJBHome", e);
            }
        }
        return ejbHome;
    }
}


