List of usage examples for javax.tools JavaCompiler getTask
CompilationTask getTask(Writer out, JavaFileManager fileManager, DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options, Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits);
From source file:org.n52.wps.webadmin.ConfigUploadBean.java
public void compile(String fileName) { ClassLoader cl = this.getClass().getClassLoader(); List<URL> classpath = new ArrayList<URL>(); if (cl instanceof URLClassLoader) { URLClassLoader cl2 = (URLClassLoader) cl; for (URL jar : cl2.getURLs()) { classpath.add(jar);//from w w w . j a v a 2 s . c o m } } String classPath = System.getProperty("java.class.path"); for (String path : classPath.split(File.pathSeparator)) { try { classpath.add(new URL("file:" + path)); } catch (MalformedURLException e) { System.err.println("Wrong url: " + e.getMessage()); e.printStackTrace(); } } StringBuffer sb = new StringBuffer(); for (URL jar : classpath) { if (SystemUtils.IS_OS_WINDOWS == false) { sb.append(jar.getPath()); sb.append(File.pathSeparatorChar); } else { sb.append(jar.getPath().substring(1)); sb.append(File.pathSeparatorChar); } } String ops[] = new String[] { "-classpath", sb.toString() }; List<String> opsIter = new ArrayList<String>(); try { for (String s : ops) { // XXX test usage, removed use of deprecated method // ((ArrayList) opsIter).add(URLDecoder.decode(s)); ((ArrayList) opsIter).add(URLDecoder.decode(s, Charset.forName("UTF-8").toString())); } } catch (UnsupportedEncodingException e) { LOGGER.warn(e.getMessage(), e); } File[] files1 = new File[1]; files1[0] = new File(fileName); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager .getJavaFileObjectsFromFiles(Arrays.asList(files1)); compiler.getTask(null, fileManager, null, opsIter, null, compilationUnits1).call(); try { fileManager.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
From source file:org.openmrs.logic.CompilingClassLoader.java
private String compile(String javaFile) throws IOException { String errorMessage = null;// w ww .ja 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:plaid.compilerjava.CompilerCore.java
private void generateCode(List<CompilationUnit> cus, final PackageRep plaidpath) throws Exception { if (cc.isVerbose()) { System.out.println("Generating code."); }//from w w w .j a v a2 s. c o m final List<File> allFiles = new ArrayList<File>(); ExecutorService taskPool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()); for (final CompilationUnit cu : cus) { if (!cc.forceRecompile()) { boolean rebuild = false; for (Decl d : cu.getDecls()) { //System.out.println(d); StringBuilder packageName = new StringBuilder(); for (String s : cu.getPackageName()) { packageName.append(s); packageName.append(System.getProperty("file.separator")); } File targetFile = new File(cc.getTempDir() + System.getProperty("file.separator") + packageName + d.getName() + ".java"); if (!targetFile.exists() || targetFile.lastModified() < cu.getSourceFile().lastModified()) { rebuild = true; break; } } if (!rebuild) { if (cc.isVerbose()) { System.out.println("file up-to-date : " + cu.getSourceFile()); } continue; } if (cc.isVerbose()) { System.out.println("Rebuild: " + cu.getSourceFile()); } } Callable<Object> task = new Callable<Object>() { @Override public Object call() throws Exception { try { if (cc.isVerbose()) System.out.println("Generating code for:\n" + cu); List<File> fileList = cu.codegen(cc, plaidpath); synchronized (allFiles) { allFiles.addAll(fileList); } } catch (PlaidException p) { System.err.println("Error while compiling " + cu.getSourceFile().toString() + ":"); System.err.println(""); printExceptionInformation(p); } return null; } }; taskPool.submit(task); } taskPool.shutdown(); while (!taskPool.isTerminated()) { taskPool.awaitTermination(1, TimeUnit.MINUTES); } if (!cc.isKeepTemporaryFiles()) { for (File f : allFiles) { f.deleteOnExit(); } } if (cc.isVerbose()) { System.out.println("invoke Java compiler"); } if (cc.isInvokeCompiler() && allFiles.size() > 0) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> fileObjects = fileManager.getJavaFileObjectsFromFiles(allFiles); List<String> optionList = new ArrayList<String>(); optionList.addAll(Arrays.asList("-target", "1.5")); // Set compiler's classpath to be same as the runtime's optionList.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path"))); // TODO: Add a separate compiler flag for this. optionList.addAll(Arrays.asList("-d", cc.getOutputDir())); // optionList.add("-verbose"); // Invoke the compiler CompilationTask task = compiler.getTask(null, null, null, optionList, null, fileObjects); Boolean resultCode = task.call(); if (!resultCode.booleanValue()) throw new RuntimeException("Error while compiling generated Java files."); } }
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 * /*from w w w.j a v a 2 s.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; }