Example usage for org.apache.maven.project MavenProject getCompileSourceRoots

List of usage examples for org.apache.maven.project MavenProject getCompileSourceRoots

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getCompileSourceRoots.

Prototype

public List<String> getCompileSourceRoots() 

Source Link

Usage

From source file:br.com.anteros.restdoc.maven.plugin.util.ResourceResolver.java

License:Apache License

@SuppressWarnings("unchecked")
private static List<String> resolveFromProject(final SourceResolverConfig config,
        final MavenProject reactorProject, final Artifact artifact) {
    final List<String> dirs = new ArrayList<String>();

    if (config.filter() == null || config.filter().include(artifact)) {
        if (config.includeCompileSources()) {
            final List<String> srcRoots = reactorProject.getCompileSourceRoots();
            for (final String root : srcRoots) {
                dirs.add(root);//  w w w.j a  v a2s. c om
            }
        }

        if (config.includeTestSources()) {
            final List<String> srcRoots = reactorProject.getTestCompileSourceRoots();
            for (final String root : srcRoots) {
                dirs.add(root);
            }
        }
    }

    return JavadocUtil.pruneDirs(reactorProject, dirs);
}

From source file:com.alibaba.citrus.maven.eclipse.base.eclipse.EclipsePlugin.java

License:Apache License

public final EclipseSourceDir[] buildDirectoryList(MavenProject project, File basedir,
        File buildOutputDirectory) throws MojoExecutionException {
    File projectBaseDir = project.getFile().getParentFile();

    String mainOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir, buildOutputDirectory, false);

    // If using the standard output location, don't mix the test output into it.
    String testOutput = null;/*  ww  w .j a v a2 s .  c om*/
    boolean useStandardOutputDir = buildOutputDirectory
            .equals(new File(project.getBuild().getOutputDirectory()));
    if (useStandardOutputDir) {
        getLog().debug("testOutput toRelativeAndFixSeparator " + projectBaseDir + " , "
                + project.getBuild().getTestOutputDirectory());
        testOutput = IdeUtils.toRelativeAndFixSeparator(projectBaseDir,
                new File(project.getBuild().getTestOutputDirectory()), false);
        getLog().debug("testOutput after toRelative : " + testOutput);
    }

    Set mainDirectories = new LinkedHashSet();

    extractSourceDirs(mainDirectories, project.getCompileSourceRoots(), basedir, projectBaseDir, false, null);

    extractResourceDirs(mainDirectories, project.getBuild().getResources(), basedir, projectBaseDir, false,
            mainOutput);

    Set testDirectories = new LinkedHashSet();

    extractSourceDirs(testDirectories, project.getTestCompileSourceRoots(), basedir, projectBaseDir, true,
            testOutput);

    extractResourceDirs(testDirectories, project.getBuild().getTestResources(), basedir, projectBaseDir, true,
            testOutput);

    // avoid duplicated entries
    Set directories = new LinkedHashSet();

    // NOTE: Since MNG-3118, test classes come before main classes
    boolean testBeforeMain = isMavenVersion("[2.0.8,)");

    // let users override this if needed, they need to simulate more than the test phase in eclipse
    if (testSourcesLast) {
        testBeforeMain = false;
    }

    if (testBeforeMain) {
        directories.addAll(testDirectories);
        directories.removeAll(mainDirectories);
        directories.addAll(mainDirectories);
    } else {
        directories.addAll(mainDirectories);
        directories.addAll(testDirectories);
    }
    if (ajdt) {
        extractAspectDirs(directories, project, basedir, projectBaseDir, testOutput);
    }
    return (EclipseSourceDir[]) directories.toArray(new EclipseSourceDir[directories.size()]);
}

From source file:com.carrotgarden.m2e.config.ConfigBuildParticipant.java

License:BSD License

/**
 * @see <a href=/*from w  w w .  j a v a 2  s.co  m*/
 *      "https://github.com/sonatype/sisu-build-api/tree/master/src/main/java/org/sonatype/plexus/build/incremental"
 *      />
 */
@Override
public Set<IProject> build(final int kind, final IProgressMonitor monitor) throws Exception {

    final BuildContext buildContext = getBuildContext();
    final MavenSession session = getSession();
    final MojoExecution execution = getMojoExecution();
    final MavenProject project = session.getCurrentProject();

    //

    log.info("### project : {}", project);
    log.info("### execution : {}", execution);
    log.info("### incremental : {}", buildContext.isIncremental());

    //

    final List<String> sourceRoots = project.getCompileSourceRoots();

    if (!MojoUtil.isValid(sourceRoots)) {
        log.warn("### not valid source roots");
        return NOOP;
    }

    int countSCR = 0;
    int countBND = 0;

    for (final String rootPath : sourceRoots) {

        if (!MojoUtil.isValid(rootPath)) {
            log.warn("### not valid root path");
            continue;
        }

        log.debug("### rootPath : {}", rootPath);

        final File rootDir = new File(rootPath);

        final Scanner scanner = buildContext.newScanner(rootDir);

        scanner.scan();

        final String[] includedFiles = scanner.getIncludedFiles();

        if (!MojoUtil.isValid(includedFiles)) {
            log.warn("### not valid included files");
            continue;
        }

        for (final String relativePath : includedFiles) {

            final File file = new File(rootDir, relativePath);

            log.debug("### file : {}", file);

            if (MojoUtil.isInterestSCR(file)) {
                countSCR++;
            }

            if (MojoUtil.isInterestBND(file)) {
                countBND++;
            }

        }

    }

    final MavenContext context = new MavenContext(session, execution);

    final boolean hasSCR = countSCR > 0 && MojoUtil.isMojoSCR(context);
    final boolean hasBND = countBND > 0 && MojoUtil.isMojoBND(context);

    if (hasSCR || hasBND) {

        final String key = context.getKey();

        // MavenJob job = (MavenJob) buildContext.getValue(key);
        MavenJob job = jobMap.get(key);

        if (job == null) {
            job = new MavenJob(context);
            // buildContext.setValue(key, job);
            jobMap.put(key, job);
        }

        job.schedule();

        log.info("### job scheduled");

    } else {

        log.warn("### no interesting files");

    }

    return NOOP;

}

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

@Override /* Play2Builder */
public boolean build() throws Play2BuildFailure, Play2BuildError/*Play2BuildException*/
{
    Set<String> changedFilePaths = null;
    Map<String, Long> prevChangedFiles = new HashMap<String, Long>();
    synchronized (changedFilesLock) {
        if (!changedFiles.isEmpty()) {
            changedFilePaths = changedFiles.keySet();
            prevChangedFiles = changedFiles;
            changedFiles = new HashMap<String, Long>();
        }//  ww  w .  jav  a  2  s .c  o m
        //TEST - more code inside synchronized block
    }

    if (!forceReloadNextTime && changedFilePaths == null /*&& afterFirstSuccessfulBuild*/ ) {
        return false;
    }

    List<MavenProject> projectsToBuild = projects;
    // - !afterFirstSuccessfulBuild => first build or no previous successful builds, build all modules
    // - currentSourceMaps.isEmpty() => first build, build all modules
    // - projects.size() == 1 => one-module project, just build it
    // - else => not the first build in multimodule-project, calculate modules subset to build
    if (afterFirstSuccessfulBuild
            /*!currentSourceMaps.isEmpty()*//*currentSourceMap != null*/ && projects.size() > 1) {
        projectsToBuild = calculateProjectsToBuild(changedFilePaths);
    }

    MavenExecutionRequest request = DefaultMavenExecutionRequest.copy(session.getRequest());
    request.setStartTime(new Date());
    request.setExecutionListener(new ExecutionEventLogger());
    request.setGoals(goals);

    MavenExecutionResult result = new DefaultMavenExecutionResult();

    MavenSession newSession = new MavenSession(container, session.getRepositorySession(), request, result);
    newSession.setProjects(projectsToBuild);
    newSession.setCurrentProject(session.getCurrentProject());
    newSession.setParallel(session.isParallel());
    newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

    lifecycleExecutor.execute(newSession);

    forceReloadNextTime = result.hasExceptions();

    if (!result.hasExceptions() && !additionalGoals.isEmpty()) {
        request = DefaultMavenExecutionRequest.copy(session.getRequest());
        request.setStartTime(new Date());
        request.setExecutionListener(new ExecutionEventLogger());
        request.setGoals(additionalGoals);

        result = new DefaultMavenExecutionResult();

        newSession = new MavenSession(container, session.getRepositorySession(), request, result);
        List<MavenProject> onlyMe = Arrays.asList(new MavenProject[] { session.getCurrentProject() });
        newSession.setProjects(onlyMe);
        newSession.setCurrentProject(session.getCurrentProject());
        newSession.setParallel(session.isParallel());
        newSession.setProjectDependencyGraph(session.getProjectDependencyGraph());

        lifecycleExecutor.execute(newSession);

        forceReloadNextTime = result.hasExceptions();
    }

    if (result.hasExceptions()) {
        synchronized (changedFilesLock) {
            changedFiles.putAll(prevChangedFiles); // restore previously changed paths, required for next rebuild
        }
        Throwable firstException = result.getExceptions().get(0);
        if (firstException.getCause() instanceof MojoFailureException) {
            MojoFailureException mfe = (MojoFailureException) firstException.getCause();
            Throwable mfeCause = mfe.getCause();
            if (mfeCause != null) {
                try {
                    Play2BuildException pbe = null;
                    String causeName = mfeCause.getClass().getName();

                    // sbt-compiler exception
                    if (CompilerException.class.getName().equals(causeName)) {
                        pbe = getSBTCompilerBuildException(mfeCause);
                    } else if (AssetCompilationException.class.getName().equals(causeName)
                            || RoutesCompilationException.class.getName().equals(causeName)
                            || TemplateCompilationException.class.getName().equals(causeName)) {
                        pbe = getPlayBuildException(mfeCause);
                    }

                    if (pbe != null) {
                        throw new Play2BuildFailure(pbe, sourceEncoding);
                    }
                    throw new Play2BuildError("Build failed without reporting any problem!"/*?, ce*/ );
                } catch (Play2BuildFailure e) {
                    throw e;
                } catch (Play2BuildError e) {
                    throw e;
                } catch (Exception e) {
                    throw new Play2BuildError(".... , check Maven console");
                }
            }
        }
        throw new Play2BuildError("The compilation task failed, check Maven console"/*?, firstException*/ );
    }

    // no exceptions
    if (!afterFirstSuccessfulBuild) // this was first successful build
    {
        afterFirstSuccessfulBuild = true;

        if (playWatchService != null) {
            // Monitor all existing, not generated (inside output directory) source and resource roots
            List<File> monitoredDirectories = new ArrayList<File>();
            for (MavenProject p : projects) {
                String targetDirectory = p.getBuild().getDirectory();
                for (String sourceRoot : p.getCompileSourceRoots()) {
                    if (!sourceRoot.startsWith(targetDirectory) && new File(sourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(sourceRoot));
                    }
                }
                for (Resource resource : p.getResources()) {
                    String resourceRoot = resource.getDirectory();
                    if (!resourceRoot.startsWith(targetDirectory) && new File(resourceRoot).isDirectory()) {
                        monitoredDirectories.add(new File(resourceRoot));
                    }
                }
            }
            //TODO - remove roots nested inside another roots (is it possible?)

            try {
                watcher = playWatchService.watch(monitoredDirectories, this);
            } catch (FileWatchException e) {
                logger.warn("File watcher initialization failed. Running without hot-reload functionality.", e);
            }
        }
    }

    Map<MavenProject, Map<String, File>> sourceMaps = new HashMap<MavenProject, Map<String, File>>(
            currentSourceMaps);
    for (MavenProject p : projectsToBuild) {
        Map<String, File> sourceMap = new HashMap<String, File>();
        File classesDirectory = new File(p.getBuild().getOutputDirectory());
        String classesDirectoryPath = classesDirectory.getAbsolutePath() + File.separator;
        File analysisCacheFile = defaultAnalysisCacheFile(p);
        Analysis analysis = sbtAnalysisProcessor.readFromFile(analysisCacheFile);
        for (File sourceFile : analysis.getSourceFiles()) {
            Set<File> sourceFileProducts = analysis.getProducts(sourceFile);
            for (File product : sourceFileProducts) {
                String absolutePath = product.getAbsolutePath();
                if (absolutePath.contains("$")) {
                    continue; // skip inner and object classes
                }
                String relativePath = absolutePath.substring(classesDirectoryPath.length());
                //                    String name = product.getName();
                String name = relativePath.substring(0, relativePath.length() - ".class".length());
                /*if (name.indexOf( '$' ) > 0)
                {
                name = name.substring( 0, name.indexOf( '$' ) );
                }*/
                name = name.replace(File.separator, ".");
                //System.out.println(sourceFile.getPath() + " -> " + name);
                sourceMap.put(name, sourceFile);
            }
            /*String[] definitionNames = analysis.getDefinitionNames( sourceFile );
            Set<String> uniqueDefinitionNames = new HashSet<String>(definitionNames.length);
            for (String definitionName: definitionNames)
            {
            if ( !uniqueDefinitionNames.contains( definitionName ) )
            {
                result.put( definitionName, sourceFile );
            //                        System.out.println( "definitionName:'" + definitionName + "', source:'"
            //                                        + sourceFile.getAbsolutePath() + "'" );
                uniqueDefinitionNames.add( definitionName );
            }
            }*/
        }
        sourceMaps.put(p, sourceMap);
    }
    this.currentSourceMaps = sourceMaps;

    boolean reloadRequired = false;
    for (MavenProject p : projectsToBuild) {
        long lastModifiedTime = 0L;
        Set<String> outputFilePaths = new HashSet<String>();
        File outputDirectory = new File(p.getBuild().getOutputDirectory());
        if (outputDirectory.exists() && outputDirectory.isDirectory()) {
            DirectoryScanner classPathScanner = new DirectoryScanner();
            classPathScanner.setBasedir(outputDirectory);
            classPathScanner.setExcludes(new String[] { assetsPrefix + "**" });
            classPathScanner.scan();
            String[] files = classPathScanner.getIncludedFiles();
            for (String fileName : files) {
                File f = new File(outputDirectory, fileName);
                outputFilePaths.add(f.getAbsolutePath());
                long lmf = f.lastModified();
                if (lmf > lastModifiedTime) {
                    lastModifiedTime = lmf;
                }
            }
        }
        if (!reloadRequired && (lastModifiedTime > currentClasspathTimestamps.get(p).longValue()
                || !outputFilePaths.equals(currentClasspathFilePaths.get(p)))) {
            reloadRequired = true;
        }
        currentClasspathTimestamps.put(p, Long.valueOf(lastModifiedTime));
        currentClasspathFilePaths.put(p, outputFilePaths);
    }

    return reloadRequired;
}

From source file:com.google.code.play2.plugin.MavenPlay2Builder.java

License:Apache License

private MavenProject findProjectFor(String filePath) {
    MavenProject result = null;/*from   w ww  .  j av a2 s. co  m*/
    search: for (MavenProject p : projects) {
        for (String sourceRoot : p.getCompileSourceRoots()) {
            if (filePath.startsWith(sourceRoot)) {
                result = p;
                break search;
            }
        }
        for (Resource resource : p.getResources()) {
            if (filePath.startsWith(resource.getDirectory())) {
                result = p;
                break search;
            }
        }
    }
    return result;
}

From source file:com.liferay.maven.plugins.AbstractToolsLiferayMojo.java

License:Open Source License

protected List<String> getProjectClassPath() throws Exception {
    List<String> projectClassPath = new ArrayList<String>();

    projectClassPath.addAll(getToolsClassPath());

    List<MavenProject> classPathMavenProjects = new ArrayList<MavenProject>();

    classPathMavenProjects.add(project);

    for (Object object : project.getDependencyArtifacts()) {
        Artifact artifact = (Artifact) object;

        ArtifactHandler artifactHandler = artifact.getArtifactHandler();

        if (!artifactHandler.isAddedToClasspath()) {
            continue;
        }//from   w w  w  .  ja v  a2s . com

        MavenProject dependencyMavenProject = resolveProject(artifact);

        if (dependencyMavenProject == null) {
            continue;
        } else {
            getLog().debug("Resolved dependency project " + dependencyMavenProject);
        }

        List<String> compileSourceRoots = dependencyMavenProject.getCompileSourceRoots();

        if (compileSourceRoots.isEmpty()) {
            continue;
        }

        getLog().debug("Adding project to class path " + dependencyMavenProject);

        classPathMavenProjects.add(dependencyMavenProject);
    }

    for (MavenProject classPathMavenProject : classPathMavenProjects) {
        for (Object object : classPathMavenProject.getCompileClasspathElements()) {

            String path = (String) object;

            getLog().debug("Class path element " + path);

            File file = new File(path);

            URI uri = file.toURI();

            URL url = uri.toURL();

            projectClassPath.add(url.toString());
        }
    }

    getLog().debug("Project class path:");

    for (String path : projectClassPath) {
        getLog().debug("\t" + path);
    }

    return projectClassPath;
}

From source file:com.mebigfatguy.fbp.FBPMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {

    if (executed) {
        return;//from  ww  w. j a v a 2  s  .  c  om
    }
    executed = true;

    try (PrintWriter pw = getFBPStream()) {

        pw.println("<Project projectName=\"" + project.getName() + "\">");

        List<MavenProject> projects = session.getProjectDependencyGraph().getSortedProjects();

        Set<String> jars = new TreeSet<>();
        for (MavenProject module : projects) {
            jars.add(module.getBuild().getOutputDirectory());
        }

        for (String jar : jars) {
            pw.println("\t<Jar>" + makeRelativePath(jar) + "</Jar>");
        }

        Set<Dependency> dependencies = new TreeSet<>(new DependencyComparator());
        for (MavenProject module : projects) {
            dependencies.addAll(module.getDependencies());
        }

        String localRepo = settings.getLocalRepository();
        if (!localRepo.endsWith("/") && !localRepo.endsWith("\\")) {
            localRepo += "/";
        }

        for (Dependency dependency : dependencies) {
            pw.println("\t<AuxClasspathEntry>" + localRepo + dependency.getGroupId().replace('.', '/') + "/"
                    + dependency.getArtifactId() + "/" + dependency.getVersion() + "/"
                    + dependency.getArtifactId() + "-" + dependency.getVersion() + "." + dependency.getType()
                    + "</AuxClasspathEntry>");
        }

        Set<String> srcRoots = new TreeSet<>();
        for (MavenProject module : projects) {
            srcRoots.addAll(module.getCompileSourceRoots());
        }

        for (String srcRoot : srcRoots) {
            pw.println("\t<SrcDir>" + makeRelativePath(srcRoot) + "</SrcDir>");
        }

        pw.println("</Project>");

    } catch (IOException e) {
        throw new MojoExecutionException("Failed to generate fbp file", e);
    }
}

From source file:com.napramirez.relief.maven.plugins.GenerateConfigurationMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    try {/*  w w w. j a  v a 2  s .  c o m*/
        JAXBContext jaxbContext = JAXBContext.newInstance(Configuration.class);
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);

        Configuration configuration = new Configuration();

        List<Project> projects = new ArrayList<Project>();
        for (MavenProject mavenProject : reactorProjects) {
            if (!MAVEN_PROJECT_PACKAGING_POM.equals(mavenProject.getPackaging())) {
                Project project = new Project();
                project.setName(mavenProject.getName());

                Jre jre = new Jre();
                String jrePath = System.getenv(ENV_VAR_JAVA_HOME);
                if (jrePath != null && !jrePath.trim().isEmpty()) {
                    jre.setPath(jrePath);
                }
                project.setJre(jre);

                project.setBuildDirectory(mavenProject.getBuild().getOutputDirectory());
                project.setSources(mavenProject.getCompileSourceRoots());

                Library library = new Library();
                library.setFullPath(mavenProject.getCompileClasspathElements());

                project.setLibrary(library);
                projects.add(project);
            }
        }

        configuration.setProjects(projects);

        if (!outputDirectory.exists() || !outputDirectory.isDirectory()) {
            if (!outputDirectory.mkdirs()) {
                throw new IOException("Failed to create directory " + outputDirectory.getAbsolutePath());
            }
        }

        File outputFile = new File(outputDirectory, outputFilename);

        marshaller.marshal(configuration, outputFile);

        getLog().info("Successfully generated configuration file " + outputFilename);
    } catch (JAXBException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (DependencyResolutionRequiredException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.tenderowls.opensource.haxemojos.components.HaxeCompiler.java

License:Apache License

public void compile(MavenProject project, Map<CompileTarget, String> targets, String main, boolean debug,
        boolean includeTestSources, ArtifactFilter artifactFilter, List<String> additionalArguments)
        throws Exception {
    List<String> args = new ArrayList<String>();

    for (String sourceRoot : project.getCompileSourceRoots()) {
        addSourcePath(args, sourceRoot);
    }/*from   w ww. j a v a 2s  .  co m*/

    if (includeTestSources) {
        for (String sourceRoot : project.getTestCompileSourceRoots()) {
            addSourcePath(args, sourceRoot);
        }
    }

    addLibs(args, project, artifactFilter);
    addHars(args, project, targets.keySet(), artifactFilter);
    addDebug(args, debug);

    if (main != null)
        addMain(args, main);

    if (additionalArguments != null)
        args.addAll(additionalArguments);

    for (CompileTarget target : targets.keySet()) {
        String output = targets.get(target);
        List<String> argsClone = new ArrayList<String>();
        argsClone.addAll(args);
        addTarget(argsClone, target);
        argsClone.add(output);

        CompilerLogger compilerLogger = new CompilerLogger(logger);
        int returnCode = haxe.execute(argsClone, compilerLogger);

        if (compilerLogger.getErrors().size() > 0) {
            logger.info("-------------------------------------------------------------");
            logger.error("COMPILATION ERROR :");
            logger.info("-------------------------------------------------------------");

            for (String error : compilerLogger.getErrors()) {
                logger.error(error);
            }

            throw new Exception("Compilation failure");
        } else if (returnCode > 0) {
            throw new Exception("Compilation failure");
        }
    }
}

From source file:com.tenderowls.opensource.haxemojos.components.HaxeCompiler.java

License:Apache License

private void addHars(List<String> argumentsList, MavenProject project, Set<CompileTarget> targets,
        ArtifactFilter artifactFilter) {
    Map<String, MavenProject> projectReferences = project.getProjectReferences();

    for (Artifact artifact : project.getArtifacts()) {
        boolean filtered = artifactFilter != null && !artifactFilter.include(artifact);

        if (!filtered && artifact.getType().equals(HaxeFileExtensions.HAR)) {
            String artifactKey = getProjectReferenceKey(artifact, ":");
            MavenProject reference = projectReferences.get(artifactKey);

            if (reference == null) {
                File harUnpackDirectory = new File(getDependenciesDirectory(),
                        getProjectReferenceKey(artifact, "-"));
                unpackHar(artifact, harUnpackDirectory);
                validateHarMetadata(targets, artifact,
                        new File(harUnpackDirectory, HarMetadata.METADATA_FILE_NAME));
                addSourcePath(argumentsList, harUnpackDirectory.getAbsolutePath());
            } else {
                String dirName = OutputNamesHelper.getHarValidationOutput(artifact);
                File validationDirectory = new File(reference.getBuild().getDirectory(), dirName);
                validateHarMetadata(targets, artifact,
                        new File(validationDirectory, HarMetadata.METADATA_FILE_NAME));

                for (String cp : reference.getCompileSourceRoots()) {
                    addSourcePath(argumentsList, cp);
                }/*from   w w  w.ja  va  2  s . c  om*/
            }
        }
    }
}