    001/*
    002 * Licensed to the Apache Software Foundation (ASF) under one or more
    003 * contributor license agreements.  See the NOTICE file distributed with
    004 * this work for additional information regarding copyright ownership.
    005 * The ASF licenses this file to You under the Apache License, Version 2.0
    006 * (the "License"); you may not use this file except in compliance with
    007 * the License.  You may obtain a copy of the License at
    008 *
    009 *      http://www.apache.org/licenses/LICENSE-2.0
    010 *
    011 *  Unless required by applicable law or agreed to in writing, software
    012 *  distributed under the License is distributed on an "AS IS" BASIS,
    013 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    014 *  See the License for the specific language governing permissions and
    015 *  limitations under the License.
    016 *
    017 */
    018package org.apache.bcel.util;
    019
    020import java.io.File;
    021import java.io.IOException;
    022import java.io.PrintWriter;
    023import java.nio.charset.Charset;
    024import java.nio.charset.StandardCharsets;
    025import java.util.HashSet;
    026import java.util.Set;
    027
    028import org.apache.bcel.Const;
    029import org.apache.bcel.Constants;
    030import org.apache.bcel.classfile.Attribute;
    031import org.apache.bcel.classfile.ClassParser;
    032import org.apache.bcel.classfile.ConstantPool;
    033import org.apache.bcel.classfile.JavaClass;
    034import org.apache.bcel.classfile.Method;
    035import org.apache.bcel.classfile.Utility;
    036
    037/**
    038 * Read class file(s) and convert them into HTML files.
    039 *
    040 * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
    041 *
    042 * <OL>
    043 * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
    044 * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
    045 * <LI>"package"."class"_cp.html contains the constant pool
    046 * <LI>"package"."class"_code.html contains the byte code
    047 * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
    048 * </OL>
    049 *
    050 * All subfiles reference each other appropriately, e.g. clicking on a method in the Method's frame will jump to the
    051 * appropriate method in the Code frame.
    052 *
    053 */
    054public class Class2HTML implements Constants {
    055
    056    private static String classPackage; // name of package, unclean to make it static, but ...
    057    private static String className; // name of current class, dito
    058    private static ConstantPool constantPool;
    059    private static final Set<String> basicTypes = new HashSet<>();
    060    static {
    061        basicTypes.add("int");
    062        basicTypes.add("short");
    063        basicTypes.add("boolean");
    064        basicTypes.add("void");
    065        basicTypes.add("char");
    066        basicTypes.add("byte");
    067        basicTypes.add("long");
    068        basicTypes.add("double");
    069        basicTypes.add("float");
    070    }
    071
    072    public static void main(final String[] argv) throws IOException {
    073        final String[] fileName = new String[argv.length];
    074        int files = 0;
    075        ClassParser parser = null;
    076        JavaClass javaClass = null;
    077        String zipFile = null;
    078        final char sep = File.separatorChar;
    079        String dir = "." + sep; // Where to store HTML files
    080        /*
    081         * Parse command line arguments.
    082         */
    083        for (int i = 0; i < argv.length; i++) {
    084            if (argv[i].charAt(0) == '-') { // command line switch
    085                if (argv[i].equals("-d")) { // Specify target directory, default '.'
    086                    dir = argv[++i];
    087                    if (!dir.endsWith("" + sep)) {
    088                        dir = dir + sep;
    089                    }
    090                    final File store = new File(dir);
    091                    if (!store.isDirectory()) {
    092                        final boolean created = store.mkdirs(); // Create target directory if necessary
    093                        if (!created && !store.isDirectory()) {
    094                            System.out.println("Tried to create the directory " + dir + " but failed");
    095                        }
    096                    }
    097                } else if (argv[i].equals("-zip")) {
    098                    zipFile = argv[++i];
    099                } else {
    100                    System.out.println("Unknown option " + argv[i]);
    101                }
    102            } else {
    103                fileName[files++] = argv[i];
    104            }
    105        }
    106        if (files == 0) {
    107            System.err.println("Class2HTML: No input files specified.");
    108        } else { // Loop through files ...
    109            for (int i = 0; i < files; i++) {
    110                System.out.print("Processing " + fileName[i] + "...");
    111                if (zipFile == null) {
    112                    parser = new ClassParser(fileName[i]); // Create parser object from file
    113                } else {
    114                    parser = new ClassParser(zipFile, fileName[i]); // Create parser object from zip file
    115                }
    116                javaClass = parser.parse();
    117                new Class2HTML(javaClass, dir);
    118                System.out.println("Done.");
    119            }
    120        }
    121    }
    122
    123    /**
    124     * Utility method that converts a class reference in the constant pool, i.e., an index to a string.
    125     */
    126    static String referenceClass(final int index) {
    127        String str = constantPool.getConstantString(index, Const.CONSTANT_Class);
    128        str = Utility.compactClassName(str);
    129        str = Utility.compactClassName(str, classPackage + ".", true);
    130        return "<A HREF=\"" + className + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + str + "</A>";
    131    }
    132
    133    static String referenceType(final String type) {
    134        String shortType = Utility.compactClassName(type);
    135        shortType = Utility.compactClassName(shortType, classPackage + ".", true);
    136        final int index = type.indexOf('['); // Type is an array?
    137        String baseType = type;
    138        if (index > -1) {
    139            baseType = type.substring(0, index); // Tack of the `['
    140        }
    141        // test for basic type
    142        if (basicTypes.contains(baseType)) {
    143            return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
    144        }
    145        return "<A HREF=\"" + baseType + ".html\" TARGET=_top>" + shortType + "</A>";
    146    }
    147
    148    static String toHTML(final String str) {
    149        final StringBuilder buf = new StringBuilder();
    150        for (int i = 0; i < str.length(); i++) {
    151            char ch;
    152            switch (ch = str.charAt(i)) {
    153            case '<':
    154                buf.append("&lt;");
    155                break;
    156            case '>':
    157                buf.append("&gt;");
    158                break;
    159            case '\n':
    160                buf.append("\\n");
    161                break;
    162            case '\r':
    163                buf.append("\\r");
    164                break;
    165            default:
    166                buf.append(ch);
    167            }
    168        }
    169        return buf.toString();
    170    }
    171
    172    private final JavaClass javaClass; // current class object
    173
    174    private final String dir;
    175
    176    /**
    177     * Write contents of the given JavaClass into HTML files.
    178     *
    179     * @param javaClass The class to write
    180     * @param dir The directory to put the files in
    181     */
    182    public Class2HTML(final JavaClass javaClass, final String dir) throws IOException {
    183        this(javaClass, dir, StandardCharsets.UTF_8);
    184    }
    185
    186    private Class2HTML(final JavaClass javaClass, final String dir, final Charset charset) throws IOException {
    187        final Method[] methods = javaClass.getMethods();
    188        this.javaClass = javaClass;
    189        this.dir = dir;
    190        className = javaClass.getClassName(); // Remember full name
    191        constantPool = javaClass.getConstantPool();
    192        // Get package name by tacking off everything after the last `.'
    193        final int index = className.lastIndexOf('.');
    194        if (index > -1) {
    195            classPackage = className.substring(0, index);
    196        } else {
    197            classPackage = ""; // default package
    198        }
    199        final ConstantHTML constantHtml = new ConstantHTML(dir, className, classPackage, methods, constantPool, charset);
    200        /*
    201         * Attributes can't be written in one step, so we just open a file which will be written consequently.
    202         */
    203        try (final AttributeHTML attributeHtml = new AttributeHTML(dir, className, constantPool, constantHtml, charset)) {
    204            new MethodHTML(dir, className, methods, javaClass.getFields(), constantHtml, attributeHtml, charset);
    205            // Write main file (with frames, yuk)
    206            writeMainHTML(attributeHtml, charset);
    207            new CodeHTML(dir, className, methods, constantPool, constantHtml, charset);
    208        }
    209    }
    210
    211    private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws IOException {
    212        try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) {
    213            file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + className + "</TITLE>" + "</HEAD>\n" + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
    214                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"ConstantPool\" SRC=\"" + className + "_cp.html" + "\"\n MARGINWIDTH=\"0\" "
    215                + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Attributes\" SRC=\"" + className + "_attributes.html"
    216                + "\"\n MARGINWIDTH=\"0\" " + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "</FRAMESET>\n"
    217                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"Code\" SRC=\"" + className + "_code.html\"\n MARGINWIDTH=0 "
    218                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Methods\" SRC=\"" + className + "_methods.html\"\n MARGINWIDTH=0 "
    219                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "</FRAMESET></FRAMESET></HTML>");
    220        }
    221        final Attribute[] attributes = javaClass.getAttributes();
    222        for (int i = 0; i < attributes.length; i++) {
    223            attributeHtml.writeAttribute(attributes[i], "class" + i);
    224        }
    225    }
    226}