void run(String... args) throws Exception { File testSrcDir = new File(System.getProperty("test.src")); File tmpClassDir = new File("."); List<String> l = new ArrayList<String>(); l.add("-d"); l.add(tmpClassDir.getPath()); for (String a : args) { if (a.endsWith(".java")) l.add(new File(testSrcDir, a).getPath()); else l.add(a); } StringWriter sw = new StringWriter(); int rc = com.sun.tools.javac.Main.compile(l.toArray(new String[l.size()]), new PrintWriter(sw)); System.err.println(sw); Pattern p = Pattern.compile("([A-Z]+).*"); for (String name : tmpClassDir.list()) { if (name.endsWith(".class")) { Matcher m = p.matcher(name); if (m.matches()) { found(m.group(1), name); } } } // for all classes that might have been compiled, check that // all the classes in the source file get generated, or none do. check("A", 3); check("B", 3); check("C", 3); check("D", 3); if (errors > 0) throw new Exception(errors + " errors"); }
String javac(String... args) throws Exception { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); int rc = com.sun.tools.javac.Main.compile(args, pw); if (rc != 0) throw new Exception("javac failed, rc=" + rc); return sw.toString(); }
void run() throws Exception { File classesDir = new File("classes"); classesDir.mkdirs(); writeFile(baseFile, baseText); String[] javacArgs = {"-d", classesDir.getPath(), baseFile.getPath()}; com.sun.tools.javac.Main.compile(javacArgs); writeFile(srcFile, srcText); String[] args = { "-d", "api", "-classpath", classesDir.getPath(), "-package", "p", srcFile.getPath() }; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream prev = System.err; System.setErr(ps); try { int rc = com.sun.tools.javadoc.Main.execute(args); } finally { System.err.flush(); System.setErr(prev); } String out = baos.toString(); System.out.println(out); String errorMessage = "java.lang.IllegalArgumentException: <clinit>"; if (out.contains(errorMessage)) throw new Exception("error message found: " + errorMessage); }
/** * The worker method for each test case. Compile the files and verify that exactly the expected * set of header files is generated. */ void test(RunKind rk, GenKind gk, List<File> files, Set<String> expect) throws Exception { List<String> args = new ArrayList<String>(); if (gk == GenKind.FULL) args.add("-XDjavah:full"); switch (rk) { case CMD: args.add("-d"); args.add(classesDir.getPath()); args.add("-h"); args.add(headersDir.getPath()); for (File f : files) args.add(f.getPath()); int rc = com.sun.tools.javac.Main.compile(args.toArray(new String[args.size()])); if (rc != 0) throw new Exception("compilation failed, rc=" + rc); break; case API: fm.setLocation(StandardLocation.SOURCE_PATH, Arrays.asList(srcDir)); fm.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(classesDir)); fm.setLocation(StandardLocation.NATIVE_HEADER_OUTPUT, Arrays.asList(headersDir)); JavacTask task = javac.getTask(null, fm, null, args, null, fm.getJavaFileObjectsFromFiles(files)); if (!task.call()) throw new Exception("compilation failed"); break; } Set<String> found = createSet(headersDir.list()); checkEqual("header files", expect, found); }
/** * Final preparations for the system's compiler, if it could be fetched. If not, compiling is down * by the compiler from com.sun.tools.javac.Main * * @param srcFiles * @return null if success; or compilation errors */ public String compile(String srcFiles[]) { Logger.getInstance().log("de.~.vm.Javac.compile(String)", Logger.DEBUG, "Begin of function"); StringWriter err = new StringWriter(); PrintWriter errPrinter = new PrintWriter(err); String args[] = buildJavacArgs(srcFiles); // Fetch the systems JavaCompiler. Fails, if Eclipse is startet // with the VM from JRE. Works with JDK. compiler = ToolProvider.getSystemJavaCompiler(); if (compiler != null) { String algorithmAsSourceCode = readfile(args[args.length - 1]); // extract the name of the algorithm. The name is always at the last position of this array String algorithmName = args[args.length - 1].split("/")[args[args.length - 1].split("/").length - 1]; String error = null; // Create a new AlvisFileObject containing the source code and let the compiler compile it try { error = compile(new AlvisFileObject(algorithmName, algorithmAsSourceCode)); } catch (URISyntaxException e) { e.printStackTrace(); } Logger.getInstance() .log( "de.~.vm.Javac.compile(String)", Logger.DEBUG, "Compile with ToolsProvider compiler was successful"); errPrinter.close(); Logger.getInstance() .log("de.~.vm.Javac.compile(String)", Logger.DEBUG, "Error? " + err.toString()); return error; } else { Logger.getInstance() .log( "de.~.vm.Javac.compile(String)", Logger.DEBUG, "ToolsProvider did not provide a compiler, using fallback"); // Grabbing the standard compiler did not work, compiling "by hand" // FIXME: 1. Find a way, so that // ToolProvider.getSystemJavaCompiler() cannot return null // 2. Delete the call to com.sun.tools.javac.Main int resultCode = com.sun.tools.javac.Main.compile(args, errPrinter); return (resultCode == 0) ? null : err.toString(); } }
public static void createClass(String className) { String fileName = className + ".java"; try { // Creates DynamicTestClass.java file FileWriter fileWriter = new FileWriter(pathOfNewClasses + fileName, false); fileWriter.write("package bgu.sim.actions.darkComet; \n\n"); fileWriter.write( "import bgu.sim.core.stat.StatisticCollector;\n" + "import bgu.sim.data.NetDevice;\n" + "import bgu.sim.data.SystemEvent;\n" + "import bgu.sim.ruleEngine.action.AbsDeviceAction;\n" + "import bgu.sim.ruleEngine.action.IndicativeFeature;\n" + "import bgu.sim.actions.darkComet.Tools.*;\n" + "import java.util.List;\n\n"); fileWriter.write("public class " + className + " extends AbsDeviceAction {\n\n"); fileWriter.write(" private List<SystemEvent> events; \n\n"); fileWriter.write( " public List<SystemEvent> getEvents() {\n" + "\treturn events;\n" + " }\n\n"); fileWriter.write(" public " + className + "() {\n"); fileWriter.write("\tsuper(\"" + className + "\", new IndicativeFeature[]{});\n"); fileWriter.write("\treadCSV rc = new readCSV();\n"); fileWriter.write("\tevents = rc.readCSV(\"DM_" + className + ".CSV\");\n"); fileWriter.write(" }\n\n"); fileWriter.write( " @Override\n" + " public Integer execute(NetDevice input) {\n" + "\tinput.getInfo().addEvents(events);\n" + "\tStatisticCollector.increaseValue(this.getName(), 1);\n" + "\treturn 1;\n" + " }\n"); fileWriter.write("}"); fileWriter.flush(); fileWriter.close(); String[] source = {new String(fileName)}; // javac -> compile method in Main class ..presents in tools.jar // Compile the DynamicTestClass.java ,created on the fly com.sun.tools.javac.Main.compile(source); } catch (Exception e) { e.printStackTrace(); } }
/** * generate the proxy class; * * @param name * @param dir */ private void compileProxy(String name, String dir) { if (log.isDebugEnabled()) { log.debug("complile proxy:" + name + " using classpath:" + this.cp); } CharArrayWriter caw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(caw); String[] params = new String[3]; params[0] = "-classpath"; params[1] = this.cp; params[2] = dir + name + ".java"; Main.compile(params, pw); if (log.isDebugEnabled()) { log.debug(caw.toString()); } }
void doTest(File testJar, String... additionalArgs) { List<String> options = new ArrayList<>(); options.add("-proc:only"); options.add("-processor"); options.add("T8076104"); options.add("-classpath"); options.add( System.getProperty("test.classes") + File.pathSeparator + testJar.getAbsolutePath()); options.addAll(Arrays.asList(additionalArgs)); options.add(System.getProperty("test.src") + File.separator + "T8076104.java"); int res = Main.compile(options.toArray(new String[0])); if (res != 0) { throw new AssertionError("Unexpected error code: " + res); } }
private AsmCodeGenerator initCodeGenerator( final String formFileName, final String className, final String testDataPath) throws Exception { String tmpPath = FileUtil.getTempDirectory(); String formPath = testDataPath + formFileName; String javaPath = testDataPath + className + ".java"; final int rc = Main.compile(new String[] {"-d", tmpPath, javaPath}); assertEquals(0, rc); final String classPath = tmpPath + "/" + className + ".class"; final File classFile = new File(classPath); assertTrue(classFile.exists()); final LwRootContainer rootContainer = loadFormData(formPath); final AsmCodeGenerator codeGenerator = new AsmCodeGenerator( rootContainer, myClassFinder, myNestedFormLoader, false, new ClassWriter(ClassWriter.COMPUTE_FRAMES)); final FileInputStream classStream = new FileInputStream(classFile); try { codeGenerator.patchClass(classStream); } finally { classStream.close(); FileUtil.delete(classFile); final File[] inners = new File(tmpPath) .listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith(className + "$") && name.endsWith(".class"); } }); if (inners != null) { for (File file : inners) FileUtil.delete(file); } } return codeGenerator; }
public static boolean compile(String classPath, String bin, String src, String warn) { setStaticClassPath(classPath); setStaticBin(bin); // setStaticSrc(src) // setStaticWarn(warn); // Debug.println("Debug: ClassPath=" + classPath); // System.out.println("((((((compile(String classPath, String bin, String src, String warn)"); // System.out.println("classPath : " + classPath + ";bin : " + bin + ";src : " + src); // System.out.println("))))))))))))))))))"); String[] args = {"-cp", classPath, "-Xstdout", warn, "-d", bin, src}; // Log.println("Debug: -cp " + classPath + " -Xstdout " + warn + " -d " + bin + " " + src); // for(String s: args){ // Debug.println(s); // } File f = new File(bin); if (!f.exists()) { try { System.out.println("************ !f.exists"); f.mkdirs(); } catch (Exception ex) { ex.printStackTrace(); return false; } } // for(int i=0;i<args.length;i++){ // Debug.println(args[i]); // } // 编译 com.sun.tools.javac.Main.compile(args); // 查看编译结果 // System.out.println("~~~~~~~~~~~~JavaCompiler :File warn path : " + warn); File result = new File(warn); if (result.length() > 0) { return false; } else return true; }
public static File compileTestFile(File f, String testClass) { int rc = com.sun.tools.javac.Main.compile( new String[] { "-source", "1.8", "-g", "-processor", "org.checkerframework.checker.nullness.NullnessChecker", f.getPath() }); if (rc != 0) { throw new Error("compilation failed. rc=" + rc); } String path; if (f.getParent() != null) { path = f.getParent(); } else { path = ""; } return new File(path + testClass + ".class"); }
private String createDefinition(Object runConfigNode) throws Exception { Element benchDefNode = (Element) xp.evaluate("fd:benchmarkDefinition", runConfigNode, XPathConstants.NODE); if (benchDefNode == null) { return null; } String definingClassName = xp.evaluate("fd:driverConfig/@name", runConfigNode); // Get the cycleTime annotation Element driverConfigNode = (Element) xp.evaluate("fd:driverConfig", runConfigNode, XPathConstants.NODE); String requestLagTime = getRequestLagTime(driverConfigNode); /** * Load the template from file Template file is small, but is there a better way to read this? */ String line = null; BufferedReader br = null; InputStream is = null; try { ClassLoader cl = this.getClass().getClassLoader(); is = cl.getResourceAsStream("driver_template"); br = new BufferedReader(new InputStreamReader(is)); } catch (Exception ex) { // what to do? ex.printStackTrace(); throw new ConfigurationException(ex); } StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { if (!line.equals("\n")) { sb.append(line).append("\n"); } } String template = sb.toString(); is.close(); // Obtain the provider. TransportProvider provider = TransportProvider.getProvider(); /** * Get the operation token out of the template. Use this to create multiple * operations/functions that will replace the token in the java file */ String opTemplate = template.substring((template.indexOf("#operation") + 10), template.indexOf("operation#")); StringBuilder operations = new StringBuilder(); Element operationNode = null; int i = 1; while ((operationNode = (Element) xp.evaluate( ("fd:driverConfig/fd:operation[" + i + "]"), runConfigNode, XPathConstants.NODE)) != null) { /* * There are many different options here. First, the operation * is either POST or GET. In either case, the subst element * indicates whether or not random strings are present in the * payload data (for backward compatibility, it is assumed * that random data is present). * * For POST, we can read the data from a file, and we can * encode the data as form-encoded or binary (octet-stream) */ boolean isPost = false; boolean isBinary = false; boolean isFile = false; boolean doSubst = true; String requestLagTimeOverride = getRequestLagTime(operationNode); String operationName = xp.evaluate("fd:name", operationNode); String url = xp.evaluate("fd:url", operationNode); String max90th = xp.evaluate("fd:max90th", operationNode); String kbps = xp.evaluate("fd:kbps", operationNode); String accept = xp.evaluate("fd:accept", operationNode); String requestString = ""; Element requestNode = (Element) xp.evaluate("fd:get", operationNode, XPathConstants.NODE); if (requestNode == null) { // Can't have both post & get either, but if both are there, // will assume you meant GET. requestNode = (Element) xp.evaluate("fd:post", operationNode, XPathConstants.NODE); if (requestNode != null) { isPost = true; if ("true".equalsIgnoreCase(requestNode.getAttributeNS(null, "file"))) { isFile = true; } if ("true".equalsIgnoreCase(requestNode.getAttributeNS(null, "binary"))) { isBinary = true; } } else { throw new ConfigurationException("<operation> " + "must have a either a get/post"); } // Can't have both post & get either, but if there, // will assume you meant GET. } if ("false".equalsIgnoreCase(requestNode.getAttributeNS(null, "subst"))) { doSubst = false; } if (isBinary && doSubst) { throw new ConfigurationException( "<operation> " + "cannot be both binary and perform substitution"); } requestString = requestNode.getNodeValue(); if (requestString == null) { CDATASection cDataNode = (CDATASection) requestNode.getFirstChild(); if (cDataNode != null) { requestString = cDataNode.getNodeValue(); } } if (requestString == null) { requestString = ""; } if (requestLagTimeOverride == null) { requestLagTimeOverride = ""; } if (operationName == null) { throw new ConfigurationException("<operation> must have a <name> "); } if (url == null) { throw new ConfigurationException("<operation> must have a <url>"); } RunInfoDefinition rid; if (isPost) { if (isFile) { rid = new RunInfoPostFileDefinition(); } else { rid = new RunInfoPostDataDefinition(); } } else { rid = new RunInfoGetDefinition(); } rid.init(doSubst, isBinary, url, requestString, kbps, accept); // Create the benchmark Operation annotation StringBuilder bmop = new StringBuilder("@BenchmarkOperation(name = \"").append(operationName); bmop.append("\", percentileLimits={ ") .append(max90th) .append(", ") .append(max90th) .append(", ") .append(max90th) .append("}, "); if (provider == TransportProvider.SUN && url.startsWith("https")) bmop.append("timing = com.sun.faban.driver.Timing.MANUAL"); else bmop.append("timing = com.sun.faban.driver.Timing.AUTO"); bmop.append(")"); String opTemplateClone = new String(opTemplate); // replace tokens with actual content opTemplateClone = opTemplateClone.replaceAll("@RequestLagTime@", requestLagTimeOverride); opTemplateClone = opTemplateClone.replaceAll("@Operations@", bmop.toString()); opTemplateClone = opTemplateClone.replaceAll("@operationName@", operationName); opTemplateClone = opTemplateClone.replaceAll("@url@", rid.getURL(i)); opTemplateClone = opTemplateClone.replaceAll("@postRequest@", rid.getPostRequest(i)); opTemplateClone = opTemplateClone.replaceAll("@Statics@", rid.getStatics(i)); opTemplateClone = opTemplateClone.replaceAll("@doKbps@", rid.getKbps(i)); opTemplateClone = opTemplateClone.replaceAll("@doHeaders@", rid.getHeaders(i)); opTemplateClone = opTemplateClone.replaceAll("@doTiming@", rid.doTiming(i, provider)); operations.append(opTemplateClone); i++; } String benchmarkDef = getBenchmarkDefinition(benchDefNode); // replace tokens in template template = template.replaceFirst("#operation(.*\\n*)*operation#", operations.toString()); template = template.replaceFirst("@RequestLagTime@", requestLagTime); template = template.replaceFirst("@BenchmarkDefinition@", benchmarkDef); template = template.replaceAll("@DriverClassName@", definingClassName); template = template.replaceFirst("@ProviderClass@", provider.providerClass); template = template.replaceFirst("@BenchmarkDriverName@", definingClassName); String tmpDir = System.getProperty("faban.tmpdir"); if (tmpDir == null) { tmpDir = System.getProperty("java.io.tmpdir"); } if (!tmpDir.endsWith(File.separator)) { tmpDir = tmpDir + File.separator; } String className = new StringBuilder(tmpDir).append(definingClassName).append(".java").toString(); try { // convert class name to filename? PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(className))); pw.print(template); pw.flush(); } catch (Exception ex) { ex.printStackTrace(); throw new ConfigurationException(ex); } String classpath = System.getProperty("java.class.path"); String arg[] = new String[] {"-classpath", classpath, className}; int errorCode = com.sun.tools.javac.Main.compile(arg); if (errorCode != 0) { throw new ConfigurationException( "unable to compile generated driver file. " + "check output for errors"); } return definingClassName; }
static void compiler(String... javacCmds) { if (com.sun.tools.javac.Main.compile(javacCmds) != 0) { throw new RuntimeException("compilation failed"); } }
/** * Programmatic interface for main function. * * @param args The command line parameters. */ public int compile(String[] args, AnnotationProcessorFactory factory) { int returnCode = 0; providedFactory = factory; Context context = new Context(); options = Options.instance(context); Bark bark; /* * Process the command line options to create the intial * options data. This processing is at least partially reused * by any recursive apt calls. */ // For testing: assume all arguments in forcedOpts are // prefixed to command line arguments. processArgs(forcedOpts); /* * A run of apt only gets passed the most recently generated * files; the initial run of apt gets passed the files from * the command line. */ java.util.List<String> origFilenames; try { // assign args the result of parse to capture results of // '@file' expansion origFilenames = processArgs((args = CommandLine.parse(args))); if (origFilenames == null) { return EXIT_CMDERR; } else if (origFilenames.size() == 0) { // it is allowed to compile nothing if just asking for help if (options.get("-help") != null || options.get("-X") != null) return EXIT_OK; } } catch (java.io.FileNotFoundException e) { Bark.printLines( out, ownName + ": " + getLocalizedString("err.file.not.found", e.getMessage())); return EXIT_SYSERR; } catch (IOException ex) { ioMessage(ex); return EXIT_SYSERR; } catch (OutOfMemoryError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (StackOverflowError ex) { resourceMessage(ex); return EXIT_SYSERR; } catch (FatalError ex) { feMessage(ex); return EXIT_SYSERR; } catch (sun.misc.ServiceConfigurationError sce) { sceMessage(sce); return EXIT_ABNORMAL; } catch (Throwable ex) { bugMessage(ex); return EXIT_ABNORMAL; } boolean firstRound = true; boolean needSourcePath = false; boolean needClassPath = false; boolean classesAsDecls = options.get("-XclassesAsDecls") != null; /* * Create augumented classpath and sourcepath values. * * If any of the prior apt rounds generated any new source * files, the n'th apt round (and any javac invocation) has the * source destination path ("-s path") as the last element of * the "-sourcepath" to the n'th call. * * If any of the prior apt rounds generated any new class files, * the n'th apt round (and any javac invocation) has the class * destination path ("-d path") as the last element of the * "-classpath" to the n'th call. */ String augmentedSourcePath = ""; String augmentedClassPath = ""; String baseClassPath = ""; try { /* * Record original options for future annotation processor * invocations. */ origOptions = new HashMap<String, String>(options.size()); for (String s : options.keySet()) { String value; if (s.equals(value = options.get(s))) origOptions.put(s, (String) null); else origOptions.put(s, value); } origOptions = Collections.unmodifiableMap(origOptions); { // Note: it might be necessary to check for an empty // component ("") of the source path or class path Paths paths = Paths.instance(context); String sourceDest = options.get("-s"); if (paths.sourcePath() != null) { for (File f : paths.sourcePath()) augmentedSourcePath += (f + File.pathSeparator); augmentedSourcePath += (sourceDest == null) ? "." : sourceDest; } else { augmentedSourcePath = "."; if (sourceDest != null) augmentedSourcePath += (File.pathSeparator + sourceDest); } String classDest = options.get("-d"); if (paths.userClassPath() != null) { for (File f : paths.userClassPath()) baseClassPath += (f + File.pathSeparator); // put baseClassPath into map to handle any // value needed for the classloader options.put("-classpath", baseClassPath); augmentedClassPath = baseClassPath + ((classDest == null) ? "." : classDest); } else { baseClassPath = "."; if (classDest != null) augmentedClassPath = baseClassPath + (File.pathSeparator + classDest); } assert options.get("-classpath") != null; } /* * Create base and augmented class loaders */ ClassLoader augmentedAptCL = null; { /* * Use a url class loader to look for classes on the * user-specified class path. Prepend computed bootclass * path, which includes extdirs, to the URLClassLoader apt * uses. */ String aptclasspath = ""; Paths paths = Paths.instance(context); String bcp = ""; Collection<File> bootclasspath = paths.bootClassPath(); if (bootclasspath != null) { for (File f : bootclasspath) bcp += (f + File.pathSeparator); } // If the factory path is set, use that path if (providedFactory == null) aptclasspath = options.get("-factorypath"); if (aptclasspath == null) aptclasspath = options.get("-classpath"); assert aptclasspath != null; aptclasspath = (bcp + aptclasspath); aptCL = new URLClassLoader(pathToURLs(aptclasspath)); if (providedFactory == null && options.get("-factorypath") != null) // same CL even if new class files written augmentedAptCL = aptCL; else { // Create class loader in case new class files are // written augmentedAptCL = new URLClassLoader( pathToURLs(augmentedClassPath.substring(baseClassPath.length())), aptCL); } } int round = 0; // For -XPrintAptRounds do { round++; Context newContext = new Context(); Options newOptions = Options.instance(newContext); // creates a new context newOptions.putAll(options); // populate with old options... don't bother reparsing command line, etc. // if genSource files, must add destination to source path if (genSourceFileNames.size() > 0 && !firstRound) { newOptions.put("-sourcepath", augmentedSourcePath); needSourcePath = true; } aggregateGenSourceFileNames.addAll(genSourceFileNames); sourceFileNames.addAll(genSourceFileNames); genSourceFileNames.clear(); // Don't really need to track this; just have to add -d // "foo" to class path if any class files are generated if (genClassFileNames.size() > 0) { newOptions.put("-classpath", augmentedClassPath); aptCL = augmentedAptCL; needClassPath = true; } aggregateGenClassFileNames.addAll(genClassFileNames); classFileNames.addAll(genClassFileNames); genClassFileNames.clear(); options = newOptions; if (options.get("-XPrintAptRounds") != null) { out.println("apt Round : " + round); out.println("filenames: " + sourceFileNames); if (classesAsDecls) out.println("classnames: " + classFileNames); out.println("options: " + options); } returnCode = compile(args, newContext); firstRound = false; // Check for reported errors before continuing bark = Bark.instance(newContext); } while (((genSourceFileNames.size() != 0) || (classesAsDecls && genClassFileNames.size() != 0)) && bark.nerrors == 0); } catch (UsageMessageNeededException umne) { help(); return EXIT_CMDERR; // will cause usage message to be printed } /* * Do not compile if a processor has reported an error or if * there are no source files to process. A more sophisticated * test would also fail for syntax errors caught by javac. */ if (options.get("-nocompile") == null && options.get("-print") == null && bark.nerrors == 0 && (origFilenames.size() > 0 || aggregateGenSourceFileNames.size() > 0)) { /* * Need to create new argument string for calling javac: * 1. apt specific arguments (e.g. -factory) must be stripped out * 2. proper settings for sourcepath and classpath must be used * 3. generated class names must be added * 4. class file names as declarations must be removed */ int newArgsLength = args.length + (needSourcePath ? 1 : 0) + (needClassPath ? 1 : 0) + aggregateGenSourceFileNames.size(); // Null out apt-specific options and don't copy over into // newArgs. This loop should be a lot faster; the options // array should be replaced with a better data structure // which includes a map from strings to options. // // If treating classes as declarations, must strip out // class names from the javac argument list argLoop: for (int i = 0; i < args.length; i++) { int matchPosition = -1; // "-A" by itself is recognized by apt but not javac if (args[i] != null && args[i].equals("-A")) { newArgsLength--; args[i] = null; continue argLoop; } else { optionLoop: for (int j = 0; j < recognizedOptions.length; j++) { if (args[i] != null && recognizedOptions[j].matches(args[i])) { matchPosition = j; break optionLoop; } } if (matchPosition != -1) { Option op = recognizedOptions[matchPosition]; if (op.aptOnly) { newArgsLength--; args[i] = null; if (op.hasArg()) { newArgsLength--; args[i + 1] = null; } } else { if (op.hasArg()) { // skip over next string i++; continue argLoop; } if ((options.get("-XclassesAsDecls") != null) && (matchPosition == (recognizedOptions.length - 1))) { // Remove class file names from // consideration by javac. if (!args[i].endsWith(".java")) { newArgsLength--; args[i] = null; } } } } } } String newArgs[] = new String[newArgsLength]; int j = 0; for (int i = 0; i < args.length; i++) { if (args[i] != null) newArgs[j++] = args[i]; } if (needClassPath) newArgs[j++] = "-XD-classpath=" + augmentedClassPath; if (needSourcePath) { newArgs[j++] = "-XD-sourcepath=" + augmentedSourcePath; for (String s : aggregateGenSourceFileNames) newArgs[j++] = s; } returnCode = com.sun.tools.javac.Main.compile(newArgs); } return returnCode; }
File compileTestFile(File f) { int rc = com.sun.tools.javac.Main.compile(new String[] {"-source", "1.7", "-g", f.getPath()}); if (rc != 0) throw new Error("compilation failed. rc=" + rc); String path = f.getPath(); return new File(path.substring(0, path.length() - 5) + ".class"); }
public void run() throws Exception { // Selection of files to be compiled File absJar = createJar(new File("abs.jar").getAbsoluteFile(), "j.A"); File relJar = createJar(new File("rel.jar"), "j.R"); File absDir = createDir(new File("abs.dir").getAbsoluteFile(), "d.A"); File relDir = createDir(new File("rel.dir"), "d.R"); File absTestFile = writeFile(new File("AbsTest.java").getAbsoluteFile(), "class AbsTest { class Inner { } }"); File relTestFile = writeFile(new File("RelTest.java"), "class RelTest { class Inner { } }"); File relTest2File = writeFile(new File("p/RelTest2.java"), "package p; class RelTest2 { class Inner { } }"); // This next class references other classes that will be found on the source path // and which will therefore need to be compiled as well. File mainFile = writeFile(new File("Main.java"), "class Main { j.A ja; j.R jr; d.A da; d.R dr; }" + ""); String sourcePath = createPath(absJar, relJar, absDir, relDir); File outDir = new File("classes"); outDir.mkdirs(); String[] args = { "-sourcepath", sourcePath, "-d", outDir.getPath(), absTestFile.getPath(), relTestFile.getPath(), relTest2File.getPath(), mainFile.getPath(), }; System.err.println("compile: " + Arrays.asList(args)); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); int rc = com.sun.tools.javac.Main.compile(args, pw); pw.close(); if (rc != 0) { System.err.println(sw.toString()); throw new Exception("unexpected exit from javac: " + rc); } Set<File> expect = getFiles( outDir, "d/A.class", "d/A$Inner.class", "d/R.class", "d/R$Inner.class", "j/A.class", "j/A$Inner.class", "j/R.class", "j/R$Inner.class", "AbsTest.class", "AbsTest$Inner.class", "RelTest.class", "RelTest$Inner.class", "p/RelTest2.class", "p/RelTest2$Inner.class", "Main.class"); Set<File> found = findFiles(outDir); if (!found.equals(expect)) { if (found.containsAll(expect)) throw new Exception("unexpected files found: " + diff(found, expect)); else if (expect.containsAll(found)) throw new Exception("expected files not found: " + diff(expect, found)); } for (File f : found) verifySourceFileAttribute(f); if (errors > 0) throw new Exception(errors + " errors occurred"); }
// used for debugging public static void main(String... args) { String rt_jar = args[0]; String dest = args[1]; args = new String[] { "-Xbootclasspath:" + rt_jar, "-XDprocess.packages", "-proc:only", "-processor", "com.sun.tools.javac.sym.CreateSymbols", "-Acom.sun.tools.javac.sym.Jar=" + rt_jar, "-Acom.sun.tools.javac.sym.Dest=" + dest, // <editor-fold defaultstate="collapsed"> "java.applet", "java.awt", "java.awt.color", "java.awt.datatransfer", "java.awt.dnd", "java.awt.event", "java.awt.font", "java.awt.geom", "java.awt.im", "java.awt.im.spi", "java.awt.image", "java.awt.image.renderable", "java.awt.print", "java.beans", "java.beans.beancontext", "java.io", "java.lang", "java.lang.annotation", "java.lang.instrument", "java.lang.management", "java.lang.ref", "java.lang.reflect", "java.math", "java.net", "java.nio", "java.nio.channels", "java.nio.channels.spi", "java.nio.charset", "java.nio.charset.spi", "java.rmi", "java.rmi.activation", "java.rmi.dgc", "java.rmi.registry", "java.rmi.server", "java.security", "java.security.acl", "java.security.cert", "java.security.interfaces", "java.security.spec", "java.sql", "java.text", "java.text.spi", "java.util", "java.util.concurrent", "java.util.concurrent.atomic", "java.util.concurrent.locks", "java.util.jar", "java.util.logging", "java.util.prefs", "java.util.regex", "java.util.spi", "java.util.zip", "javax.accessibility", "javax.activation", "javax.activity", "javax.annotation", "javax.annotation.processing", "javax.crypto", "javax.crypto.interfaces", "javax.crypto.spec", "javax.imageio", "javax.imageio.event", "javax.imageio.metadata", "javax.imageio.plugins.jpeg", "javax.imageio.plugins.bmp", "javax.imageio.spi", "javax.imageio.stream", "javax.jws", "javax.jws.soap", "javax.lang.model", "javax.lang.model.element", "javax.lang.model.type", "javax.lang.model.util", "javax.management", "javax.management.loading", "javax.management.monitor", "javax.management.relation", "javax.management.openmbean", "javax.management.timer", "javax.management.modelmbean", "javax.management.remote", "javax.management.remote.rmi", "javax.naming", "javax.naming.directory", "javax.naming.event", "javax.naming.ldap", "javax.naming.spi", "javax.net", "javax.net.ssl", "javax.print", "javax.print.attribute", "javax.print.attribute.standard", "javax.print.event", "javax.rmi", "javax.rmi.CORBA", "javax.rmi.ssl", "javax.script", "javax.security.auth", "javax.security.auth.callback", "javax.security.auth.kerberos", "javax.security.auth.login", "javax.security.auth.spi", "javax.security.auth.x500", "javax.security.cert", "javax.security.sasl", "javax.sound.sampled", "javax.sound.sampled.spi", "javax.sound.midi", "javax.sound.midi.spi", "javax.sql", "javax.sql.rowset", "javax.sql.rowset.serial", "javax.sql.rowset.spi", "javax.swing", "javax.swing.border", "javax.swing.colorchooser", "javax.swing.filechooser", "javax.swing.event", "javax.swing.table", "javax.swing.text", "javax.swing.text.html", "javax.swing.text.html.parser", "javax.swing.text.rtf", "javax.swing.tree", "javax.swing.undo", "javax.swing.plaf", "javax.swing.plaf.basic", "javax.swing.plaf.metal", "javax.swing.plaf.multi", "javax.swing.plaf.synth", "javax.tools", "javax.transaction", "javax.transaction.xa", "javax.xml.parsers", "javax.xml.bind", "javax.xml.bind.annotation", "javax.xml.bind.annotation.adapters", "javax.xml.bind.attachment", "javax.xml.bind.helpers", "javax.xml.bind.util", "javax.xml.soap", "javax.xml.ws", "javax.xml.ws.handler", "javax.xml.ws.handler.soap", "javax.xml.ws.http", "javax.xml.ws.soap", "javax.xml.ws.spi", "javax.xml.transform", "javax.xml.transform.sax", "javax.xml.transform.dom", "javax.xml.transform.stax", "javax.xml.transform.stream", "javax.xml", "javax.xml.crypto", "javax.xml.crypto.dom", "javax.xml.crypto.dsig", "javax.xml.crypto.dsig.dom", "javax.xml.crypto.dsig.keyinfo", "javax.xml.crypto.dsig.spec", "javax.xml.datatype", "javax.xml.validation", "javax.xml.namespace", "javax.xml.xpath", "javax.xml.stream", "javax.xml.stream.events", "javax.xml.stream.util", "org.ietf.jgss", "org.omg.CORBA", "org.omg.CORBA.DynAnyPackage", "org.omg.CORBA.ORBPackage", "org.omg.CORBA.TypeCodePackage", "org.omg.stub.java.rmi", "org.omg.CORBA.portable", "org.omg.CORBA_2_3", "org.omg.CORBA_2_3.portable", "org.omg.CosNaming", "org.omg.CosNaming.NamingContextExtPackage", "org.omg.CosNaming.NamingContextPackage", "org.omg.SendingContext", "org.omg.PortableServer", "org.omg.PortableServer.CurrentPackage", "org.omg.PortableServer.POAPackage", "org.omg.PortableServer.POAManagerPackage", "org.omg.PortableServer.ServantLocatorPackage", "org.omg.PortableServer.portable", "org.omg.PortableInterceptor", "org.omg.PortableInterceptor.ORBInitInfoPackage", "org.omg.Messaging", "org.omg.IOP", "org.omg.IOP.CodecFactoryPackage", "org.omg.IOP.CodecPackage", "org.omg.Dynamic", "org.omg.DynamicAny", "org.omg.DynamicAny.DynAnyPackage", "org.omg.DynamicAny.DynAnyFactoryPackage", "org.w3c.dom", "org.w3c.dom.events", "org.w3c.dom.bootstrap", "org.w3c.dom.ls", "org.xml.sax", "org.xml.sax.ext", "org.xml.sax.helpers", "com.sun.java.browser.dom", "org.w3c.dom", "org.w3c.dom.bootstrap", "org.w3c.dom.ls", "org.w3c.dom.ranges", "org.w3c.dom.traversal", "org.w3c.dom.html", "org.w3c.dom.stylesheets", "org.w3c.dom.css", "org.w3c.dom.events", "org.w3c.dom.views", "com.sun.management", "com.sun.security.auth", "com.sun.security.auth.callback", "com.sun.security.auth.login", "com.sun.security.auth.module", "com.sun.security.jgss", "com.sun.net.httpserver", "com.sun.net.httpserver.spi", "javax.smartcardio" // </editor-fold> }; com.sun.tools.javac.Main.compile(args); }