Java Code Examples for javax.tools.JavaCompiler.run()

The following are Jave code examples for showing how to use run() of the javax.tools.JavaCompiler class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
Example 1
Project: MaxSim   File: TestBootNativeLibraryPath.java   Source Code and License Vote up 7 votes
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 2
Project: openjdk-jdk10   File: TestBootNativeLibraryPath.java   Source Code and License Vote up 6 votes
static void createTestClass() throws IOException {
    FileOutputStream fos = new FileOutputStream(TESTFILE + ".java");
    PrintStream ps = new PrintStream(fos);
    ps.println("public class " + TESTFILE + "{");
    ps.println("public static void main(String[] args) {\n");
    ps.println("System.out.println(System.getProperty(\"sun.boot.library.path\"));\n");
    ps.println("}}\n");
    ps.close();
    fos.close();

    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    String javacOpts[] = {TESTFILE + ".java"};
    if (javac.run(null, null, null,  javacOpts) != 0) {
        throw new RuntimeException("compilation of " + TESTFILE + ".java Failed");
    }
}
 
Example 3
Project: ditb   File: TestClassFinder.java   Source Code and License Vote up 6 votes
/**
 * Compiles the test class with bogus code into a .class file.
 * Unfortunately it's very tedious.
 * @param counter Unique test counter.
 * @param packageNameSuffix Package name suffix (e.g. ".suffix") for nesting, or "".
 * @return The resulting .class file and the location in jar it is supposed to go to.
 */
private static FileAndPath compileTestClass(long counter,
    String packageNameSuffix, String classNamePrefix) throws Exception {
  classNamePrefix = classNamePrefix + counter;
  String packageName = makePackageName(packageNameSuffix, counter);
  String javaPath = basePath + classNamePrefix + ".java";
  String classPath = basePath + classNamePrefix + ".class";
  PrintStream source = new PrintStream(javaPath);
  source.println("package " + packageName + ";");
  source.println("public class " + classNamePrefix
      + " { public static void main(String[] args) { } };");
  source.close();
  JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
  int result = jc.run(null, null, null, javaPath);
  assertEquals(0, result);
  File classFile = new File(classPath);
  assertTrue(classFile.exists());
  return new FileAndPath(packageName.replace('.', '/') + '/', classFile);
}
 
Example 4
Project: incubator-netbeans   File: AnnotationProcessorTestUtils.java   Source Code and License Vote up 5 votes
/**
 * Run the Java compiler.
 * (A JSR 199 implementation must be available.)
 * @param src a source root (runs javac on all *.java it finds matching {@code srcIncludes})
 * @param srcIncludes a pattern of source files names without path to compile (useful for testing incremental compiles), or null for all
 * @param dest a dest dir to compile classes to
 * @param cp classpath entries; if null, use Java classpath of test
 * @param stderr output stream to print messages to, or null for test console (i.e. do not capture)
 * @return true if compilation succeeded, false if it failed
 */
public static boolean runJavac(File src, String srcIncludes, File dest, File[] cp, OutputStream stderr) {
    List<String> args = new ArrayList<String>();
    args.add("-classpath");
    StringBuilder b = new StringBuilder(dest.getAbsolutePath());
    if (cp != null) {
        for (File entry : cp) {
            b.append(File.pathSeparatorChar);
            b.append(entry.getAbsolutePath());
        }
    } else {
        b.append(File.pathSeparatorChar).append(System.getProperty("java.class.path"));
    }
    args.add(b.toString());
    args.add("-d");
    args.add(dest.getAbsolutePath());
    args.add("-sourcepath");
    args.add(src.getAbsolutePath());
    args.add("-s");
    File destG = new File(dest.getParentFile(), "generated-" + dest.getName());
    args.add(destG.getAbsolutePath());
    args.add("-source");
    args.add("6");
    args.add("-Xlint:-options");
    dest.mkdirs();
    destG.mkdirs();
    scan(args, src, srcIncludes);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    Assert.assertNotNull(String.format(
            "No JSR 199 compiler impl found; perhaps tools.jar missing from CP? BootClassPath: %s. ClassPath: %s",
            System.getProperty("sun.boot.class.path"),  //NOI18N
            System.getProperty("java.class.path")       //NOI18N
            ),
        compiler);
    //System.err.println("running javac with args: " + args);
    return compiler.run(null, null, stderr, args.toArray(new String[args.size()])) == 0;
}
 
Example 5
Project: rdf4j-schema-generator   File: AbstractSchemaSpecificTest.java   Source Code and License Vote up 5 votes
@Test
public void testCompilation() throws Exception {
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    int result = compiler.run(null, null, null, output.toString());
    Assert.assertEquals("Compiling the Schema failed", 0, result);

}
 
Example 6
Project: rdf4j-schema-generator   File: SchemaGeneratorCompileTest.java   Source Code and License Vote up 5 votes
@Test
public void testSchemaCompilation() throws ClassNotFoundException, MalformedURLException {
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    int result = compiler.run(null, null, null, output.toString());
    Assert.assertEquals("Compiling the Vocab failed", 0, result);

}
 
Example 7
Project: json-log-domain   File: YamlTest.java   Source Code and License Vote up 5 votes
@Test
public void generateSources() throws Exception {
    Path directory = Paths.get("target/generated-sources/log/");

	JavaGenerator.generate(Paths.get("src/test/resources/yaml/agresso.yaml"), directory);
	JavaGenerator.generate(Paths.get("src/test/resources/yaml/global.yaml"), directory);
	JavaGenerator.generate(Paths.get("src/test/resources/yaml/network.yaml"), directory);
	
	// verify that the generated classes can be loaded
	for(String domain : new String[]{"agresso", "global", "network"}) {
		File network = new File(String.format("target/generated-sources/log/com/example/%s/", domain));
		File[] results = network.listFiles(new FileFilter() {
			public boolean accept(File pathname) {
				return pathname.getName().endsWith(".java");
			}
		});

		List<String> files = new ArrayList<>();
		for(File result : results) {
			files.add(result.getAbsolutePath());
		}

	    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
	    int status = compiler.run(null, null, null, files.toArray(new String[files.size()]));
	    if(status != 0) {
	    	throw new IllegalArgumentException();
	    }			
	}
}
 
Example 8
Project: rocketmq-rocketmq-all-4.1.0-incubating   File: DynaCode.java   Source Code and License Vote up 5 votes
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!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}
 
Example 9
Project: reading-and-annotate-rocketmq-3.4.6   File: DynaCode.java   Source Code and License Vote up 5 votes
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!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString());
    }
}
 
Example 10
Project: scala-playground   File: Javac.java   Source Code and License Vote up 5 votes
/**
 * Given a list of file-scope java code (equivalent to a .java file, including package and
 * import declarations), compile() invokes javac to compile them, produce classfiles and return
 * a list of <className, byte[]> pairs.
 * <p>
 * compile() dumps the source strings into their respective files, has javac compile them, then
 * reads back the equivalent class files. The name of the source file is gleaned from the string
 * itself; a string containing "public class Foo" is stored in tmpDir/Foo.java (where tmpDir is
 * a temporary directory that's deleted after the compilation), and if no public class or
 * interface is found, the name of the first class in the string is used.
 * <p>
 * Note that the list of returned classes may be larger than
 *
 * @param srcCodes . List of strings.
 * @return List<className,byte[]>. className is fully qualified, and byte[] contains the
 * bytecode of the class.
 * @throws IOException
 */
public static List<ClassInfo> compile(List<String> srcCodes) throws IOException {

  List<SourceInfo> srcInfos = getSourceInfos(srcCodes);

  File rootDir = getTmpDir(); // something like "/tmp/kilim$2348983948"

  File classDir = new File(rootDir.getAbsolutePath() + File.separatorChar + "classes");
  classDir.mkdir(); // "<rootDir>/classes"

  String options[] = {"-d", classDir.getAbsolutePath()};

  String args[] = new String[options.length + srcCodes.size()];
  System.arraycopy(options, 0, args, 0, options.length);
  int i = options.length;

  for (SourceInfo srci : srcInfos) {
    String name = rootDir.getAbsolutePath() + File.separatorChar + srci.className + ".java";
    writeFile(new File(name), srci.srcCode.getBytes());
    args[i++] = name;
  }

  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  compiler.run(null, null, null, args);

  List<ClassInfo> ret = new ArrayList<ClassInfo>();
  addClasses(ret, "", classDir);
  deleteDir(rootDir);
  return ret;
}
 
Example 11
Project: openjdk-jdk10   File: Xprint.java   Source Code and License Vote up 5 votes
public static void main(String[] args) {
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    javac.run(System.in, null, null,
              "-Xprint",
              "com.sun.tools.javac.code.Types",
              "com.sun.tools.javac.parser.Parser",
              "java.util.EnumSet");
}
 
Example 12
Project: openjdk-jdk10   File: JavaCompilerHelper.java   Source Code and License Vote up 5 votes
static boolean compile(String[] args, OutputStream out, ErrorReceiver receiver){
    try {
        JavaCompiler comp = ToolProvider.getSystemJavaCompiler();
        if (comp == null) {
            receiver.error(JavacompilerMessages.NO_JAVACOMPILER_ERROR(), null);
            return false;
        }
        return 0 == comp.run(null, out, out, args);
    } catch (SecurityException e) {
        receiver.error(e);
    }
    return false;
}
 
Example 13
Project: rmq4note   File: DynaCode.java   Source Code and License Vote up 5 votes
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!");
    }
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}