Example usage for javax.tools JavaCompiler getTask

List of usage examples for javax.tools JavaCompiler getTask

Introduction

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

Prototype

CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options,
        Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits);

Source Link

Document

Creates a future for a compilation task with the given components and arguments.

Usage

From source file:Main.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> dc = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager sjfm = compiler.getStandardFileManager(dc, null, null);
    Iterable<? extends JavaFileObject> fileObjects = sjfm.getJavaFileObjects(args);
    compiler.getTask(null, sjfm, dc, null, null, fileObjects).call();
    for (Diagnostic d : dc.getDiagnostics()) {
        System.out.println(d.getMessage(null));
        System.out.printf("Line number = %d\n", d.getLineNumber());
        System.out.printf("File = %s\n", d.getSource());
    }/*from w ww  .  ja v  a 2  s  . c  o  m*/
}

From source file:CompileFiles2.java

public static void main(String[] args) {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> dc;
    dc = new DiagnosticCollector<JavaFileObject>();

    StandardJavaFileManager sjfm;
    sjfm = compiler.getStandardFileManager(dc, null, null);

    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = sjfm.getJavaFileObjects(args);

    compiler.getTask(null, sjfm, dc, null, null, fileObjects).call();

    for (Diagnostic d : dc.getDiagnostics()) {
        System.out.println(d.getMessage(null));
        System.out.printf("Line number = %d\n", d.getLineNumber());
        System.out.printf("File = %s\n", d.getSource());
    }//ww w . j  a  v  a 2 s. c  om
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String sourceFile = "c:/HelloWorld.Java";
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(sourceFileList);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    boolean result = task.call();
    if (result) {
        System.out.println("Compilation was successful");
    } else {//www.j a va 2  s .c om
        System.out.println("Compilation failed");
    }
    fileManager.close();
}

From source file:CompileString.java

public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    String program = "class Test{" + "   public static void main (String [] args){"
            + "      System.out.println (\"Hello, World\");" + "      System.out.println (args.length);"
            + "   }" + "}";

    Iterable<? extends JavaFileObject> fileObjects;
    fileObjects = getJavaSourceFromString(program);

    compiler.getTask(null, null, null, null, null, fileObjects).call();

    Class<?> clazz = Class.forName("Test");
    Method m = clazz.getMethod("main", new Class[] { String[].class });
    Object[] _args = new Object[] { new String[0] };
    m.invoke(null, _args);// ww  w  .  j  a v a 2 s  . c o  m
}

From source file:DiagnosticCollectorCompile.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromStrings(Arrays.asList("Foo.java"));
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, null, null,
            compilationUnits);/*ww w.ja v  a  2s.c o m*/
    boolean success = task.call();
    fileManager.close();
    System.out.println("Success: " + success);
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    String sourceFile = "c:/HelloWorld.Java";
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFileList = new ArrayList<File>();
    sourceFileList.add(new File(sourceFile));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromFiles(sourceFileList);
    CompilationTask task = compiler.getTask(null, fileManager, null, null, null, compilationUnits);
    task.call();//w  w w  . ja v  a 2 s.c  o m
    fileManager.close();
    List<Diagnostic<? extends JavaFileObject>> diagnosticList = diagnostics.getDiagnostics();
    for (Diagnostic<? extends JavaFileObject> diagnostic : diagnosticList) {
        System.out.println("Position:" + diagnostic.getStartPosition());
    }
}

From source file:Main.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
    Iterable<? extends JavaFileObject> compilationUnits = fileManager
            .getJavaFileObjectsFromStrings(Arrays.asList("YourFile.java"));
    Iterable<String> options = Arrays.asList("-d", "classes", "-sourcepath", "src");
    JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, options, null,
            compilationUnits);//  ww  w  .j  a v  a 2  s .co  m

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));
    }
    fileManager.close();
    System.out.println("Success: " + success);
}

From source file:CompileSourceInMemory.java

public static void main(String args[]) throws IOException {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();

    StringWriter writer = new StringWriter();
    PrintWriter out = new PrintWriter(writer);
    out.println("public class HelloWorld {");
    out.println("  public static void main(String args[]) {");
    out.println("    System.out.println(\"This is in another java file\");");
    out.println("  }");
    out.println("}");
    out.close();/*from  w  w w  .  j  ava  2s  .c om*/
    JavaFileObject file = new JavaSourceFromString("HelloWorld", writer.toString());

    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);

    boolean success = task.call();
    for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
        System.out.println(diagnostic.getCode());
        System.out.println(diagnostic.getKind());
        System.out.println(diagnostic.getPosition());
        System.out.println(diagnostic.getStartPosition());
        System.out.println(diagnostic.getEndPosition());
        System.out.println(diagnostic.getSource());
        System.out.println(diagnostic.getMessage(null));

    }
    System.out.println("Success: " + success);

    if (success) {
        try {
            Class.forName("HelloWorld").getDeclaredMethod("main", new Class[] { String[].class }).invoke(null,
                    new Object[] { null });
        } catch (ClassNotFoundException e) {
            System.err.println("Class not found: " + e);
        } catch (NoSuchMethodException e) {
            System.err.println("No such method: " + e);
        } catch (IllegalAccessException e) {
            System.err.println("Illegal access: " + e);
        } catch (InvocationTargetException e) {
            System.err.println("Invocation target: " + e);
        }
    }
}

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 w w  . j ava2  s.  co  m
 * @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();
}

From source file:com.asakusafw.compiler.bootstrap.OperatorCompilerDriver.java

/**
 * ??/*  ww  w . j a v a2  s . c  o m*/
 * @param sourcePath 
 * @param outputPath ?
 * @param encoding 
 * @param operatorClasses ?
 * @throws IOException ???????
 * @throws IllegalArgumentException ?{@code null}????
 */
public static void compile(File sourcePath, File outputPath, Charset encoding, List<Class<?>> operatorClasses)
        throws IOException {
    if (sourcePath == null) {
        throw new IllegalArgumentException("sourcePath must not be null"); //$NON-NLS-1$
    }
    if (outputPath == null) {
        throw new IllegalArgumentException("outputPath must not be null"); //$NON-NLS-1$
    }
    if (encoding == null) {
        throw new IllegalArgumentException("encoding must not be null"); //$NON-NLS-1$
    }
    if (operatorClasses == null) {
        throw new IllegalArgumentException("operatorClasses must not be null"); //$NON-NLS-1$
    }

    // ??JSR-199?????
    List<File> sourceFiles = toSources(sourcePath, operatorClasses);
    LOG.info(MessageFormat.format("Compiling {0}", sourceFiles));
    List<String> arguments = toArguments(sourcePath, outputPath, encoding);
    LOG.debug("Compiler arguments {}", arguments); //$NON-NLS-1$
    if (outputPath.isDirectory() == false && outputPath.mkdirs() == false) {
        throw new IOException(MessageFormat.format("Failed to create {0}", outputPath));
    }
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new IOException("Failed to create a compiler");
    }
    StandardJavaFileManager files = compiler.getStandardFileManager(null, null, encoding);
    try {
        CompilationTask task = compiler.getTask(null, files, null, arguments, Collections.<String>emptyList(),
                files.getJavaFileObjectsFromFiles(sourceFiles));
        if (task.call() == false) {
            LOG.error("Compilation Failed");
        }
    } finally {
        files.close();
    }
    LOG.info("Completed");
}