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:cop.raml.processor.RestProcessor.java

private static void saveRamlToFile(@NotNull RestApi api, @NotNull String fileName) throws Exception {
    FileObject file = ThreadLocalContext.getProcessingEnv().getFiler()
            .createResource(StandardLocation.CLASS_OUTPUT, "", fileName);
    String template = Config.get().ramlVersion().getTemplate();

    try (OutputStreamWriter out = new OutputStreamWriter(file.openOutputStream(), StandardCharsets.UTF_8)) {
        assemble(out, api, template);/*from   w w w . j a  va  2s.  c o m*/
    }
}

From source file:org.apache.sqoop.integration.connectorloading.ClasspathTest.java

private Map<String, String> buildJar(String outputDir, Map<String, JarContents> sourceFileToJarMap)
        throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

    List<File> sourceFiles = new ArrayList<>();
    for (JarContents jarContents : sourceFileToJarMap.values()) {
        sourceFiles.addAll(jarContents.sourceFiles);
    }//w ww .  j a  v a 2  s  . c  o m

    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(new File(outputDir.toString())));

    Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(sourceFiles);

    boolean compiled = compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();
    if (!compiled) {
        throw new RuntimeException("failed to compile");
    }

    for (Map.Entry<String, JarContents> jarNameAndContents : sourceFileToJarMap.entrySet()) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        manifest.getMainAttributes().put(Attributes.Name.CLASS_PATH, ".");

        JarOutputStream target = new JarOutputStream(
                new FileOutputStream(outputDir.toString() + File.separator + jarNameAndContents.getKey()),
                manifest);
        List<String> classesForJar = new ArrayList<>();
        for (File sourceFile : jarNameAndContents.getValue().getSourceFiles()) {
            //split the file on dot to get the filename from FILENAME.java
            String fileName = sourceFile.getName().split("\\.")[0];
            classesForJar.add(fileName);
        }

        File dir = new File(outputDir);
        File[] directoryListing = dir.listFiles();
        for (File compiledClass : directoryListing) {
            String classFileName = compiledClass.getName().split("\\$")[0].split("\\.")[0];
            if (classesForJar.contains(classFileName)) {
                addFileToJar(compiledClass, target);
            }
        }

        for (File propertiesFile : jarNameAndContents.getValue().getProperitesFiles()) {
            addFileToJar(propertiesFile, target);
        }

        target.close();

    }
    //delete non jar files
    File dir = new File(outputDir);
    File[] directoryListing = dir.listFiles();
    for (File file : directoryListing) {
        String extension = file.getName().split("\\.")[1];
        if (!extension.equals("jar")) {
            file.delete();
        }
    }

    Map<String, String> jarMap = new HashMap<>();
    jarMap.put(TEST_CONNECTOR_JAR_NAME, outputDir.toString() + File.separator + TEST_CONNECTOR_JAR_NAME);
    jarMap.put(TEST_DEPENDENCY_JAR_NAME, outputDir.toString() + File.separator + TEST_DEPENDENCY_JAR_NAME);
    return jarMap;
}

From source file:org.openmrs.logic.CompilingClassLoader.java

private String compile(String javaFile) throws IOException {
    String errorMessage = null;/*from  www . jav a 2s  . co m*/
    String ruleClassDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_CLASS_FOLDER);
    String ruleJavaDir = Context.getAdministrationService()
            .getGlobalProperty(LogicConstants.RULE_DEFAULT_SOURCE_FOLDER);
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    log.info("JavaCompiler is null: " + compiler == null);
    if (compiler != null) {
        // java compiler only available on JDK. This part of "IF" will not get executed when we run JUnit test
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] options = {};
        DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();
        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnosticCollector,
                Context.getLocale(), Charset.defaultCharset());
        fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(outputFolder));
        // create compiling classpath
        String stringProperties = System.getProperty("java.class.path");
        if (log.isDebugEnabled())
            log.debug("Compiler classpath: " + stringProperties);
        String[] properties = StringUtils.split(stringProperties, File.pathSeparator);
        List<File> classpathFiles = new ArrayList<File>();
        for (String property : properties) {
            File f = new File(property);
            if (f.exists())
                classpathFiles.add(f);
        }
        classpathFiles.addAll(getCompilerClasspath());
        fileManager.setLocation(StandardLocation.CLASS_PATH, classpathFiles);
        // create the compilation task
        CompilationTask compilationTask = compiler.getTask(null, fileManager, diagnosticCollector,
                Arrays.asList(options), null, fileManager.getJavaFileObjects(javaFile));
        boolean success = compilationTask.call();
        fileManager.close();
        if (success) {
            return null;
        } else {
            errorMessage = "";
            for (Diagnostic<?> diagnostic : diagnosticCollector.getDiagnostics()) {
                errorMessage += diagnostic.getLineNumber() + ": " + diagnostic.getMessage(Context.getLocale())
                        + "\n";
            }
            return errorMessage;
        }
    } else {
        File outputFolder = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleClassDir);
        String[] commands = { "javac", "-classpath", System.getProperty("java.class.path"), "-d",
                outputFolder.getAbsolutePath(), javaFile };
        // Start up the compiler
        File workingDirectory = OpenmrsUtil.getDirectoryInApplicationDataDirectory(ruleJavaDir);
        boolean success = LogicUtil.executeCommand(commands, workingDirectory);
        return success ? null : "Compilation error. (You must be using the JDK to see details.)";
    }
}

From source file:rita.compiler.CompileString.java

/**
 * El mtodo compile crea el archivo compilado a partir de un codigo fuente
 * y lo deja en un directorio determinado
 * /*from  w w w .  j  a  v a2 s . co m*/
 * @param sourceCode
 *            el codigo fuente
 * @param className
 *            el nombre que debera llevar la clase
 * @param packageName
 *            nombre del paquete
 * @param outputDirectory
 *            directorio donde dejar el archivo compilado
 * */
public static final Collection<File> compile(File sourceCode, File outputDirectory) throws Exception {
    diagnostics = new ArrayList<Diagnostic<? extends JavaFileObject>>();
    JavaCompiler compiler = new EclipseCompiler();

    System.out.println(sourceCode);

    DiagnosticListener<JavaFileObject> listener = new DiagnosticListener<JavaFileObject>() {
        @Override
        public void report(Diagnostic<? extends JavaFileObject> diagnostic) {
            if (diagnostic.getKind().equals(javax.tools.Diagnostic.Kind.ERROR)) {
                System.err.println("=======================ERROR==========================");
                System.err.println("Tipo: " + diagnostic.getKind());
                System.err.println("mensaje: " + diagnostic.getMessage(Locale.ENGLISH));
                System.err.println("linea: " + diagnostic.getLineNumber());
                System.err.println("columna: " + diagnostic.getColumnNumber());
                System.err.println("CODE: " + diagnostic.getCode());
                System.err.println(
                        "posicion: de " + diagnostic.getStartPosition() + " a " + diagnostic.getEndPosition());
                System.err.println(diagnostic.getSource());
                diagnostics.add(diagnostic);
            }
        }

    };

    StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);
    /* guardar los .class y  directorios (packages) en un directorio separado; de esta manera
     * si se genera mas de 1 clase (porque p.ej. hay inner classes en el codigo) podemos identificar
     * a todas las clases resultantes de esta compilacion
     */
    File tempOutput = createTempDirectory();
    fileManager.setLocation(StandardLocation.CLASS_OUTPUT, Arrays.asList(tempOutput));
    Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects(sourceCode);
    try {
        if (compiler.getTask(null, fileManager, listener, null, null, compilationUnits).call()) {
            // copiar .class y  directorios (packages) generados por el compilador en tempOutput al directorio final
            FileUtils.copyDirectory(tempOutput, outputDirectory);
            // a partir de los paths de los archivos .class generados en el dir temp, modificarlos para que sean relativos a outputDirectory
            Collection<File> compilationResults = new ArrayList<File>();
            final int tempPrefix = tempOutput.getAbsolutePath().length();
            for (File classFile : FileUtils.listFiles(tempOutput, new SuffixFileFilter(".class"),
                    TrueFileFilter.INSTANCE)) {
                compilationResults
                        .add(new File(outputDirectory, classFile.getAbsolutePath().substring(tempPrefix)));
            }
            // retornar los paths de todos los .class generados
            return compilationResults;
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Error al realizar el compilado");
    } finally {
        FileUtils.deleteDirectory(tempOutput);
        fileManager.close();
    }
    return null;
}

From source file:therian.buildweaver.StandardOperatorsProcessor.java

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    try {/*from   w w w.java  2 s .co  m*/
        final FileObject resource = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT,
                StringUtils.substringBeforeLast(TARGET_CLASSNAME, ".").replace('.', '/'),
                StringUtils.substringAfterLast(TARGET_CLASSNAME, ".") + ".class");

        if (resource.getLastModified() > 0L) {
            processingEnv.getMessager().printMessage(Kind.NOTE,
                    String.format("%s already generated", TARGET_CLASSNAME));
            return false;
        }
    } catch (IOException e1) {
        // expected, swallow
    }
    try {
        ClassUtils.getClass(TARGET_CLASSNAME);
        processingEnv.getMessager().printMessage(Kind.ERROR,
                String.format("%s exists on classpath", TARGET_CLASSNAME));
        return false;
    } catch (ClassNotFoundException e) {
        // expected, swallow
    }

    if (roundEnv.processingOver()) {
        write();
        return true;
    }
    for (TypeElement ann : annotations) {
        final Set<? extends Element> standardOperatorElements = roundEnv.getElementsAnnotatedWith(ann);
        originatingElements.addAll(standardOperatorElements);

        for (Element element : standardOperatorElements) {
            Validate.validState(isValidStandardOperator(element), "%s is not a valid @StandardOperator",
                    appendTo(new StringBuilder(), element).toString());

            if (element.getKind() == ElementKind.CLASS) {
                operators.add(appendTo(new StringBuilder("new "), element).append("()").toString());
            }
            if (element.getKind() == ElementKind.METHOD) {
                operators.add(appendTo(new StringBuilder(), element).append("()").toString());
            }
            if (element.getKind() == ElementKind.FIELD) {
                operators.add(appendTo(new StringBuilder(), element).toString());
            }
        }
    }
    return true;
}

From source file:uniol.apt.compiler.AbstractServiceProcessor.java

/**
 * Function that writes a resource list into the class output directory.
 * Existing entries are preserved. This means that this function only ever adds new entries.
 * @param resourceName Name of the file in which the resource list should be saved.
 * @param entries Entries that should be added to the list.
 * @throws IOException In case I/O errors occur.
 *///from w  ww . ja  va  2s  .co m
protected void writeResourceList(String resourceName, Collection<String> entries) throws IOException {
    entries = new TreeSet<>(entries);

    // read already listed services
    try {
        FileObject fo = this.filer.getResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
        try (InputStream is = fo.openInputStream()) {
            LineIterator lIter = IOUtils.lineIterator(is, "UTF-8");
            while (lIter.hasNext()) {
                String entry = lIter.next();
                entries.add(entry);
            }
        }
    } catch (IOException ex) {
        /* It's ok if the resource can't get found; we only skip reading it */
    }

    // write new list
    FileObject fo = this.filer.createResource(StandardLocation.CLASS_OUTPUT, "", resourceName);
    Writer writer = fo.openWriter();
    for (String entry : entries) {
        writer.append(entry + "\n");
    }
    writer.close();
}