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

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

Introduction

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

Prototype

public File getBasedir() 

Source Link

Usage

From source file:org.codehaus.mojo.dashboard.report.plugin.utils.MavenUtils.java

License:Apache License

/**
 * // w w  w .  ja  v  a2s .  co  m
 * @param project
 * @param pluginArtifact
 * @param optionName
 * @param defaultValue
 * @return
 */
public String getConfiguration(MavenProject project, String pluginArtifact, String pluginGroupId,
        String optionName, String defaultValue) {
    String result = null;
    String value = "";
    try {
        value = getMavenPluginConfiguration(project, pluginArtifact, pluginGroupId, optionName, "");
        if (value != null && value.length() > 0) {
            if (value.indexOf("$") > -1) {
                result = getInterpolatorValue(project, value);
            } else {

                File dir = new File(value);
                boolean isExists = dir.exists();
                if (!isExists) {
                    File resultFile = FileUtils.resolveFile(project.getBasedir(), value);
                    result = resultFile.getAbsolutePath();
                } else {
                    result = value;
                }
            }
        } else {
            result = getInterpolatorValue(project, defaultValue);
        }
    } catch (IOException e) {
        result = null;
    }
    return result;
}

From source file:org.codehaus.mojo.emma.EmmaUtils.java

License:Open Source License

/**
 * Fix EMMA data file locations. EMMA generates data files in wrong locations: this method moves these files to
 * valid locations./*ww w .j  av a  2  s .  c o  m*/
 * 
 * @param project current Maven project
 * @param dataFiles to fix
 * @return new data file locations
 */
public static File[] fixDataFileLocations(MavenProject project, File[] dataFiles) {
    if (dataFiles == null) {
        return new File[0];
    }

    final List newDataFiles = new ArrayList(dataFiles.length);
    for (int i = 0; i < dataFiles.length; ++i) {
        final File src = dataFiles[i];
        if (!src.exists()) {
            // if the file does not exist, we cannot use it
            continue;
        }

        if (src.getParentFile().equals(project.getBasedir())) {
            // EMMA generates coverage data files in project root
            // (as it is actually the current directory):
            // move these files to the "target" directory
            final File dst = new File(project.getBuild().getDirectory(), "coverage-" + i + ".ec");
            try {
                FileUtils.rename(src, dst);
            } catch (IOException e) {
                final RuntimeException e2 = new IllegalStateException(
                        "Failed to move coverage data file: " + src.getAbsolutePath());
                e2.initCause(e);
                throw e2;
            }
            newDataFiles.add(dst);
        } else {
            newDataFiles.add(src);
        }
    }

    return (File[]) newDataFiles.toArray(new File[newDataFiles.size()]);
}

From source file:org.codehaus.mojo.gwt.eclipse.EclipseUtil.java

License:Apache License

/**
 * Read the Eclipse project name for .project file. Fall back to artifactId on error
 *
 * @return project name in eclipse workspace
 *//*from w  w  w . j  a  v  a  2s .  c  o  m*/
public String getProjectName(MavenProject project) {
    File dotProject = new File(project.getBasedir(), ".project");
    try {
        Xpp3Dom dom = Xpp3DomBuilder.build(ReaderFactory.newXmlReader(dotProject));
        return dom.getChild("name").getValue();
    } catch (Exception e) {
        getLogger().warn("Failed to read the .project file");
        return project.getArtifactId();
    }
}

From source file:org.codehaus.mojo.javancss.NcssReportMojo.java

License:Apache License

private void generateAggregateReport(Locale locale) throws MavenReportException {
    // All this work just to get "target" so that we can scan the filesystem for
    // child javancss xml files...
    String basedir = project.getBasedir().toString();
    String output = xmlOutputDirectory.toString();
    if (getLog().isDebugEnabled()) {
        getLog().debug("basedir: " + basedir);
        getLog().debug("output: " + output);
    }/*ww w  . j  a va  2s  . c  om*/
    String relative = null;
    if (output.startsWith(basedir)) {
        relative = output.substring(basedir.length() + 1);
    } else {
        getLog().error("Unable to aggregate report because I can't "
                + "determine the relative location of the XML report");
        return;
    }
    getLog().debug("relative: " + relative);
    List reports = new ArrayList();
    for (Iterator it = reactorProjects.iterator(); it.hasNext();) {
        MavenProject child = (MavenProject) it.next();
        File xmlReport = new File(child.getBasedir() + File.separator + relative, tempFileName);
        if (xmlReport.exists()) {
            reports.add(new ModuleReport(child, loadDocument(xmlReport)));
        } else {
            getLog().debug("xml file not found: " + xmlReport);
        }
    }
    getLog().debug("Aggregating " + reports.size() + " JavaNCSS reports");

    // parse the freshly generated file and write the report
    NcssAggregateReportGenerator reportGenerator = new NcssAggregateReportGenerator(getSink(),
            getBundle(locale), getLog());
    reportGenerator.doReport(locale, reports, lineThreshold);
}

From source file:org.codehaus.mojo.jsimport.LocalRepositoryCollector.java

License:Apache License

/**
 * Constructor.//from   w ww . jav  a  2  s.  c om
 * 
 * @param project The Maven project to be processed.
 * @param localRepository The local repository being used by Maven.
 * @param additionalFolderBases an array containing the locations of additional base folders to be considered.
 */
public LocalRepositoryCollector(MavenProject project, //
        ArtifactRepository localRepository, File[] additionalFolderBases) {
    // The local repo will always be in this list and it is optimal to assume that it will be hit tested the most
    // outside of here.
    localRepositoryPaths.add(localRepository.getBasedir());

    // Determine the root project

    String projectArtifactId = project.getArtifactId();

    MavenProject parentProject = project.getParent();
    while (parentProject != null) {
        List<?> modules = parentProject.getModules();
        if (modules.contains(projectArtifactId)) {
            projectArtifactId = parentProject.getArtifactId();
            String parentProjectPath = parentProject.getBasedir().getAbsolutePath();
            localRepositoryPaths.add(parentProjectPath);
        } else {
            break;
        }

        parentProject = parentProject.getParent();
    }

    // Consider additional folders and their immediate sub folders.

    for (File additionalFolderBase : additionalFolderBases) {
        File[] additionalFolders = additionalFolderBase.listFiles();
        if (additionalFolders != null) {
            for (File additionalFolder : additionalFolders) {
                if (additionalFolder.isDirectory()) {
                    localRepositoryPaths.add(additionalFolder.getAbsolutePath());
                }
            }
        }
    }
}

From source file:org.codehaus.mojo.license.AggregatorAddThirdPartyMojo.java

License:Open Source License

/**
 * {@inheritDoc}/*  w ww.  j a v  a2  s. c om*/
 */
@Override
protected SortedProperties createUnsafeMapping() throws ProjectBuildingException, IOException {

    String path = getMissingFile().getAbsolutePath()
            .substring(getProject().getBasedir().getAbsolutePath().length() + 1);

    if (isVerbose()) {
        getLog().info("Use missing file path : " + path);
    }

    SortedProperties unsafeMappings = new SortedProperties(getEncoding());

    LicenseMap licenseMap = getLicenseMap();

    for (Object o : reactorProjects) {
        MavenProject p = (MavenProject) o;

        File file = new File(p.getBasedir(), path);

        if (file.exists()) {

            SortedProperties tmp = getHelper().loadUnsafeMapping(licenseMap, file, getProjectDependencies());
            unsafeMappings.putAll(tmp);
        }

        SortedSet<MavenProject> unsafes = getHelper().getProjectsWithNoLicense(licenseMap);
        if (CollectionUtils.isEmpty(unsafes)) {

            // no more unsafe dependencies, can break
            break;
        }
    }
    return unsafeMappings;
}

From source file:org.codehaus.mojo.nbm.CreateClusterMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    Project antProject = registerNbmAntTasks();

    if (!nbmBuildDir.exists()) {
        nbmBuildDir.mkdirs();//w w w  .  ja  v a2 s  . c o m
    }

    if (reactorProjects != null && reactorProjects.size() > 0) {
        for (MavenProject proj : reactorProjects) {
            //TODO how to figure where the the buildDir/nbm directory is
            File nbmDir = new File(proj.getBasedir(),
                    "target" + File.separator + "nbm" + File.separator + "netbeans");
            if (nbmDir.exists()) {
                Copy copyTask = (Copy) antProject.createTask("copy");
                copyTask.setTodir(nbmBuildDir);
                copyTask.setOverwrite(true);
                FileSet set = new FileSet();
                set.setDir(nbmDir);
                set.createInclude().setName("**");
                copyTask.addFileset(set);

                try {
                    copyTask.execute();
                } catch (BuildException ex) {
                    getLog().error("Cannot merge modules into cluster");
                    throw new MojoExecutionException("Cannot merge modules into cluster", ex);
                }
            } else {
                if ("nbm".equals(proj.getPackaging())) {
                    String error = "The NetBeans binary directory structure for " + proj.getId()
                            + " is not created yet."
                            + "\n Please execute 'mvn install nbm:cluster' to build all relevant projects in the reactor.";
                    throw new MojoFailureException(error);
                }
                if ("bundle".equals(proj.getPackaging())) {
                    Artifact art = proj.getArtifact();
                    final ExamineManifest mnf = new ExamineManifest(getLog());

                    File jar = new File(proj.getBuild().getDirectory(),
                            proj.getBuild().getFinalName() + ".jar");
                    if (!jar.exists()) {
                        getLog().error("Skipping " + proj.getId()
                                + ". Cannot find the main artifact in output directory.");
                        continue;
                    }
                    mnf.setJarFile(jar);
                    mnf.checkFile();

                    File cluster = new File(nbmBuildDir, defaultCluster);
                    getLog().debug("Copying " + art.getId() + " to cluster " + defaultCluster);
                    File modules = new File(cluster, "modules");
                    modules.mkdirs();
                    File config = new File(cluster, "config");
                    File confModules = new File(config, "Modules");
                    confModules.mkdirs();
                    File updateTracting = new File(cluster, "update_tracking");
                    updateTracting.mkdirs();

                    final String cnb = mnf.getModule();
                    final String cnbDashed = cnb.replace(".", "-");
                    final File moduleArt = new File(modules, cnbDashed + ".jar"); //do we need the file in some canotical name pattern?
                    final String specVer = mnf.getSpecVersion();
                    try {
                        FileUtils.copyFile(jar, moduleArt);
                        final File moduleConf = new File(confModules, cnbDashed + ".xml");
                        FileUtils.copyStreamToFile(new InputStreamFacade() {
                            public InputStream getInputStream() throws IOException {
                                return new StringInputStream(CreateClusterAppMojo.createBundleConfigFile(cnb,
                                        mnf.isBundleAutoload()), "UTF-8");
                            }
                        }, moduleConf);
                        FileUtils.copyStreamToFile(new InputStreamFacade() {
                            public InputStream getInputStream() throws IOException {
                                return new StringInputStream(CreateClusterAppMojo.createBundleUpdateTracking(
                                        cnb, moduleArt, moduleConf, specVer), "UTF-8");
                            }
                        }, new File(updateTracting, cnbDashed + ".xml"));
                    } catch (IOException exc) {
                        getLog().error(exc);
                    }

                }
            }
        }
        //in 6.1 the rebuilt modules will be cached if the timestamp is not touched.
        File[] files = nbmBuildDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                File stamp = new File(files[i], ".lastModified");
                if (!stamp.exists()) {
                    try {
                        stamp.createNewFile();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                stamp.setLastModified(new Date().getTime());
            }
        }
        getLog().info("Created NetBeans module cluster(s) at " + nbmBuildDir);
    } else {
        throw new MojoExecutionException("This goal only makes sense on reactor projects.");
    }
}

From source file:org.codehaus.mojo.unix.maven.plugin.MavenProjectWrapper.java

License:Open Source License

public static MavenProjectWrapper mavenProjectWrapper(final MavenProject project, MavenSession session) {
    SortedMap<String, String> properties = new TreeMap<String, String>();

    // This is perhaps not ideal. Maven uses reflection to dynamically extract properties from the project
    // when interpolating each file. This uses a static list that doesn't contain the project.* properties, except
    // the new we hard-code support for.
    //// ww w .ja va  2s  . c om
    // The user can work around this like this:
    // <properties>
    //   <project.build.directory>${project.build.directory}</project.build.directory>
    // </properties>
    //
    // If this has to change, the properties has to be a F<String, String> and interpolation tokens ("${" and "}")
    // has to be defined. Doable but too painful for now.
    properties.putAll(toMap(session.getSystemProperties()));
    properties.putAll(toMap(session.getUserProperties()));
    properties.putAll(toMap(project.getProperties()));
    properties.put("project.groupId", project.getGroupId());
    properties.put("project.artifactId", project.getArtifactId());
    properties.put("project.version", project.getVersion());

    return new MavenProjectWrapper(project.getGroupId(), project.getArtifactId(), project.getVersion(),
            project.getArtifact(), project.getName(), project.getDescription(), project.getBasedir(),
            new File(project.getBuild().getDirectory()), new LocalDateTime(), project.getArtifacts(),
            project.getLicenses(), new ArtifactMap(project.getArtifacts()), unmodifiableSortedMap(properties));
}

From source file:org.codehaus.mojo.versions.AbstractVersionsSetMojo.java

License:Apache License

/**
 * Sets the version to the given value./* ww  w  .j av a 2  s  .c o m*/
 * 
 * @param newVersion
 * 
 * @throws org.apache.maven.plugin.MojoExecutionException
 *          when things go wrong.
 * @throws org.apache.maven.plugin.MojoFailureException
 *          when things go wrong.
 */
protected void setVersion(String newVersion) throws MojoExecutionException, MojoFailureException {
    if (updateMatchingVersions == null) {
        updateMatchingVersions = Boolean.TRUE;
    }

    // this is the triggering change
    addChange(groupId, artifactId, oldVersion, newVersion);

    try {
        final MavenProject project = PomHelper.getLocalRoot(projectBuilder, getProject(), localRepository, null,
                getLog());

        getLog().info("Local aggregation root: " + project.getBasedir());
        final Map<String, Model> reactor = PomHelper.getReactorModels(project, getLog());

        // now fake out the triggering change
        final Model current = PomHelper.getModel(reactor, getProject().getGroupId(),
                getProject().getArtifactId());
        current.setVersion(newVersion);

        final Set<File> files = new LinkedHashSet<File>();
        files.add(getProject().getFile());

        final List<String> order = new ArrayList<String>(reactor.keySet());
        Collections.sort(order, new ReactorDepthComparator(reactor));

        final Iterator i = order.iterator();
        while (i.hasNext()) {
            final String sourcePath = (String) i.next();
            final Model sourceModel = (Model) reactor.get(sourcePath);

            getLog().debug(sourcePath.length() == 0 ? "Processing root module as parent"
                    : "Processing " + sourcePath + " as a parent.");

            final String sourceGroupId = PomHelper.getGroupId(sourceModel);
            if (sourceGroupId == null) {
                getLog().warn("Module " + sourcePath + " is missing a groupId.");
                continue;
            }
            final String sourceArtifactId = PomHelper.getArtifactId(sourceModel);
            if (sourceArtifactId == null) {
                getLog().warn("Module " + sourcePath + " is missing an artifactId.");
                continue;
            }
            final String sourceVersion = PomHelper.getVersion(sourceModel);
            if (sourceVersion == null) {
                getLog().warn("Module " + sourcePath + " is missing a version.");
                continue;
            }

            final File moduleDir = new File(project.getBasedir(), sourcePath);

            final File moduleProjectFile;

            if (moduleDir.isDirectory()) {
                moduleProjectFile = new File(moduleDir, "pom.xml");
            } else {
                // i don't think this should ever happen... but just in case
                // the module references the file-name
                moduleProjectFile = moduleDir;
            }

            files.add(moduleProjectFile);

            getLog().debug("Looking for modules which use "
                    + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + " as their parent");

            final Iterator j = PomHelper.getChildModels(reactor, sourceGroupId, sourceArtifactId).entrySet()
                    .iterator();

            while (j.hasNext()) {
                final Map.Entry target = (Map.Entry) j.next();
                final String targetPath = (String) target.getKey();
                final Model targetModel = (Model) target.getValue();
                final Parent parent = targetModel.getParent();
                getLog().debug("Module: " + targetPath);
                if (sourceVersion.equals(parent.getVersion())) {
                    getLog().debug("    parent already is "
                            + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId) + ":"
                            + sourceVersion);
                } else {
                    getLog().debug(
                            "    parent is " + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId)
                                    + ":" + parent.getVersion());
                    getLog().debug(
                            "    will become " + ArtifactUtils.versionlessKey(sourceGroupId, sourceArtifactId)
                                    + ":" + sourceVersion);
                }
                final boolean targetExplicit = PomHelper.isExplicitVersion(targetModel);
                if ((updateMatchingVersions.booleanValue() || !targetExplicit)
                        && StringUtils.equals(parent.getVersion(), PomHelper.getVersion(targetModel))) {
                    getLog().debug("    module is "
                            + ArtifactUtils.versionlessKey(PomHelper.getGroupId(targetModel),
                                    PomHelper.getArtifactId(targetModel))
                            + ":" + PomHelper.getVersion(targetModel));
                    getLog().debug(
                            "    will become " + ArtifactUtils.versionlessKey(PomHelper.getGroupId(targetModel),
                                    PomHelper.getArtifactId(targetModel)) + ":" + sourceVersion);
                    addChange(PomHelper.getGroupId(targetModel), PomHelper.getArtifactId(targetModel),
                            PomHelper.getVersion(targetModel), sourceVersion);
                    targetModel.setVersion(sourceVersion);
                } else {
                    getLog().debug("    module is "
                            + ArtifactUtils.versionlessKey(PomHelper.getGroupId(targetModel),
                                    PomHelper.getArtifactId(targetModel))
                            + ":" + PomHelper.getVersion(targetModel));
                }
            }
        }

        // now process all the updates
        final Iterator k = files.iterator();
        while (k.hasNext()) {
            process((File) k.next());
        }

    } catch (IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.codehaus.mojo.versions.api.PomHelper.java

License:Apache License

/**
 * Modifies the collection of child modules removing those which cannot be found relative to the parent.
 *
 * @param logger       The logger to log to.
 * @param project      the project./*from  ww w.ja  v  a  2s .com*/
 * @param childModules the child modules.
 */
public static void removeMissingChildModules(Log logger, MavenProject project,
        Collection<String> childModules) {
    removeMissingChildModules(logger, project.getBasedir(), childModules);
}