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 */
017package org.apache.bcel.util;
018
019import java.io.File;
020import java.io.FileNotFoundException;
021import java.io.IOException;
022import java.io.PrintWriter;
023import java.io.UnsupportedEncodingException;
024import java.nio.charset.Charset;
025import java.nio.charset.StandardCharsets;
026import java.util.HashSet;
027import java.util.Set;
028
029import org.apache.bcel.Const;
030import org.apache.bcel.Constants;
031import org.apache.bcel.classfile.Attribute;
032import org.apache.bcel.classfile.ClassParser;
033import org.apache.bcel.classfile.ConstantPool;
034import org.apache.bcel.classfile.JavaClass;
035import org.apache.bcel.classfile.Method;
036import org.apache.bcel.classfile.Utility;
037
038/**
039 * Read class file(s) and convert them into HTML files.
040 *
041 * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
042 *
043 * <OL>
044 * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
045 * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
046 * <LI>"package"."class"_cp.html contains the constant pool
047 * <LI>"package"."class"_code.html contains the byte code
048 * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
049 * </OL>
050 *
051 * All subfiles reference each other appropriately, e.g. clicking on a method in the Method's frame will jump to the
052 * appropriate method in the Code frame.
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 += 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     * @throws IOException Thrown when an I/O exception of some sort has occurred.
182     */
183    public Class2HTML(final JavaClass javaClass, final String dir) throws IOException {
184        this(javaClass, dir, StandardCharsets.UTF_8);
185    }
186
187    private Class2HTML(final JavaClass javaClass, final String dir, final Charset charset) throws IOException {
188        final Method[] methods = javaClass.getMethods();
189        this.javaClass = javaClass;
190        this.dir = dir;
191        className = javaClass.getClassName(); // Remember full name
192        constantPool = javaClass.getConstantPool();
193        // Get package name by tacking off everything after the last '.'
194        final int index = className.lastIndexOf('.');
195        if (index > -1) {
196            classPackage = className.substring(0, index);
197        } else {
198            classPackage = ""; // default package
199        }
200        final ConstantHTML constantHtml = new ConstantHTML(dir, className, classPackage, methods, constantPool, charset);
201        /*
202         * Attributes can't be written in one step, so we just open a file which will be written consequently.
203         */
204        try (AttributeHTML attributeHtml = new AttributeHTML(dir, className, constantPool, constantHtml, charset)) {
205            new MethodHTML(dir, className, methods, javaClass.getFields(), constantHtml, attributeHtml, charset);
206            // Write main file (with frames, yuk)
207            writeMainHTML(attributeHtml, charset);
208            new CodeHTML(dir, className, methods, constantPool, constantHtml, charset);
209        }
210    }
211
212    private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws FileNotFoundException, UnsupportedEncodingException {
213        try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) {
214            file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + className + "</TITLE>" + "</HEAD>\n" + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
215                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"ConstantPool\" SRC=\"" + className + "_cp.html" + "\"\n MARGINWIDTH=\"0\" "
216                + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Attributes\" SRC=\"" + className + "_attributes.html"
217                + "\"\n MARGINWIDTH=\"0\" " + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "</FRAMESET>\n"
218                + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"Code\" SRC=\"" + className + "_code.html\"\n MARGINWIDTH=0 "
219                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Methods\" SRC=\"" + className + "_methods.html\"\n MARGINWIDTH=0 "
220                + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "</FRAMESET></FRAMESET></HTML>");
221        }
222        final Attribute[] attributes = javaClass.getAttributes();
223        for (int i = 0; i < attributes.length; i++) {
224            attributeHtml.writeAttribute(attributes[i], "class" + i);
225        }
226    }
227}