Class2HTML.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  *  Unless required by applicable law or agreed to in writing, software
  12.  *  distributed under the License is distributed on an "AS IS" BASIS,
  13.  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  *  See the License for the specific language governing permissions and
  15.  *  limitations under the License.
  16.  */
  17. package org.apache.bcel.util;

  18. import java.io.File;
  19. import java.io.FileNotFoundException;
  20. import java.io.IOException;
  21. import java.io.PrintWriter;
  22. import java.io.UnsupportedEncodingException;
  23. import java.nio.charset.Charset;
  24. import java.nio.charset.StandardCharsets;
  25. import java.util.HashSet;
  26. import java.util.Set;

  27. import org.apache.bcel.Const;
  28. import org.apache.bcel.Constants;
  29. import org.apache.bcel.classfile.Attribute;
  30. import org.apache.bcel.classfile.ClassParser;
  31. import org.apache.bcel.classfile.ConstantPool;
  32. import org.apache.bcel.classfile.JavaClass;
  33. import org.apache.bcel.classfile.Method;
  34. import org.apache.bcel.classfile.Utility;

  35. /**
  36.  * Read class file(s) and convert them into HTML files.
  37.  *
  38.  * Given a JavaClass object "class" that is in package "package" five files will be created in the specified directory.
  39.  *
  40.  * <OL>
  41.  * <LI>"package"."class".html as the main file which defines the frames for the following subfiles.
  42.  * <LI>"package"."class"_attributes.html contains all (known) attributes found in the file
  43.  * <LI>"package"."class"_cp.html contains the constant pool
  44.  * <LI>"package"."class"_code.html contains the byte code
  45.  * <LI>"package"."class"_methods.html contains references to all methods and fields of the class
  46.  * </OL>
  47.  *
  48.  * All subfiles reference each other appropriately, e.g. clicking on a method in the Method's frame will jump to the
  49.  * appropriate method in the Code frame.
  50.  */
  51. public class Class2HTML implements Constants {

  52.     private static String classPackage; // name of package, unclean to make it static, but ...
  53.     private static String className; // name of current class, dito
  54.     private static ConstantPool constantPool;
  55.     private static final Set<String> basicTypes = new HashSet<>();
  56.     static {
  57.         basicTypes.add("int");
  58.         basicTypes.add("short");
  59.         basicTypes.add("boolean");
  60.         basicTypes.add("void");
  61.         basicTypes.add("char");
  62.         basicTypes.add("byte");
  63.         basicTypes.add("long");
  64.         basicTypes.add("double");
  65.         basicTypes.add("float");
  66.     }

  67.     public static void main(final String[] argv) throws IOException {
  68.         final String[] fileName = new String[argv.length];
  69.         int files = 0;
  70.         ClassParser parser = null;
  71.         JavaClass javaClass = null;
  72.         String zipFile = null;
  73.         final char sep = File.separatorChar;
  74.         String dir = "." + sep; // Where to store HTML files
  75.         /*
  76.          * Parse command line arguments.
  77.          */
  78.         for (int i = 0; i < argv.length; i++) {
  79.             if (argv[i].charAt(0) == '-') { // command line switch
  80.                 if (argv[i].equals("-d")) { // Specify target directory, default '.'
  81.                     dir = argv[++i];
  82.                     if (!dir.endsWith("" + sep)) {
  83.                         dir += sep;
  84.                     }
  85.                     final File store = new File(dir);
  86.                     if (!store.isDirectory()) {
  87.                         final boolean created = store.mkdirs(); // Create target directory if necessary
  88.                         if (!created && !store.isDirectory()) {
  89.                             System.out.println("Tried to create the directory " + dir + " but failed");
  90.                         }
  91.                     }
  92.                 } else if (argv[i].equals("-zip")) {
  93.                     zipFile = argv[++i];
  94.                 } else {
  95.                     System.out.println("Unknown option " + argv[i]);
  96.                 }
  97.             } else {
  98.                 fileName[files++] = argv[i];
  99.             }
  100.         }
  101.         if (files == 0) {
  102.             System.err.println("Class2HTML: No input files specified.");
  103.         } else { // Loop through files ...
  104.             for (int i = 0; i < files; i++) {
  105.                 System.out.print("Processing " + fileName[i] + "...");
  106.                 if (zipFile == null) {
  107.                     parser = new ClassParser(fileName[i]); // Create parser object from file
  108.                 } else {
  109.                     parser = new ClassParser(zipFile, fileName[i]); // Create parser object from ZIP file
  110.                 }
  111.                 javaClass = parser.parse();
  112.                 new Class2HTML(javaClass, dir);
  113.                 System.out.println("Done.");
  114.             }
  115.         }
  116.     }

  117.     /**
  118.      * Utility method that converts a class reference in the constant pool, i.e., an index to a string.
  119.      */
  120.     static String referenceClass(final int index) {
  121.         String str = constantPool.getConstantString(index, Const.CONSTANT_Class);
  122.         str = Utility.compactClassName(str);
  123.         str = Utility.compactClassName(str, classPackage + ".", true);
  124.         return "<A HREF=\"" + className + "_cp.html#cp" + index + "\" TARGET=ConstantPool>" + str + "</A>";
  125.     }

  126.     static String referenceType(final String type) {
  127.         String shortType = Utility.compactClassName(type);
  128.         shortType = Utility.compactClassName(shortType, classPackage + ".", true);
  129.         final int index = type.indexOf('['); // Type is an array?
  130.         String baseType = type;
  131.         if (index > -1) {
  132.             baseType = type.substring(0, index); // Tack of the '['
  133.         }
  134.         // test for basic type
  135.         if (basicTypes.contains(baseType)) {
  136.             return "<FONT COLOR=\"#00FF00\">" + type + "</FONT>";
  137.         }
  138.         return "<A HREF=\"" + baseType + ".html\" TARGET=_top>" + shortType + "</A>";
  139.     }

  140.     static String toHTML(final String str) {
  141.         final StringBuilder buf = new StringBuilder();
  142.         for (int i = 0; i < str.length(); i++) {
  143.             char ch;
  144.             switch (ch = str.charAt(i)) {
  145.             case '<':
  146.                 buf.append("&lt;");
  147.                 break;
  148.             case '>':
  149.                 buf.append("&gt;");
  150.                 break;
  151.             case '\n':
  152.                 buf.append("\\n");
  153.                 break;
  154.             case '\r':
  155.                 buf.append("\\r");
  156.                 break;
  157.             default:
  158.                 buf.append(ch);
  159.             }
  160.         }
  161.         return buf.toString();
  162.     }

  163.     private final JavaClass javaClass; // current class object

  164.     private final String dir;

  165.     /**
  166.      * Write contents of the given JavaClass into HTML files.
  167.      *
  168.      * @param javaClass The class to write
  169.      * @param dir The directory to put the files in
  170.      * @throws IOException Thrown when an I/O exception of some sort has occurred.
  171.      */
  172.     public Class2HTML(final JavaClass javaClass, final String dir) throws IOException {
  173.         this(javaClass, dir, StandardCharsets.UTF_8);
  174.     }

  175.     private Class2HTML(final JavaClass javaClass, final String dir, final Charset charset) throws IOException {
  176.         final Method[] methods = javaClass.getMethods();
  177.         this.javaClass = javaClass;
  178.         this.dir = dir;
  179.         className = javaClass.getClassName(); // Remember full name
  180.         constantPool = javaClass.getConstantPool();
  181.         // Get package name by tacking off everything after the last '.'
  182.         final int index = className.lastIndexOf('.');
  183.         if (index > -1) {
  184.             classPackage = className.substring(0, index);
  185.         } else {
  186.             classPackage = ""; // default package
  187.         }
  188.         final ConstantHTML constantHtml = new ConstantHTML(dir, className, classPackage, methods, constantPool, charset);
  189.         /*
  190.          * Attributes can't be written in one step, so we just open a file which will be written consequently.
  191.          */
  192.         try (AttributeHTML attributeHtml = new AttributeHTML(dir, className, constantPool, constantHtml, charset)) {
  193.             new MethodHTML(dir, className, methods, javaClass.getFields(), constantHtml, attributeHtml, charset);
  194.             // Write main file (with frames, yuk)
  195.             writeMainHTML(attributeHtml, charset);
  196.             new CodeHTML(dir, className, methods, constantPool, constantHtml, charset);
  197.         }
  198.     }

  199.     private void writeMainHTML(final AttributeHTML attributeHtml, final Charset charset) throws FileNotFoundException, UnsupportedEncodingException {
  200.         try (PrintWriter file = new PrintWriter(dir + className + ".html", charset.name())) {
  201.             file.println("<HTML>\n" + "<HEAD><TITLE>Documentation for " + className + "</TITLE>" + "</HEAD>\n" + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
  202.                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"ConstantPool\" SRC=\"" + className + "_cp.html" + "\"\n MARGINWIDTH=\"0\" "
  203.                 + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Attributes\" SRC=\"" + className + "_attributes.html"
  204.                 + "\"\n MARGINWIDTH=\"0\" " + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n" + "</FRAMESET>\n"
  205.                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n" + "<FRAME NAME=\"Code\" SRC=\"" + className + "_code.html\"\n MARGINWIDTH=0 "
  206.                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "<FRAME NAME=\"Methods\" SRC=\"" + className + "_methods.html\"\n MARGINWIDTH=0 "
  207.                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n" + "</FRAMESET></FRAMESET></HTML>");
  208.         }
  209.         final Attribute[] attributes = javaClass.getAttributes();
  210.         for (int i = 0; i < attributes.length; i++) {
  211.             attributeHtml.writeAttribute(attributes[i], "class" + i);
  212.         }
  213.     }
  214. }