package io.trygvis.container.compiler; import org.apache.commons.io.IOUtils; import org.testng.annotations.Test; import javax.tools.Diagnostic; import javax.tools.DiagnosticCollector; import javax.tools.JavaCompiler; import javax.tools.JavaFileObject; import javax.tools.SimpleJavaFileObject; import javax.tools.StandardJavaFileManager; import javax.tools.ToolProvider; import java.net.URI; import java.nio.charset.Charset; import java.util.Arrays; import java.util.Locale; import static java.util.Collections.singletonList; import static org.fest.assertions.Assertions.assertThat; public class ProcessorTest { Charset UTF_8 = Charset.forName("utf-8"); /** * A file object used to represent source coming from a string. */ public class JavaSourceFromString extends SimpleJavaFileObject { /** * The source code of this "file". */ final String code; /** * Constructs a new JavaSourceFromString. * * @param name the name of the compilation unit represented by this file object * @param code the source code for the compilation unit represented by this file object */ JavaSourceFromString(String name, String code) { super(URI.create("string:///" + name.replace('.', '/') + JavaFileObject.Kind.SOURCE.extension), JavaFileObject.Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } @Test public void testBasic() throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector collector = new DiagnosticCollector<>(); StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(collector, Locale.ENGLISH, UTF_8); InMemoryJavaFileManager fileManager = new InMemoryJavaFileManager(standardFileManager); JavaSourceFromString myEntity = new JavaSourceFromString("Person", IOUtils.toString(getClass().getResource("/Person.java"), UTF_8)); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, collector, null, null, singletonList(myEntity)); task.setProcessors(Arrays.asList(new MyProcessor())); Boolean result = task.call(); for (Diagnostic diagnostic : collector.getDiagnostics()) { // System.out.println("diagnostic = " + diagnostic); System.out.println("diagnostic.source = ->" + diagnostic.getSource().getName() + "<-"); System.out.println("diagnostic.message = " + diagnostic.getMessage(Locale.ENGLISH)); } assertThat(collector.getDiagnostics()).isEmpty(); assertThat(result).isTrue(); fileManager.close(); assertThat(fileManager.codes.keySet()).containsOnly("Person_Sql"); System.out.println(fileManager.codes.get("Person_Sql")); } }