view src/PrintClassList.java @ 2:8612fcdfab82

2012-01-06 Pavel Tisnovsky <ptisnovs@redhat.com> * src/PrintClassList.java: Fixed: closing Java archive when it is read Refactoring, added JavaDoc to all methods * src/PrintTestCoverage.java: Fixed exception thrown if the log file does not exists It's ok because some classes are not covered by tests at all.
author Pavel Tisnovsky <ptisnovs@redhat.com>
date Fri, 06 Jan 2012 12:25:10 +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.io.File;
import java.io.IOException;
import java.lang.reflect.Modifier;
import java.util.Enumeration;
import java.util.Set;
import java.util.TreeSet;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;



/**
 * This class is used to generate and print list of all public classes which are
 * stored in specified JAR archive. This JAR archive should be accessible
 * through classloader (this means that -cp should be used in certain
 * situations).
 * 
 * This tool could be used (and is plannet to be used) against "rt.jar"
 * 
 * @author Pavel Tisnovsky
 */
public class PrintClassList {

    /**
     * Default path to system-wide rt.jar.
     */
    private static final String DEFAULT_PATH_TO_SYSTEM_RT_JAR = "/usr/lib/jvm/java-1.6.0/jre/lib/rt.jar";

    /**
     * Generate and print sorted list of public all classes.
     * 
     * @param pathToJarArchive
     *            path to rt.jar or other JAR archive to be investigated.
     */
    private static void generateClassList(String pathToJarArchive) {
        // it's better to print sorted class names
        // and TreeSet sorted its elements by default
        Set<String> setOfClassNames = new TreeSet<String>();
        // try to read all public classes from Java archive
        readAllPublicClassesFromJarFile(pathToJarArchive, setOfClassNames);
        // now we have the list filled, time to print them
        printAllPublicClassNames(setOfClassNames);
    }

    /**
     * Read all public classes from Java archive
     * 
     * @param pathToJarArchive
     *            path to Java archive
     * @param setOfClassNames
     *            set containing all public class names
     */
    private static void readAllPublicClassesFromJarFile(String pathToJarArchive, Set<String> setOfClassNames)
    {
        JarFile jarFile = null;
        try {
            // open the archive and acquire all its entries
            jarFile = new JarFile(pathToJarArchive);

            // entries inside Java archive
            Enumeration<JarEntry> entries = jarFile.entries();

            // test each JAR entry
            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String className = generateClassName(entry.getName());
                // only public classes are interesting at this moment
                if (isPublicClass(className)) {
                    setOfClassNames.add(className);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        finally {
            // Java archive should be closed in all cases
            if (jarFile != null) {
                try {
                    jarFile.close();
                }
                catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * Print all public class names
     * 
     * @param setOfClassNames
     *            set containing all public class names
     */
    private static void printAllPublicClassNames(Set<String> setOfClassNames)
    {
        for (String className : setOfClassNames) {
            System.out.println(className);
        }
    }

    /**
     * Returns true if given className represents true class and the class is
     * public.
     * 
     * @param className
     *            class name
     * @return true if className represents true class and the class is public
     */
    @SuppressWarnings("unchecked")
    private static boolean isPublicClass(String className) {
        try {
            Class clazz = Class.forName(className);
            // interfaces are not our job at this moment 
            if (clazz.isInterface()) {
                return false;
            }
            int classModifiers = clazz.getModifiers();
            // we are interested only in public classes
            if (!Modifier.isPublic(classModifiers)) {
                return false;
            }
        }
        catch (ClassNotFoundException e) {
            // it might happen because jar file could
            // include other types of files files
            return false;
        }
        catch (UnsatisfiedLinkError e) {
            // it might happen too in some cases
            return false;
        }
        catch (ExceptionInInitializerError e) {
            // it might happen too in some cases
            return false;
        }
        catch (NoClassDefFoundError e) {
            // it might happen too in some cases
            return false;
        }
        return true;
    }

    /**
     * Try to change given JAR entry into proper class name.
     * 
     * @param name
     *            JAR entry name
     * @return class name transformed from JAR entry name
     */
    private static String generateClassName(String name)
    {
        String out = name;
        int postfixIndex = out.indexOf(".class");
        // remove postfix if its present in name
        if (postfixIndex > 0)
        {
            out = out.substring(0, postfixIndex);
        }
        // change path separator into dot separator
        out = out.replace('/', '.');
        // I'm not sure about JAR files created on Windows platform
        out = out.replace(File.separatorChar, '.');
        return out;
    }

    /**
     * Entry point to this tool.
     * 
     * @param args
     *            first argument should contains path to JAR file.
     *            If the first argument does not exists, constant
     *            path is used instead.
     */
    public static void main(String[] args) {
        String pathToRtJar = DEFAULT_PATH_TO_SYSTEM_RT_JAR;
        // path to rt.jar could be specified as first command line argument
        if (args.length == 1) {
            pathToRtJar = args[0];
        }
        System.err.println("Path to Jar file is set to: " + pathToRtJar);
        generateClassList(pathToRtJar);
    }

}