List of usage examples for javax.tools ToolProvider getSystemJavaCompiler
public static JavaCompiler getSystemJavaCompiler()
From source file:net.sourceforge.mavenhippo.gen.BeanGeneratorTest.java
@Test public void compilationTest() throws ContentTypeException, TemplateException, IOException, ClassNotFoundException { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, baseDocument.getAbsolutePath())); Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, newsDocument.getAbsolutePath())); Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, testCompound.getAbsolutePath())); URLClassLoader classLoader = new URLClassLoader(new URL[] { tempFolder.toURI().toURL() }); Assert.assertNotNull(Class.forName("generated.beans.TestCompound", true, classLoader)); Assert.assertEquals(0, compiler.run(System.in, System.out, System.err, myCompound.getAbsolutePath())); Assert.assertEquals(0,/* w w w .ja v a 2s . com*/ compiler.run(System.in, System.out, System.err, carouselBannerPickerMixin.getAbsolutePath())); }
From source file:com.cloudera.sqoop.orm.CompilationManager.java
/** * Compile the .java files into .class files via embedded javac call. * On success, move .java files to the code output dir. *//* w ww . java 2 s . c o m*/ public void compile() throws IOException { List<String> args = new ArrayList<String>(); // ensure that the jar output dir exists. String jarOutDir = options.getJarOutputDir(); File jarOutDirObj = new File(jarOutDir); if (!jarOutDirObj.exists()) { boolean mkdirSuccess = jarOutDirObj.mkdirs(); if (!mkdirSuccess) { LOG.debug("Warning: Could not make directories for " + jarOutDir); } } else if (LOG.isDebugEnabled()) { LOG.debug("Found existing " + jarOutDir); } // Make sure jarOutDir ends with a '/'. if (!jarOutDir.endsWith(File.separator)) { jarOutDir = jarOutDir + File.separator; } // find hadoop-*-core.jar for classpath. String coreJar = findHadoopCoreJar(); if (null == coreJar) { // Couldn't find a core jar to insert into the CP for compilation. If, // however, we're running this from a unit test, then the path to the // .class files might be set via the hadoop.alt.classpath property // instead. Check there first. String coreClassesPath = System.getProperty("hadoop.alt.classpath"); if (null == coreClassesPath) { // no -- we're out of options. Fail. throw new IOException("Could not find hadoop core jar!"); } else { coreJar = coreClassesPath; } } // find sqoop jar for compilation classpath String sqoopJar = Jars.getSqoopJarPath(); if (null != sqoopJar) { sqoopJar = File.pathSeparator + sqoopJar; } else { LOG.warn("Could not find sqoop jar; child compilation may fail"); sqoopJar = ""; } String curClasspath = System.getProperty("java.class.path"); args.add("-sourcepath"); args.add(jarOutDir); args.add("-d"); args.add(jarOutDir); args.add("-classpath"); args.add(curClasspath + File.pathSeparator + coreJar + sqoopJar); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (null == compiler) { LOG.error("It seems as though you are running sqoop with a JRE."); LOG.error("Sqoop requires a JDK that can compile Java code."); LOG.error("Please install a JDK and set $JAVA_HOME to use it."); throw new IOException("Could not start Java compiler."); } StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); ArrayList<String> srcFileNames = new ArrayList<String>(); for (String srcfile : sources) { srcFileNames.add(jarOutDir + srcfile); LOG.debug("Adding source file: " + jarOutDir + srcfile); } if (LOG.isDebugEnabled()) { LOG.debug("Invoking javac with args:"); for (String arg : args) { LOG.debug(" " + arg); } } Iterable<? extends JavaFileObject> srcFileObjs = fileManager.getJavaFileObjectsFromStrings(srcFileNames); JavaCompiler.CompilationTask task = compiler.getTask(null, // Write to stderr fileManager, null, // No special diagnostic handling args, null, // Compile all classes in the source compilation units srcFileObjs); boolean result = task.call(); if (!result) { throw new IOException("Error returned by javac"); } // Where we should move source files after compilation. String srcOutDir = new File(options.getCodeOutputDir()).getAbsolutePath(); if (!srcOutDir.endsWith(File.separator)) { srcOutDir = srcOutDir + File.separator; } // Move these files to the srcOutDir. for (String srcFileName : sources) { String orig = jarOutDir + srcFileName; String dest = srcOutDir + srcFileName; File fOrig = new File(orig); File fDest = new File(dest); File fDestParent = fDest.getParentFile(); if (null != fDestParent && !fDestParent.exists()) { if (!fDestParent.mkdirs()) { LOG.error("Could not make directory: " + fDestParent); } } if (!fOrig.renameTo(fDest)) { LOG.error("Could not rename " + orig + " to " + dest); } } }
From source file:gool.parser.java.JavaParser.java
/** * if the parser is called on a directory, wrap it into a compilation unit, * and call the parser on that file./*ww w. j a v a 2s .c o m*/ */ public Collection<ClassDef> parseGoolFiles(Platform defaultPlatform, List<File> dirs) throws Exception { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(dirs); return parseGool(defaultPlatform, compilationUnits); }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName/*ww w . j a v a 2s . c o m*/ * * Returns false if something wrong, otherwise true (API interface * already exists or just well downloaded) */ private static boolean downloadLib(String libraryName) { URL url; URLConnection urlConn; // check (or make) for apiStore directory File apiStoreDir = new File(apiStore); if (!apiStoreDir.isDirectory()) apiStoreDir.mkdir(); String javaFilePath = apiStore + libraryName + ".java"; File javaFile = new File(javaFilePath); // check if the API interface exists if (javaFile.exists()) return true; try { // download the API interface's archive url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName); urlConn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setInstanceFollowRedirects(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); // extract the archive stream ZipInputStream zip = new ZipInputStream(urlConn.getInputStream()); String expectedEntryName = libraryName + ".java"; while (true) { ZipEntry nextEntry = zip.getNextEntry(); if (nextEntry == null) return false; String name = nextEntry.getName(); if (name.equals(expectedEntryName)) { // save .java locally FileOutputStream javaFileStream = new FileOutputStream(javaFilePath); byte[] buf = new byte[1024]; int n; while ((n = zip.read(buf, 0, 1024)) > -1) javaFileStream.write(buf, 0, n); // compile it into .class file JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, javaFilePath); System.out.println(result); return result == 0; } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:com.alibaba.rocketmq.filtersrv.filter.DynaCode.java
private void compile(String[] srcFiles) throws Exception { String args[] = this.buildCompileJavacArgs(srcFiles); ByteArrayOutputStream err = new ByteArrayOutputStream(); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { throw new NullPointerException( "ToolProvider.getSystemJavaCompiler() return null,please use JDK replace JRE!"); }/* www . ja va 2 s . com*/ int resultCode = compiler.run(null, null, err, args); if (resultCode != 0) { throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET)); } }
From source file:com.qwazr.compiler.JavaCompiler.java
private void compileDirectory(File sourceDirectory) throws IOException { if (sourceDirectory == null) return;//from w w w.j av a 2 s.c om if (!sourceDirectory.isDirectory()) return; compilerLock.w.lock(); try { javax.tools.JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); Objects.requireNonNull(compiler, "No compiler is available. This feature requires a JDK (not a JRE)."); compileDirectory(compiler, sourceDirectory); } finally { compilerLock.w.unlock(); } }
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 ww.j ava 2 s.co 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:net.nicholaswilliams.java.licensing.encryption.TestRSAKeyPairGenerator.java
@SuppressWarnings("unchecked") private JavaFileManager compileClass(String fqcn, String code) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); JavaFileManager fileManager = new MockClassFileManager<StandardJavaFileManager>( compiler.getStandardFileManager(null, null, null)); List<JavaFileObject> javaFiles = new ArrayList<JavaFileObject>(); javaFiles.add(new MockCharSequenceJavaFileObject(fqcn, code)); ByteArrayOutputStream compilerOutput = new ByteArrayOutputStream(); JavaCompiler.CompilationTask task = compiler.getTask(new OutputStreamWriter(compilerOutput), fileManager, null, null, null, javaFiles); if (!task.call()) fail("Compiling of generated class did not succeed. Java code:\r\n" + code + "\r\nCompiler output:\r\n" + compilerOutput.toString()); return fileManager; }
From source file:de.uni_koblenz.jgralab.utilities.tgschema2java.TgSchema2Java.java
public void compile() throws Exception { String packageFolder = schema.getPathName(); File folder = new File(commitPath + File.separator + packageFolder); List<File> files1 = findFilesInDirectory(folder); JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null); Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1); ArrayList<String> options = new ArrayList<>(); if (classpath != null) { options.add("-cp"); options.add(classpath);//w ww . j av a2 s . co m } System.out.print("Starting compilation...."); compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call(); System.out.println("finished"); }
From source file:com.cisco.oss.foundation.logging.structured.AbstractFoundationLoggingMarker.java
private static Class<FoundationLoggingMarkerFormatter> generateMarkerClass(String sourceCode, String newClassName) {//from w w w. jav a2 s .co m 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); } }