/* JFox, the OpenSource J2EE Application Server
 *
 * Distributable under GNU LGPL license by gun.org
 * more details please visit http://www.huihoo.org/jfox
 */
package org.jfox.deployment.ejb;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;

import org.jfox.deployment.J2EEClassLoader;
import org.jfox.deployment.NestedModule;
import org.jfox.deployment.application.EARModule;
import org.jfox.ejb.meta.EJBBundle;
import org.jfox.ejb.meta.XmlUtil;
import org.jfox.framework.deploy.DeployException;
import org.jfox.framework.deploy.Deployer;

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

public class NestedEJBModule extends EJBModule implements NestedModule {
    public static final String Target = "apps" + File.separator;
    private EARModule earModule;
    private EJBBundle ejbBundle;

    public NestedEJBModule(EARModule earModule, File jarFile) throws DeployException {
        super(jarFile);
        this.earModule = earModule;
        init();
    }

    private void init() throws DeployException {
        try {
            ((J2EEClassLoader) getClassLoader()).addURL(getModuleFile().toURL());
            ejbBundle = new EJBBundle(XmlUtil.getDocument(getDescriptorURL()));
        }
        catch(Exception e) {
            throw new DeployException(e);
        }
    }

    public URL getDescriptorURL() {
        try {
            //can use earModule's classloader,
            // because a ear module may be container many ejb module
            // many ejb-jar.xml descriptor
            return new URLClassLoader(new URL[]{getModuleFile().toURL()}, null).findResource("META-INF/ejb-jar.xml");
//      return earModule.getClassLoader().findResource("META-INF/ejb-jar.xml");
        }
        catch(Exception e) {
            return null;
        }
    }

    public File getModuleFile() {
        return super.getModuleFile();
    }

    public URLClassLoader getClassLoader() {
        return earModule.getClassLoader();
    }

    public void deploy(Deployer deployer) throws DeployException {
        super.deploy(deployer);
    }

    public File getTempDeployDirectory() {
        return new File(earModule.getTempDeployDirectory(), Target);
    }

    public EARModule getEARModule() {
        return earModule;
    }

    public EJBBundle getEJBBundle() {
        return ejbBundle;
    }

    public static void main(String[] args) {

    }
}

