view src/PrintPublicMethods.java @ 16:b6c8372f5723 draft

* src/ClassInfo.java: * src/FileUtils.java: * src/PrintClassList.java: * src/PrintPublicMethods.java: * src/PrintTestCoverage.java: * src/ReportGenerator.java: Minor changes - JavaDoc and refactoring.
author Pavel Tisnovsky <ptisnovs@redhat.com>
date Wed, 16 May 2012 10:59:45 +0200
parents 342d366654ce
children 7cd98b5c3440
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 stored in a test file "class_list.txt"
 * or in a text file specified by a command line parameter.
 * 
 * @author Pavel Tisnovsky
 */
public class PrintPublicMethods
{
    /**
     * Return a Class instance for a given class name or null value if something
     * goes wrong.
     * 
     * @param className
     *            name of a class (including package name)
     * @return Class instance for a given class name. Null value is returned if
     *         something goes wrong, ie. class could not be found or it's not a
     *         public class etc.
     */
    @SuppressWarnings("unchecked")
    private static Class getClass(String className) {
        // variable to be returned from this method
        Class clazz = null;
        try {
            // try to get a class for given class name
            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) {
            // it might happen
            return null;
        }
        catch (UnsatisfiedLinkError e) {
            // it might happen
            return null;
        }
        catch (ExceptionInInitializerError e) {
            // it might happen
            return null;
        }
        catch (NoClassDefFoundError e) {
            // it might also happen
            return null;
        }
        // it is not a class at all or the class is not public
        // only null value is returned
        return null;
    }

    /**
     * Remove "public", "static", "final", "synchronized" and "native" prefixes
     * from full method name.
     * 
     * @param methodName
     *            method name containing possibly some 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);
        }
        // "throws" declaration should be removed too
        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 the selected prefix
     */
    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()
     * </pre>
     *
     * When the method does not contain "throws" declaration, it's name is not
     * changed.
     *
     * @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;
        }
        // retrieve all declared methods
        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 constructors 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;
        }
        // get all declared constructors
        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)
    {
        // get and print all public constructors 
        printAllConstructors(className);
        // get and print all public methods 
        printAllPublicMethods(className);
    }

    /**
     * List all public constructors for given class
     * 
     * @param className
     *            name of class to list
     */
    private static void printAllConstructors(String className)
    {
        // iterate over all constructors
        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)
    {
        // iterate over all public methods
        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
        {
            // used did not specified class list
            System.err.println("Usage java PrintPublicMethods package.className");
        }
    }

}