Make up a compilable version of a given Sun or other API
/*
* Copyright (c) Ian F. Darwin, http://www.darwinsys.com/, 1996-2002.
* All rights reserved. Software written by Ian F. Darwin and others.
* $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Java, the Duke mascot, and all variants of Sun's Java "steaming coffee
* cup" logo are trademarks of Sun Microsystems. Sun's, and James Gosling's,
* pioneering role in inventing and promulgating (and standardizing) the Java
* language and environment is gratefully acknowledged.
*
* The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
* inventing predecessor languages C and C++ is also gratefully acknowledged.
*/
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
/** Make up a compilable version of a given Sun or other API,
* so developers can compile against it without a licensed copy. In Sun's case,
* all public API info is public on Sun's web site, so this does not disclose
* anything that is Sun Confidential.
* <p>This is a clean-room implementation: I did not look at the code
* for Sun's javap or any similar tool in preparing this program.
* XXX TODO:<ul>
* <li>Class printing: add superclasses.
* <li>Collapse common code in printing Constructors and Methods
* <li>Method printing: add exceptions
* <li>Arguments: Handle arrays (names begin [L)
* <li>Provide default (0, false, null) based on type; use in return statements
* and in assigment to protected final variables.
* </ul>
* @author Ian Darwin, http://www.darwinsys.com/
* @version $Id: RevEngAPI.java,v 1.11 2004/05/30 01:43:43 ian Exp $
*/
public class RevEngAPI extends APIFormatter {
public static void main(String[] argv) throws Exception {
new RevEngAPI().doArgs(argv);
}
private final static String PREFIX_ARG = "arg";
/** Make up names like "arg0" "arg1", etc. */
private String mkName(String name, int number) {
return new StringBuffer(name).append(number).toString();
}
/** NOT THREAD SAFE */
private String className;
private int classNameOffset;
/** Generate a .java file for the outline of the given class. */
public void doClass(Class c) throws IOException {
className = c.getName();
// pre-compute offset for stripping package name
classNameOffset = className.lastIndexOf('.') + 1;
// Inner class
if (className.indexOf('$') != -1)
return;
// get name, as String, with . changed to /
String slashName = className.replace('.','/');
String fileName = slashName + ".java";
System.out.println(className + " --> " + fileName);
String dirName = slashName.substring(0, slashName.lastIndexOf("/"));
new File(dirName).mkdirs();
// create the file.
PrintWriter out = new PrintWriter(new FileWriter(fileName));
out.println("// Generated by RevEngAPI for class " + className);
// If in a package, say so.
Package pkg;
if ((pkg = c.getPackage()) != null) {
out.println("package " + pkg.getName() + ';');
out.println();
}
// print class header
int cMods = c.getModifiers();
printMods(cMods, out);
out.print("class ");
out.print(trim(c.getName()));
out.print(' ');
// XXX get superclass
out.println('{');
// print constructors
Constructor[] ctors = c.getDeclaredConstructors();
for (int i=0; i< ctors.length; i++) {
if (i == 0) {
out.println();
out.println("\t// Constructors");
}
Constructor cons = ctors[i];
int mods = cons.getModifiers();
if (Modifier.isPrivate(mods))
continue;
out.print('\t');
printMods(mods, out);
out.print(trim(cons.getName()) + "(");
Class[] classes = cons.getParameterTypes();
for (int j = 0; j<classes.length; j++) {
if (j > 0) out.print(", ");
out.print(trim(classes[j].getName()) + ' ' +
mkName(PREFIX_ARG, j));
}
out.println(") {");
out.print("\t}");
}
// print method names
Method[] mems = c.getDeclaredMethods();
for (int i=0; i< mems.length; i++) {
if (i == 0) {
out.println();
out.println("\t// Methods");
}
Method m = mems[i];
if (m.getName().startsWith("access$"))
continue;
int mods = m.getModifiers();
if (Modifier.isPrivate(mods))
continue;
out.print('\t');
printMods(mods, out);
out.print(m.getReturnType());
out.print(' ');
out.print(trim(m.getName()) + "(");
Class[] classes = m.getParameterTypes();
for (int j = 0; j<classes.length; j++) {
if (j > 0) out.print(", ");
out.print(trim(classes[j].getName()) + ' ' +
mkName(PREFIX_ARG, j));
}
out.println(") {");
out.println("\treturn " + defaultValue(m.getReturnType()) + ';');
out.println("\t}");
}
// print fields
Field[] flds = c.getDeclaredFields();
for (int i=0; i< flds.length; i++) {
if (i == 0) {
out.println();
out.println("\t// Fields");
}
Field f = flds[i];
int mods = f.getModifiers();
if (Modifier.isPrivate(mods))
continue;
out.print('\t');
printMods(mods, out);
out.print(trim(f.getType().getName()));
out.print(' ');
out.print(f.getName());
if (Modifier.isFinal(mods)) {
try {
out.print(" = " + f.get(null));
} catch (IllegalAccessException ex) {
out.print("; // " + ex.toString());
}
}
out.println(';');
}
out.println("}");
//out.flush();
out.close();
}
private String trim(String theName) {
return theName.startsWith(className) ?
theName.substring(classNameOffset) : theName;
}
private class ModInfo {
int val;
String name;
ModInfo(int v, String n) {
val = v;
name = n;
}
}
private ModInfo[] modInfo = {
new ModInfo(16, "final"),
new ModInfo(2, "private"),
new ModInfo(1, "public"),
new ModInfo(4, "protected"),
new ModInfo(1024, "abstract"),
new ModInfo(8, "static"),
new ModInfo(32, "synchronized"),
new ModInfo(256, "native"),
new ModInfo(128, "transient"),
new ModInfo(64, "volatile"),
new ModInfo(2048, "strict"),
};
private void printMods(int mods, PrintWriter out) {
for (int i=0; i < modInfo.length; i++) {
if ((mods & modInfo[i].val) == modInfo[i].val) {
out.print(modInfo[i].name);
out.print(' ');
}
}
}
private String defaultValue(Class c) {
if (c.getName().equals("boolean"))
return "false";
// XXX else if object type return null;
else return "0";
}
public void startFile() {
// XXX save filename as project name
}
public void endFile() {
// XXX generate a trivial "build.xml" for Ant to create the jar file.
}
}
/**
* <p>
* APIFormatter reads one or more Zip files, gets all entries from each
* and, for each entry that ends in ".class", loads it with Class.forName()
* and hands it off to a doClass(Class c) method declared in a subclass.
* <br/>TODO<br/>
* Use GETOPT to control doingStandardClasses, verbosity level, etc.
* @author Ian Darwin, Ian@DarwinSys.com
* @version $Id: APIFormatter.java,v 1.6 2004/03/14 14:00:34 ian Exp $
*/
abstract class APIFormatter {
/** True if we are doing classpath, so only do java. and javax. */
protected static boolean doingStandardClasses = true;
protected int doArgs(String[] argv) throws IOException {
/** Counter of fields/methods printed. */
int n = 0;
// TODO: options
// -b - process bootclasspath
// -c - process classpath (default)
// -s - only process "java." and "javax."
if (argv.length == 0) {
// No arguments, look in CLASSPATH
String s = System.getProperty("java.class.path");
// break apart with path sep.
String pathSep = System.getProperty("path.separator");
StringTokenizer st = new StringTokenizer(s, pathSep);
// Process each zip in classpath
while (st.hasMoreTokens()) {
String thisFile = st.nextToken();
System.err.println("Trying path " + thisFile);
if (thisFile.endsWith(".zip") || thisFile.endsWith(".jar"))
processOneZip(thisFile);
}
} else {
// We have arguments, process them as zip/jar files
// doingStandardClasses = false;
for (int i=0; i<argv.length; i++)
processOneZip(argv[i]);
}
return n;
}
/** For each Zip file, for each entry, xref it */
public void processOneZip(String fileName) throws IOException {
List entries = new ArrayList();
ZipFile zipFile = null;
try {
zipFile = new ZipFile(new File(fileName));
} catch (ZipException zz) {
throw new FileNotFoundException(zz.toString() + fileName);
}
Enumeration all = zipFile.entries();
// Put the entries into the List for sorting...
while (all.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry)all.nextElement();
entries.add(zipEntry);
}
// Sort the entries (by class name)
// Collections.sort(entries);
// Process all the entries in this zip.
Iterator it = entries.iterator();
while (it.hasNext()) {
ZipEntry zipEntry = (ZipEntry)it.next();
String zipName = zipEntry.getName();
// Ignore package/directory, other odd-ball stuff.
if (zipEntry.isDirectory()) {
continue;
}
// Ignore META-INF stuff
if (zipName.startsWith("META-INF/")) {
continue;
}
// Ignore images, HTML, whatever else we find.
if (!zipName.endsWith(".class")) {
continue;
}
// If doing CLASSPATH, Ignore com.* which are "internal API".
// if (doingStandardClasses && !zipName.startsWith("java")){
// continue;
// }
// Convert the zip file entry name, like
// java/lang/Math.class
// to a class name like
// java.lang.Math
String className = zipName.replace('/', '.').
substring(0, zipName.length() - 6); // 6 for ".class"
// Now get the Class object for it.
Class c = null;
try {
c = Class.forName(className);
} catch (ClassNotFoundException ex) {
System.err.println("Error: " + ex);
}
// Hand it off to the subclass...
doClass(c);
}
}
/** Format the fields and methods of one class, given its name.
*/
protected abstract void doClass(Class c) throws IOException;
}
Related examples in the same category