Example usage for javax.tools StandardJavaFileManager setLocation

List of usage examples for javax.tools StandardJavaFileManager setLocation

Introduction

In this page you can find the example usage for javax.tools StandardJavaFileManager setLocation.

Prototype

void setLocation(Location location, Iterable<? extends File> files) throws IOException;

Source Link

Document

Associates the given search path with the given location.

Usage

From source file:org.glowroot.common2.repo.util.Compilations.java

public static Class<?> compile(String source) throws Exception {
    JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnosticCollector = new DiagnosticCollector<JavaFileObject>();

    IsolatedClassLoader isolatedClassLoader = new IsolatedClassLoader();

    StandardJavaFileManager standardFileManager = javaCompiler.getStandardFileManager(diagnosticCollector,
            Locale.ENGLISH, UTF_8);
    standardFileManager.setLocation(StandardLocation.CLASS_PATH, getCompilationClassPath());
    JavaFileManager fileManager = new IsolatedJavaFileManager(standardFileManager, isolatedClassLoader);
    try {/* ww  w .  j a v a 2 s .  c om*/
        List<JavaFileObject> compilationUnits = Lists.newArrayList();

        String className = getPublicClassName(source);
        int index = className.lastIndexOf('.');
        String simpleName;
        if (index == -1) {
            simpleName = className;
        } else {
            simpleName = className.substring(index + 1);
        }
        compilationUnits.add(new SourceJavaFileObject(simpleName, source));

        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, diagnosticCollector, null,
                null, compilationUnits);
        task.call();

        List<Diagnostic<? extends JavaFileObject>> diagnostics = diagnosticCollector.getDiagnostics();
        if (!diagnostics.isEmpty()) {
            List<String> compilationErrors = Lists.newArrayList();
            for (Diagnostic<? extends JavaFileObject> diagnostic : diagnostics) {
                compilationErrors.add(checkNotNull(diagnostic.toString()));
            }
            throw new CompilationException(compilationErrors);
        }
        if (className.isEmpty()) {
            throw new CompilationException(ImmutableList.of("Class must be public"));
        }
        return isolatedClassLoader.loadClass(className);
    } finally {
        fileManager.close();
    }
}

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   www  . j a va2s . 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:com.wavemaker.tools.compiler.ProjectCompiler.java

public String compile(Folder webAppRootFolder, Iterable<Folder> sources, Folder destination,
        Iterable<Resource> classpath) {
    try {//from   w w w  .j a  va2s  .c  o  m
        if (webAppRootFolder != null) {
            copyRuntimeServiceFiles(webAppRootFolder, destination);
        }
        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, sources);
        ArrayList<Folder> destinations = new ArrayList<Folder>();
        destinations.add(destination);
        projectFileManager.setLocation(StandardLocation.CLASS_OUTPUT, destinations);
        projectFileManager.setLocation(StandardLocation.CLASS_PATH, classpath);
        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(), null, compilationUnits);
        if (!compilationTask.call()) {
            throw new WMRuntimeException("Compile failed with output:\n\n" + compilerOutput.toString());
        }
        return compilerOutput.toString();
    } catch (IOException e) {
        throw new WMRuntimeException("Compile error: " + e);
    }
}

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

public String compile(final Project project) {
    try {//from   w  w  w  .jav  a 2  s . c  o m
        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.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);
    }//from w  ww. j a v a  2 s . com

    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.j  a va  2s .c  om*/
    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
 * // ww  w .jav  a 2 s. c o  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;
}