package org.jfox.ejb.handler;

import java.util.Iterator;

import org.jfox.ejb.Bucket;
import org.jfox.ejb.Invocation;
import org.jfox.ejb.naming.EJBEnterpriseContextContainer;
import org.jfox.jndi.enc.AbstractEnterpriseContextContainer;
import org.jfox.jndi.enc.EnterpriseContextFactory;

/**
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class A2_EnterpriseContextHandler extends AbstractHandler {
    private static AbstractEnterpriseContextContainer encContainer = EJBEnterpriseContextContainer.getInstance();

    public Object invokeHome(Bucket bucket, Invocation invocation, Iterator iter) throws Exception {
        EnterpriseContextFactory.EnterpriseType type = EnterpriseContextFactory.enterEjb();
        String old = encContainer.setCurrentEnterpriseContextName(invocation.getObjectId().getEjbName());
        try {
            return super.invokeHome(bucket, invocation, iter);
        }
        finally {
            // bind the old J2EEModuleName, maybe web module context name, or other ejb name, or null
            encContainer.setCurrentEnterpriseContextName(old);
            EnterpriseContextFactory.enter(type);
        }
    }

    public Object invokeBean(Bucket bucket, Invocation invocation, Iterator iter) throws Exception {
        EnterpriseContextFactory.EnterpriseType type = EnterpriseContextFactory.enterEjb();
        String old = encContainer.setCurrentEnterpriseContextName(invocation.getObjectId().getEjbName());
        try {
            return super.invokeBean(bucket, invocation, iter);
        }
        finally {
            // bind the old J2EEModuleName, maybe web module context name, or other ejb name, or null
            encContainer.setCurrentEnterpriseContextName(old);
            EnterpriseContextFactory.enter(type);
        }

    }

    public static void main(String[] args) {

    }
}

