Search in sources :

Example 76 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon-compiler by ceylon.

the class CMRTests method compileJavaModule.

private void compileJavaModule(File jarOutputFolder, File classesOutputFolder, String moduleName, String moduleVersion, File sourceFolder, File[] extraClassPath, String... sourceFileNames) throws IOException {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    assertNotNull("Missing Java compiler, this test is probably being run with a JRE instead of a JDK!", javaCompiler);
    StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
    Set<String> sourceDirectories = new HashSet<String>();
    File[] javaSourceFiles = new File[sourceFileNames.length];
    for (int i = 0; i < javaSourceFiles.length; i++) {
        javaSourceFiles[i] = new File(sourceFolder, sourceFileNames[i]);
        String sfn = sourceFileNames[i].replace(File.separatorChar, '/');
        int p = sfn.lastIndexOf('/');
        String sourceDir = sfn.substring(0, p);
        sourceDirectories.add(sourceDir);
    }
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(javaSourceFiles);
    StringBuilder cp = new StringBuilder();
    for (int i = 0; i < extraClassPath.length; i++) {
        if (i > 0)
            cp.append(File.pathSeparator);
        cp.append(extraClassPath[i]);
    }
    CompilationTask task = javaCompiler.getTask(null, null, null, Arrays.asList("-d", classesOutputFolder.getPath(), "-cp", cp.toString(), "-sourcepath", sourceFolder.getPath()), null, compilationUnits);
    assertEquals(Boolean.TRUE, task.call());
    File jarFolder = new File(jarOutputFolder, moduleName.replace('.', File.separatorChar) + File.separatorChar + moduleVersion);
    jarFolder.mkdirs();
    File jarFile = new File(jarFolder, moduleName + "-" + moduleVersion + ".jar");
    // now jar it up
    JarOutputStream outputStream = new JarOutputStream(new FileOutputStream(jarFile));
    for (String sourceFileName : sourceFileNames) {
        String classFileName = sourceFileName.substring(0, sourceFileName.length() - 5) + ".class";
        ZipEntry entry = new ZipEntry(classFileName);
        outputStream.putNextEntry(entry);
        File classFile = new File(classesOutputFolder, classFileName);
        FileInputStream inputStream = new FileInputStream(classFile);
        Util.copy(inputStream, outputStream);
        inputStream.close();
        outputStream.flush();
    }
    outputStream.close();
    for (String sourceDir : sourceDirectories) {
        File module = null;
        String sourceName = "module.properties";
        File properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
        if (properties.exists()) {
            module = properties;
        } else {
            sourceName = "module.xml";
            properties = new File(sourceFolder, sourceDir + File.separator + sourceName);
            if (properties.exists()) {
                module = properties;
            }
        }
        if (module != null) {
            File moduleFile = new File(sourceFolder, sourceDir + File.separator + sourceName);
            FileInputStream inputStream = new FileInputStream(moduleFile);
            FileOutputStream moduleOutputStream = new FileOutputStream(new File(jarFolder, sourceName));
            Util.copy(inputStream, moduleOutputStream);
            inputStream.close();
            moduleOutputStream.flush();
            moduleOutputStream.close();
        }
    }
}
Also used : ZipEntry(java.util.zip.ZipEntry) JavaCompiler(javax.tools.JavaCompiler) JarOutputStream(java.util.jar.JarOutputStream) CompilationTask(javax.tools.JavaCompiler.CompilationTask) FileInputStream(java.io.FileInputStream) FileOutputStream(java.io.FileOutputStream) StandardJavaFileManager(javax.tools.StandardJavaFileManager) JarFile(java.util.jar.JarFile) ZipFile(java.util.zip.ZipFile) File(java.io.File) HashSet(java.util.HashSet)

Example 77 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon-compiler by ceylon.

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 78 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon-compiler by ceylon.

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 79 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project ceylon-compiler by ceylon.

the class EagerInterfaceCompletionTest 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) {
        e.printStackTrace();
        error("Internal compilation error");
    }
}
Also used : CompilationTask(javax.tools.JavaCompiler.CompilationTask)

Example 80 with CompilationTask

use of javax.tools.JavaCompiler.CompilationTask in project jOOQ by jOOQ.

the class Compile method compile.

static Class<?> compile(String className, String content, CompileOptions compileOptions) {
    Lookup lookup = MethodHandles.lookup();
    ClassLoader cl = lookup.lookupClass().getClassLoader();
    try {
        return cl.loadClass(className);
    } catch (ClassNotFoundException ignore) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        try {
            ClassFileManager fileManager = new ClassFileManager(compiler.getStandardFileManager(null, null, null));
            List<CharSequenceJavaFileObject> files = new ArrayList<>();
            files.add(new CharSequenceJavaFileObject(className, content));
            StringWriter out = new StringWriter();
            List<String> options = new ArrayList<>(compileOptions.options);
            if (!options.contains("-classpath")) {
                StringBuilder classpath = new StringBuilder();
                String separator = System.getProperty("path.separator");
                String cp = System.getProperty("java.class.path");
                String mp = System.getProperty("jdk.module.path");
                if (cp != null && !"".equals(cp))
                    classpath.append(cp);
                if (mp != null && !"".equals(mp))
                    classpath.append(mp);
                if (cl instanceof URLClassLoader) {
                    for (URL url : ((URLClassLoader) cl).getURLs()) {
                        if (classpath.length() > 0)
                            classpath.append(separator);
                        if ("file".equals(url.getProtocol()))
                            classpath.append(new File(url.toURI()));
                    }
                }
                options.addAll(Arrays.asList("-classpath", classpath.toString()));
            }
            CompilationTask task = compiler.getTask(out, fileManager, null, options, null, files);
            if (!compileOptions.processors.isEmpty())
                task.setProcessors(compileOptions.processors);
            task.call();
            if (fileManager.isEmpty())
                throw new ReflectException("Compilation error: " + out);
            Class<?> result = null;
            if (Reflect.CACHED_LOOKUP_CONSTRUCTOR != null) {
                result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> Reflect.on(cl).call("defineClass", name, bytes, 0, bytes.length).get());
            } else // Lookup.defineClass() has only been introduced in Java 9. It is
            // required to get private-access to interfaces in the class hierarchy
            {
                // This method is called by client code from two levels up the current stack frame
                // We need a private-access lookup from the class in that stack frame in order to get
                // private-access to any local interfaces at that location.
                Class<?> caller = StackWalker.getInstance(RETAIN_CLASS_REFERENCE).walk(s -> s.skip(2).findFirst().get().getDeclaringClass());
                // we can use the private-access Lookup of the caller class
                if (className.startsWith(caller.getPackageName() + ".") && // A better implementation is difficult at this point.
                Character.isUpperCase(className.charAt(caller.getPackageName().length() + 1))) {
                    Lookup privateLookup = MethodHandles.privateLookupIn(caller, lookup);
                    result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> privateLookup.defineClass(bytes));
                } else // Otherwise, use an arbitrary class loader. This approach doesn't allow for
                // loading private-access interfaces in the compiled class's type hierarchy
                {
                    ByteArrayClassLoader c = new ByteArrayClassLoader(fileManager.classes());
                    result = fileManager.loadAndReturnMainClass(className, (name, bytes) -> c.loadClass(name));
                }
            }
            return result;
        } catch (ReflectException e) {
            throw e;
        } catch (Exception e) {
            throw new ReflectException("Error while compiling " + className, e);
        }
    }
}
Also used : Arrays(java.util.Arrays) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JavaFileManager(javax.tools.JavaFileManager) URL(java.net.URL) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) FileObject(javax.tools.FileObject) ForwardingJavaFileManager(javax.tools.ForwardingJavaFileManager) Lookup(java.lang.invoke.MethodHandles.Lookup) URLClassLoader(java.net.URLClassLoader) Charset(java.nio.charset.Charset) CompilationTask(javax.tools.JavaCompiler.CompilationTask) Map(java.util.Map) URI(java.net.URI) OutputStream(java.io.OutputStream) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) RETAIN_CLASS_REFERENCE(java.lang.StackWalker.Option.RETAIN_CLASS_REFERENCE) JavaCompiler(javax.tools.JavaCompiler) StringWriter(java.io.StringWriter) MethodHandles(java.lang.invoke.MethodHandles) File(java.io.File) StandardCharsets(java.nio.charset.StandardCharsets) StandardJavaFileManager(javax.tools.StandardJavaFileManager) List(java.util.List) Entry(java.util.Map.Entry) ToolProvider(javax.tools.ToolProvider) JavaCompiler(javax.tools.JavaCompiler) URL(java.net.URL) CompilationTask(javax.tools.JavaCompiler.CompilationTask) StringWriter(java.io.StringWriter) URLClassLoader(java.net.URLClassLoader) URLClassLoader(java.net.URLClassLoader) Lookup(java.lang.invoke.MethodHandles.Lookup) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File)

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