/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 2006 Bull S.A.S.
 * Contact: jonas-team@objectweb.org
 * Copyright (C) 2006 Distributed Systems Lab.
 * Universidad Polit??cnica de Madrid (Spain)
 * Contact: http://lsd.ls.fi.upm.es/lsd
 *
 * 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
 *
 * --------------------------------------------------------------------------
 *
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas_ejb.container;

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

import org.objectweb.carol.cmi.ClusterStub;
import org.objectweb.carol.cmi.DistributorEntityRemote;
import org.objectweb.carol.cmi.ServerConfigException;
import org.objectweb.carol.cmi.configuration.TraceCmi;
import org.objectweb.carol.cmi.ha.RequestId;
import org.objectweb.carol.util.configuration.ConfigurationRepository;
import org.objectweb.jonas.ha.interceptor.HACurrentDelegateImpl;
import org.objectweb.jonas_ejb.deployment.api.EntityDesc;

/**
 * This class is the Standard Home for clustered entity objects It exists only
 * for beans that have declared a Remote Interface.
 * @author Francisco Perez-Sorrosal (fpsorrosal@no-spam@fi.upm.es)
 * @author Alberto Paz-Jimenez (apaz@no-spam@fi.upm.es)
 */
public abstract class JRepEntityHome extends JEntityHome {
    
    public JRepEntityHome(EntityDesc dd, JEntityFactory bf) throws RemoteException {
        super(dd, bf);
    }

    /**
     * Called if we have to replicate a request
     * @param rctx The RequestCtx that was returned at preInvoke()
     */
    protected void replicateCreate(JEntityContext bctx, Object response) {
        if (TraceCmi.isDebugCmiHA()) {
            TraceCmi.debugCmiHA("replicateBean : this=" + this);
        }
        // Create the rootId from the current HACtx/Thread association
        HACurrentDelegateImpl current = HACurrentDelegateImpl.getCurrent();
        // Obtain the root request
        RequestId rootId = null;
        try { 
            rootId = (RequestId) current.getRequests().get(0);
            JRepUtil.addEntityBean(bctx, rootId);

            // If this is the root request, then associate response with rootId
            if (current.getRequests().size() == 1) {
                try {
                    JRepUtil.getRepMgr().addResponse(rootId, response);
                } catch (Exception e) {
                    e.printStackTrace();
                    TraceCmi.error("unable to obtain replication manager.", e);
                }
            }
            
        } catch (ArrayIndexOutOfBoundsException e) {
            if (TraceCmi.isDebugCmiHA()) {
                TraceCmi.debugCmiHA("Not in a remote method call chain.");
            }
            // do nothing
        } finally {
            // We dont need the request anymore so remove it
            removeCurrentRequest();
        }
    }
    
    /**
     * Get the remote object as a stub object for HA remote object LB
     * @param remote remote object
     * @return get remote object
     * @throws RemoteException
     * @throws ServerConfigException
     * @throws NoSuchObjectException if the clustered object is not found in the
     *         CMI registry
     */
    public Remote getHARemoteStub(Remote remote, Object primaryKey) throws RemoteException {
        Remote remo = JRepUtil.getHARemoteStub(remote, dd);
        String protocol = ConfigurationRepository.getCurrentConfiguration().getProtocol().getName();
        if (protocol.equals("cmi")) {
            ClusterStub cs = (ClusterStub) remo;
            DistributorEntityRemote der = (DistributorEntityRemote) cs.getDistrib();
            der.setPrimaryKey(primaryKey);
        }        
        return remo; 
    }
     
    /**
     * Removes the curren request from the requests heap
     */
    private void removeCurrentRequest() {
        HACurrentDelegateImpl current = HACurrentDelegateImpl.getCurrent();
        current.getRequests().pop();
    }
}
