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