/*
 * @(#)BytecodeLoaderUtil.java
 *
 * Copyright (C) 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.codecoverage.v2;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import junit.framework.Assert;
import net.sourceforge.groboutils.util.io.v1.ReadByteStream;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.Code;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.generic.ConstantPoolGen;


/**
 * Helper for loading bytecode.
 *
 * @author    Matt Albrecht <a href="mailto:groboclown@users.sourceforge.net">groboclown@users.sourceforge.net</a>
 * @version   $Date: 2004/04/15 05:48:27 $
 * @since     January 7, 2003
 */
public class BytecodeLoaderUtil
{
    private static final Class THIS_CLASS = BytecodeLoaderUtil.class;

    public static String getClassFilename( Class c )
    {
        Assert.assertNotNull( "Null class.", c );
        return getClassFilename( c.getName() );
    }
    
    public static String getClassFilename( String name )
    {
        Assert.assertNotNull( "Null class name.", name );
        String filename = name.replace( '.', '/' )+".class";
        return filename;
    }
    
    public static InputStream loadBytecodeStream( String filename )
            throws IOException
    {
        Assert.assertNotNull( "Null filename.", filename );
        ClassLoader cl = THIS_CLASS.getClassLoader();
        InputStream is = cl.getSystemResourceAsStream( filename );
        Assert.assertNotNull(
            "resource '"+filename+"' could not be found.",
            is );
        return is;
    }
    
    public static byte[] loadBytecode( String filename )
            throws IOException
    {
        Assert.assertNotNull( "Null filename.", filename );
        InputStream is = loadBytecodeStream( filename );
        return ReadByteStream.readByteStream( is );
    }
    
    public static JavaClass loadJavaClass( String className )
            throws IOException
    {
        String filename = getClassFilename( className );
        InputStream is = loadBytecodeStream( filename );
        ClassParser cp = new ClassParser( is, filename );
        JavaClass jc = cp.parse();
        return jc;
    }
    
    public static JavaClass loadJavaClass( String className, byte[] bytecode )
            throws IOException
    {
        String filename = getClassFilename( className );
        ByteArrayInputStream is = new ByteArrayInputStream( bytecode );
        ClassParser cp = new ClassParser( is, filename );
        JavaClass jc = cp.parse();
        return jc;
    }

    
    public static Class loadClassFromBytecode( String className, byte[] b )
            throws ClassNotFoundException
    {
        ArrayClassLoader acl = new ArrayClassLoader();
        acl.addClass( className, b );
        Class c = acl.loadClass( className );
        return c;
    }
    
    
    public static void runMain( Class cz )
            throws Exception
    {
        String s[] = new String[0];
        java.lang.reflect.Method m = cz.getMethod( "main",
            new Class[] { s.getClass() } );
        m.invoke( null, new Object[] { s } );
    }
    
    
    public static void verifyClass( String className, byte[] b )
            throws Exception
    {
        JavaClass jc = loadJavaClass( className, b );
        
        // ensure the integrety of the class file.
        org.apache.bcel.generic.ClassGen modClass =
            new org.apache.bcel.generic.ClassGen( jc );
        ConstantPoolGen constantPool = modClass.getConstantPool();
        org.apache.bcel.classfile.Method mL[] = modClass.getMethods();
        
        for (int i = 0; i < mL.length; ++i)
        {
            verifyMethod( mL[i], constantPool );
        }
    }
    
    
    public static void verifyMethod( org.apache.bcel.classfile.Method m,
            ConstantPoolGen cp )
            throws Exception
    {
        Code c = m.getCode();
        org.apache.bcel.classfile.CodeException ce[] = c.getExceptionTable();
        for (int i = 0; i < ce.length; ++i)
        {
            /* this isn't an error - it can really happen
            Assert.assertTrue(
                "Method "+m+" includes a '0' catch type in code exception.",
                ce[i].getCatchType() != 0);
            */
            
            // a better test is to check this catch type against the
            // original catch type.
        }
    }
}

