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

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

Introduction

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

Prototype

public String getId() 

Source Link

Usage

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

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing./*from w  ww .  ja  v a  2s  . co m*/
 *
 * @return resolved IDE dependencies, with attached jars for non-reactor dependencies
 * @throws MojoExecutionException if dependencies can't be resolved
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    if (ideDeps == null) {
        if (resolveDependencies) {
            MavenProject project = getProject();
            ArtifactRepository localRepo = getLocalRepository();

            List deps = getProject().getDependencies();

            // Collect the list of resolved IdeDependencies.
            List dependencies = new ArrayList();

            if (deps != null) {
                Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(),
                        project.getDependencyManagement());

                ArtifactResolutionResult artifactResolutionResult = null;

                try {

                    List listeners = new ArrayList();

                    if (logger.isDebugEnabled()) {
                        listeners.add(new DebugResolutionListener(logger));
                    }

                    listeners.add(new WarningResolutionListener(logger));

                    artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(),
                            project.getArtifact(), managedVersions, localRepo,
                            project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null,
                            listeners);
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().error(
                            Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$
                                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

                    // if we are here artifactResolutionResult is null, create a project without dependencies but
                    // don't fail
                    // (this could be a reactor projects, we don't want to fail everything)
                    // Causes MECLIPSE-185. Not sure if it should be handled this way??
                    return new IdeDependency[0];
                }

                // keep track of added reactor projects in order to avoid duplicates
                Set emittedReactorProjectId = new HashSet();

                for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i
                        .hasNext();) {

                    ResolutionNode node = (ResolutionNode) i.next();
                    int dependencyDepth = node.getDepth();
                    Artifact art = node.getArtifact();
                    // don't resolve jars for reactor projects
                    if (hasToResolveJar(art)) {
                        try {
                            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                        } catch (ArtifactNotFoundException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        } catch (ArtifactResolutionException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution",
                                    new Object[] { //$NON-NLS-1$
                                            e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        }
                    }

                    boolean includeArtifact = true;
                    if (getExcludes() != null) {
                        String artifactFullId = art.getGroupId() + ":" + art.getArtifactId();
                        if (getExcludes().contains(artifactFullId)) {
                            getLog().info("excluded: " + artifactFullId);
                            includeArtifact = false;
                        }
                    }

                    if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art))
                            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) {

                        // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar"
                        // also
                        // if the packaging specified in pom.xml is different.

                        // osgi-bundle packaging is provided by the felix osgi plugin
                        // eclipse-plugin packaging is provided by this eclipse plugin
                        // String packaging = art.getArtifactHandler().getPackaging();
                        // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals(
                        // packaging );

                        // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be
                        // considered
                        // an osgi bundle
                        boolean isOsgiBundle = false;
                        String osgiSymbolicName = null;
                        if (art.getFile() != null) {
                            JarFile jarFile = null;
                            try {
                                jarFile = new JarFile(art.getFile(), false, ZipFile.OPEN_READ);

                                Manifest manifest = jarFile.getManifest();
                                if (manifest != null) {
                                    osgiSymbolicName = manifest.getMainAttributes()
                                            .getValue(new Attributes.Name("Bundle-SymbolicName"));
                                }
                            } catch (IOException e) {
                                getLog().info("Unable to read jar manifest from " + art.getFile());
                            } finally {
                                if (jarFile != null) {
                                    try {
                                        jarFile.close();
                                    } catch (IOException e) {
                                        // ignore
                                    }
                                }
                            }
                        }

                        isOsgiBundle = osgiSymbolicName != null;

                        IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(),
                                art.getVersion(), art.getClassifier(), useProjectReference(art),
                                Artifact.SCOPE_TEST.equals(art.getScope()),
                                Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                                Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                                art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(),
                                isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art));
                        // no duplicate entries allowed. System paths can cause this problem.
                        if (!dependencies.contains(dep)) {
                            dependencies.add(dep);
                        }
                    }
                }

                // @todo a final report with the list of
                // missingArtifacts?

            }

            ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]);
        } else {
            ideDeps = new IdeDependency[0];
        }
    }

    return ideDeps;
}

From source file:com.atlassian.maven.plugin.clover.CloverAggregateMojo.java

License:Apache License

private List<String> getChildrenCloverDatabases() {
    // Ideally we'd need to find out where each module stores its Clover
    // database. However that's not
    // currently possible in m2 (see
    // http://jira.codehaus.org/browse/MNG-2180). Thus we'll assume for now
    // that all modules use the cloverDatabase configuration from the top
    // level module.

    // Find out the location of the clover DB relative to the root module.
    // Note: This is a pretty buggy algorithm and we really need a proper
    // solution (see MNG-2180)
    final String resolvedCloverDb = resolveCloverDatabase();
    final String projectBaseDir = getProject().getBasedir().getPath();
    getLog().debug("Calculating relative database path of '" + resolvedCloverDb
            + "' against the project base directory '" + projectBaseDir + "'");
    final String relativeCloverDatabasePath = resolvedCloverDb.substring(projectBaseDir.length());
    getLog().debug("Relative path is '" + relativeCloverDatabasePath + "'");
    final List<String> dbFiles = new ArrayList<String>();
    final List<MavenProject> projects = getDescendantModuleProjects(getProject());

    for (MavenProject childProject : projects) {
        getLog().debug("Looking for Clover database for module " + childProject.getId() + " ("
                + childProject.getBasedir() + ")");
        final File cloverDb = new File(childProject.getBasedir(), relativeCloverDatabasePath);
        if (cloverDb.exists()) {
            getLog().debug("Database found at " + cloverDb.getAbsolutePath() + " . Adding for merge.");
            dbFiles.add(cloverDb.getPath());
        } else {/*  w w  w  . ja v  a 2 s.c om*/
            getLog().debug("No database at " + cloverDb.getAbsolutePath());
        }
    }

    return dbFiles;
}

From source file:com.atlassian.maven.plugin.clover.CloverLogMojo.java

License:Apache License

/**
 * Configures test source roots for clover log task for a single maven project.
 * It takes original test directory and  directories from maven compilation.
 * @param cloverLogTask//w  ww  .  jav a2s.c om
 * @param project
 */
private void setTestSourceRootsForProject(final CloverLogTask cloverLogTask, final MavenProject project) {
    // original src/test directory
    String originalSrcTestDir = CloverSetupMojo.getOriginalSrcTestDir(project.getId());
    if (originalSrcTestDir != null) {
        addTestSrcDir(cloverLogTask, originalSrcTestDir);
    }

    // src/test directories from maven compilation
    final List<String> testSourceRoots = project.getTestCompileSourceRoots();
    addTestSrcDirs(cloverLogTask, testSourceRoots.iterator());
}

From source file:com.atlassian.maven.plugin.clover.internal.AbstractCloverMojo.java

License:Apache License

/**
 * Returns all the projects that are modules, or modules of modules, of the
 * specified project found within the reactor.
 *
 * The searchLevel parameter controls how many descendent levels of modules
 * are returned. With a searchLevels equals to 1, only the immediate modules
 * of the specified project are returned.
 *
 * A searchLevel equals to 2 returns those module's modules as well.
 *
 * A searchLevel equals to -1 returns the entire module hierarchy beneath the
 * specified project. Note that this is simply the equivalent to the entire reactor
 * if the specified project is the root execution project.
 *
 * @param project the project to search under
 * @param levels  the number of descendent levels to return (List&lt;MavenProject&gt;)
 * @return the list of module projects./*from   ww  w. jav  a  2s . co  m*/
 */
protected List<MavenProject> getModuleProjects(final MavenProject project, final int levels) {
    final List<MavenProject> projects = new ArrayList<MavenProject>();
    final boolean infinite = (levels == -1);

    getLog().debug("getModuleProjects: project=" + project.getId() + " getReactorProjects is "
            + (getReactorProjects() == null ? "null" : "not null") + " infinite=" + infinite + " levels="
            + levels);

    if ((getReactorProjects() != null) && (infinite || levels > 0)) {
        for (final MavenProject reactorProject : getReactorProjects()) {
            getLog().debug(
                    "getModuleProjects: checking " + reactorProject.getId() + " against " + project.getId());
            if (isModuleOfProject(project, reactorProject)) {
                getLog().debug("getModuleProjects: reactor project " + reactorProject.getId()
                        + " is a module of " + project.getId());
                projects.add(reactorProject);
                if (project == reactorProject) {
                    projects.add(project); //CLMVN-78 don't recurse if project is the same as reactorProject.
                } else {
                    projects.addAll(getModuleProjects(reactorProject, infinite ? levels : levels - 1));
                }
            } else {
                getLog().debug("getModuleProjects: reactor project " + reactorProject.getId()
                        + " is not a module of " + project.getId());
            }
        }
    }

    return projects;
}

From source file:com.blackducksoftware.integration.hub.jenkins.maven.HubMavenReporter.java

License:Open Source License

private BuildArtifact createBuildArtifact(final MavenProject pom) {
    final BuildArtifact artifact = new BuildArtifact();
    artifact.setType("org.apache.maven");
    artifact.setGroup(pom.getGroupId());
    artifact.setArtifact(pom.getArtifactId());
    artifact.setVersion(pom.getVersion());
    artifact.setId(pom.getId());
    return artifact;
}

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

License:BSD License

private void launchMaven(final File pomFile, final List<String> commandList, final IProgressMonitor monitor)
        throws CoreException {

    final IMaven maven = MavenPlugin.getMaven();

    final Model mavenModel = maven.readModel(pomFile);

    final MavenProject mavenProject = new MavenProject(mavenModel);

    final Properties mavenProps = mavenProject.getProperties();

    for (final Map.Entry<?, ?> entry : mavenProps.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = entry.getValue().toString();
        // ConfigPlugin.logInfo("key= " + key + " value=" + value);
    }/*from w w  w.ja va 2s  . c o m*/

    //

    final List<String> goalList = new LinkedList<String>();
    final List<String> profileActiveList = new LinkedList<String>();
    final List<String> profileInactiveList = new LinkedList<String>();

    for (final String command : commandList) {

        if (command.startsWith("-")) {

            /** command line options */

            if (command.startsWith("--activate-profiles")) {
                ConfigPlugin.log(IStatus.ERROR, "TODO : " + command);
            } else {
                ConfigPlugin.log(IStatus.ERROR, "not supported : " + command);
            }

        } else {

            /** maven execution goals */

            goalList.add(command);

        }

    }

    //

    final MavenExecutionRequest request = maven.createExecutionRequest(monitor);

    request.setPom(pomFile);
    request.setGoals(goalList);

    // TODO
    // request.setActiveProfiles(profileActiveList);
    // request.setInactiveProfiles(profileInactiveList);

    //

    final String id = mavenProject.getId();

    ConfigPlugin.log(IStatus.INFO,
            "maven execute : " + mavenProject.getId() + " " + MojoUtil.join(commandList, ","));

    // final Job job = new Job(id) {
    // {
    // setSystem(true);
    // setPriority(BUILD);
    // }
    // @Override
    // protected IStatus run(final IProgressMonitor monitor) {
    // return null;
    // }
    // };

    final MavenExecutionResult result = maven.execute(request, monitor);

    if (result.hasExceptions()) {
        throw new CoreException(new Status(IStatus.ERROR, ConfigPlugin.ID, "maven execution failed",
                result.getExceptions().get(0)));
    }

}

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

License:BSD License

public String getKey() {

    final MavenProject project = session.getCurrentProject();

    final String projId = project.getId();

    final String execId = execution.toString();

    final String key = projId + "/" + execId;

    return key;/*www .j  a va 2s  .com*/

}

From source file:com.carrotgarden.maven.osgi.BaseMojo.java

License:BSD License

/**
 *//*w ww .j ava 2s .c om*/
protected void addProjectBundles(MavenProject project, String tab) {

    if (PomUtils.isBundleProject(//
            project, m_resolver, m_remoteRepos, m_localRepo, true)) {

        getLog().warn(tab + "found bundle : " + project.getId());

        provisionBundle(project.getArtifact(), tab);

    } else {

        getLog().warn(tab + "check non-bundle: " + project.getId());

    }

    addProjectDependencies(project, tab + TAB);

}

From source file:com.exentes.maven.versions.UseReleasesMojo.java

License:Apache License

private Collection<String> processProject() throws MojoFailureException {
    List<String> errors = Lists.newArrayList();

    getLog().info("Processing all projects snapshots...");
    SetMultimap<Artifact, MavenProject> allSnapshotProjectArtifacts = VersionMojoUtils
            .allSnapshotProjectArtifacts(session);
    Map<String, Dependency> allDependenciesMap = allDependenciesMap(session);
    Map<Object, MavenProject> origins = origins(session);
    Set<MavenProject> projectsToUpdate = Sets.newHashSet();

    for (Map.Entry<Artifact, Collection<MavenProject>> artifactWithProjects : allSnapshotProjectArtifacts
            .asMap().entrySet()) {//from ww w .ja  va  2 s.  c  o m
        Artifact snapshotArtifact = artifactWithProjects.getKey();
        Collection<MavenProject> projects = artifactWithProjects.getValue();

        try {
            ArtifactResult artifactResult = resolveReleasedArtifact(snapshotArtifact);
            for (MavenProject project : projects) {
                Dependency dependencyToUpdate = allDependenciesMap
                        .get(projectArtifactKey(project, snapshotArtifact));

                if (isPropertyPlaceholder(dependencyToUpdate.getVersion())) {
                    MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                    String propertyName = getPropertyName(dependencyToUpdate.getVersion());
                    Properties projectProperties = projectToUpdate.getOriginalModel().getProperties();
                    if (projectProperties != null && projectProperties.containsKey(propertyName)) {
                        String newVersion = null;
                        String versionPropertyValue = projectProperties.getProperty(propertyName);
                        VersionRange versionRange = VersionRange.createFromVersionSpec(versionPropertyValue);
                        if (versionRange.getRecommendedVersion() == null) {
                            int restrictionIndex = 0;
                            for (Restriction restriction : versionRange.getRestrictions()) {
                                if (restriction.isUpperBoundInclusive()) {
                                    if (snapshotArtifact.getVersion()
                                            .equals(restriction.getUpperBound().toString())) {
                                        DefaultArtifactVersion updatedVersion = new DefaultArtifactVersion(
                                                artifactResult.getArtifact().getVersion());
                                        Restriction updatedRestriction = new Restriction(
                                                restriction.getUpperBound().equals(restriction.getLowerBound())
                                                        ? updatedVersion
                                                        : restriction.getLowerBound(),
                                                restriction.isLowerBoundInclusive(), updatedVersion,
                                                restriction.isUpperBoundInclusive());
                                        versionRange.getRestrictions().set(restrictionIndex,
                                                updatedRestriction);
                                        newVersion = versionRange.toString();
                                        break;
                                    }
                                }
                                restrictionIndex++;
                            }
                        } else {
                            newVersion = artifactResult.getArtifact().getVersion();
                        }
                        if (newVersion != null) {
                            projectProperties.setProperty(propertyName, newVersion);
                            projectsToUpdate.add(projectToUpdate);
                            getLog().info("Version property {" + propertyName + "} in the project ["
                                    + projectToUpdate.getId() + "] set to the value: "
                                    + artifactResult.getArtifact().getVersion());
                            getLog().info("Snapshot dependency [" + snapshotArtifact + "] is replaced with ["
                                    + artifactResult.getArtifact() + "] in the project: ["
                                    + projectToUpdate.getId() + "]");
                        } else {
                            errors.add("Dependency version value '" + versionPropertyValue
                                    + "' defined as a value of property '" + propertyName + "' not supported");
                        }
                    } else {
                        errors.add("Property [" + propertyName + "] not found in the project ["
                                + projectsToUpdate + "] properties. The artifact version cannot be resolved");
                    }
                } else if (snapshotArtifact.getVersion().equals(dependencyToUpdate.getVersion())) {
                    MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                    projectsToUpdate.add(projectToUpdate);
                    dependencyToUpdate.setVersion(artifactResult.getArtifact().getVersion());
                    getLog().info("Snapshot dependency [" + snapshotArtifact + "] is replaced with ["
                            + artifactResult.getArtifact() + "] in the project: [" + projectToUpdate.getId()
                            + "]");
                } else if (dependencyToUpdate.getVersion() == null) {
                    errors.add("Unknown version for the dependency [" + dependencyToUpdate + "]");
                } else {
                    // check if this is version range
                    try {
                        VersionRange versionRange = VersionRange
                                .createFromVersionSpec(dependencyToUpdate.getVersion());
                        if (versionRange.getRecommendedVersion() == null) {
                            // this this a version range. now all inclusive upper bounds should be inspected and the one which match resolved snapshot version must be upgraded
                            int restrictionIndex = 0;
                            for (Restriction restriction : versionRange.getRestrictions()) {
                                if (restriction.isUpperBoundInclusive()) {
                                    if (isPropertyPlaceholder(restriction.getUpperBound().toString())) {
                                        // try to update a property which is used as an upper version boundary
                                        String propertyName = getPropertyName(
                                                restriction.getUpperBound().toString());
                                        getLog().info("property name: " + propertyName);
                                        MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                                        Properties projectProperties = projectToUpdate.getOriginalModel()
                                                .getProperties();
                                        if (projectProperties != null
                                                && projectProperties.containsKey(propertyName)
                                                && projectProperties.getProperty(propertyName)
                                                        .equals(snapshotArtifact.getVersion())) {
                                            projectProperties.setProperty(propertyName,
                                                    artifactResult.getArtifact().getVersion());
                                            projectsToUpdate.add(projectToUpdate);
                                            getLog().info(
                                                    "Version property {" + propertyName + "} in the project ["
                                                            + projectToUpdate.getId() + "] set to the value: "
                                                            + artifactResult.getArtifact().getVersion());
                                            getLog().info("Snapshot dependency [" + snapshotArtifact
                                                    + "] is replaced with [" + artifactResult.getArtifact()
                                                    + "] in the project: [" + projectToUpdate.getId() + "]");
                                            break;
                                        }
                                    } else {
                                        if (snapshotArtifact.getVersion()
                                                .equals(restriction.getUpperBound().toString())) {
                                            DefaultArtifactVersion updatedVersion = new DefaultArtifactVersion(
                                                    artifactResult.getArtifact().getVersion());
                                            Restriction updatedRestriction = new Restriction(
                                                    restriction.getUpperBound().equals(
                                                            restriction.getLowerBound()) ? updatedVersion
                                                                    : restriction.getLowerBound(),
                                                    restriction.isLowerBoundInclusive(), updatedVersion,
                                                    restriction.isUpperBoundInclusive());
                                            versionRange.getRestrictions().set(restrictionIndex,
                                                    updatedRestriction);
                                            MavenProject projectToUpdate = origins.get(dependencyToUpdate);
                                            projectsToUpdate.add(projectToUpdate);
                                            dependencyToUpdate.setVersion(versionRange.toString());
                                            getLog().info("Snapshot dependency [" + snapshotArtifact
                                                    + "] is replaced with [" + dependencyToUpdate
                                                    + "] in the project: [" + projectToUpdate.getId() + "]");
                                            break;
                                        }
                                    }
                                }
                                restrictionIndex++;
                            }
                        } else {
                            errors.add("Dependency version value [" + dependencyToUpdate.getVersion()
                                    + "] not supported");
                        }
                    } catch (InvalidVersionSpecificationException e) {
                        errors.add("Invalid version specified: " + dependencyToUpdate.getVersion()
                                + ". Exception when parsing version: " + e.getMessage());
                    }
                }
            }
        } catch (ArtifactResolutionException e) {
            getLog().info(e);
            errors.add("Failed to resolve a RELEASE version for [" + snapshotArtifact + "]. Exception: "
                    + e.getMessage());
        } catch (InvalidVersionSpecificationException e) {
            errors.add("Invalid version specified: " + snapshotArtifact.getVersion()
                    + ". Exception when parsing version: " + e.getMessage());
        }
    }

    if (!dryRun) {
        for (MavenProject project : projectsToUpdate) {
            try {
                modelWriter.write(project.getFile(), null, project.getOriginalModel());
            } catch (IOException e) {
                throw new MojoFailureException("Error writing POM", e);
            }
        }
    }
    return errors;
}

From source file:com.exentes.maven.versions.VersionMojoUtils.java

License:Apache License

public static String projectArtifactKey(MavenProject project, Artifact artifact) {
    return project.getId() + "->" + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
            + artifact.getType() + (artifact.getClassifier() != null ? artifact.getClassifier() : "");
}