List of usage examples for javax.tools DiagnosticCollector DiagnosticCollector
DiagnosticCollector
From source file:com.github.pellaton.jazoon2012.AnnotationProcessorTestCompiler.java
/** * Processes the java class specified. This implementation only parses and processes the java classes and does not * fully compile them - i.e. it does not write class files back to the disk. Basically, {@code javac} is called with * {@code -proc:only}.//from w ww .jav a 2s . c o m * * @param classToCompile the Java class to compile * @param processor the annotation {@link Processor} to use during compilation * @return a list of {@link Diagnostic} messages emitted during the compilation */ public static List<Diagnostic<? extends JavaFileObject>> compileClass(String classToCompile, Processor processor) throws IOException { DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = null; try { fileManager = getFileManager(collector); Iterable<? extends JavaFileObject> compilationUnits = getCompilationUnitOfClass(fileManager, classToCompile); CompilationTask task = COMPILER.getTask(null, fileManager, collector, COMPILER_OPTIONS, null, compilationUnits); task.setProcessors(Arrays.asList(processor)); task.call(); return collector.getDiagnostics(); } finally { if (fileManager != null) { fileManager.close(); } } }
From source file:com.jhash.oimadmin.Utils.java
public static DiagnosticCollector<JavaFileObject> compileJava(String className, String code, String outputFileLocation) { logger.trace("Entering compileJava({},{},{})", new Object[] { className, code, outputFileLocation }); File outputFileDirectory = new File(outputFileLocation); logger.trace("Validating if the output location {} exists and is a directory", outputFileLocation); if (outputFileDirectory.exists()) { if (outputFileDirectory.isDirectory()) { try { logger.trace("Deleting the directory and its content"); FileUtils.deleteDirectory(outputFileDirectory); } catch (IOException exception) { throw new OIMAdminException( "Failed to delete directory " + outputFileLocation + " and its content", exception); }// w w w. j av a2 s . c om } else { throw new InvalidParameterException( "The location " + outputFileLocation + " was expected to be a directory but it is a file."); } } logger.trace("Creating destination directory for compiled class file"); outputFileDirectory.mkdirs(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new NullPointerException( "Failed to locate a java compiler. Please ensure that application is being run using JDK (Java Development Kit) and NOT JRE (Java Runtime Environment) "); } StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<File> files = Arrays.asList(new File(outputFileLocation)); boolean success = false; DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); try { JavaFileObject javaFileObject = new InMemoryJavaFileObject(className, code); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, files); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, Arrays.asList("-source", "1.6", "-target", "1.6"), null, Arrays.asList(javaFileObject)); success = task.call(); fileManager.close(); } catch (Exception exception) { throw new OIMAdminException("Failed to compile " + className, exception); } if (!success) { logger.trace("Exiting compileJava(): Return Value {}", diagnostics); return diagnostics; } else { logger.trace("Exiting compileJava(): Return Value null"); return null; } }
From source file:clear.cdb.support.test.AnnotationProcessorTestCompiler.java
public static List<Diagnostic<? extends JavaFileObject>> compileClass(String classToCompile, Processor processor, String options) throws IOException { DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); final StandardJavaFileManager fileManager = getFileManager(collector); return compileClassInternal(processor, fileManager, getCompilationUnitOfClass(fileManager, classToCompile), options);/*from ww w . j av a 2s .c o m*/ }
From source file:clear.cdb.support.test.AnnotationProcessorTestCompiler.java
public static List<Diagnostic<? extends JavaFileObject>> compileClasses(String[] classesToCompile, Processor processor, String options) throws IOException { DiagnosticCollector<JavaFileObject> collector = new DiagnosticCollector<JavaFileObject>(); final StandardJavaFileManager fileManager = getFileManager(collector); return compileClassInternal(processor, fileManager, getCompilationUnitsOfClasses(fileManager, classesToCompile), options); }
From source file:com.sun.script.java.JavaCompiler.java
/** * compile given String source and return bytecodes as a Map. * /*from w ww. jav a 2 s . c o m*/ * @param fileName source fileName to be used for error messages etc. * @param source Java source as String * @param err error writer where diagnostic messages are written * @param sourcePath location of additional .java source files * @param classPath location of additional .class files * @return classBytes */ public Map<String, byte[]> compile(String fileName, String source, Writer err, String sourcePath, String classPath) { // to collect errors, warnings etc. DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); // create a new memory JavaFileManager MemoryJavaFileManager manager = new MemoryJavaFileManager(); // prepare the compilation unit List<JavaFileObject> compUnits = new ArrayList<JavaFileObject>(1); compUnits.add(MemoryJavaFileManager.makeStringSource(fileName, source)); // javac options List<String> options = new ArrayList<String>(); options.add("-Xlint:all"); options.add("-g"); options.add("-deprecation"); if (sourcePath != null) { options.add("-sourcepath"); options.add(sourcePath); } if (classPath != null) { options.add("-classpath"); options.add(classPath); } // create a compilation task javax.tools.JavaCompiler.CompilationTask task = tool.getTask(err, manager, diagnostics, options, null, compUnits); if (task.call() == false) { PrintWriter perr = new PrintWriter(err); for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { perr.println(diagnostic.getMessage(null)); } perr.flush(); return null; } Map<String, byte[]> classBytes = manager.getClassBytes(); IOUtils.closeQuietly(manager); return classBytes; }
From source file:gov.nih.nci.restgen.util.GeneratorUtil.java
public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder, GeneratorContext context) {/* ww w . j a v a 2 s. co m*/ StandardJavaFileManager fileManager = null; boolean success = true; try { List<String> compilerFiles = GeneratorUtil.getFiles(srcFolder, new String[] { "java" }); GeneratorUtil.createOutputDir(destFolder); List<String> options = new ArrayList<String>(); options.add("-classpath"); String classPathStr = GeneratorUtil.getFiles(libFolder, new String[] { "jar" }, File.pathSeparator); options.add(classPathStr); options.add("-nowarn"); options.add("-Xlint:-unchecked"); options.add("-d"); options.add(destFolder); options.add("-s"); options.add(srcFolder); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); fileManager = compiler.getStandardFileManager(diagnostics, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromStrings(compilerFiles); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits); success = task.call(); for (Diagnostic diagnostic : diagnostics.getDiagnostics()) { //context.getLogger().error(diagnostic.getCode()); //context.getLogger().error(diagnostic.getKind().toString()); //context.getLogger().error(diagnostic.getPosition() + ""); //context.getLogger().error(diagnostic.getStartPosition() + ""); //context.getLogger().error(diagnostic.getEndPosition() + ""); //context.getLogger().error(diagnostic.getSource().toString()); context.getLogger().error(diagnostic.toString()); } } catch (Throwable t) { context.getLogger().error("Error compiling java code", t); } finally { try { fileManager.close(); } catch (Throwable t) { } } return success; }
From source file:nl.elucidator.patterns.builder.annotations.processor.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p/>/*from w w w . j av a 2 s .c o m*/ * The compilation units and all their dependencies are expected to be on the classpath. * * @param compilationUnitPaths the paths of the source files to compile, as would be expected * by {@link ClassLoader#getResource(String)} * @return the {@link Diagnostic diagnostics} returned by the compilation, * as demonstrated in the documentation for {@link JavaCompiler} * @see #compileTestCase(Class...) */ protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) { assert (compilationUnitPaths != null); Collection<File> compilationUnits; try { compilationUnits = findClasspathFiles(compilationUnitPaths); } catch (IOException exception) { throw new IllegalArgumentException("Unable to resolve compilation units " + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception); } DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null); /* * Call the compiler with the "-proc:only" option. The "class names" * option (which could, in principle, be used instead of compilation * units for annotation processing) isn't useful in this case because * only annotations on the classes being compiled are accessible. * * Information about the classes being compiled (such as what they are annotated * with) is *not* available via the RoundEnvironment. However, if these classes * are annotations, they certainly need to be validated. */ CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"), null, fileManager.getJavaFileObjectsFromFiles(compilationUnits)); task.setProcessors(getProcessors()); task.call(); try { fileManager.close(); } catch (IOException exception) { //Nothing to do } return diagnosticCollector.getDiagnostics(); }
From source file:org.mule.devkit.apt.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p>/* ww w. j a v a 2 s . com*/ * The compilation units and all their dependencies are expected to be on the classpath. * * @param compilationUnitPaths * the paths of the source files to compile, as would be expected * by {@link ClassLoader#getResource(String)} * @return the {@link Diagnostic diagnostics} returned by the compilation, * as demonstrated in the documentation for {@link JavaCompiler} * @see #compileTestCase(Class...) * */ protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) { assert (compilationUnitPaths != null); Collection<File> compilationUnits; try { compilationUnits = findClasspathFiles(compilationUnitPaths); } catch (IOException exception) { throw new IllegalArgumentException("Unable to resolve compilation units " + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception); } DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null); /* * Call the compiler with the "-proc:only" option. The "class names" * option (which could, in principle, be used instead of compilation * units for annotation processing) isn't useful in this case because * only annotations on the classes being compiled are accessible. * * Information about the classes being compiled (such as what they are annotated * with) is *not* available via the RoundEnvironment. However, if these classes * are annotations, they certainly need to be validated. */ CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"), null, fileManager.getJavaFileObjectsFromFiles(compilationUnits)); task.setProcessors(getProcessors()); task.call(); try { fileManager.close(); } catch (IOException exception) { } return diagnosticCollector.getDiagnostics(); }
From source file:de.monticore.codegen.GeneratorTest.java
/** * Compiles the files in the given directory, printing errors to the console * if any occur./*from ww w. java 2 s . c o m*/ * * @param sourceCodePath the source directory to be compiled * @return true if the compilation succeeded */ protected boolean compile(Path sourceCodePath) { DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); boolean compilationSuccess = false; Optional<CompilationTask> task = setupCompilation(sourceCodePath, diagnostics); if (!task.isPresent()) { return compilationSuccess; } compilationSuccess = task.get().call(); if (!compilationSuccess) { for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { Log.error(diagnostic.toString()); } } return compilationSuccess; }
From source file:com.qrmedia.commons.test.annotation.processing.AbstractAnnotationProcessorTest.java
/** * Attempts to compile the given compilation units using the Java Compiler API. * <p>/*from w ww .java 2 s .c o m*/ * The compilation units and all their dependencies are expected to be on the classpath. * * @param compilationUnitPaths * the paths of the source files to compile, as would be expected * by {@link ClassLoader#getResource(String)} * @return the {@link Diagnostic diagnostics} returned by the compilation, * as demonstrated in the documentation for {@link JavaCompiler} * @see #compileTestCase(Class...) * */ protected List<Diagnostic<? extends JavaFileObject>> compileTestCase(String... compilationUnitPaths) { assert (compilationUnitPaths != null); Collection<File> compilationUnits; try { compilationUnits = findClasspathFiles(compilationUnitPaths); } catch (IOException exception) { throw new IllegalArgumentException("Unable to resolve compilation units " + Arrays.toString(compilationUnitPaths) + " due to: " + exception.getMessage(), exception); } DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = COMPILER.getStandardFileManager(diagnosticCollector, null, null); /* * Call the compiler with the "-proc:only" option. The "class names" * option (which could, in principle, be used instead of compilation * units for annotation processing) isn't useful in this case because * only annotations on the classes being compiled are accessible. * * Information about the classes being compiled (such as what they are annotated * with) is *not* available via the RoundEnvironment. However, if these classes * are annotations, they certainly need to be validated. */ CompilationTask task = COMPILER.getTask(null, fileManager, diagnosticCollector, Arrays.asList("-proc:only"), null, fileManager.getJavaFileObjectsFromFiles(compilationUnits)); task.setProcessors(getProcessors()); task.call(); try { fileManager.close(); } catch (IOException exception) { } return diagnosticCollector.getDiagnostics(); }