view src/PrintPublicMethods.java @ 3:61f453c6b172

2012-01-09 Pavel Tisnovsky <ptisnovs@redhat.com> * src/index.html: * src/style.css: * templates/index.html: * templates/style.css: Moved into other directory. * templates/all_classes_template.html: * templates/all_packages_template.html: * templates/package_template.html: Prepared templates for test coverage HTML report. * src/PrintPublicMethods.java: * src/PrintTestCoverage.java: Refactoring and Javadoc. * Makefile: Updated
author Pavel Tisnovsky <ptisnovs@redhat.com>
date Mon, 09 Jan 2012 14:57:59 +0100
parents 29318fe8d6d0
children 342d366654ce
line wrap: on
line source

/*
  Test coverage tool.

   Copyright (C) 2012 Red Hat

This tool is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.

This tool is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
General Public License for more details.

You should have received a copy of the GNU General Public License
along with this tool; see the file COPYING.  If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301 USA.

Linking this library statically or dynamically with other modules is
making a combined work based on this library.  Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.

As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module.  An independent module is a module which is not derived from
or based on this library.  If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so.  If you do not wish to do so, delete this
exception statement from your version.
*/

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Set;
import java.util.TreeSet;

/**
 * This class generates a list containing all public methods and its argument
 * types and return type for all classes specified in a file "class_list.txt"
 * or in a file specified by a command line parameter.
 * 
 * @author Pavel Tisnovsky
 */
public class PrintPublicMethods
{
    /**
     * Get a Class instance for a given class name or null if something goes
     * wrong.
     * 
     * @param className
     *            name of a class (including package name)
     * @return Class instance
     */
    @SuppressWarnings("unchecked")
    private static Class getClass(String className) {
        Class clazz = null;
        try {
            clazz = Class.forName(className);
            // we need to get a list of public classes only
            // (Interfaces and non public classes is not interesting ATM)
            if (!clazz.isInterface() && Modifier.isPublic(clazz.getModifiers())) {
                return clazz;
            }
        }
        // some exceptions could be thrown by Class.forName()
        catch (ClassNotFoundException e) {
            return null;
        }
        catch (UnsatisfiedLinkError e) {
            return null;
        }
        catch (ExceptionInInitializerError e) {
            return null;
        }
        catch (NoClassDefFoundError e) {
            return null;
        }
        return null;
    }

    /**
     * Remove "public", "static", "final", "synchronized" and "native" prefixes
     * from full method name;
     * 
     * @param methodName
     *            method name with all prefixes
     * @return method name without prefixes
     */
    private static String acquireMethodName(String methodName) {
        // please note, that sequence of prefixes is very important
        final String[] prefixes = new String[] {"public", "final", "native", "synchronized", "static"};
        String methodNameString = methodName;
        // remove all prefixes
        for (String prefix : prefixes) {
            // remove one prefix
            methodNameString = removePrefix(methodNameString, prefix);
        }
        return removeThrowsFromDeclaration(methodNameString);
    }

    /**
     * Remove one given prefix from method name.
     * 
     * @param methodName
     *            method name that could contains prefix.
     * @param prefix
     *            prefix to be removed.
     * @return method name without prefixes
     */
    private static String removePrefix(String methodName, String prefix) {
        String prefixStr = prefix + " ";
        if (methodName.startsWith(prefixStr)) {
            return methodName.substring(prefixStr.length());
        }
        return methodName;
    }

    /**
     * Removes throws declaration from method name, i.e.:
     * 
     * <pre>
     * void java.lang.Object.wait() throws java.lang.InterruptedException
     * </pre>
     * 
     * is changed to:
     * 
     * <pre>
     * void java.lang.Object.wait() throws java.lang.InterruptedException
     * </pre>
     * 
     * @param methodName
     *            method name which could contain throws declaration
     * @return method name without throws declaration
     */
    private static String removeThrowsFromDeclaration(String methodName) {
        int throwDeclarationIndex = methodName.indexOf(" throws ");
        if (throwDeclarationIndex > 1) {
            return methodName.substring(0, throwDeclarationIndex);
        }
        return methodName;
    }

    /**
     * Get all public methods from given class name (if such class exists).
     * 
     * @param className
     *            name of a class (including package name)
     * @return set of all public methods
     */
    @SuppressWarnings("unchecked")
    private static Set<String> getAllPublicMethodsForClass(String className) {
        Set<String> out = new TreeSet<String>();
        Class clazz = getClass(className);
        // in case of error, empty set is returned (not null)
        if (clazz == null) {
            return out;
        }
        Method[] methods = clazz.getDeclaredMethods();
        // process all methods select add only public ones
        for (Method method : methods) {
            if (Modifier.isPublic(method.getModifiers())) {
                String methodName = acquireMethodName(method.toString());
                out.add(methodName);
            }
        }
        return out;
    }

    /**
     * Get all public methods from given class name (if such class exists).
     * 
     * 
     * @param className
     *            name of a class (including package name)
     * @return set of all public constructors
     */
    @SuppressWarnings("unchecked")
    private static Set<String> getAllConstructors(String className) {
        Set<String> out = new TreeSet<String>();
        Class clazz = getClass(className);
        // in case of error, empty set is returned (not null)
        if (clazz == null) {
            return out;
        }
        Constructor[] constructors = clazz.getConstructors();
        // process all constructors select add only public ones
        for (Constructor constructor : constructors) {
            if (Modifier.isPublic(constructor.getModifiers())) {
                String methodName = acquireMethodName(constructor.toString());
                out.add("<init> " + methodName);
            }
        }
        return out;
    }

    /**
     * List all public methods and public constructors for given class
     * 
     * @param className
     *            name of class to list
     */
    private static void printAllPublicMethodsAndConstructors(String className)
    {
        printAllConstructors(className);
        printAllPublicMethods(className);
    }

    /**
     * List all public constructors for given class
     * 
     * @param className
     *            name of class to list
     */
    private static void printAllConstructors(String className)
    {
        for (String methodSignature : getAllConstructors(className))
        {
            System.out.println(methodSignature);
        }
    }

    /**
     * List all public methods for given class
     * 
     * @param className
     *            name of class to list
     */
    private static void printAllPublicMethods(String className)
    {
        for (String methodSignature : getAllPublicMethodsForClass(className))
        {
            System.out.println(methodSignature);
        }
    }

    /**
     * Entry point to this tool.
     * 
     * @param args
     *            first argument could contains path to file containing class
     *            list. 
     */
    public static void main(String[] args) {
        // first argument should exists - it should contains path to file with class list
        if (args.length == 1)
        {
            printAllPublicMethodsAndConstructors(args[0].trim());
        }
        else
        {
            System.err.println("Usage java PrintPublicMethods package.className");
        }
    }

}