List of usage examples for javax.tools JavaCompiler getStandardFileManager
StandardJavaFileManager getStandardFileManager(DiagnosticListener<? super JavaFileObject> diagnosticListener,
Locale locale, Charset charset);
From source file:gov.nih.nci.restgen.util.GeneratorUtil.java
public static boolean compileJavaSource(String srcFolder, String destFolder, String libFolder, GeneratorContext context) {// w w w. j av a2s . c om 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: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); }/*ww w . j a v a2 s. co m*/ } 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:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java
private static Class<FoundationLoggingMarkerFormatter> generateMarkerClass(String sourceCode, String newClassName) {// www.jav a 2 s . c om try { // We get an instance of JavaCompiler. Then // we create a file manager // (our custom implementation of it) JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null)); // Dynamic compiling requires specifying // a list of "files" to compile. In our case // this is a list containing one "file" which is in our case // our own implementation (see details below) List<JavaFileObject> jfiles = new ArrayList<JavaFileObject>(); jfiles.add(new DynamicJavaSourceCodeObject(newClassName, sourceCode)); List<String> optionList = new ArrayList<String>(); // set compiler's classpath to be same as the runtime's optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path"))); // We specify a task to the compiler. Compiler should use our file // manager and our list of "files". // Then we run the compilation with call() compiler.getTask(null, fileManager, null, optionList, null, jfiles).call(); // Creating an instance of our compiled class and // running its toString() method Class<FoundationLoggingMarkerFormatter> clazz = (Class<FoundationLoggingMarkerFormatter>) fileManager .getClassLoader(null).loadClass(newClassName); return clazz; } catch (Exception e) { throw new UnsupportedOperationException("can't create class of: " + newClassName, e); } }
From source file:adalid.util.meta.MetaJavaCompiler.java
public static void compile() { String dp1 = System.getProperties().getProperty("user.dir"); String sep = System.getProperties().getProperty("file.separator"); File src = new File(dp1 + sep + "src"); File trg = new File(dp1 + sep + "bin"); boolean dir = trg.isDirectory() || trg.mkdirs(); List<File> files = getJavaFiles(src); // Get the java compiler provided with this platform JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); // Get the writer for the compiler output StringWriter out = new StringWriter(); // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics DiagnosticListener<JavaFileObject> diagnosticListener1 = null; // new DiagnosticCollector<JavaFileObject>(); // Get the locale to apply when formatting diagnostics; null means the default locale Locale locale = null;/*from w w w.ja v a 2 s . c o m*/ // Get the character set used for decoding bytes; if null use the platform default Charset charset = null; // Get an instance of the standard file manager implementation StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener1, locale, charset); // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics DiagnosticListener<JavaFileObject> diagnosticListener2 = null; // new DiagnosticCollector<JavaFileObject>(); // Get the list of compiler options, null means no options List<String> options = Arrays .asList(new String[] { "-g", "-source", "1.7", "-Xlint:unchecked", "-d", trg.getAbsolutePath() }); // Get the list of class names (for annotation processing), null means no class names List<String> classes = null; // Get the list of java file objects to compile Iterable<? extends JavaFileObject> units = fileManager.getJavaFileObjectsFromFiles(files); // Create the compilation task CompilationTask task = compiler.getTask(out, fileManager, diagnosticListener2, options, classes, units); // Perform the compilation task // task.call(); // java.lang.NullPointerException at com.sun.tools.javac.api.JavacTaskImpl.parse(JavacTaskImpl.java:228) if (task instanceof JavacTask) { javacTask(task); } }
From source file:com.googlecode.jsonschema2pojo.integration.util.Compiler.java
public void compile(File directory, String classpath) { JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(findAllSourceFiles(directory)); if (compilationUnits.iterator().hasNext()) { Boolean success = javaCompiler .getTask(null, fileManager, null, asList("-classpath", classpath), null, compilationUnits) .call();//from w w w. j av a 2 s. c o m assertThat("Compilation was not successful, check stdout for errors", success, is(true)); } }
From source file:edu.harvard.i2b2.fhir.FhirUtil.java
public static List<Class> getAllFhirResourceClasses(String packageName) throws IOException { // logger.trace("Running getAllFhirResourceClasses for:" + // packageName); List<Class> commands = new ArrayList<Class>(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Location location = StandardLocation.CLASS_PATH; Set<JavaFileObject.Kind> kinds = new HashSet<JavaFileObject.Kind>(); kinds.add(JavaFileObject.Kind.CLASS); boolean recurse = false; Iterable<JavaFileObject> list = fileManager.list(location, packageName, kinds, recurse); for (JavaFileObject javaFileObject : list) { // commands.add(javaFileObject.getClass()); }// w w w .j a va2 s . c o m Class c = null; for (String x : Arrays.asList(RESOURCE_LIST_REGEX.replace("(", "").replace(")", "").split("\\|"))) { x = "org.hl7.fhir." + x; // logger.trace("X:"+x); c = Utils.getClassFromClassPath(x); if (c != null) commands.add(c); } // logger.trace(commands.toString()); return commands; }
From source file:com.github.aliakhtar.annoTest.util.Compiler.java
private boolean compile(Processor processor, SourceFile... sourceFiles) throws Exception { Builder<String> builder = ImmutableList.builder(); builder.add("-classpath").add(buildClassPath(outputDir)); builder.add("-d").add(outputDir.getAbsolutePath()); for (Map.Entry<String, String> entry : parameterMap.entrySet()) { builder.add("-A" + entry.getKey() + "=" + entry.getValue()); }/*from w ww. java 2s .c o m*/ File[] files = new File[sourceFiles.length]; for (int i = 0; i < sourceFiles.length; i++) { files[i] = writeSourceFile(sourceFiles[i]); } JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(files); CompilationTask compilationTask = compiler.getTask(null, null, null, builder.build(), null, javaFileObjects); if (processor != null) compilationTask.setProcessors(Arrays.asList(processor)); Boolean success = compilationTask.call(); fileManager.close(); return success; }
From source file:com.yahoo.maven.visitor.SuccessfulCompilationAsserter.java
public void assertNoCompilationErrors() throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<>(); try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, StandardCharsets.UTF_8)) { List<File> javaFiles = new ArrayList<>(); try (Stream<Path> stream = Files.walk(scratchSpace)) { Iterator<Path> iterator = stream.iterator(); while (iterator.hasNext()) { Path path = iterator.next(); if (Files.isRegularFile(path) && "java".equals(FilenameUtils.getExtension(path.toString()))) { javaFiles.add(path.toFile()); }/*from w w w. j ava2 s . c om*/ } } Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjectsFromFiles(javaFiles); compiler.getTask(null, fileManager, diagnostics, Arrays.asList("-classpath", System.getProperty("java.class.path")), null, compilationUnits) .call(); } int errors = 0; for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics.getDiagnostics()) { if (Diagnostic.Kind.ERROR.equals(diagnostic.getKind())) { System.err.println(diagnostic); errors++; } } assertEquals(0, errors); }
From source file:net.morematerials.manager.HandlerManager.java
private void compile(File file) throws IOException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(file); CompilationTask task = compiler.getTask(null, fileManager, null, this.compilerOptions, null, compilationUnits);/*from www . j a va2s . c o m*/ task.call(); }
From source file:com.kelveden.rastajax.core.DynamicClassCompiler.java
private void compileFromFiles(final Set<String> sourceFilePaths) { final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); try {/* w w w. ja v a 2s. c o m*/ fileManager = compiler.getStandardFileManager(null, null, null); final Iterable<? extends JavaFileObject> fileObjects = fileManager .getJavaFileObjectsFromStrings(sourceFilePaths); if (!compiler.getTask(null, null, null, null, null, fileObjects).call()) { throw new RuntimeException("Failed to compile class."); } } finally { IOUtils.closeQuietly(fileManager); } }