List of usage examples for javax.tools StandardJavaFileManager getJavaFileObjects
Iterable<? extends JavaFileObject> getJavaFileObjects(String... names);
From source file:org.apache.pig.test.TestJobControlCompiler.java
/** * creates a jar containing a UDF not in the current classloader * @param jarFile the jar to create/*from w w w .j a va 2s . c om*/ * @return the name of the class created (in the default package) * @throws IOException * @throws FileNotFoundException */ private String createTestJar(File jarFile) throws IOException, FileNotFoundException { // creating the source .java file File javaFile = File.createTempFile("TestUDF", ".java"); javaFile.deleteOnExit(); String className = javaFile.getName().substring(0, javaFile.getName().lastIndexOf('.')); FileWriter fw = new FileWriter(javaFile); try { fw.write("import org.apache.pig.EvalFunc;\n"); fw.write("import org.apache.pig.data.Tuple;\n"); fw.write("import java.io.IOException;\n"); fw.write("public class " + className + " extends EvalFunc<String> {\n"); fw.write(" public String exec(Tuple input) throws IOException {\n"); fw.write(" return \"test\";\n"); fw.write(" }\n"); fw.write("}\n"); } finally { fw.close(); } // compiling it JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFile); CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits1); task.call(); // here is the compiled file File classFile = new File(javaFile.getParentFile(), className + ".class"); Assert.assertTrue(classFile.exists()); // putting it in the jar JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile)); try { jos.putNextEntry(new ZipEntry(classFile.getName())); try { InputStream testClassContentIS = new FileInputStream(classFile); try { byte[] buffer = new byte[64000]; int n; while ((n = testClassContentIS.read(buffer)) != -1) { jos.write(buffer, 0, n); } } finally { testClassContentIS.close(); } } finally { jos.closeEntry(); } } finally { jos.close(); } return className; }
From source file:org.apache.pig.test.TestRegisteredJarVisibility.java
private static List<File> compile(File[] javaFiles) { LOG.info("Compiling: " + Arrays.asList(javaFiles)); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjects(javaFiles); JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits1);/*from www . j ava 2s.c o m*/ task.call(); List<File> classFiles = Lists.newArrayList(); for (File javaFile : javaFiles) { File classFile = new File(javaFile.getAbsolutePath().replace(".java", ".class")); classFile.deleteOnExit(); Assert.assertTrue(classFile.exists()); classFiles.add(classFile); LOG.info("Created " + classFile.getAbsolutePath()); } return classFiles; }
From source file:org.cdmckay.coffeep.Program.java
private static JavaFileObject getFileObject(String className) throws IOException { final Context context = new Context(); final JavaFileManager fileManager = new JavacFileManager(context, true, null); JavaFileObject fileObject;// w w w .ja va 2 s . c om fileObject = fileManager.getJavaFileForInput(StandardLocation.PLATFORM_CLASS_PATH, className, JavaFileObject.Kind.CLASS); if (fileObject != null) return fileObject; fileObject = fileManager.getJavaFileForInput(StandardLocation.CLASS_PATH, className, JavaFileObject.Kind.CLASS); if (fileObject != null) return fileObject; final StandardJavaFileManager standardFileManager = (StandardJavaFileManager) fileManager; return standardFileManager.getJavaFileObjects(className).iterator().next(); }
From source file:org.cloudfoundry.tools.compiler.CloudFoundryJavaCompilerTest.java
@Test public void shouldCompilePhysicalFile() throws Exception { StandardJavaFileManager fileManager = this.javaCompiler.getStandardFileManager(null, null, null); try {/*from ww w . j a va 2 s .c o m*/ Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjects(new File[] { createExampleJavaFile() }); CompilationTask task = this.javaCompiler.getTask(null, fileManager, null, standardCompilerOptions(), null, compilationUnits); assertThat(task.call(), is(Boolean.TRUE)); assertTrue(new File(this.tempFolder.getRoot(), "Example.class").exists()); } finally { fileManager.close(); } }
From source file:org.echocat.redprecursor.impl.sun.compilertree.SunNodeFactoryIntegrationTest.java
private void compile(File... files) { final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); final Iterable<? extends JavaFileObject> compilationUnits2 = fileManager.getJavaFileObjects(files); final DiagnosticCollector<Object> listener = null; //new DiagnosticCollector<Object>(); final CompilationTask task = compiler.getTask(null, fileManager, listener, Arrays.<String>asList("-processor", RedprecursorProcessor.class.getName()), null, compilationUnits2);//from w w w . j a va2 s . c o m //final CompilationTask task = compiler.getTask(null, fileManager, listener, Arrays.<String>asList(), null, compilationUnits2); task.call(); }
From source file:org.javascool.compiler.Compiler.java
/** * Lance la compilation des fichiers vers un autre rpertoire. Va compiler les fichier dans un autre rpertoire. * * @param binDirectory Rpertoire cible pour la compilation. Il doit dj exister et tre un dossier * @return Les erreurs de la compilation *//*from ww w . j a v a2s . c o m*/ public ArrayList<Diagnostic<? extends JavaFileObject>> compile(File binDirectory) { assertDirectoryExists(binDirectory); final ArrayList<Diagnostic<? extends JavaFileObject>> errors = new ArrayList<Diagnostic<? extends JavaFileObject>>(); ArrayList<String> sourceFiles = new ArrayList<String>(filesToCompile.length); for (File srcFile : filesToCompile) sourceFiles.add(srcDirectory.toURI().relativize(srcFile.toURI()).getPath()); classLoader = new JVSClassLoader(binDirectory); JavaCompiler eclipseCompiler; ArrayList<String> options; eclipseCompiler = new EclipseCompiler(); options = getCompilerOptions(); DiagnosticListener<? super JavaFileObject> diagnosticListener = new DiagnosticListener<JavaFileObject>() { public void report(Diagnostic<? extends JavaFileObject> diagnostic) { errors.add(diagnostic); } }; StandardJavaFileManager fileManager = eclipseCompiler.getStandardFileManager(diagnosticListener, null, Charset.forName("UTF-8")); Iterable<? extends JavaFileObject> compilationUnits = fileManager .getJavaFileObjects(sourceFiles.toArray(new String[sourceFiles.size()])); eclipseCompiler.getTask(null, fileManager, diagnosticListener, options, null, compilationUnits).call(); return errors; }
From source file:org.openmrs.logic.CompilingClassLoader.java
private String compile(String javaFile) throws IOException { String errorMessage = null;// ww w. j a v a 2 s .co m String ruleClassDir = Context.getAdministrationService() .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER); String ruleJavaDir = Context.getAdministrationService() .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); log.info("JavaCompiler is null: " + compiler == null); if (compiler != null) { // java compiler only available on JDK. This part of "IF" will not get executed when we run JUnit test File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir); String[] options = {}; DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector, Context.getLocale(), Charset.defaultCharset()); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFolder)); // create compiling classpath String stringProperties = System.getProperty("java.class.path"); if (log.isDebugEnabled()) log.debug("Compiler classpath: " + stringProperties); String[] properties = StringUtils.split(stringProperties, File.pathSeparator); List<File> classpathFiles = new ArrayList<File>(); for (String property : properties) { File f = new File(property); if (f.exists()) classpathFiles.add(f); } classpathFiles.addAll(getCompilerClasspath()); fileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles); // create the compilation task CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnosticCollector, Arrays.asList(options), null, fileManager.getJavaFileObjects(javaFile)); boolean success = compilationTask.call(); fileManager.close(); if (success) { return null; } else { errorMessage = ""; for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) { errorMessage += diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Context.getLocale()) + "\n"; } return errorMessage; } } else { File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir); String[] commands = { "javac", "-classpath", System.getProperty("java.class.path"), "-d", outputFolder.getAbsolutePath(), javaFile }; // Start up the compiler File workingDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir); boolean success = LogicUtil.executeCommand(commands, workingDirectory); return success ? null : "Compilation error. (You must be using the JDK to see details.)"; } }
From source file:rita.compiler.CompileString.java
/** * El mtodo compile crea el archivo compilado a partir de un codigo fuente * y lo deja en un directorio determinado * // ww w .j a v a 2s.c o m * @param sourceCode * el codigo fuente * @param className * el nombre que debera llevar la clase * @param packageName * nombre del paquete * @param outputDirectory * directorio donde dejar el archivo compilado * */ public static final Collection<File> compile(File sourceCode, File outputDirectory) throws Exception { diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>(); JavaCompiler compiler = new EclipseCompiler(); System.out.println(sourceCode); DiagnosticListener<JavaFileObject> listener = new DiagnosticListener<JavaFileObject>() { @Override public void report(Diagnostic<? extends JavaFileObject> diagnostic) { if (diagnostic.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) { System.err.println("=======================ERROR=========================="); System.err.println("Tipo: " + diagnostic.getKind()); System.err.println("mensaje: " + diagnostic.getMessage(Locale.ENGLISH)); System.err.println("linea: " + diagnostic.getLineNumber()); System.err.println("columna: " + diagnostic.getColumnNumber()); System.err.println("CODE: " + diagnostic.getCode()); System.err.println( "posicion: de " + diagnostic.getStartPosition() + " a " + diagnostic.getEndPosition()); System.err.println(diagnostic.getSource()); diagnostics.add(diagnostic); } } }; StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); /* guardar los .class y directorios (packages) en un directorio separado; de esta manera * si se genera mas de 1 clase (porque p.ej. hay inner classes en el codigo) podemos identificar * a todas las clases resultantes de esta compilacion */ File tempOutput = createTempDirectory(); fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempOutput)); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceCode); try { if (compiler.getTask(null, fileManager, listener, null, null, compilationUnits).call()) { // copiar .class y directorios (packages) generados por el compilador en tempOutput al directorio final FileUtils.copyDirectory(tempOutput, outputDirectory); // a partir de los paths de los archivos .class generados en el dir temp, modificarlos para que sean relativos a outputDirectory Collection<File> compilationResults = new ArrayList<File>(); final int tempPrefix = tempOutput.getAbsolutePath().length(); for (File classFile : FileUtils.listFiles(tempOutput, new SuffixFileFilter(".class"), TrueFileFilter.INSTANCE)) { compilationResults .add(new File(outputDirectory, classFile.getAbsolutePath().substring(tempPrefix))); } // retornar los paths de todos los .class generados return compilationResults; } } catch (Exception e) { e.printStackTrace(); System.out.println("Error al realizar el compilado"); } finally { FileUtils.deleteDirectory(tempOutput); fileManager.close(); } return null; }