/**
 * 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:JHomeHandleIIOP.java 11039 2007-07-26 13:35:52Z durieuxp $
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.lib.svc;

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

import javax.ejb.EJBHome;
import javax.ejb.HomeHandle;
import javax.ejb.spi.HandleDelegate;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import javax.rmi.CORBA.Util;

import org.omg.PortableServer.Servant;


/**
 * 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 JHomeHandleIIOP implements HomeHandle, Serializable {

    /**
     * JDK logger to be portable.
     */
    private static Logger logger = Logger.getLogger("org.ow2.jonas.lib.svc");

    /**
     * CORBA ref.
     * @serial
     */
    private String ior = null;

    /**
     * Classloader of EJB.
     */
    private ClassLoader cl = null;

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

    /**
     * constructor.
     * @param h EJBHome
     * @param cl classloader used for EJB
     */
    public JHomeHandleIIOP(final EJBHome h, final ClassLoader cl) {
        if (logger.isLoggable(Level.FINE)) {
            logger.log(Level.FINE, "h=" + h);
        }
        try {
            Servant servant = (Servant) Util.getTie(h);
            org.omg.CORBA.Object o = servant._this_object();
            this.ior = Utility.getORB().object_to_string(o);
            this.cl = cl;
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE, "ior=" + ior);
            }
        } catch (Exception e) {
            logger.log(Level.SEVERE, "cannot get Handle: ", e);
        }
    }

    // -----------------------------------------------------------------------
    // 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 {
        logger.log(Level.FINE, "");
        ClassLoader old = Thread.currentThread().getContextClassLoader();
        logger.log(Level.FINE, "");
        if (ejbHome == null) {
            try {
                Thread.currentThread().setContextClassLoader(cl);
                ejbHome = (EJBHome) PortableRemoteObject.narrow(Utility.getORB().string_to_object(ior), EJBHome.class);
            } catch (NamingException e) {
                logger.log(Level.SEVERE, "Cannot narrow ior '" + ior + "'", e);
                throw new RemoteException("Cannot narrow ior '" + ior + "'", e);
            } finally {
                // reset
                Thread.currentThread().setContextClassLoader(old);
            }
        }
        return ejbHome;
    }

    /**
     * Specific implementation of serialization.
     * Must call HandleDelegate.writeEJBObject, as specified in 19.5.5.1 of spec EJB 2.1
     * @param out The output stream used to write object
     * @throws IOException error when writing object.
     */
    private void writeObject(final java.io.ObjectOutputStream out)
    throws IOException {
        logger.log(Level.FINE, "");
        HandleDelegate hdld;
        try {
            hdld = Utility.getHandleDelegate();
        } catch (NamingException e) {
            logger.log(Level.SEVERE, "Cannot get HandleDelegate", e);
            throw new IOException("Cannot get HandleDelegate");
        }
        hdld.writeEJBHome(getEJBHome(), out);
    }

    /**
     * Specific implementation of deserialization.
     * Must call HandleDelegate.readEJBObject, as specified in 19.5.5.1 of spec EJB 2.1
     * @param in The input Stream from where is read the object.
     * @throws IOException error when reading object.
     * @throws ClassNotFoundException -
     */
    private void readObject(final java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException {
        logger.log(Level.FINE, "");
        HandleDelegate hdld;
        try {
            hdld = Utility.getHandleDelegate();
        } catch (NamingException e) {
            logger.log(Level.SEVERE, "Cannot get HandleDelegate", e);
            throw new IOException("Cannot get HandleDelegate");
        }
        try {
            ejbHome = hdld.readEJBHome(in);
        } catch (ClassNotFoundException e) {
            logger.log(Level.SEVERE, "Cant read EJBHome:", e);
            throw e;
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Cant read EJBHome:" + e);
            throw e;
        }
    }

}

