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

/*
 * @(#) ClassLoaderUtils.java
 *
 * Copyright 2001-2002 by iPlanet/Sun Microsystems, Inc.,
 * 901 San Antonio Road, Palo Alto, California, 94303, U.S.A.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information
 * of iPlanet/Sun Microsystems, Inc. ("Confidential Information").
 * You shall not disclose such Confidential Information and shall
 * use it only in accordance with the terms of the license
 * agreement you entered into with iPlanet/Sun Microsystems.
 */
package com.sun.enterprise.loader;

import java.io.File;
import java.util.List;
import java.util.ArrayList;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.StringTokenizer;

import com.sun.enterprise.util.io.FileUtils;

import java.io.IOException;

import java.util.logging.Level;
import java.util.logging.Logger;
import com.sun.logging.LogDomains;


/**
 * Contains utility methods to create class loaders.
 *
 * @author Nazrul Islam
 * @since  JDK1.4
 */
public class ClassLoaderUtils {

    /** logger for this class */
    private static Logger _logger =
        LogDomains.getLogger(LogDomains.LOADER_LOGGER);

    /**
     * Returns a new class loader based on the given directory paths and 
     * the jar files & zip files found under jar directory.  
     *
     * @param    dirs     array of directory path names
     * @param    jarDirs  array of path name to directories that contains
     *                    JAR & ZIP files.
     * @param    parent   parent class loader for the new class loader
     *
     * @return   a new class loader based on the urls from the given params
     *
     * @throws  IOException  if an i/o error while constructing the urls
     */
    public static ClassLoader getClassLoader(File[] dirs, File[] jarDirs, 
            ClassLoader parent) throws IOException {

        URLClassLoader loader  = null;
        URL[] urls             = getUrls(dirs, jarDirs);

        if (urls != null) {
            if (parent != null) {
                loader = new URLClassLoader(urls, parent); 
            } else {
                loader = new URLClassLoader(urls);
            }
        }

        return loader;
    }

    /**
     * Returns an array of urls that contains ..
     * <pre>
     *    i.   all the valid directories from the given directory (dirs) array
     *    ii.  all jar files from the given directory (jarDirs) array
     *    iii. all zip files from the given directory (jarDirs) array
     * </pre>
     *
     * @param    dirs     array of directory path names
     * @param    jarDirs  array of path name to directories that contains
     *                    JAR & ZIP files.
     * @return   an array of urls that contains all the valid dirs, 
     *           *.jar & *.zip
     *
     * @throws  IOException  if an i/o error while constructing the urls
     */
    public static URL[] getUrls(File[] dirs, File[] jarDirs) 
            throws IOException {

        URL[] urls  = null;
        List list   = new ArrayList();

        // adds all directories
        if (dirs != null) {
            for (int i=0; i<dirs.length; i++) {
                File dir = dirs[i];
                if (dir.isDirectory() || dir.canRead()) {
                    URL url = dir.toURI().toURL();
                    list.add(url);

                    if (_logger.isLoggable(Level.FINE)) {
                        _logger.log(Level.FINE, 
                            "Adding directory to class path:" + url.toString());
                    }
                }
            }
        } 

        // adds all the jars
        if (jarDirs != null) {
            for (int i=0; i<jarDirs.length; i++) {
                File jarDir =  jarDirs[i];

                if (jarDir.isDirectory() || jarDir.canRead()) {
                    File[] files = jarDir.listFiles();

                    for (int j=0; j<files.length; j++) {
                        File jar = files[j];

                        if ( FileUtils.isJar(jar) || FileUtils.isZip(jar) ) {
                            list.add(jar.toURI().toURL());

                            if (_logger.isLoggable(Level.FINE)) {
                                _logger.log(Level.FINE, 
                                    "Adding jar to class path:" + jar.toURL());
                            }
                        }
                    }
                }
            }
        }

        // converts the list to an array
        if (list.size() > 0) {
            urls = new URL[list.size()];
            urls = (URL[]) list.toArray(urls);
        }

        return urls;
    }

    /**
     * Returns a list of urls that contains ..
     * <pre>
     *    i.   all the valid directories from the given directory (dirs) array
     *    ii.  all jar files from the given directory (jarDirs) array
     *    iii. all zip files from the given directory (jarDirs) array
     * </pre>
     *
     * This is similar to getUrls(File[], File[])
     *
     * @param    dirs     array of directory path names
     * @param    jarDirs  array of path name to directories that contains
     *                    JAR & ZIP files.
     * @return   a list of urls that contains all the valid dirs, 
     *           *.jar & *.zip; the obj representing the paths are
     *           of type java.lang.String. It returns an empty list
     *           if no valid dir, jar or zip present.
     *
     * @throws  IOException  if an i/o error while constructing the urls
     *
     * @see #getUrls(File[], File[]);
     */
    public static List getUrlList(File[] dirs, File[] jarDirs) 
        throws IOException {
        return getUrlList(dirs, jarDirs, false); 
    }

    /**
     * Returns a list of urls that contains ..
     * <pre>
     *    i.   all the valid directories from the given directory (dirs) 
     *         array    
     *    ii.  all jar files from the given directory (jarDirs) array
     *    iii. all zip files from the given directory (jarDirs) array if
     *         not ignoring zip file (ignoreZip is false).
     * 
     * </pre>
     * 
     * @param    dirs     array of directory path names
     * @param    jarDirs  array of path name to directories that contains
     *                    JAR & ZIP files.
     * @return   a list of urls that contains all the valid dirs,
     *           *.jar & *.zip if not ignoring zip file, the obj 
     *           representing the paths are of type java.lang.String. 
     *           It returns an empty list if no valid dir, jar or zip 
     *           present.
     *
     * @throws  IOException  if an i/o error while constructing the urls
     *
     */
    public static List getUrlList(File[] dirs, File[] jarDirs,
        boolean ignoreZip) throws IOException {

        List list   = new ArrayList();

        // adds all directories
        if (dirs != null) {
            for (int i=0; i<dirs.length; i++) {
                File dir = dirs[i];
                if (dir.isDirectory() || dir.canRead()) {
                    list.add( dir.getCanonicalPath() );

                    if (_logger.isLoggable(Level.FINE)) {
                        _logger.log(Level.FINE, 
                            "Adding directory to class path:" 
                            + dir.getCanonicalPath());
                    }
                }
            }
        } 

        // adds all the jars
        if (jarDirs != null) {
            for (int i=0; i<jarDirs.length; i++) {
                File jarDir =  jarDirs[i];

                if (jarDir.isDirectory() || jarDir.canRead()) {
                    File[] files = jarDir.listFiles();

                    for (int j=0; j<files.length; j++) {
                        File jar = files[j];

                        if ( FileUtils.isJar(jar) || 
                            (!ignoreZip && FileUtils.isZip(jar)) ) {
                            list.add( jar.getCanonicalPath() );

                            if (_logger.isLoggable(Level.FINE)) {
                                _logger.log(Level.FINE, 
                                    "Adding jar to class path:" 
                                    + jar.getCanonicalPath());
                            }
                        }
                    }
                }
            }
        }

        return list;
    }

    /**
     * get URL[] from classpath
     * catches exception for wrong files
     */
    public static URL[] getUrlsFromClasspath(String classpath) {

        List urls  = new ArrayList();
        
        if (classpath == null) return (URL[]) urls.toArray(); //return empty arr
        
        // tokenize classpath
        StringTokenizer st = new StringTokenizer(classpath, File.pathSeparator);
        while (st.hasMoreTokens()) {
            try {
                File f = new File(st.nextToken());
                urls.add(f.toURI().toURL());
            } catch(Exception e) {
                  _logger.log(Level.WARNING,
				  			"loader.unexpected_error_while_creating_urls",e);
            }
        }
         
        // converts the list to an array
        URL[] ret;
        if (urls.size() > 0) {
            ret = new URL[urls.size()];
            ret = (URL[]) urls.toArray(ret);
        } else {
            ret = new URL[0];
        }

        return ret;
     }

    /**
     * Unit test code.
     */
    public static void main(String[] args) {

        try {
            URL[] urls = getUrls(new File[] {new File(args[0])}, 
                     new File[] {new File(args[1])});
            for (int i=0; i<urls.length; i++) {
                System.out.println(urls[i]);
            }

            URLClassLoader loader = (URLClassLoader) 
                    getClassLoader(new File[] {new File(args[0])},
                        new File[] {new File(args[1])}, null);

            //Class c = Class.forName(args[2], true, loader);
            Class c = loader.loadClass(args[2]);
            System.out.println("Loaded: " + c.getName());
            System.out.println("Loaded class has the following methods...");
            java.lang.reflect.Method[] m = c.getDeclaredMethods();
            for (int i=0; i<m.length; i++) {
                System.out.println(m[i]);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
