/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (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/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.deployment.archivist;

import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.*;
import javax.enterprise.deploy.shared.ModuleType;
import org.xml.sax.SAXParseException;

import com.sun.enterprise.deployment.Application;
import com.sun.enterprise.deployment.deploy.shared.AbstractArchive;
import com.sun.enterprise.deployment.deploy.shared.Archive;
import com.sun.enterprise.deployment.Descriptor;
import com.sun.enterprise.deployment.io.DeploymentDescriptorFile;
import com.sun.enterprise.deployment.io.DescriptorConstants;
import com.sun.enterprise.deployment.io.runtime.WebRuntimeDDFile;
import com.sun.enterprise.deployment.io.WebDeploymentDescriptorFile;
import com.sun.enterprise.deployment.RootDeploymentDescriptor;
import com.sun.enterprise.deployment.util.ApplicationValidator;
import com.sun.enterprise.deployment.util.DOLUtils;
import com.sun.enterprise.deployment.util.DOLLoadingContextFactory;
import com.sun.enterprise.deployment.util.ModuleContentValidator;
import com.sun.enterprise.deployment.util.WebBundleVisitor;
import com.sun.enterprise.deployment.WebBundleDescriptor;


/**
 * This module is responsible for reading and write web applications
 * archive files (war).
 *
 * @author  Jerome Dochez
 * @version 
 */
public class WebArchivist extends Archivist {

    private WebBundleDescriptor descriptor;
    
    /** 
     * The DeploymentDescriptorFile handlers we are delegating for XML i/o
     */
    DeploymentDescriptorFile standardDD = new WebDeploymentDescriptorFile();    

    /** Creates new WebArchivist */
    public WebArchivist() {
    }   
        
    /**
     * @return the  module type handled by this archivist
     * as defined in the application DTD
     *
     */
    public ModuleType getModuleType() {
        return ModuleType.WAR;
    }        
    
    /**
     * Archivist read XML deployment descriptors and keep the
     * parsed result in the DOL descriptor instances. Sets the descriptor
     * for a particular Archivst type
     */
    public void setDescriptor(Descriptor descriptor) {
        if (descriptor instanceof WebBundleDescriptor) {
            this.descriptor = (WebBundleDescriptor) descriptor;
        } else {
            if (descriptor instanceof Application) {
                // this is acceptable if the application actually represents 
                // a standalone module
                java.util.Set webBundles = ((Application) descriptor).getWebBundleDescriptors();
                if (webBundles.size()>0) {
                    this.descriptor = (WebBundleDescriptor) webBundles.iterator().next();
                    if (this.descriptor.getModuleDescriptor().isStandalone()) 
                        return;
                    else 
                        this.descriptor=null;
                }      
            }
            DOLUtils.getDefaultLogger().log(Level.SEVERE, "enterprise.deployment.backend.descriptorFailure", new Object[] {this});
            throw new RuntimeException("Error setting descriptor " + descriptor + " in " + this);
        }
    }  
    
    /** 
     * @return the location of the web services related deployment 
     * descriptor file inside this archive or null if this archive
     * does not support webservices implementation.
     */
    public String getWebServicesDeploymentDescriptorPath() {
        return DescriptorConstants.WEB_WEBSERVICES_JAR_ENTRY;
    }    
    
    /**
     * @return the DeploymentDescriptorFile responsible for handling
     * standard deployment descriptor
     */
    public DeploymentDescriptorFile getStandardDDFile() {
        return standardDD;
    }
    
    /**
     * @return if exists the DeploymentDescriptorFile responsible for
     * handling the configuration deployment descriptors
     */
    public DeploymentDescriptorFile getConfigurationDDFile() {
        return new WebRuntimeDDFile();
    }      
    
    /**
     * @return the Descriptor for this archvist
     */ 
    public Descriptor getDescriptor() {
        return descriptor;
    }  

    /**
     * @return a default BundleDescriptor for this archivist
     */
    public Descriptor getDefaultBundleDescriptor() {
        WebBundleDescriptor webBundleDesc =
            DOLLoadingContextFactory.getDefaultWebBundleDescriptor();
        return webBundleDesc;
    }
    
    /**
     * perform any post deployment descriptor reading action
     *
     * @param descriptor the deployment descriptor for the module
     * @param archive the module archive
     */
    protected void postOpen(RootDeploymentDescriptor descriptor, AbstractArchive archive) 
        throws IOException
    {
        super.postOpen(descriptor, archive);
        WebBundleDescriptor webBundle = (WebBundleDescriptor) descriptor;
        ModuleContentValidator mdv = new ModuleContentValidator(archive);
        webBundle.visit(mdv);
    }

    /**
     * validates the DOL Objects associated with this archivist, usually
     * it requires that a class loader being set on this archivist or passed
     * as a parameter
     */
    public void validate(ClassLoader aClassLoader) {
        ClassLoader cl = aClassLoader;
        if (cl==null) {
            cl = classLoader;
        }
        if (cl==null) {
            return;
        }
        descriptor.setClassLoader(cl);
        descriptor.visit((WebBundleVisitor) new ApplicationValidator());        
    }            

    /**
     * In the case of web archive, the super handles() method should be able 
     * to make a unique identification.  If not, then the archive is definitely 
     * not a war.
     */
    protected boolean postHandles(AbstractArchive abstractArchive) 
            throws IOException {
        return false;
    }

    protected String getArchiveExtension() {
        return WEB_EXTENSION;
    }
    
    /**
     * @return a list of libraries included in the archivist
     */
    public Vector getLibraries(AbstractArchive archive) {
        
        Enumeration<String> entries = archive.entries();
        if (entries==null)
            return null;
        
        Vector libs = new Vector();        
        while (entries.hasMoreElements()) {
            
            String entryName = entries.nextElement();
            if (!entryName.startsWith("WEB-INF/lib")) {
                continue; // not in WEB-INF...
            }
            if (entryName.endsWith(".jar")) {
                libs.add(entryName);
            }            
        }
        return libs;
    }

    @Override public void readPersistenceDeploymentDescriptors(
            AbstractArchive archive, Descriptor descriptor) throws IOException, SAXParseException {
        if(logger.isLoggable(Level.FINE)) {
            logger.logp(Level.FINE, "WebArchivist",
                    "readPersistenceDeploymentDescriptors", "archive = {0}",
                    archive.getURI());
        }
        Map<String, Archive> subArchives = new HashMap<String, Archive>();
        Enumeration entries = archive.entries();
        final String CLASSES_DIR = "WEB-INF/classes/";
        final String LIB_DIR = "WEB-INF/lib/";
        final String JAR_EXT = ".jar";
        try {
            final String pathOfPersistenceXMLInsideClassesDir =
                    CLASSES_DIR+DescriptorConstants.PERSISTENCE_DD_ENTRY;
            while(entries.hasMoreElements()){
                final String nextEntry = String.class.cast(entries.nextElement());
                if(pathOfPersistenceXMLInsideClassesDir.equals(nextEntry)) {
                    subArchives.put(CLASSES_DIR, archive.getSubArchive(CLASSES_DIR));
                } else if (nextEntry.startsWith(LIB_DIR) && nextEntry.endsWith(JAR_EXT)) {
                    String jarFile = nextEntry.substring(LIB_DIR.length(), nextEntry.length()-JAR_EXT.length());
                    if(jarFile.indexOf('/') == -1) { // to avoid WEB-INF/lib/foo/bar.jar
                        // this jarFile is directly inside WEB-INF/lib directory
                        subArchives.put(nextEntry, archive.getSubArchive(nextEntry));
                    } else {
                        if(logger.isLoggable(Level.FINE)) {
                            logger.logp(Level.FINE, "WebArchivist",
                                    "readPersistenceDeploymentDescriptors",
                                    "skipping {0} as it exists inside a directory in {1}.",
                                    new Object[]{nextEntry, LIB_DIR});
                        }
                        continue;
                    }
                }
            }
            for(Map.Entry<String, Archive> pathToArchiveEntry : subArchives.entrySet()) {
                readPersistenceDeploymentDescriptor(pathToArchiveEntry.getValue(), pathToArchiveEntry.getKey(), descriptor);
            }
        } finally {
            for(Archive subArchive : subArchives.values()) {
                subArchive.close();
            }
        }
    }

}
