Search in sources :

Example 11 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project evosuite by EvoSuite.

the class JUnitAnalyzer method compileTests.

private static List<File> compileTests(List<TestCase> tests, File dir) {
    TestSuiteWriter suite = new TestSuiteWriter();
    suite.insertAllTests(tests);
    // to get name, remove all package before last '.'
    int beginIndex = Properties.TARGET_CLASS.lastIndexOf(".") + 1;
    String name = Properties.TARGET_CLASS.substring(beginIndex);
    // postfix
    name += "_" + (NUM++) + "_tmp_" + Properties.JUNIT_SUFFIX;
    try {
        // now generate the JUnit test case
        List<File> generated = suite.writeTestSuite(name, dir.getAbsolutePath(), Collections.EMPTY_LIST);
        for (File file : generated) {
            if (!file.exists()) {
                logger.error("Supposed to generate " + file + " but it does not exist");
                return null;
            }
        }
        // try to compile the test cases
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        if (compiler == null) {
            logger.error("No Java compiler is available");
            return null;
        }
        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
        Locale locale = Locale.getDefault();
        Charset charset = Charset.forName("UTF-8");
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, locale, charset);
        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromFiles(generated);
        List<String> optionList = new ArrayList<>();
        String evosuiteCP = ClassPathHandler.getInstance().getEvoSuiteClassPath();
        if (JarPathing.containsAPathingJar(evosuiteCP)) {
            evosuiteCP = JarPathing.expandPathingJars(evosuiteCP);
        }
        String targetProjectCP = ClassPathHandler.getInstance().getTargetProjectClasspath();
        if (JarPathing.containsAPathingJar(targetProjectCP)) {
            targetProjectCP = JarPathing.expandPathingJars(targetProjectCP);
        }
        String classpath = targetProjectCP + File.pathSeparator + evosuiteCP;
        optionList.addAll(Arrays.asList("-classpath", classpath));
        CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null, compilationUnits);
        boolean compiled = task.call();
        fileManager.close();
        if (!compiled) {
            logger.error("Compilation failed on compilation units: " + compilationUnits);
            logger.error("Classpath: " + classpath);
            // TODO remove
            logger.error("evosuiteCP: " + evosuiteCP);
            for (Diagnostic<?> diagnostic : diagnostics.getDiagnostics()) {
                if (diagnostic.getMessage(null).startsWith("error while writing")) {
                    logger.error("Error is due to file permissions, ignoring...");
                    return generated;
                }
                logger.error("Diagnostic: " + diagnostic.getMessage(null) + ": " + diagnostic.getLineNumber());
            }
            StringBuffer buffer = new StringBuffer();
            for (JavaFileObject sourceFile : compilationUnits) {
                List<String> lines = FileUtils.readLines(new File(sourceFile.toUri().getPath()));
                buffer.append(compilationUnits.iterator().next().toString() + "\n");
                for (int i = 0; i < lines.size(); i++) {
                    buffer.append((i + 1) + ": " + lines.get(i) + "\n");
                }
            }
            logger.error(buffer.toString());
            return null;
        }
        return generated;
    } catch (IOException e) {
        logger.error("" + e, e);
        return null;
    }
}
Also used : JavaCompiler(javax.tools.JavaCompiler) Charset(java.nio.charset.Charset) IOException(java.io.IOException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) JavaFileObject(javax.tools.JavaFileObject) TestSuiteWriter(org.evosuite.junit.writer.TestSuiteWriter) StandardJavaFileManager(javax.tools.StandardJavaFileManager) DiagnosticCollector(javax.tools.DiagnosticCollector) File(java.io.File)

Example 12 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class TestJavacTask_Multiple method test.

void test(JavaCompiler comp, StandardJavaFileManager fm, TestKind tk) {
    System.err.println("test " + tk);
    File testSrc = new File(System.getProperty("test.src"));
    String thisClassName = TestJavacTask_Multiple.class.getName();
    Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(new File(testSrc, thisClassName + ".java"));
    List<CompilationTask> tasks = new ArrayList<CompilationTask>();
    for (int i = 1; i <= MAX_TASKS; i++) {
        File tmpDir = new File(tk + "_" + i);
        tmpDir.mkdirs();
        List<String> options = Arrays.asList("-d", tmpDir.getPath());
        CompilationTask t = comp.getTask(null, fm, null, options, null, files);
        ((JavacTask) t).setTaskListener(createTaskListener(tk, i));
        tasks.add(t);
    }
    for (CompilationTask t : tasks) count += tk.test(t);
    System.err.println();
}
Also used : CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 13 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class T6956462 method main.

public static void main(String[] args) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    if (compiler == null) {
        throw new RuntimeException("can't get javax.tools.JavaCompiler!");
    }
    StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
    List<File> files = new ArrayList<File>();
    files.add(new File(T6956462.class.getResource("TestClass.java").toURI()));
    final CompilationTask task = compiler.getTask(null, fm, null, null, null, fm.getJavaFileObjectsFromFiles(files));
    JavacTask javacTask = (JavacTask) task;
    for (CompilationUnitTree cu : javacTask.parse()) {
        cu.accept(new MyVisitor(javacTask), null);
    }
}
Also used : CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 14 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class T6550655 method compile.

void compile(DiagnosticChecker dc, JavaSource... sources) {
    try {
        CompilationTask ct = javacTool.getTask(null, null, dc, Arrays.asList("-d", testDir.getAbsolutePath(), "-cp", testDir.getAbsolutePath()), null, Arrays.asList(sources));
        ct.call();
    } catch (Exception e) {
        error("Internal compilation error");
    }
}
Also used : CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 15 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon by eclipse.

the class Test method test.

void test(List<String> options, String expect) throws Exception {
    System.err.println("test: " + options);
    JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    JavaFileObject f = new MyFileObject("myfo://test", "class Bad { Missing x; }");
    List<? extends JavaFileObject> files = Arrays.asList(f);
    CompilationTask task = javac.getTask(pw, null, null, options, null, files);
    boolean ok = task.call();
    pw.close();
    String out = sw.toString();
    if (!out.isEmpty())
        System.err.println(out);
    if (ok)
        throw new Exception("Compilation succeeded unexpectedly");
    if (!out.contains(expect))
        throw new Exception("expected text not found: " + expect);
}
Also used : CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Aggregations

CompilationTask (javax.tools.JavaCompiler.CompilationTask)84 JavaCompiler (javax.tools.JavaCompiler)38 File (java.io.File)33 JavaFileObject (javax.tools.JavaFileObject)32 StandardJavaFileManager (javax.tools.StandardJavaFileManager)28 DiagnosticCollector (javax.tools.DiagnosticCollector)27 IOException (java.io.IOException)20 ArrayList (java.util.ArrayList)18 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)14 URLClassLoader (java.net.URLClassLoader)10 StringWriter (java.io.StringWriter)9 URL (java.net.URL)6 JavaFileManager (javax.tools.JavaFileManager)6 ByteArrayOutputStream (java.io.ByteArrayOutputStream)5 Test (org.junit.Test)5 OutputStream (java.io.OutputStream)4 PrintWriter (java.io.PrintWriter)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)4 FileInputStream (java.io.FileInputStream)3 FileOutputStream (java.io.FileOutputStream)3