/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved.
 *
 * The contents of this file are subject to the terms of either the GNU
 * General Public License Version 2 only ("GPL") or the Common Development
 * and Distribution License("CDDL") (collectively, the "License").  You
 * may not use this file except in compliance with the License. You can obtain
 * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
 * or glassfish/bootstrap/legal/LICENSE.txt.  See the License for the specific
 * language governing permissions and limitations under the License.
 *
 * When distributing the software, include this License Header Notice in each
 * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
 * Sun designates this particular file as subject to the "Classpath" exception
 * as provided by Sun in the GPL Version 2 section of the License file that
 * accompanied this code.  If applicable, add the following below the License
 * Header, with the fields enclosed by brackets [] replaced by your own
 * identifying information: "Portions Copyrighted [year]
 * [name of copyright owner]"
 *
 * Contributor(s):
 *
 * If you wish your version of this file to be governed by only the CDDL or
 * only the GPL Version 2, indicate your decision by adding "[Contributor]
 * elects to include this software in this distribution under the [CDDL or GPL
 * Version 2] license."  If you don't indicate a single choice of license, a
 * recipient has the option to distribute your version of this file under
 * either the CDDL, the GPL Version 2 or to extend the choice of license to
 * its licensees as provided above.  However, if you add GPL Version 2 code
 * and therefore, elected the GPL Version 2 license, then the option applies
 * only if the new code is made subject to such option by the copyright
 * holder.
 */

package com.sun.enterprise.deployment.pluggable;

import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.logging.Logger;
import java.util.logging.Level;
import org.xml.sax.SAXParseException;

import javax.enterprise.deploy.shared.ModuleType;

import com.sun.logging.LogDomains;

import com.sun.enterprise.deployment.deploy.shared.FileArchive;
import com.sun.enterprise.deployment.interfaces.pluggable.*;
import com.sun.enterprise.deployment.util.XModuleType;
import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.BundleDescriptor;
import com.sun.enterprise.deployment.archivist.Archivist;
import com.sun.enterprise.deployment.archivist.ApplicationArchivist;
import com.sun.enterprise.deployment.archivist.ArchivistFactory;
import com.sun.enterprise.deployment.phasing.ExtensionModuleDeployer;
import com.sun.enterprise.deployment.archivist.ExtensionModuleArchivist;
import com.sun.enterprise.deployment.annotation.AnnotationHandler;
import com.sun.enterprise.deployment.annotation.factory.ExtensionFactoryFactory;
import com.sun.enterprise.deployment.annotation.factory.ExtensionModuleAnnotationFactory;
import com.sun.enterprise.deployment.annotation.AnnotationProcessor;
import com.sun.enterprise.deployment.backend.DeploymentLogger;
import com.sun.enterprise.loader.InstrumentableClassLoader;
import com.sun.enterprise.instance.ExtensionModuleConfigManager;
                                                                                
/**
 * This class is the central point for the interactions between the 
 * 3rd party code and the glassfish code. 
 * It contains APIs for registering/retrieving the 3rd party SPI 
 * implementation classes, and also the utility APIs for the 3rd party to 
 * leverage the existing glassfish logic.
 */

public class PluggableDeploymentInfo {

    protected static Logger logger = DeploymentLogger.get();
    
   /**
     * This API registers an instance of the archive deployer.
     * <p>The 3rd party extension container will register itself
     * as a lifecycle module and call this API to register archive
     * deployer when it's being loaded (in INIT_EVENT). 
     *
     * @param archiveDeployerClassName the implementation class 
     *                                 of ArchiveDeployer
     */
    public static void registerArchiveDeployerLoader(
        String archiveDeployerClassName, String archiveLoaderClassName)
                                                        throws Exception {
        ArchiveDeployer archiveDeployer = 
                  (ArchiveDeployer)Class.forName(
                        archiveDeployerClassName).newInstance();
        ExtensionModuleArchivist extensionModuleArchivist =
                                  new ExtensionModuleArchivist(archiveDeployer);
        ArchivistFactory.registerArchivist(extensionModuleArchivist);
        ExtensionModuleDeployer extensionModuleDeployer =
                                   new ExtensionModuleDeployer(archiveDeployer);
        if(archiveLoaderClassName != null ) {
            logger.log(Level.INFO, "Setting a custom loader"+
                                     archiveLoaderClassName+ 
                                     " for Deployer "+archiveLoaderClassName); 
            ArchiveLoader archiveLoader = 
                  (ArchiveLoader)Class.forName(
                        archiveLoaderClassName).newInstance();            
            extensionModuleDeployer.setExtensionLoader(archiveLoader);
        }
        /* extensionModuleDeployer.
                setConfigManager(ArchiveDeployerFactory.
                                     getArchiveDeployerFactory().
                                        getConfigManagerForType(
                                        extensionModuleDeployer.getModuleType()));
         */       
        ArchiveDeployerFactory.getArchiveDeployerFactory().registerDeployer(
            extensionModuleDeployer);
    }
    
    //MARKED FOR DELETION
    public static void registerConfigManager(ExtensionModuleConfigManager mgr,
                                                ModuleType moduleType) {
        ArchiveDeployerFactory.getArchiveDeployerFactory().
                    registerConfigManager(mgr, moduleType);
     }

    /**
     * This API will be called by the glassfish code to retrieve
     * the extension module archivist for a particular module type.
     *
     * @return the extension module archivist for the module type
     */
    public static ExtensionModuleArchivist getExtensionModuleArchivist(
        ModuleType moduleType) {
        Archivist archivist =  ArchivistFactory.getArchivistForType(moduleType);
        return (ExtensionModuleArchivist)archivist;
    }

    /**
     * This API will be called by the glassfish code to retrieve 
     * the extension module deployer for a particular module type.
     *
     * @return the extension module deployer for the module type
     */
    public static ExtensionModuleDeployer getExtensionModuleDeployer(
        ModuleType moduleType) {
        return ArchiveDeployerFactory.getArchiveDeployerFactory().getDeployerForType(
            moduleType);
    }

    /**
     *  This is a utility API for the 3rd party code to leverage glassfish
     *  annotation framework.
     *  This API retrieves an annotation processor for the particular extension
     *  module.
     *
     *  @param archiveDeployerClassName the implementation class 
     *        of ArchiveDeployer used as key
     *  @return the annotation processor for this module type
     */ 
    public static AnnotationProcessor getExtensionAnnotationProcessor(
        String archiveDeployerClassName) {
        ExtensionModuleAnnotationFactory factory = 
            ExtensionFactoryFactory.getExtensionModuleAnnotationFactory(
                archiveDeployerClassName);
        return factory.getAnnotationProcessor();
    }

    /**
     *  This is a utility API for the 3rd party code to leverage glassfish
     *  annotation framework.
     *  This API registers an annotation handler for the particular extension
     *  module.
     *
     *  @param handler the annotation handler to register with the 
     *                extension module annotation factory.
     *  @param archiveDeployerClassName the implementation class 
     *        of ArchiveDeployer used as key
     */
    public static void registerAnnotationHandler(
        AnnotationHandler handler, String archiveDeployerClassName) {
        ExtensionModuleAnnotationFactory factory = 
            ExtensionFactoryFactory.getExtensionModuleAnnotationFactory(
                archiveDeployerClassName);
        factory.registerAnnotationHandler(handler);
    }

    /**
     *  This is a utility API for the 3rd party code to leverage glassfish
     *  for processing javaee metadata (javaee deployment descriptors and 
     *  javaee annotations).
     *
     *  @param moduleRootDirectory the module root directory
     *  @param moduleScratchDirectory the directory where the generated
     *                               artificacts could be stored
     *  @param moduleClassLoader the module classloader
     *  @param isDeploy whether this is called in the deployment scenario
     *  @return the application which contains all the processed JavaEE
     *         metadata
     */
    public static Application processJavaEEMetaData(File moduleRootDirectory, 
        File moduleScratchDirectory, ClassLoader moduleClassLoader, 
        boolean isDeploy) throws IOException, SAXParseException {
        FileArchive archive = new FileArchive();
        try {
            if (isDeploy) { 
                // If this is deployment scenario, we should process JavaEE 
                // annotations and all deployment descriptors should be loaded 
                // from module root directory

                archive.open(moduleRootDirectory.getAbsolutePath());
                Archivist moduleArchivist = 
                    ArchivistFactory.getArchivistForArchive(archive);
                moduleArchivist.setAnnotationProcessingRequested(true);
                moduleArchivist.setClassLoader(moduleClassLoader);
                return ApplicationArchivist.openArchive(moduleArchivist, 
                    archive, true);
            } else {
                // If this is server start up scenario, we do not need to 
                // process JavaEE annotations again. The application
                // deployment descriptors will be loaded from 
                // moduleScratchDirectory and persistence descriptors from
                // moduleRootDirectory

                archive.open(moduleScratchDirectory.getAbsolutePath());
                Archivist moduleArchivist = 
                    ArchivistFactory.getArchivistForArchive(archive);
                ClassLoader tcl = (moduleClassLoader instanceof InstrumentableClassLoader) ?  InstrumentableClassLoader.class.cast(moduleClassLoader).copy() : moduleClassLoader; 
                moduleArchivist.setClassLoader(tcl);
                Application application = ApplicationArchivist.openArchive(
                    moduleArchivist, archive, true);
                application.setClassLoader(tcl);
                for (BundleDescriptor bd : (Collection <BundleDescriptor>)
                    application.getBundleDescriptors()) {
                    bd.setClassLoader(tcl);
                }
                // we need to read persistence descriptors separately
                // because they are read from appDir as oppsed to xmlDir.
                FileArchive archive2 = new FileArchive();
                try {
                    archive2.open(moduleRootDirectory.getAbsolutePath());
                    ApplicationArchivist.readPersistenceDeploymentDescriptorsRecursively(archive2, application);
                } finally {
                    archive2.close();
                }
                return application;
            }
        } finally {
            archive.close();
        }
    }
}

