Example usage for javax.tools ToolProvider getSystemJavaCompiler

List of usage examples for javax.tools ToolProvider getSystemJavaCompiler

Introduction

In this page you can find the example usage for javax.tools ToolProvider getSystemJavaCompiler.

Prototype

public static JavaCompiler getSystemJavaCompiler() 

Source Link

Document

Returns the Java™ programming language compiler provided with this platform.

Usage

From source file:adalid.util.meta.MetaJavaCompiler.java

public static void compile() {
    String dp1 = System.getProperties().getProperty("user.dir");
    String sep = System.getProperties().getProperty("file.separator");
    File src = new File(dp1 + sep + "src");
    File trg = new File(dp1 + sep + "bin");
    boolean dir = trg.isDirectory() || trg.mkdirs();
    List<File> files = getJavaFiles(src);
    // Get the java compiler provided with this platform
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    // Get the writer for the compiler output
    StringWriter out = new StringWriter();
    // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics
    DiagnosticListener<JavaFileObject> diagnosticListener1 = null; // new DiagnosticCollector<JavaFileObject>();
    // Get the locale to apply when formatting diagnostics; null means the default locale
    Locale locale = null;//w  w w.  j a  v  a  2 s.com
    // Get the character set used for decoding bytes; if null use the platform default
    Charset charset = null;
    // Get an instance of the standard file manager implementation
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticListener1, locale, charset);
    // Get the diagnostic listener for non-fatal diagnostics; if null use the compiler's default method for reporting diagnostics
    DiagnosticListener<JavaFileObject> diagnosticListener2 = null; // new DiagnosticCollector<JavaFileObject>();
    // Get the list of compiler options, null means no options
    List<String> options = Arrays
            .asList(new String[] { "-g", "-source", "1.7", "-Xlint:unchecked", "-d", trg.getAbsolutePath() });
    // Get the list of class names (for annotation processing), null means no class names
    List<String> classes = null;
    // Get the list of java file objects to compile
    Iterable<? extends JavaFileObject> units = fileManager.getJavaFileObjectsFromFiles(files);
    // Create the compilation task
    CompilationTask task = compiler.getTask(out, fileManager, diagnosticListener2, options, classes, units);
    // Perform the compilation task
    // task.call(); // java.lang.NullPointerException at com.sun.tools.javac.api.JavacTaskImpl.parse(JavacTaskImpl.java:228)
    if (task instanceof JavacTask) {
        javacTask(task);
    }
}

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();//from   w  w  w. j a va 2s .  co  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.joliciel.talismane.utils.compiler.DynamicCompiler.java

public DynamicCompiler(ClassLoader classLoader, DiagnosticListener<JavaFileObject> diagnosticListener) {
    this.javaCompiler = ToolProvider.getSystemJavaCompiler();
    this.diagonosticListener = diagnosticListener;
    JavaFileManager standardFileManager = javaCompiler.getStandardFileManager(diagnosticListener, null, null);
    this.inMemoryClassLoader = new InMemoryClassLoader(classLoader);
    this.inMemoryFileManager = new InMemoryFileManager(standardFileManager, inMemoryClassLoader);
}

From source file:com.jhash.oimadmin.Utils.java

public static DiagnosticCollector<JavaFileObject> compileJava(String className, String code,
        String outputFileLocation) {
    logger.trace("Entering compileJava({},{},{})", new Object[] { className, code, outputFileLocation });
    File outputFileDirectory = new File(outputFileLocation);
    logger.trace("Validating if the output location {} exists and is a directory", outputFileLocation);
    if (outputFileDirectory.exists()) {
        if (outputFileDirectory.isDirectory()) {
            try {
                logger.trace("Deleting the directory and its content");
                FileUtils.deleteDirectory(outputFileDirectory);
            } catch (IOException exception) {
                throw new OIMAdminException(
                        "Failed to delete directory " + outputFileLocation + " and its content", exception);
            }/*  w ww  .jav a  2s. co  m*/
        } else {
            throw new InvalidParameterException(
                    "The location " + outputFileLocation + " was expected to be a directory but it is a file.");
        }
    }
    logger.trace("Creating destination directory for compiled class file");
    outputFileDirectory.mkdirs();

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new NullPointerException(
                "Failed to locate a java compiler. Please ensure that application is being run using JDK (Java Development Kit) and NOT JRE (Java Runtime Environment) ");
    }
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<File> files = Arrays.asList(new File(outputFileLocation));
    boolean success = false;
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    try {
        JavaFileObject javaFileObject = new InMemoryJavaFileObject(className, code);
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, files);

        JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics,
                Arrays.asList("-source", "1.6", "-target", "1.6"), null, Arrays.asList(javaFileObject));
        success = task.call();
        fileManager.close();
    } catch (Exception exception) {
        throw new OIMAdminException("Failed to compile " + className, exception);
    }

    if (!success) {
        logger.trace("Exiting compileJava(): Return Value {}", diagnostics);
        return diagnostics;
    } else {
        logger.trace("Exiting compileJava(): Return Value null");
        return null;
    }
}

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();/*from  w w w  .ja  v  a 2  s  .  co  m*/
    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:gruifo.output.jsni.BaseJsTest.java

private boolean compile(final String file) {
    final File fileToCompile = getJavaSourceFile(file);
    final JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("No compiler installed", compiler);
    final List<String> options = new ArrayList<>();
    options.add("-source");
    options.add("1.6");
    options.add("-Xlint:-options");
    options.add("-classpath");
    options.add(getClass().getProtectionDomain().getCodeSource().getLocation().getFile());
    final StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    final JavaCompiler.CompilationTask task = compiler.getTask(/*default System.err*/ null,
            /*std file manager*/ null, /*std DiagnosticListener */ null, /*compiler options*/ options,
            /*no annotation*/ null, fileManager.getJavaFileObjects(fileToCompile));
    return task.call();
}

From source file:net.morematerials.manager.HandlerManager.java

public HandlerManager(MoreMaterials plugin) {
    this.plugin = plugin;

    File folder = new File(plugin.getDataFolder(), "handlers");

    // We can only compile if the JDK is found.
    if (ToolProvider.getSystemJavaCompiler() != null) {
        this.prepareCompiler(new File(folder, "bin"));
        for (File file : (new File(folder, "src")).listFiles()) {
            if (file.getName().endsWith(".java")) {
                try {
                    this.compile(file);
                } catch (Exception exception) {
                    this.plugin.getUtilsManager().log("Error compiling handler: " + file.getName(),
                            Level.WARNING);
                }//ww  w . jav  a 2s . co m
            }
        }
    } else {
        this.plugin.getUtilsManager()
                .log("Server not using Java JDK environment, custom handlers will not function.", Level.INFO);
        this.plugin.getUtilsManager()
                .log("Ignore this error if your not trying to use your own custom handlers.", Level.INFO);
    }

    for (File file : (new File(folder, "bin")).listFiles()) {
        if (file.getName().endsWith(".class") && file.getName().indexOf("$") == -1) {
            this.load(file);
        }
    }
}

From source file:de.xirp.ate.ATEManager.java

/**
 * Compiles the given Java {@link java.io.File} to the
 * corresponding byte code class files./*from  w w w  . j  a  v  a 2  s  .com*/
 * 
 * @param javaFile
 *            The file containing the Java code.
 */
public static void compile(File javaFile) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(Collections.singletonList(javaFile));
    compiler.getTask(new PrintWriter(System.out), fileManager, null, null, null, compilationUnits).call();

    try {
        fileManager.close();
    } catch (IOException e) {
        logClass.error("Error: " + e.getMessage() //$NON-NLS-1$
                + Constants.LINE_SEPARATOR, e);
    }
}

From source file:com.github.aliakhtar.annoTest.util.Compiler.java

private boolean compile(Processor processor, SourceFile... sourceFiles) throws Exception {
    Builder<String> builder = ImmutableList.builder();
    builder.add("-classpath").add(buildClassPath(outputDir));
    builder.add("-d").add(outputDir.getAbsolutePath());

    for (Map.Entry<String, String> entry : parameterMap.entrySet()) {
        builder.add("-A" + entry.getKey() + "=" + entry.getValue());
    }//www  .  j ava2  s.  c  o m

    File[] files = new File[sourceFiles.length];
    for (int i = 0; i < sourceFiles.length; i++) {
        files[i] = writeSourceFile(sourceFiles[i]);
    }

    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(files);
    CompilationTask compilationTask = compiler.getTask(null, null, null, builder.build(), null,
            javaFileObjects);
    if (processor != null)
        compilationTask.setProcessors(Arrays.asList(processor));

    Boolean success = compilationTask.call();
    fileManager.close();
    return success;
}

From source file:gool.parser.java.JavaParser.java

/**
 * Parsing concrete Java into abstract GOOL is done in three steps. - We
 * call Sun's java parser to produce abstract Java; - We visit abstract Java
 * with the JavaRecognizer to produce abstract GOOL; - We annotate the
 * abstract GOOL so that it carries the Target language.
 * //w  ww.j a v a  2 s  .c  om
 * @param defaultPlatform
 *            : specifies the Target language of the code generation that
 *            will later be applied to the abstract GOOL, once this Java
 *            parsing is performed.
 * @param compilationUnits
 *            : An Iterable of JavaFileObject, which are Sun's java parser's
 *            representation of the files to be parsed.
 * @param dependencies
 *            : specifies imported libraries
 * @param visitor
 *            : this is the class that transforms Sun's abstract java, into
 *            abstract GOOL, i.e. the JavaRecognizer.
 * @return a list of classdefs, i.e. of abstract GOOL classes.
 * @throws Exception
 */

public static Collection<ClassDef> parseGool(Platform defaultPlatform,
        Iterable<? extends JavaFileObject> compilationUnits, List<File> dependencies, JavaRecognizer visitor)
        throws Exception {
    if (visitor == null) {
        throw new IllegalArgumentException("The gool visitor is null.");
    }

    /**
     * concreteJavaToConcretePlatform We will now setup the options to Sun's
     * java compiler This requires working out the dependencies
     */
    // convert dependencies into a list of file paths to reach them
    List<String> stringDependencies = new ArrayList<String>();
    if (dependencies != null && !dependencies.isEmpty()) {
        for (File file : dependencies) {
            stringDependencies.add(file.getAbsolutePath());
        }
    }
    // further, add the GOOL library as a dependency
    // so that the program can use gool.imports.java
    stringDependencies.add(Settings.get("gool_library").toString());

    // with the dependencies all set, we can make up the options
    List<String> options = Arrays.asList("-classpath",
            StringUtils.join(stringDependencies, File.pathSeparator));

    /**
     * We now parse using Sun's java compiler
     */
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    JavacTask task = (JavacTask) compiler.getTask(null, null, null, options, null, compilationUnits);
    Iterable<? extends CompilationUnitTree> asts = task.parse();
    visitor.setTypes(task.getTypes());
    /**
     * We now analyze using Sun's java compiler so as to get a Java abstract
     * type tree.
     */
    task.analyze();
    Trees typetrees = Trees.instance(task);

    /**
     * We now prepare the JavaRecognizer for conversion of abstract Java to
     * abstract GOOL.
     */

    // The visitor needs to know what the Target language is
    // Because it will annotate the abstract GOOL with this information.
    visitor.setDefaultPlatform(defaultPlatform);
    GoolGeneratorController.setCodeGenerator(defaultPlatform.getCodePrinter().getCodeGenerator());

    // The visitor might need Sun's analyzed Java abstract type tree.
    visitor.setTrees(typetrees);

    /**
     * We launch the JavaRecognizer against each abstract Java AST
     */
    for (CompilationUnitTree ast : asts) {
        visitor.setCurrentCompilationUnit(ast);
        visitor.scan();
    }

    /**
     * Register each abstract GOOL class, so that they can see each other
     * and therefore represent valid types
     */
    for (ClassDef classDef : visitor.getGoolClasses()) {
        classDef.getPlatform().registerCustomDependency(classDef.toString(), classDef);
    }

    return visitor.getGoolClasses();
}