/*
 * @(#)ClassUtil.java      0.9.0 11/13/2000 - 14:06:34
 *
 * Copyright (C) 2000,2002-2003 Matt Albrecht
 * groboclown@users.sourceforge.net
 * http://groboutils.sourceforge.net
 *
 *  Permission is hereby granted, free of charge, to any person obtaining a
 *  copy of this software and associated documentation files (the "Software"),
 *  to deal in the Software without restriction, including without limitation
 *  the rights to use, copy, modify, merge, publish, distribute, sublicense,
 *  and/or sell copies of the Software, and to permit persons to whom the 
 *  Software is furnished to do so, subject to the following conditions:
 *
 *  The above copyright notice and this permission notice shall be included in 
 *  all copies or substantial portions of the Software. 
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 *  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 *  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL 
 *  THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 *  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 
 *  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 */

package net.sourceforge.groboutils.util.classes.v1;

import java.util.Hashtable;




/**
 * Utility class for loading classes and creating instances.  It decides
 * which JDK version to use as the loader.  Class instances are put
 * into a Hashtable, based on URL and classname.  When the Java-Doc defines
 * a <tt>jarName</tt>, as in {@link #getClass( String, String )}, the
 * <tt>jarName</tt> may be a filename loadable from the {@link java.io.File}
 * class, or a proper URL loadable from the {@link java.net.URL} class.
 * If the <tt>jarName</tt> does not have a protocol, then it is assumed to
 * be a file, otherwise, it is used as a URL.
 * <P>
 * Note that this class is not thread safe.  It is assumed that applications
 * will use the ClassUtil only during initialization times, since dynamic
 * class loading can be very expensive.  If you need thread safety, then you
 * will need to ensure that either all class loading is done in a single thread,
 * or that your application properly <tt>synchronize</tt>s the method calls.
 * <P>
 * Update v0.9.1: the constructor will now check for jdk2 first like before,
 * but now if it is not found, it will try to use jdk0 compatibility - before,
 * it would just fail out.  This allows the libraries to be repackaged to
 * contain only the jdk0 classes if so desired.
 *
 * @author  Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version $Date: 2003/02/10 22:52:36 $
 * @since   November 13, 2000 (GroboUtils Alpha 0.9.0)
 */
public class ClassUtil
{
    //----------------------------
    // Public data
    
    //----------------------------
    // Private data
    
    /**
     * Subclasses must instantiate themselves in this variable in their
     * static initialization block, and overload the {@link #getInstance()}
     * static method.
     */
    protected static ClassUtil s_instance = new ClassUtil();
    
    private IUrlClassLoader classLoader = null;
    private Hashtable classHash = new Hashtable();
    
    //----------------------------
    // constructors
    
    /**
     * Default constructor - made protected so
     * users won't instantiate the utility
     */
    protected ClassUtil()
    {
        // detect which JDK we're using, and from that use the correct
        // IUrlClassLoader instance.
        
        if (isJdk2Compatible())
        {
            this.classLoader = (IUrlClassLoader)createObject(
                getClassPackage( ClassUtil.class ) + ".jdk2.UrlClassLoader" );
        }
        if (this.classLoader == null)
        {
            this.classLoader = (IUrlClassLoader)createObject(
                getClassPackage( ClassUtil.class ) + ".jdk0.UrlClassLoader" );
            if (this.classLoader == null)
            {
                throw new IllegalStateException(
                    "There was an error loading a class loader." );
            }
        }
    }
    
    
    //----------------------------
    // Public Static methods
    
    
    /**
     * Retrieve the shared instance of the utility class.
     *
     * @return the utility instance
     */
    public static ClassUtil getInstance()
    {
        // Due to threading issues, the instance is created
        // in the static initialization block.
        
        return s_instance;
    }
     
     
     
    //----------------------------
    // Public methods
    
    
    /**
     * Call this to flush out the cache.  The cache may be huge, depending
     * on the Jar files loaded, as well as the Class instances.  This
     * should be called whenever a mass class instantiation process is
     * finished.
     */
    public void flush()
    {
        this.classHash = new Hashtable();
        this.classLoader.flush();
    }
    
     
    /**
     * Either finds or loads from cache the given class, using the
     * default class loader.
     *
     * @param name the name of the class to load.
     * @return the discovered Class, or <tt>null</tt> if it could not be found.
     * @see #getClass( String, String )
     */
    public Class getClass( String name )
    {
        return getClass( name, null );
    }
    
    
    /**
     * Either finds or loads from cache the given class.
     *
     * @param name the name of the class to load.
     * @param jarName the URL to load the class from - it may be <tt>null</tt>.
     * @return the discovered Class, or <tt>null</tt> if it could not be found.
     * @see #getClass( String )
     */
    public Class getClass( String name, String jarName )
    {
        String hashName = getClassHashName( name, jarName );
        Class c = (Class)classHash.get( hashName );
        if (c == null)
        {
            c = loadClass( name, jarName );
            if (c != null)
            {
                classHash.put( hashName, c );
            }
        }
        return c;
    }
    
    
    /**
     * Creates a new instance of the class with the given <tt>className</tt>
     * using the default constructor.  If there was an error during the
     * creation, such as the class was not found, the class does not have
     * a default constructor, or the constructor threw an exception, then
     * <tt>null</tt> is returned.
     *
     * @param className the name of the class to create an instance.
     * @return the new instance, or <tt>null</tt> if there was a problem.
     * @see #getClass( String )
     * @see #createObject( String, String )
     */
    public Object createObject( String className )
    {
        return createObject( className, null );
    }
    
    
    /**
     * Creates a new instance of the class with the given <tt>className</tt>
     * using the default constructor, from the given URL.  If there was an
     * error during the creation, such as the class was not found, the class
     * does not have a default constructor, or the constructor threw an
     * exception, then <tt>null</tt> is returned.
     *
     * @param className the name of the class to create an instance.
     * @param jarName the URL to load the class from - it may be <tt>null</tt>.
     * @return the new instance, or <tt>null</tt> if there was a problem.
     * @see #getClass( String, String )
     * @see #createObject( String )
     */
    public Object createObject( String className, String jarName )
    {
        return createObject( getClass( className, jarName ) );
    }
    
    
    /**
     * Creates an Object from the given Class, using its default constructor.
     * All creation exceptions are swallowed.  If the object could not
     * be created, then <tt>null</tt> is returned.
     *
     * @param c the Class object from which a new instance will be created
     *      using its default constructor.
     * @return the instantiated object, or <tt>null</tt> if <tt>c</tt> is
     *      <tt>null</tt>, or if there was an error during initialization.
     */
    public Object createObject( Class c )
    {
        if (c == null) return null;
        
        Object obj = null;
        try
        {
            obj = c.newInstance();
        }
        catch (InstantiationException ie)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+ie.getMessage());
            obj = null;
        }
        catch (IllegalAccessException iae)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+iae.getMessage());
            obj = null;
        }
        catch (NoSuchMethodError nsme)
        {
            System.out.println("Could not instantiate "+c.getName()+
                ": "+nsme.getMessage());
            obj = null;
        }
        return obj;
    }
    
    
    /**
     * Checks if the current JVM version is 1.2 compatible.  We check by
     * seeing if <tt>java.net.URLClassLoader</tt> exists.
     *
     * @return <tt>true</tt> if {@link java.net.URLClassLoader} exists
     *      in the classpath, or <tt>false</tt> otherwise.
     */
    public boolean isJdk2Compatible()
    {
        return (getClass( "java.net.URLClassLoader" ) != null);
    }
    
    
    /**
     * Discovers the package name for the given class.  The package name
     * will not have a final '.'.
     *
     * @param c the class to find the package name.
     * @return the package name, or <tt>null</tt> if <tt>c</tt> is
     *      <tt>null</tt>.
     */
    public String getClassPackage( Class c )
    {
        if (c == null)
        {
            return null;
        }
        String fullname = c.getName();
        int pos = fullname.lastIndexOf( '.' );
        if (pos < 0)
        {
            // no package
            return "";
        }
        
        // else, extract the pacakge name.
        return fullname.substring( 0, pos );
    }
     
     
    //----------------------------
    // Protected methods
    
    
    /**
     * Creates the name of the class for the hashtable lookup, which is
     * a junction of the jar name and the class name.  It allows for multiple
     * classes with the same name.
     *
     * @param name the class name
     * @param jarName the jar name - may be <tt>null</tt>.
     * @return the name for the hashtable lookup.
     */
    protected String getClassHashName( String name, String jarName )
    {
        if (jarName == null)
        {
            jarName = "<null>";
        }
        StringBuffer sb = new StringBuffer( jarName );
        sb.append( ';' );
        sb.append( name );
        return new String( sb );
    }
    
    
    /**
     * Attempts to load the class from the current classpath if <tt>baseJar</tt>
     * is <tt>null</tt>, or from the appropriate class loader if it is not
     * <tt>null</tt>.  If the class is not found, then this returns
     * <tt>null</tt>.  This never throws an exception.
     *
     * @param className name of the class to load
     * @param baseJar the URL file to load the class from - may be
     *          <tt>null</tt>.
     * @return the Class instance, or <tt>null</tt> if it was not found.
     */
    protected Class loadClass( String className, String baseJar )
    {
        Class c;
        
        try
        {
            if (baseJar == null || baseJar.length() <= 0)
            {
                try
                {
                    c = Class.forName( className );
                }
                catch (ClassNotFoundException cnfe)
                {
//                System.out.println("Class "+className+" not found");
                    c = null;
                }
            }
            else
            {
                c = this.classLoader.loadClass( className, baseJar );
            }
        }
        catch (Throwable t)
        {
            // probably a NoClassDefFoundError
            c = null;
        }
        return c;
    }
    
    
    
    //----------------------------
    // Private methods
}
 
