Coverage Report - org.truth0.codegen.CompilingClassLoader
 
Classes in this File Line Coverage Branch Coverage Complexity
CompilingClassLoader
82%
19/23
50%
2/4
1.9
CompilingClassLoader$CompilerException
0%
0/2
N/A
1.9
CompilingClassLoader$InMemoryFileManager
100%
4/4
N/A
1.9
CompilingClassLoader$InMemoryFileManager$1
85%
6/7
50%
1/2
1.9
CompilingClassLoader$InMemoryJavaFile
71%
5/7
N/A
1.9
 
 1  
 package org.truth0.codegen;
 2  
 
 3  
 import static java.util.Collections.singleton;
 4  
 
 5  
 import java.io.ByteArrayOutputStream;
 6  
 import java.io.IOException;
 7  
 import java.io.OutputStream;
 8  
 import java.net.URI;
 9  
 import java.net.URISyntaxException;
 10  
 import java.util.HashMap;
 11  
 import java.util.LinkedList;
 12  
 import java.util.List;
 13  
 import java.util.Map;
 14  
 
 15  
 import javax.tools.DiagnosticListener;
 16  
 import javax.tools.FileObject;
 17  
 import javax.tools.ForwardingJavaFileManager;
 18  
 import javax.tools.JavaCompiler;
 19  
 import javax.tools.JavaFileManager;
 20  
 import javax.tools.JavaFileObject;
 21  
 import javax.tools.SimpleJavaFileObject;
 22  
 import javax.tools.ToolProvider;
 23  
 
 24  
 // NICKED FROM JSILVER -- BUT DAVID BEAUMONT WROTE MOST OF THAT ONE TOO !
 25  
 /**
 26  
  * This is a Java ClassLoader that will attempt to load a class from a string of source code.
 27  
  *
 28  
  * <h3>Example</h3>
 29  
  *
 30  
  * <pre>
 31  
  * String className = "com.foo.MyClass";
 32  
  * String classSource =
 33  
  *   "package com.foo;\n" +
 34  
  *   "public class MyClass implements Runnable {\n" +
 35  
  *   "  @Override public void run() {\n" +
 36  
  *   "   log(\"Hello world\");\n" +
 37  
  *   "  }\n" +
 38  
  *   "}";
 39  
  *
 40  
  * // Load class from source.
 41  
  * ClassLoader classLoader = new CompilingClassLoader(
 42  
  *     parentClassLoader, className, classSource);
 43  
  * Class myClass = classLoader.loadClass(className);
 44  
  *
 45  
  * // Use it.
 46  
  * Runnable instance = (Runnable)myClass.newInstance();
 47  
  * instance.run();
 48  
  * </pre>
 49  
  *
 50  
  * Only one chunk of source can be compiled per instance of CompilingClassLoader. If you need to
 51  
  * compile more, create multiple CompilingClassLoader instances.
 52  
  *
 53  
  * Uses Java 1.6's in built compiler API.
 54  
  *
 55  
  * If the class cannot be compiled, loadClass() will throw a ClassNotFoundException and log the
 56  
  * compile errors to System.err. If you don't want the messages logged, or want to explicitly handle
 57  
  * the messages you can provide your own {@link javax.tools.DiagnosticListener} through
 58  
  * {#setDiagnosticListener()}.
 59  
  *
 60  
  * @see java.lang.ClassLoader
 61  
  * @see javax.tools.JavaCompiler
 62  
  */
 63  6
 public class CompilingClassLoader extends ClassLoader {
 64  
 
 65  
   /**
 66  
    * Thrown when code cannot be compiled.
 67  
    */
 68  
   public static class CompilerException extends Exception {
 69  
 
 70  
     private static final long serialVersionUID = -2936958840023603270L;
 71  
 
 72  
     public CompilerException(String message) {
 73  0
       super(message);
 74  0
     }
 75  
   }
 76  
 
 77  2
   private final Map<String, ByteArrayOutputStream> byteCodeForClasses =
 78  
       new HashMap<String, ByteArrayOutputStream>();
 79  
 
 80  
   private static final URI EMPTY_URI;
 81  
 
 82  
   static {
 83  
     try {
 84  
       // Needed to keep SimpleFileObject constructor happy.
 85  1
       EMPTY_URI = new URI("");
 86  0
     } catch (URISyntaxException e) {
 87  0
       throw new Error(e);
 88  1
     }
 89  1
   }
 90  
 
 91  
   /**
 92  
    * @param parent Parent classloader to resolve dependencies from.
 93  
    * @param className Name of class to compile. eg. "com.foo.MyClass".
 94  
    * @param sourceCode Java source for class. e.g. "package com.foo; class MyClass { ... }".
 95  
    * @param diagnosticListener Notified of compiler errors (may be null).
 96  
    */
 97  
   public CompilingClassLoader(ClassLoader parent, String className, String sourceCode,
 98  
       DiagnosticListener<JavaFileObject> diagnosticListener) throws CompilerException {
 99  2
     super(parent);
 100  2
     if (!compileSourceCodeToByteCode(className, sourceCode, diagnosticListener)) {
 101  0
       throw new CompilerException("Could not compile " + className);
 102  
     }
 103  2
   }
 104  
 
 105  
   /**
 106  
    * Override ClassLoader's class resolving method. Don't call this directly, instead use
 107  
    * {@link ClassLoader#loadClass(String)}.
 108  
    */
 109  
   @Override
 110  
   public Class<?> findClass(String name) throws ClassNotFoundException {
 111  2
     ByteArrayOutputStream byteCode = byteCodeForClasses.get(name);
 112  2
     if (byteCode == null) {
 113  0
       throw new ClassNotFoundException(name);
 114  
     }
 115  2
     return defineClass(name, byteCode.toByteArray(), 0, byteCode.size());
 116  
   }
 117  
 
 118  
   /**
 119  
    * @return Whether compilation was successful.
 120  
    */
 121  
   private boolean compileSourceCodeToByteCode(String className, String sourceCode,
 122  
       DiagnosticListener<JavaFileObject> diagnosticListener) {
 123  2
     JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
 124  
 
 125  
     // Set up the in-memory filesystem.
 126  2
     InMemoryFileManager fileManager =
 127  
         new InMemoryFileManager(javaCompiler.getStandardFileManager(null, null, null));
 128  2
     JavaFileObject javaFile = new InMemoryJavaFile(className, sourceCode);
 129  
 
 130  
     // Javac option: remove these when the javac zip impl is fixed
 131  
     // (http://b/issue?id=1822932)
 132  2
     System.setProperty("useJavaUtilZip", "true"); // setting value to any non-null string
 133  2
     List<String> options = new LinkedList<String>();
 134  
     // this is ignored by javac currently but useJavaUtilZip should be
 135  
     // a valid javac XD option, which is another bug
 136  2
     options.add("-XDuseJavaUtilZip");
 137  
 
 138  
     // Now compile!
 139  2
     JavaCompiler.CompilationTask compilationTask = javaCompiler.getTask(null, // Null: log any
 140  
                                                                               // unhandled errors to
 141  
                                                                               // stderr.
 142  
         fileManager, diagnosticListener, options, null, singleton(javaFile));
 143  2
     return compilationTask.call();
 144  
   }
 145  
 
 146  
   /**
 147  
    * Provides an in-memory representation of JavaFileManager abstraction, so we do not need to write
 148  
    * any files to disk.
 149  
    *
 150  
    * When files are written to, rather than putting the bytes on disk, they are appended to buffers
 151  
    * in byteCodeForClasses.
 152  
    *
 153  
    * @see javax.tools.JavaFileManager
 154  
    */
 155  
   private class InMemoryFileManager extends ForwardingJavaFileManager<JavaFileManager> {
 156  
 
 157  2
     public InMemoryFileManager(JavaFileManager fileManager) {
 158  2
       super(fileManager);
 159  2
     }
 160  
 
 161  
     @Override
 162  
     public JavaFileObject getJavaFileForOutput(Location location, final String className,
 163  
         JavaFileObject.Kind kind, FileObject sibling) throws IOException {
 164  2
       return new SimpleJavaFileObject(EMPTY_URI, kind) {
 165  
         @Override
 166  
         public OutputStream openOutputStream() throws IOException {
 167  2
           ByteArrayOutputStream outputStream = byteCodeForClasses.get(className);
 168  2
           if (outputStream != null) {
 169  0
             throw new IllegalStateException("Cannot write more than once");
 170  
           }
 171  
           // Reasonable size for a simple .class.
 172  2
           outputStream = new ByteArrayOutputStream(256);
 173  2
           byteCodeForClasses.put(className, outputStream);
 174  2
           return outputStream;
 175  
         }
 176  
       };
 177  
     }
 178  
   }
 179  
 
 180  
   private static class InMemoryJavaFile extends SimpleJavaFileObject {
 181  
 
 182  
     private final String sourceCode;
 183  
 
 184  
     public InMemoryJavaFile(String className, String sourceCode) {
 185  2
       super(makeUri(className), Kind.SOURCE);
 186  2
       this.sourceCode = sourceCode;
 187  2
     }
 188  
 
 189  
     private static URI makeUri(String className) {
 190  
       try {
 191  2
         return new URI(className.replaceAll("\\.", "/") + Kind.SOURCE.extension);
 192  0
       } catch (URISyntaxException e) {
 193  0
         throw new RuntimeException(e); // Not sure what could cause this.
 194  
       }
 195  
     }
 196  
 
 197  
     @Override
 198  
     public CharSequence getCharContent(boolean ignoreEncodingErrors) throws IOException {
 199  2
       return sourceCode;
 200  
     }
 201  
   }
 202  
 }