Example usage for javax.tools JavaCompiler run

List of usage examples for javax.tools JavaCompiler run

Introduction

In this page you can find the example usage for javax.tools JavaCompiler run.

Prototype

int run(InputStream in, OutputStream out, OutputStream err, String... arguments);

Source Link

Document

Run the tool with the given I/O channels and arguments.

Usage

From source file:CompileFiles1.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, args);
}

From source file:Main.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int result = compiler.run(null, null, null, "Hello.java");

    System.out.println("Compile result code = " + result);
}

From source file:FirstCompile.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    int results = compiler.run(null, null, null, "Foo.java");
    System.out.println("Success: " + (results == 0));
}

From source file:mashapeautoloader.MashapeAutoloader.java

/**
 * @param libraryName//  w w w .  j a v  a2s .  c om
 *
 * 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.metadave.stow.TestStow.java

@Test
public void testGen() throws Exception {
    InputStream is = this.getClass().getResourceAsStream("/Stow.stg");
    File f = File.createTempFile("stow", "test.stg");
    String root = f.getParent();//  w ww  .j av  a2s .com
    String classdir = root + File.separator + "stowtest";

    String stgPath = f.getAbsolutePath();
    String stowStg = org.apache.commons.io.IOUtils.toString(is);

    org.apache.commons.io.FileUtils.writeStringToFile(f, stowStg);

    File d = new File(classdir);
    d.mkdirs();

    Stow.generateObjects(stgPath, "stowtest", "Test", classdir);

    File testSTBean = new File(classdir + File.separator + "TestSTBean.java");
    assertTrue(testSTBean.exists());

    File testSTAccessor = new File(classdir + File.separator + "TestSTAccessor.java");
    assertTrue(testSTAccessor.exists());

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    compiler.run(null, null, null, testSTBean.getAbsolutePath());
    compiler.run(null, null, null, testSTAccessor.getAbsolutePath());

    File testSTAccessorClass = new File(classdir + File.separator + "TestSTAccessor.class");
    assertTrue(testSTAccessorClass.exists());

    File testSTBeanClass = new File(classdir + File.separator + "TestSTBean.class");
    assertTrue(testSTBeanClass.exists());

    URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File(root).toURI().toURL() });
    Class<?> cls = Class.forName("stowtest.TestSTBean", true, classLoader);

    Constructor<?> c = cls.getConstructors()[0];
    STGroup stg = new STGroupFile(f.getAbsolutePath());
    Object o = c.newInstance(stg);

    Set<String> methods = new HashSet<String>();
    methods.add("addPackage");
    methods.add("addBeanClass");
    methods.add("addTemplateName");
    methods.add("addAccessor");

    int count = 0;
    for (Method m : o.getClass().getMethods()) {
        if (methods.contains(m.getName())) {
            count++;
        }
    }
    assertEquals("Look for 8 generated methods", 8, count);
}

From source file:bear.main.JavaCompiler2.java

public List<File> compileScripts(File sourcesDir) {
    FileFilter filter = new SuffixFileFilter(extensions);

    final File[] files = sourcesDir.listFiles(filter);

    final ArrayList<String> params = newArrayListWithExpectedSize(files.length);

    if (!buildDir.exists()) {
        buildDir.mkdir();//from  w  ww. jav a 2s.com
    }

    Collections.addAll(params, "-d", buildDir.getAbsolutePath());
    List<File> javaFilesList = newArrayList(files);

    List<File> filesListToCompile = ImmutableList.copyOf(Iterables.filter(javaFilesList, new Predicate<File>() {
        @Override
        public boolean apply(File javaFile) {
            File classFile = new File(buildDir, FilenameUtils.getBaseName(javaFile.getName()) + ".class");

            boolean upToDate = classFile.exists() && classFile.lastModified() > javaFile.lastModified();

            if (upToDate) {
                logger.info("{} is up-to-date", javaFile);
            }

            return !upToDate;
        }
    }));

    if (filesListToCompile.isEmpty()) {
        logger.info("all files are up-to-date");
        return javaFilesList;
    }

    final List<String> filePaths = Lists.transform(filesListToCompile, new Function<File, String>() {
        public String apply(File input) {
            return input.getAbsolutePath();
        }
    });

    params.addAll(filePaths);

    logger.info("compiling {}", params);

    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();

    final int r = compiler.run(null, null, null, params.toArray(new String[params.size()]));

    if (r == 0) {
        logger.info("compilation OK.");
    } else {
        logger.info("compilation failed.");
    }

    return javaFilesList;
}

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,//from  www  . j av a2s  .c om
            compiler.run(System.in, System.out, System.err, carouselBannerPickerMixin.getAbsolutePath()));
}

From source file:de.icongmbh.oss.maven.plugin.javassist.JavassistTransformerExecutorTestBase.java

private void compileSourceFiles(File... sourceFiles) {
    // Compile source files
    JavaCompiler compiler = getSystemJavaCompiler();
    for (File sourceFile : sourceFiles) {
        assertThat(compiler.run(null, out, err, sourceFile.getPath()), is(0));
    }//  w  w  w.  ja va2 s. c  o m
}

From source file:com.seer.datacruncher.eventtrigger.DynamicJavaCompiler.java

public String compile(String srcFiles[]) {
    StringWriter err = new StringWriter();
    PrintWriter errPrinter = new PrintWriter(err);

    String args[] = buildJavacArgs(srcFiles);

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintStream ps = new PrintStream(baos);
    int resultCode = compiler.run(null, System.out, ps, args);
    errPrinter.close();//w  w  w. jav  a2  s.  c  o  m
    String errorMsg = baos.toString();
    if (StringUtils.isNotEmpty(errorMsg)) {
        String[] eMsg = errorMsg.split("error:");
        errorMsg = eMsg[1];
    }
    return (resultCode == 0) ? null : errorMsg;
}

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!");
    }//from  w w w.  ja  va2 s.  co m
    int resultCode = compiler.run(null, null, err, args);
    if (resultCode != 0) {
        throw new Exception(err.toString(RemotingHelper.DEFAULT_CHARSET));
    }
}