/*
 * 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.
 */

/*
 * Copyright 2004-2005 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

  
package com.sun.enterprise.deployment.backend;

import java.io.*;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.jar.Attributes;
import java.net.URL;
import com.sun.logging.LogDomains;
import java.util.logging.*;
import java.util.*;
import java.util.zip.ZipException;
import java.rmi.RemoteException;


/**
 * This class resolves the dependencies between optional packages and also between 
 * apps/stand-alone modules that depend on optional packages
 * @author Sheetal Vartak
 */

public class OptionalPkgDependency {

    //optional packages are stored in hashtable that is keyed by the extension name
    private static Hashtable optionalPackageStore = new Hashtable();

    // Fully qualified names of all jar files in all ext dirs.  Note that
    // this will include even jars that do not explicitly declare the
    // extension name and specification version in their manifest.
    private static Set extDirJars = new LinkedHashSet();

    private static Logger logger = LogDomains.getLogger(LogDomains.DPL_LOGGER);

    public OptionalPkgDependency() {      
    }

    public static boolean optionalPkgDependencyLogic(Manifest manifest, String archiveUri) {     

        boolean dependencySatisfied = true;

        String extensionList = null;
        try {
            extensionList = manifest.getMainAttributes().
                    getValue(Attributes.Name.EXTENSION_LIST);
            logger.fine("extensionList..." + extensionList);
        } catch (Exception npe) {
            //ignore this exception
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE,
                        "OptionalPkgDependency : exception occurred ==> " + npe.toString());
            }
        }
        
        if (extensionList == null) 
            return dependencySatisfied;
        
        StringTokenizer st =
                new StringTokenizer(extensionList, " ");
        while (st.hasMoreTokens()) {
            
            String token = st.nextToken().trim();
            String extName = manifest.getMainAttributes().
                    getValue(token + "-" + Attributes.Name.EXTENSION_NAME);
            
            String specVersion = manifest.getMainAttributes().
                    getValue(token + "-" + Attributes.Name.SPECIFICATION_VERSION);
            
            if (specVersion == null) {
                specVersion = new String("");
            }
            if (!optionalPackageStore.containsKey(extName)) {
                logger.log(Level.WARNING,
                        "enterprise.deployment.backend.optionalpkg.dependency.notexist",
                        new Object[] {extName, archiveUri});
                        dependencySatisfied = false;
            } else if (!specVersion.equals("") &&
                    (optionalPackageStore.get(extName).toString().equals("")) ||
                    !specVersion.equals(optionalPackageStore.get(extName).toString())) {
                logger.log(Level.WARNING,
                        "enterprise.deployment.backend.optionalpkg.dependency.notexist",
                        new Object[] {extName, archiveUri});
                        dependencySatisfied = false;
            }
        }
        if (dependencySatisfied == true) {
            logger.log(Level.INFO,
                    "enterprise.deployment.backend.optionalpkg.dependency.satisfied",
                    new Object[] {archiveUri});
        }
        return dependencySatisfied;
    }

    /**
     * check whether the optional packages have all their 
     * internal dependencies resolved
     */
    public static void satisfyOptionalPackageDependencies() {

	String ext_dirStr = new String(
				       System.getProperty("java.ext.dirs"));
	logger.fine("ext_dirStr..." + ext_dirStr);

	Vector ext_dirs = new Vector();
	StringTokenizer st = new StringTokenizer(ext_dirStr, File.pathSeparator);
	while (st.hasMoreTokens()) {
	    String next = st.nextToken();
	    logger.log(Level.FINE,"string tokens..." + next);
	    ext_dirs.addElement(next);
	}
        
        for (int v = 0; v < ext_dirs.size(); v++) {
            
            File ext_dir = new File((String)ext_dirs.elementAt(v));
            
            if (logger.isLoggable(Level.FINE)) {
                logger.log(Level.FINE,"extension dir..." + ext_dir);
            }
            
            
            File[] optionalPackages = ext_dir.listFiles();
            if (optionalPackages != null) {
                try {
                    for (int i = 0; i < optionalPackages.length; i++) {
                        
                        if (logger.isLoggable(Level.FINE)) {
                            logger.log(Level.FINE,"optional package..." + optionalPackages[i]);
                        }
                        
                        if (!optionalPackages[i].isDirectory()) {
                            JarFile jarFile = new JarFile(optionalPackages[i]);
                            Manifest manifest = jarFile.getManifest();
                            jarFile.close();
                            
                            extDirJars.add(optionalPackages[i].toString());
                            
                            //Extension-Name of optional package
                            if (manifest!=null) {
                                String extNameOfOptionalPkg = manifest.getMainAttributes().
                                        getValue(Attributes.Name.EXTENSION_NAME);
                                logger.fine("extNameOfOptionalPkg..." + extNameOfOptionalPkg);
                                String specVersion = manifest.getMainAttributes().
                                        getValue(Attributes.Name.SPECIFICATION_VERSION);
                                logger.fine("specVersion..." + specVersion);
                                if (extNameOfOptionalPkg != null) {
                                    if (specVersion == null) {
                                        logger.log(Level.WARNING,
                                                "enterprise.tools.deployment.backend.optionalpkg.dependency.specversion.null",
                                                new Object[] {extNameOfOptionalPkg});
                                                specVersion = new String("");
                                    }
                                    optionalPackageStore.put(extNameOfOptionalPkg,
                                            specVersion);
                                    
                                }
                            }
                        }
                    }
                    for (int i = 0; i < optionalPackages.length; i++) {
                        if (!optionalPackages[i].isDirectory()) {
                            JarFile jarFile = null;
                            try {
                                jarFile = new JarFile(optionalPackages[i]);
                                Manifest m = jarFile.getManifest();
                                if (m!=null) {
                                    optionalPkgDependencyLogic(m, optionalPackages[i].getAbsolutePath());
                                }
                            } finally {
                                if (jarFile!=null)
                                    jarFile.close();
                            }
                            
                        }
                    }
                } catch (IOException e) {
                    logger.log(Level.WARNING,
                            "enterprise.deployment.backend.optionalpkg.dependency.exception", new Object[] {e.getMessage()});
                }
            }            
        }
    }

    /**
     * Adds all the jar files in all of the ext dirs into a single string
     * in classpath format.  Returns the empty string if there are no
     * jar files in any ext dirs.
     */
    public static String getExtDirFilesAsClasspath() {
       
        StringBuffer classpath = new StringBuffer();

        for(Iterator iter = extDirJars.iterator(); iter.hasNext();) {
            String next = (String) iter.next();
            if( classpath.length() > 0 ) {
                classpath.append(File.pathSeparator);                
            }
            classpath.append(next);
        }

        return classpath.toString();
    }
    
}
