/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2004-2007 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: JacORBPRODelegate.java 20501 2010-10-21 19:34:09Z alitokmen $
 * --------------------------------------------------------------------------
 */
package org.ow2.jonas.registry.carol.delegate;

import java.rmi.Remote;
import java.rmi.RemoteException;

import javax.rmi.CORBA.Tie;
import javax.rmi.CORBA.Util;

import org.jacorb.poa.RequestProcessor;
import org.ow2.carol.jndi.ns.JacORBCosNaming;
import org.omg.PortableServer.Servant;
import org.ow2.jonas.lib.ejb21.JHome;
import org.ow2.jonas.lib.ejb21.JRemote;

/**
 * Use EJB context classloader when possible
 * @author Florent Benoit
 */
public class JacORBPRODelegate extends org.ow2.carol.rmi.multi.JacORBPRODelegate {


    /**
     * Makes a server object ready to receive remote calls. Note that subclasses
     * of PortableRemoteObject do not need to call this method, as it is called
     * by the constructor.
     * @param obj the server object to export.
     * @exception RemoteException if export fails.
     */
    public void exportObject(Remote obj) throws RemoteException {

        // For JacORB, we need first to unexport object as it is not associated
        // to an ORB
        try {
            unexportObject(obj);
        } catch (Exception eee) {
            // Nothing
        }

        /* Now export it */
        try {
            super.exportObject(obj);
        } catch (Exception ee) {
            // Nothing
        }

        boolean ejb2 = false;
        try {
            if (obj instanceof JHome || obj instanceof JRemote) {
                ejb2 = true;
            }
        } catch (NoClassDefFoundError ignored) {
            // ejb2 service not active
        }

        // Connect all EJB2 Home and Remote interfaces, and objectweb components (JOTM, JORAM, ...)
        if (ejb2 || obj.getClass().getName().indexOf("org.objectweb") != -1 ||
            obj.getClass().getName().equals("javax.management.remote.rmi.RMIConnectionImpl")) {

            Tie theTie = Util.getTie(obj);

            // Then connect it to the ORB
            if (theTie != null) {
                theTie.orb(JacORBCosNaming.getOrb());
            }
        }
    }

    /**
     * Checks to ensure that an object of a remote or abstract interface type
     * can be cast to a desired type.
     * @param narrowFrom the object to check.
     * @param narrowTo the desired type.
     * @return an object which can be cast to the desired type.
     * @throws ClassCastException if narrowFrom cannot be cast to narrowTo.
     */
    public Object narrow(Object narrowFrom, Class narrowTo) throws ClassCastException {
        // Save old classloader
        ClassLoader old = Thread.currentThread().getContextClassLoader();

        try {
            // Try to get EJB classloader
            Thread currentThread = Thread.currentThread();
            if (currentThread != null && (currentThread instanceof RequestProcessor)) {
                RequestProcessor rp = (RequestProcessor) currentThread;
                if (rp != null) {
                    Servant servant = rp.getServant();
                    if (servant != null) {
                        Tie tie = null;
                        if (servant instanceof Tie) {
                            tie = (Tie) servant;
                            Remote target = tie.getTarget();
                            if (target instanceof JHome) {
                                JHome jHome = (JHome) target;
                                ClassLoader cll = jHome.getBf().myClassLoader();
                                Thread.currentThread().setContextClassLoader(cll);
                            } else if (target instanceof JRemote) {
                                JRemote jRemote = (JRemote) target;
                                ClassLoader cll = jRemote.getBf().myClassLoader();
                                Thread.currentThread().setContextClassLoader(cll);
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            // nothing
        } catch (Error e) {
            // nothing
        }

        // Call super method with right classloader
        Object narrowResult = null;
        try {
            narrowResult = super.narrow(narrowFrom, narrowTo);
        } finally {
            // reset to old classloader
            Thread.currentThread().setContextClassLoader(old);
        }

        return narrowResult;
    }

}