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:org.sonatype.flexmojos.asdoc.AsDocMojo.java

License:Apache License

@SuppressWarnings("unchecked")
protected void setUp() throws MojoExecutionException, MojoFailureException {
    if (sourcePaths == null) {
        List<MavenProject> projects;
        if (aggregate) {
            projects = new ArrayList<MavenProject>();
            for (MavenProject project : this.reactorProjects) {
                // filter flex projects
                if (SWF.equals(project.getPackaging()) || SWC.equals(project.getPackaging())
                        || AIR.equals(project.getPackaging())) {
                    projects.add(project);
                }/*w ww. ja  va2 s  .com*/
            }
        } else {
            projects = Arrays.asList(project);
        }

        List<File> sources = new ArrayList<File>();
        for (MavenProject project : projects) {
            List<String> sourceRoots = project.getCompileSourceRoots();
            for (String sourceRoot : sourceRoots) {
                File source = new File(sourceRoot);
                if (source.exists()) {
                    sources.add(source);
                }
            }
        }

        sourcePaths = sources.toArray(new File[sources.size()]);
    }
    if (docSources == null && docClasses == null && docNamespaces == null) {
        getLog().warn("Nothing expecified to include.  Assuming source paths.");
        docSources = sourcePaths;
    }

    libraries = new ArrayList<File>();
    for (Artifact artifact : getDependencyArtifacts()) {
        if (SWC.equals(artifact.getType())) {
            libraries.add(artifact.getFile());
        }
    }

    if (outputDirectory != null) {
        outputDirectory.mkdirs();
    }

    if (configFile == null) {
        List<Resource> resources = build.getResources();
        for (Resource resource : resources) {
            File cfg = new File(resource.getDirectory(), "config.xml");
            if (cfg.exists()) {
                configFile = cfg;
                break;
            }
        }
    }

    if (fontsSnapshot == null) {
        URL url;
        if (MavenUtils.isMac()) {
            url = getClass().getResource("/fonts/macFonts.ser");
        } else {
            // And linux?!
            // if(os.contains("windows")) {
            url = getClass().getResource("/fonts/winFonts.ser");
        }
        File fontsSer = new File(build.getDirectory(), "fonts.ser");
        try {
            FileUtils.copyURLToFile(url, fontsSer);
        } catch (IOException e) {
            throw new MojoExecutionException("Error creating fonts.ser");
        }
        fontsSnapshot = fontsSer;
    }

    if (templatesPath == null) {
        templatesPath = generateDefaultTemplate();
    }

    FDKConfigResolver sdkConfigResolver = new FDKConfigResolver(getDependencyArtifacts(), build,
            getCompilerVersion());
    List<Namespace> fdkNamespaces = sdkConfigResolver.getNamespaces();
    // we must merge user custom namespaces and default SDK namespaces, because we not use compiler API ?
    // https://bugs.adobe.com/jira/browse/SDK-15405
    if (fdkNamespaces != null) {
        if (namespaces != null) {
            fdkNamespaces.addAll(Arrays.asList(namespaces));
        }
        namespaces = fdkNamespaces.toArray(new Namespace[fdkNamespaces.size()]);
    }
}

From source file:org.wisdom.maven.utils.MavenUtils.java

License:Apache License

/**
 * Gets the default set of properties for the given project.
 *
 * @param currentProject the project/*from ww  w  .ja  va2 s .co m*/
 * @return the set of properties, containing default bundle packaging instructions.
 */
public static Properties getDefaultProperties(MavenProject currentProject) {
    Properties properties = new Properties();
    String bsn = DefaultMaven2OsgiConverter.getBundleSymbolicName(currentProject.getArtifact());

    // Setup defaults
    properties.put(MAVEN_SYMBOLICNAME, bsn);
    properties.put("bundle.file.name",
            DefaultMaven2OsgiConverter.getBundleFileName(currentProject.getArtifact()));
    properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn);
    properties.put(Analyzer.IMPORT_PACKAGE, "*");
    properties.put(Analyzer.BUNDLE_VERSION, DefaultMaven2OsgiConverter.getVersion(currentProject.getVersion()));

    header(properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription());
    StringBuilder licenseText = printLicenses(currentProject.getLicenses());
    if (licenseText != null) {
        header(properties, Analyzer.BUNDLE_LICENSE, licenseText);
    }
    header(properties, Analyzer.BUNDLE_NAME, currentProject.getName());

    if (currentProject.getOrganization() != null) {
        if (currentProject.getOrganization().getName() != null) {
            String organizationName = currentProject.getOrganization().getName();
            header(properties, Analyzer.BUNDLE_VENDOR, organizationName);
            properties.put("project.organization.name", organizationName);
            properties.put("pom.organization.name", organizationName);
        }
        if (currentProject.getOrganization().getUrl() != null) {
            String organizationUrl = currentProject.getOrganization().getUrl();
            header(properties, Analyzer.BUNDLE_DOCURL, organizationUrl);
            properties.put("project.organization.url", organizationUrl);
            properties.put("pom.organization.url", organizationUrl);
        }
    }

    properties.putAll(currentProject.getModel().getProperties());

    for (String s : currentProject.getFilters()) {
        File filterFile = new File(s);
        if (filterFile.isFile()) {
            properties.putAll(PropertyUtils.loadProperties(filterFile));
        }
    }

    properties.putAll(getProperties(currentProject.getModel(), "project.build."));
    properties.putAll(getProperties(currentProject.getModel(), "pom."));
    properties.putAll(getProperties(currentProject.getModel(), "project."));

    properties.put("project.baseDir", currentProject.getBasedir().getAbsolutePath());
    properties.put("project.build.directory", currentProject.getBuild().getDirectory());
    properties.put("project.build.outputdirectory", currentProject.getBuild().getOutputDirectory());

    properties.put("project.source.roots", getArray(currentProject.getCompileSourceRoots()));
    properties.put("project.testSource.roots", getArray(currentProject.getTestCompileSourceRoots()));

    properties.put("project.resources", toString(currentProject.getResources()));
    properties.put("project.testResources", toString(currentProject.getTestResources()));

    return properties;
}

From source file:plugin.MyMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    for (Iterator it = reactorProjects.iterator(); it.hasNext();) {
        MavenProject project = (MavenProject) it.next();

        String basedir = project.getBasedir().getAbsolutePath();
        List compileSourceRoots = project.getCompileSourceRoots();

        System.out.println(//w w  w  .  j a v a  2s . c o m
                " Compile-source roots for project: " + project + " are: " + project.getCompileSourceRoots());
        for (Iterator srcIt = compileSourceRoots.iterator(); srcIt.hasNext();) {
            String srcRoot = (String) srcIt.next();

            if (!srcRoot.startsWith(basedir)) {
                throw new MojoExecutionException(
                        "Source root: " + srcRoot + " doesn't begin with project basedir: " + basedir);
            }
        }
    }
}

From source file:se.jguru.nazgul.tools.codestyle.enforcer.rules.CorrectPackagingRule.java

License:Apache License

/**
 * Delegate method, implemented by concrete subclasses.
 *
 * @param project The active MavenProject.
 * @param helper  The EnforcerRuleHelper instance, from which the MavenProject has been retrieved.
 * @throws RuleFailureException If the enforcer rule was not satisfied.
 */// w  w  w.  j a  v  a  2 s. c  o  m
@Override
@SuppressWarnings("unchecked")
protected void performValidation(final MavenProject project, final EnforcerRuleHelper helper)
        throws RuleFailureException {

    // Find all java source files, and map their packages to their names.
    final List<String> compileSourceRoots = (List<String>) project.getCompileSourceRoots();
    if (compileSourceRoots.size() == 0) {
        return;
    }

    final SortedMap<String, SortedSet<String>> packageName2SourceFileNameMap = new TreeMap<String, SortedSet<String>>();

    for (String current : compileSourceRoots) {
        addPackages(new File(current), packageName2SourceFileNameMap);
    }

    // Retrieve the groupId of this project
    final String groupId = project.getGroupId();
    if (groupId == null || groupId.equals("")) {

        // Don't accept empty groupIds
        throw new RuleFailureException("Maven groupId cannot be null or empty.", project.getArtifact());

    } else {

        // Correct packaging everywhere?
        final SortedSet<String> incorrectPackages = new TreeSet<String>();
        for (Map.Entry<String, SortedSet<String>> currentPackage : packageName2SourceFileNameMap.entrySet()) {

            final String candidate = currentPackage.getKey();
            if (!candidate.startsWith(groupId)) {
                incorrectPackages.add(candidate);
            }
        }

        if (incorrectPackages.size() > 0) {

            final SortedMap<String, SortedSet<String>> result = new TreeMap<String, SortedSet<String>>();
            for (String current : incorrectPackages) {
                result.put(current, packageName2SourceFileNameMap.get(current));
            }

            throw new RuleFailureException("Incorrect packaging detected; required [" + groupId
                    + "] but found package to file names: " + result, project.getArtifact());
        }
    }
}

From source file:se.jguru.nazgul.tools.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

License:Apache License

public CheckstyleResults executeCheckstyle(CheckstyleExecutorRequest request)
        throws CheckstyleExecutorException, CheckstyleException {

    // Checkstyle will always use the context classloader in order
    // to load resources (dtds), so we have to fix it
    // olamy this hack is not anymore needed in Maven 3.x
    ClassLoader checkstyleClassLoader = PackageNamesLoader.class.getClassLoader();
    Thread.currentThread().setContextClassLoader(checkstyleClassLoader);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("executeCheckstyle start headerLocation : " + request.getHeaderLocation());
    }/*from   w ww.  ja  v a 2 s .  c o  m*/

    MavenProject project = request.getProject();

    configureResourceLocator(locator, request, null);

    configureResourceLocator(licenseLocator, request, request.getLicenseArtifacts());

    // Config is less critical than License, locator can still be used.
    // configureResourceLocator( configurationLocator, request, request.getConfigurationArtifacts() );

    List<File> files;
    try {
        files = getFilesToProcess(request);
    } catch (IOException e) {
        throw new CheckstyleExecutorException("Error getting files to process", e);
    }

    final String suppressionsFilePath = getSuppressionsFilePath(request);
    FilterSet filterSet = getSuppressionsFilterSet(suppressionsFilePath);

    Checker checker = new Checker();

    // setup classloader, needed to avoid "Unable to get class information for ..." errors
    List<String> classPathStrings = new ArrayList<>();
    List<String> outputDirectories = new ArrayList<>();

    // stand-alone
    Collection<File> sourceDirectories = null;
    Collection<File> testSourceDirectories = request.getTestSourceDirectories();

    // aggregator
    Map<MavenProject, Collection<File>> sourceDirectoriesByProject = new HashMap<>();
    Map<MavenProject, Collection<File>> testSourceDirectoriesByProject = new HashMap<>();

    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = new ArrayList<>(childProject.getCompileSourceRoots().size());
            List<String> compileSourceRoots = childProject.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }
            sourceDirectoriesByProject.put(childProject, sourceDirectories);

            testSourceDirectories = new ArrayList<>(childProject.getTestCompileSourceRoots().size());
            List<String> testCompileSourceRoots = childProject.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }
            testSourceDirectoriesByProject.put(childProject, testSourceDirectories);

            prepareCheckstylePaths(request, childProject, classPathStrings, outputDirectories,
                    sourceDirectories, testSourceDirectories);
        }
    } else {
        sourceDirectories = request.getSourceDirectories();
        prepareCheckstylePaths(request, project, classPathStrings, outputDirectories, sourceDirectories,
                testSourceDirectories);
    }

    final List<URL> urls = new ArrayList<>(classPathStrings.size());

    for (String path : classPathStrings) {
        try {
            urls.add(new File(path).toURL());
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    for (String outputDirectoryString : outputDirectories) {
        try {
            if (outputDirectoryString != null) {
                File outputDirectoryFile = new File(outputDirectoryString);
                if (outputDirectoryFile.exists()) {
                    URL outputDirectoryUrl = outputDirectoryFile.toURL();
                    getLogger().debug("Adding the outputDirectory " + outputDirectoryUrl.toString()
                            + " to the Checkstyle class path");
                    urls.add(outputDirectoryUrl);
                }
            }
        } catch (MalformedURLException e) {
            throw new CheckstyleExecutorException(e.getMessage(), e);
        }
    }

    URLClassLoader projectClassLoader = AccessController.doPrivileged(new PrivilegedAction<URLClassLoader>() {
        public URLClassLoader run() {
            return new URLClassLoader(urls.toArray(new URL[urls.size()]), null);
        }
    });

    checker.setClassLoader(projectClassLoader);

    checker.setModuleClassLoader(Thread.currentThread().getContextClassLoader());

    if (filterSet != null) {
        checker.addFilter(filterSet);
    }
    Configuration configuration = getConfiguration(request);
    checker.configure(configuration);

    AuditListener listener = request.getListener();

    if (listener != null) {
        checker.addListener(listener);
    }

    if (request.isConsoleOutput()) {
        checker.addListener(request.getConsoleListener());
    }

    CheckstyleCheckerListener checkerListener = new CheckstyleCheckerListener(configuration);
    if (request.isAggregate()) {
        for (MavenProject childProject : request.getReactorProjects()) {
            sourceDirectories = sourceDirectoriesByProject.get(childProject);
            testSourceDirectories = testSourceDirectoriesByProject.get(childProject);
            addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories,
                    childProject.getResources(), request);
        }
    } else {
        addSourceDirectory(checkerListener, sourceDirectories, testSourceDirectories, request.getResources(),
                request);
    }

    checker.addListener(checkerListener);

    int nbErrors = checker.process(files);

    checker.destroy();

    if (projectClassLoader instanceof Closeable) {
        try {
            ((Closeable) projectClassLoader).close();
        } catch (IOException ex) {
            // Nothing we can do - and not detrimental to the build (save running out of file handles).
            getLogger().info("Failed to close custom Classloader - this indicated a bug in the code.", ex);
        }
    }

    if (request.getStringOutputStream() != null) {
        String message = request.getStringOutputStream().toString().trim();

        if (message.length() > 0) {
            getLogger().info(message);
        }
    }

    if (nbErrors > 0) {
        StringBuilder message = new StringBuilder("There ");
        if (nbErrors == 1) {
            message.append("is");
        } else {
            message.append("are");
        }
        message.append(" ");
        message.append(nbErrors);
        message.append(" error");
        if (nbErrors != 1) {
            message.append("s");
        }
        message.append(" reported by Checkstyle");
        String version = getCheckstyleVersion();
        if (version != null) {
            message.append(" ");
            message.append(version);
        }
        message.append(" with ");
        message.append(request.getConfigLocation());
        message.append(" ruleset.");

        if (request.isFailsOnError()) {
            // TODO: should be a failure, not an error. Report is not meant to
            // throw an exception here (so site would
            // work regardless of config), but should record this information
            throw new CheckstyleExecutorException(message.toString());
        } else {
            getLogger().info(message.toString());
        }
    }

    return checkerListener.getResults();
}

From source file:se.jguru.nazgul.tools.plugin.checkstyle.exec.DefaultCheckstyleExecutor.java

License:Apache License

private List<File> getFilesToProcess(CheckstyleExecutorRequest request) throws IOException {
    StringBuilder excludesStr = new StringBuilder();

    if (StringUtils.isNotEmpty(request.getExcludes())) {
        excludesStr.append(request.getExcludes());
    }/*from   www  . j  ava2s.  com*/

    String[] defaultExcludes = FileUtils.getDefaultExcludes();
    for (String defaultExclude : defaultExcludes) {
        if (excludesStr.length() > 0) {
            excludesStr.append(",");
        }

        excludesStr.append(defaultExclude);
    }

    Set<File> files = new LinkedHashSet<>();
    if (request.isAggregate()) {
        for (MavenProject project : request.getReactorProjects()) {
            Set<File> sourceDirectories = new LinkedHashSet<>();

            // CompileSourceRoots are absolute paths
            List<String> compileSourceRoots = project.getCompileSourceRoots();
            for (String compileSourceRoot : compileSourceRoots) {
                sourceDirectories.add(new File(compileSourceRoot));
            }

            Set<File> testSourceDirectories = new LinkedHashSet<>();
            // CompileSourceRoots are absolute paths
            List<String> testCompileSourceRoots = project.getTestCompileSourceRoots();
            for (String testCompileSourceRoot : testCompileSourceRoots) {
                testSourceDirectories.add(new File(testCompileSourceRoot));
            }

            addFilesToProcess(request, sourceDirectories, project.getResources(), project.getTestResources(),
                    files, testSourceDirectories);
        }
    } else {
        Collection<File> sourceDirectories = request.getSourceDirectories();
        addFilesToProcess(request, sourceDirectories, request.getResources(), request.getTestResources(), files,
                request.getTestSourceDirectories());
    }

    getLogger().debug("Added " + files.size() + " files to process.");

    return new ArrayList<>(files);
}

From source file:ws.epigraph.java.mojo.MainCodegenMojo.java

License:Apache License

@Override
protected Collection<? extends String> getSourceRoots(@NotNull MavenProject project) throws IOException {
    project.addCompileSourceRoot(sourceDirectory.getCanonicalPath());
    return project.getCompileSourceRoots();
}