Example usage for javax.tools StandardLocation CLASS_OUTPUT

List of usage examples for javax.tools StandardLocation CLASS_OUTPUT

Introduction

In this page you can find the example usage for javax.tools StandardLocation CLASS_OUTPUT.

Prototype

StandardLocation CLASS_OUTPUT

To view the source code for javax.tools StandardLocation CLASS_OUTPUT.

Click Source Link

Document

Location of new class files.

Usage

From source file:io.fabric8.kubernetes.generator.processor.AbstractKubernetesAnnotationProcessor.java

KubernetesResource readJson(String fileName) {
    try {/*from  ww w  .  ja  v  a  2  s  .  c  o m*/
        FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
                (fileName == null ? KUBERNETES_JSON : fileName));
        try (Reader reader = fileObject.openReader(false)) {
            return MAPPER.readValue(reader, KubernetesResource.class);
        }
    } catch (IOException e) {
        processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, fileName + " JSON not found.");
    }
    return null;
}

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);
            }//from  w w w  . j  a v a  2 s  . c om
        } 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:io.fabric8.kubernetes.generator.processor.AbstractKubernetesAnnotationProcessor.java

private FileObject getFileObject(String fileName) throws IOException {
    FileObject fileObject = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    Path path = Paths.get(fileObject.toUri());
    File file = path.toFile();//  www.j  a  v a  2  s  .c  o  m
    if (file.exists() && !file.delete()) {
        throw new IOException("Failed to delete old kubernetes json file: " + fileName);
    }
    fileObject = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    return fileObject;
}

From source file:name.martingeisse.webide.features.java.compiler.memfile.MemoryFileManager.java

@Override
public FileObject getFileForOutput(final Location location, final String packageName, final String relativeName,
        final FileObject sibling) throws IOException {
    final String loggingName = "output file; location [" + location + "], package [" + packageName + "], name ["
            + relativeName + "], sibling [" + sibling + "]";
    if (location == StandardLocation.CLASS_OUTPUT) {
        logger.trace("searching memory files: " + loggingName);
        final String key = getPackageFileName(packageName, relativeName);
        IMemoryFileObject file = outputFiles.get(key);
        if (file == null) {
            logger.trace("key [" + key + "] not found, creating");
            file = new MemoryBlobFileObject(key);
            outputFiles.put(key, file);/*w ww. j  a  v  a  2s .  c  om*/
        } else {
            logger.trace("key [" + key + "] found");
        }
        return file;
    } else {
        logger.trace("skipping memory files for " + loggingName);
    }
    return super.getFileForOutput(location, packageName, relativeName, sibling);
}

From source file:org.cloudfoundry.practical.demo.web.controller.CompilerController.java

private boolean compile(Folders folders, Writer out) throws IOException {
    JavaFileManager standardFileManager = this.compiler.getStandardFileManager(null, null, null);
    ResourceJavaFileManager fileManager = new ResourceJavaFileManager(standardFileManager);
    fileManager.setLocation(StandardLocation.SOURCE_PATH, folders.getSource());
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, folders.getOutput());
    fileManager.setLocation(StandardLocation.CLASS_PATH, folders.getLibJars());
    Iterable<? extends JavaFileObject> units = fileManager.list(StandardLocation.SOURCE_PATH, "",
            EnumSet.of(Kind.SOURCE), true);
    CompilationTask task = this.compiler.getTask(out, fileManager, null, COMPILER_OPTIONS, null, units);
    return task.call();
}

From source file:com.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(final Project project) {
    try {//from w  ww.  ja v a  2s  .  com
        copyRuntimeServiceFiles(project.getWebAppRootFolder(), project.getClassOutputFolder());
        JavaCompiler compiler = new WaveMakerJavaCompiler();
        StandardJavaFileManager standardFileManager = compiler.getStandardFileManager(null, null, null);
        standardFileManager.setLocation(StandardLocation.CLASS_PATH, getStandardClassPath());
        ResourceJavaFileManager projectFileManager = new ResourceJavaFileManager(standardFileManager);
        projectFileManager.setLocation(StandardLocation.SOURCE_PATH, project.getSourceFolders());
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT,
                Collections.singleton(project.getClassOutputFolder()));
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, getClasspath(project));
        copyResources(project);
        Iterable<JavaFileObject> compilationUnits = projectFileManager.list(StandardLocation.SOURCE_PATH, "",
                Collections.singleton(Kind.SOURCE), true);
        StringWriter compilerOutput = new StringWriter();
        CompilationTask compilationTask = compiler.getTask(compilerOutput, projectFileManager, null,
                getCompilerOptions(project), null, compilationUnits);
        ServiceDefProcessor serviceDefProcessor = configure(new ServiceDefProcessor(), projectFileManager);
        ServiceConfigurationProcessor serviceConfigurationProcessor = configure(
                new ServiceConfigurationProcessor(), projectFileManager);
        compilationTask.setProcessors(Arrays.asList(serviceConfigurationProcessor, serviceDefProcessor));
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Unable to compile " + project.getProjectName(), e);
    }
}

From source file:org.cloudfoundry.tools.compiler.CloudFoundryJavaCompiler.java

@Override
@SuppressWarnings("unchecked")
public CompilationTask getTask(Writer out, JavaFileManager fileManager,
        DiagnosticListener<? super JavaFileObject> diagnosticListener, Iterable<String> options,
        Iterable<String> classes, Iterable<? extends JavaFileObject> compilationUnits) {

    if (fileManager == null) {
        fileManager = this.getStandardFileManager(diagnosticListener, null, null);
    }/*from w  w  w  . ja  v a 2 s.  c o  m*/

    PrintWriter writer = createPrintWriter(out);

    EclipseBatchCompiler batchCompiler = new EclipseBatchCompiler(writer, writer, false);

    batchCompiler.options.put(CompilerOptions.OPTION_Compliance, CompilerOptions.VERSION_1_6);
    batchCompiler.options.put(CompilerOptions.OPTION_Source, CompilerOptions.VERSION_1_6);
    batchCompiler.options.put(CompilerOptions.OPTION_TargetPlatform, CompilerOptions.VERSION_1_6);
    batchCompiler.diagnosticListener = diagnosticListener;
    batchCompiler.fileManager = fileManager;
    batchCompiler.setCompilationUnits(compilationUnits);

    if (options != null) {
        for (Iterator<String> iterator = options.iterator(); iterator.hasNext();) {
            batchCompiler.fileManager.handleOption(iterator.next(), iterator);
        }
    }
    batchCompiler.configure(getArgumentsForBatchCompiler(asList(options), asList(classes)));
    if (fileManager instanceof StandardJavaFileManager) {
        Iterable<? extends File> location = ((StandardJavaFileManager) fileManager)
                .getLocation(StandardLocation.CLASS_OUTPUT);
        if (location != null) {
            batchCompiler.setDestinationPath(location.iterator().next().getAbsolutePath());
        }
    }

    return new CompilationTaskImpl(batchCompiler);
}

From source file:com.predic8.membrane.annot.SpringConfigurationXSDGeneratingAnnotationProcessor.java

@SuppressWarnings("unchecked")
private void read() {
    if (cache != null)
        return;//ww w  .  j  av  a2  s  .co  m

    cache = new HashMap<Class<? extends Annotation>, HashSet<Element>>();

    try {
        FileObject o = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
                "META-INF/membrane.cache");
        BufferedReader r = new BufferedReader(o.openReader(false));
        try {
            if (!CACHE_FILE_FORMAT_VERSION.equals(r.readLine()))
                return;
            HashSet<Element> currentSet = null;
            Class<? extends Annotation> annotationClass = null;
            while (true) {
                String line = r.readLine();
                if (line == null)
                    break;
                if (line.startsWith(" ")) {
                    line = line.substring(1);
                    TypeElement element = null;
                    try {
                        element = processingEnv.getElementUtils().getTypeElement(line);
                    } catch (RuntimeException e) {
                        // do nothing (Eclipse)
                    }
                    if (element != null) {
                        if (element.getAnnotation(annotationClass) != null)
                            currentSet.add(element);
                    }
                } else {
                    try {
                        annotationClass = (Class<? extends Annotation>) getClass().getClassLoader()
                                .loadClass(line);
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                    currentSet = new HashSet<Element>();
                    cache.put(annotationClass, currentSet);
                }
            }
        } finally {
            r.close();
        }
    } catch (FileNotFoundException e) {
        // do nothing (Maven)
    } catch (IOException e) {
        // do nothing (Eclipse)
    }

    for (Set<Element> e : cache.values()) {
        String status = "read " + e.size();
        log(status);
    }

}

From source file:net.minecrell.quartz.mappings.processor.MappingsGeneratorProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (roundEnv.processingOver()) {
        return false;
    }//w  w w  .  jav  a 2 s.c om

    List<TypeElement> mappingClasses = new ArrayList<>();

    for (Element element : roundEnv.getElementsAnnotatedWith(Mapping.class)) {
        if (element instanceof TypeElement) {
            mappingClasses.add((TypeElement) element);
        }
    }

    if (mappingClasses.isEmpty()) {
        return true;
    }

    try {
        FileObject file = this.processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "",
                "mappings.json");

        Map<String, MappedClass> mappings;
        try (Reader reader = file.openReader(false)) {
            mappings = Mappings.read(reader);
        } catch (IOException ignored) {
            mappings = new HashMap<>();
        }

        ClassMapper classMappings = createMapper(mappingClasses);

        // We need to remap the descriptors of the fields and methods, use ASM for convenience
        Remapper unmapper = classMappings.createUnmapper();

        for (TypeElement mappingClass : mappingClasses) {
            String internalName = getInternalName(mappingClass);

            Mapping annotation = mappingClass.getAnnotation(Mapping.class);
            String mappedName = annotation.value();
            if (mappedName.isEmpty()) {
                mappedName = internalName;
            }

            MappedClass mapping = new MappedClass(mappedName);

            Accessible accessible = mappingClass.getAnnotation(Accessible.class);
            if (accessible != null) {
                mapping.getAccess().put("", parseAccessible(accessible));
            }

            for (Element element : mappingClass.getEnclosedElements()) {
                accessible = element.getAnnotation(Accessible.class);

                Constructor constructor = element.getAnnotation(Constructor.class);
                if (constructor != null) {
                    if (accessible != null) {
                        String constructorDesc = getDescriptor((ExecutableElement) element);

                        mapping.getAccess().put("<init>" + constructorDesc, parseAccessible(accessible));
                    }
                    continue;
                }

                annotation = element.getAnnotation(Mapping.class);
                if (annotation == null) {
                    continue;
                }

                mappedName = annotation.value();
                checkArgument(!mappedName.isEmpty(), "Mapping detection is not supported yet");

                switch (element.getKind()) {
                case METHOD:
                    ExecutableElement method = (ExecutableElement) element;
                    String methodName = method.getSimpleName().toString();
                    String methodDesc = getDescriptor(method);
                    mapping.getMethods().put(mappedName + unmapper.mapMethodDesc(methodDesc), methodName);

                    if (accessible != null) {
                        mapping.getAccess().put(methodName + methodDesc, parseAccessible(accessible));
                    }

                    break;
                case FIELD:
                case ENUM_CONSTANT:
                    VariableElement field = (VariableElement) element;
                    String fieldName = field.getSimpleName().toString();
                    mapping.getFields().put(mappedName + ':' + unmapper.mapDesc(getDescriptor(field)),
                            fieldName);

                    if (accessible != null) {
                        mapping.getAccess().put(fieldName, parseAccessible(accessible));
                    }

                    break;
                default:
                }
            }

            mappings.put(internalName, mapping);
        }

        // Generate JSON output
        file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "mappings.json");
        try (Writer writer = file.openWriter()) {
            Mappings.write(writer, mappings);
        }

        return true;
    } catch (IOException e) {
        this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getStackTrace(e));
        throw new RuntimeException("Failed to create mappings.json", e);
    }
}

From source file:android.databinding.tool.util.GenerationalClassUtil.java

public static void writeIntermediateFile(ProcessingEnvironment processingEnv, String packageName,
        String fileName, Serializable object) {
    ObjectOutputStream oos = null;
    try {/*from www .j  ava  2  s  .com*/
        FileObject intermediate = processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT,
                packageName, fileName);
        OutputStream ios = intermediate.openOutputStream();
        oos = new ObjectOutputStream(ios);
        oos.writeObject(object);
        oos.close();
        L.d("wrote intermediate bindable file %s %s", packageName, fileName);
    } catch (IOException e) {
        L.e(e, "Could not write to intermediate file: %s", fileName);
    } finally {
        IOUtils.closeQuietly(oos);
    }
}