Java Code Examples for org.apache.maven.model.Dependency#getVersion()

The following examples show how to use org.apache.maven.model.Dependency#getVersion() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LockSnapshotsMojo.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Determine the timestamp version of the snapshot dependency used in the build.
 *
 * @param dep
 * @return The timestamp version if exists, otherwise the original snapshot dependency version is returned.
 */
private String resolveSnapshotVersion( Dependency dep )
{
    getLog().debug( "Resolving snapshot version for dependency: " + dep );

    String lockedVersion = dep.getVersion();

    try
    {
        Artifact depArtifact =
            artifactFactory.createDependencyArtifact( dep.getGroupId(), dep.getArtifactId(),
                                                      VersionRange.createFromVersionSpec( dep.getVersion() ),
                                                      dep.getType(), dep.getClassifier(), dep.getScope() );
        resolver.resolve( depArtifact, getProject().getRemoteArtifactRepositories(), localRepository );

        lockedVersion = depArtifact.getVersion();
    }
    catch ( Exception e )
    {
        getLog().error( e );
    }
    return lockedVersion;
}
 
Example 2
Source File: ConfluenceDeployMojo.java    From maven-confluence-plugin with Apache License 2.0 6 votes vote down vote up
/**
 *
 * @param projectId
 * @param dependencyManagement
 * @return
 * @throws ProjectBuildingException
 */
private Map<String,Artifact> createManagedVersionMap(String projectId, DependencyManagement dependencyManagement) throws ProjectBuildingException {
    Map<String,Artifact> map;
    if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
        map = new HashMap<>();
        for (Dependency d : dependencyManagement.getDependencies()) {
            try {
                VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
                Artifact artifact = factory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(),
                        versionRange, d.getType(), d.getClassifier(),
                        d.getScope());
                map.put(d.getManagementKey(), artifact);
            } catch (InvalidVersionSpecificationException e) {
                throw new ProjectBuildingException(projectId, "Unable to parse version '" + d.getVersion()
                        + "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e);
            }
        }
    } else {
        map = Collections.emptyMap();
    }
    return map;
}
 
Example 3
Source File: MavenHelper.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the version of the given plugin that is specified in the POM of the
 * plugin in which this mojo is located.
 *
 * @param groupId the identifier of the group.
 * @param artifactId thidentifier of the artifact.
 * @return the version, never {@code null}
 * @throws MojoExecutionException if the plugin was not found.
 */
public String getPluginDependencyVersion(String groupId, String artifactId) throws MojoExecutionException {
	final Map<String, Dependency> deps = getPluginDependencies();
	final String key = ArtifactUtils.versionlessKey(groupId, artifactId);
	this.log.debug("COMPONENT DEPENDENCIES(getPluginVersionFromDependencies):"); //$NON-NLS-1$
	this.log.debug(deps.toString());
	final Dependency dep = deps.get(key);
	if (dep != null) {
		final String version = dep.getVersion();
		if (version != null && !version.isEmpty()) {
			return version;
		}
		throw new MojoExecutionException(MessageFormat.format(Messages.MavenHelper_2, key));
	}
	throw new MojoExecutionException(MessageFormat.format(Messages.MavenHelper_3, key, deps));
}
 
Example 4
Source File: MavenProjectConfigurator.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Configure the GWT Nature.
 *
 * @param mavenProject
 * @param monitor
 */
protected void configureGwtProject(MavenProject mavenProject, IProgressMonitor monitor) {
  // Get the GWT version from the project pom
  String gwtVersion = null;
  List<Dependency> dependencies = mavenProject.getDependencies();
  for (Dependency dependency : dependencies) {
    boolean hasGwtGroupId = GWTMavenRuntime.MAVEN_GWT_GROUP_ID.equals(dependency.getGroupId());
    boolean hasGwtUserArtivactId = GWTMavenRuntime.MAVEN_GWT_USER_ARTIFACT_ID.equals(dependency.getArtifactId());
    boolean hasGwtUserServletId = GWTMavenRuntime.MAVEN_GWT_SERVLET_ARTIFACT_ID.equals(dependency.getArtifactId());
    if (hasGwtGroupId && (hasGwtUserArtivactId || hasGwtUserServletId)) {
      gwtVersion = dependency.getVersion();
      Activator.log("MavenProjectConfigurator, Maven: Setting up Gwt Project. hasGwtGroupId=" + hasGwtGroupId
          + " hasGwtUser=" + hasGwtUserArtivactId + " hasGwtUserServletId=" + hasGwtUserServletId);
      break;
    }
  }

  Activator.log("MavenProjectConfigurator, Maven: gwtVersion=" + gwtVersion);

  resolveGwtDevJar(mavenProject, monitor, gwtVersion);
}
 
Example 5
Source File: DependencyUpdatesReport.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of dependencies where the dependencies which are defined in the dependency management section have
 * been filtered out.
 *
 * @param dependencies The set of dependencies.
 * @param dependencyManagement The set of dependencies from the dependency management section.
 * @return A new set of dependencies which are from the set of dependencies but not from the set of dependency
 *         management dependencies.
 * @since 1.0-beta-1
 */
private static Set<Dependency> removeDependencyManagment( Set<Dependency> dependencies, Set<Dependency> dependencyManagement )
{
    Set<Dependency> result = new TreeSet<>( new DependencyComparator() );
    for ( Dependency c : dependencies )
    {
        boolean matched = false;
        Iterator<Dependency> j = dependencyManagement.iterator();
        while ( !matched && j.hasNext() )
        {
            Dependency t = j.next();
            if ( StringUtils.equals( t.getGroupId(), c.getGroupId() )
                && StringUtils.equals( t.getArtifactId(), c.getArtifactId() )
                && ( t.getScope() == null || StringUtils.equals( t.getScope(), c.getScope() ) )
                && ( t.getClassifier() == null || StringUtils.equals( t.getClassifier(), c.getClassifier() ) )
                && ( c.getVersion() == null || t.getVersion() == null
                    || StringUtils.equals( t.getVersion(), c.getVersion() ) ) )
            {
                matched = true;
                break;
            }
        }
        if ( !matched )
        {
            result.add( c );
        }
    }
    return result;
}
 
Example 6
Source File: LockSnapshotsMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void lockSnapshots( ModifiedPomXMLEventReader pom, Collection<Dependency> dependencies )
    throws XMLStreamException, MojoExecutionException
{
    for ( Dependency dep : dependencies )
    {
        if ( isExcludeReactor() && isProducedByReactor( dep ) )
        {
            getLog().info( "Ignoring reactor dependency: " + toString( dep ) );
            continue;
        }

        if ( isHandledByProperty( dep ) )
        {
            getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) );
            continue;
        }

        if ( !isIncluded( this.toArtifact( dep ) ) )
        {
            continue;
        }

        String version = dep.getVersion();
        Matcher versionMatcher = matchSnapshotRegex.matcher( version );
        if ( versionMatcher.find() && versionMatcher.end() == version.length() )
        {
            String lockedVersion = resolveSnapshotVersion( dep );
            if ( !version.equals( lockedVersion ) )
            {
                if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), version,
                                                     lockedVersion, getProject().getModel() ) )
                {
                    getLog().info( "Locked " + toString( dep ) + " to version " + lockedVersion );
                }
            }
        }
    }
}
 
Example 7
Source File: UnlockSnapshotsMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void unlockSnapshots( ModifiedPomXMLEventReader pom, List<Dependency> dependencies )
    throws XMLStreamException, MojoExecutionException
{
    for ( Dependency dep : dependencies )
    {
        if ( isExcludeReactor() && isProducedByReactor( dep ) )
        {
            getLog().info( "Ignoring reactor dependency: " + toString( dep ) );
            continue;
        }

        if ( isHandledByProperty( dep ) )
        {
            getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) );
            continue;
        }

        if ( !isIncluded( this.toArtifact( dep ) ) )
        {
            continue;
        }

        String version = dep.getVersion();
        Matcher versionMatcher = matchSnapshotRegex.matcher( version );
        if ( versionMatcher.find() && versionMatcher.end() == version.length() )
        {
            String unlockedVersion = versionMatcher.replaceFirst( "-SNAPSHOT" );
            if ( PomHelper.setDependencyVersion( pom, dep.getGroupId(), dep.getArtifactId(), dep.getVersion(),
                                                 unlockedVersion, getProject().getModel() ) )
            {
                getLog().info( "Unlocked " + toString( dep ) + " to version " + unlockedVersion );
            }
        }
    }
}
 
Example 8
Source File: DisplayDependencyUpdatesMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a set of dependencies where the dependencies which are defined in the dependency management section have
 * been filtered out.
 *
 * @param dependencies The set of dependencies.
 * @param dependencyManagement The set of dependencies from the dependency management section.
 * @return A new set of dependencies which are from the set of dependencies but not from the set of dependency
 *         management dependencies.
 * @since 1.0-beta-1
 */
private static Set<Dependency> removeDependencyManagment( Set<Dependency> dependencies, Set<Dependency> dependencyManagement )
{
    Set<Dependency> result = new TreeSet<>( new DependencyComparator() );
    for ( Iterator<Dependency> i = dependencies.iterator(); i.hasNext(); )
    {
        Dependency c = i.next();
        boolean matched = false;
        Iterator<Dependency> j = dependencyManagement.iterator();
        while ( !matched && j.hasNext() )
        {
            Dependency t =j.next();
            if ( StringUtils.equals( t.getGroupId(), c.getGroupId() )
                && StringUtils.equals( t.getArtifactId(), c.getArtifactId() )
                && ( t.getScope() == null || StringUtils.equals( t.getScope(), c.getScope() ) )
                && ( t.getClassifier() == null || StringUtils.equals( t.getClassifier(), c.getClassifier() ) )
                && ( c.getVersion() == null || t.getVersion() == null
                    || StringUtils.equals( t.getVersion(), c.getVersion() ) ) )
            {
                matched = true;
                break;
            }
        }
        if ( !matched )
        {
            result.add( c );
        }
    }
    return result;
}
 
Example 9
Source File: DevServerMojo.java    From yawp with MIT License 5 votes vote down vote up
public String getYawpVersion() {
    for (Dependency dependency : project.getDependencies()) {
        if (dependency.getGroupId().equals(YAWP_GROUP_ID)) {
            return dependency.getVersion();
        }
    }
    throw new RuntimeException("Could not resolve YAWP! version in Maven.");
}
 
Example 10
Source File: GenerateMetadataMojo.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private Artifact toArtifact(final Dependency dependency) {
    final ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
    final ArtifactType type = registry.get(dependency.getType());

    return new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getClassifier(),
        type.getExtension(), dependency.getVersion(), type);
}
 
Example 11
Source File: AbstractVersionsDependencyUpdaterMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected String toString( Dependency d )
{
    StringBuilder buf = new StringBuilder();
    buf.append( d.getGroupId() );
    buf.append( ':' );
    buf.append( d.getArtifactId() );
    if ( d.getType() != null && d.getType().length() > 0 )
    {
        buf.append( ':' );
        buf.append( d.getType() );
    }
    else
    {
        buf.append( ":jar" );
    }
    if ( d.getClassifier() != null && d.getClassifier().length() > 0 )
    {
        buf.append( ':' );
        buf.append( d.getClassifier() );
    }
    if ( d.getVersion() != null && d.getVersion().length() > 0 )
    {
        buf.append( ":" );
        buf.append( d.getVersion() );
    }
    return buf.toString();
}
 
Example 12
Source File: CompareDependenciesMojo.java    From versions-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the candidate version to use for the specified property.
 * <p/>
 * The dependencies currently linked to the property must all be defined by the remote POM and they should refer to
 * the same version. If that's the case, that same version is returned. Otherwise, <tt>null</tt> is returned
 * indicating that there is no candidate.
 *
 * @param remoteDependencies the remote dependencies
 * @param property the property to update
 * @param propertyVersions the association
 * @return the candidate version or <tt>null</tt> if there isn't any
 */
private String computeCandidateVersion( Map<String, Dependency> remoteDependencies, Property property,
                                        PropertyVersions propertyVersions )
{
    String candidateVersion = null;
    for ( ArtifactAssociation artifactAssociation : propertyVersions.getAssociations() )
    {
        String id = generateId( artifactAssociation.getArtifact() );
        Dependency dependency = remoteDependencies.get( id );
        if ( dependency == null )
        {
            getLog().info( "Not updating ${" + property.getName() + "}: no info for " + id );
            return null;
        }
        else
        {
            if ( candidateVersion == null )
            {
                candidateVersion = dependency.getVersion();
            }
            else if ( !candidateVersion.equals( dependency.getVersion() ) )
            {
                getLog().warn( "Could not update ${" + property.getName() + "}: version mismatch" );
                return null;
            }
        }
    }
    return candidateVersion;
}
 
Example 13
Source File: GenerateBomMojo.java    From sundrio with Apache License 2.0 4 votes vote down vote up
private Artifact toArtifact(Dependency dependency) {
    return new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(), dependency.getVersion(), dependency.getScope(), dependency.getType(), dependency.getClassifier(),
            getArtifactHandler());
}
 
Example 14
Source File: Analyzer.java    From Moss with Apache License 2.0 4 votes vote down vote up
private static PomInfo readPom(InputStream is) throws SAXException, IOException, ParserConfigurationException {
    if (null != is) {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        try {
            Model model = reader.read(is);
            PomInfo pomInfo = new PomInfo();
            pomInfo.setArtifactId(model.getArtifactId());
            if (StringUtils.isEmpty(model.getGroupId())) {
                pomInfo.setGroupId(model.getParent().getGroupId());
            } else {
                pomInfo.setGroupId(model.getGroupId());
            }
            if (StringUtils.isEmpty(model.getVersion())) {
                pomInfo.setVersion(model.getParent().getVersion());
            } else {
                pomInfo.setVersion(model.getVersion());
            }
            List<Dependency> dependencies = model.getDependencies();
            List<PomDependency> pomDependencies = Lists.newArrayList();
            for (Dependency dependency : dependencies) {
                PomDependency pomDependency = new PomDependency();
                String groupId = dependency.getGroupId();
                if (StringUtils.isNotEmpty(groupId) && (groupId.equals("${project.groupId}"))) {
                    groupId = pomInfo.groupId;
                }
                pomDependency.setGroupId(groupId);
                pomDependency.setArtifactId(dependency.getArtifactId());
                String version = dependency.getVersion();
                if (StringUtils.isNotEmpty(version) && (version.startsWith("${") && version.endsWith("}"))) {
                    version = model.getProperties().getProperty(version.substring(2, version.length() - 1));
                }
                pomDependency.setVersion(version);

                pomDependency.setScope(dependency.getScope());
                pomDependencies.add(pomDependency);
            }
            pomInfo.setDependencies(pomDependencies);
            return pomInfo;
        } catch (XmlPullParserException e) {
            e.printStackTrace();
            logger.error("read pom failed!" + e.getMessage());
        }
    }

    return null;
}
 
Example 15
Source File: IsSnapshotDependency.java    From unleash-maven-plugin with Eclipse Public License 1.0 4 votes vote down vote up
@Override
public boolean apply(Dependency d) {
  String version = d.getVersion();
  version = propertyResolver.expandPropertyReferences(version);
  return version != null && MavenVersionUtil.isSnapshot(version);
}
 
Example 16
Source File: ArtifactHelper.java    From maven-dependency-mapper with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static String getId(Dependency dependency){
    return dependency.getGroupId() + ":"+ dependency.getArtifactId()+ ":" + dependency.getVersion();
}
 
Example 17
Source File: MavenUtils.java    From developer-studio with Apache License 2.0 4 votes vote down vote up
private static String getDependencyString(Dependency dependency) {
	String ds=dependency.getGroupId()+":"+dependency.getArtifactId()+":"+dependency.getVersion()+":"+dependency.getType()+":";
	return ds;
}
 
Example 18
Source File: PomHelper.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static void addDependencyAssocations( VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
                                              Map<String, PropertyVersionsBuilder> result,
                                              List<Dependency> dependencies, boolean usePluginRepositories )
    throws ExpressionEvaluationException
{
    if ( dependencies == null )
    {
        return;
    }
    for ( Dependency dependency : dependencies )
    {
        String version = dependency.getVersion();
        if ( version != null && version.contains( "${" ) && version.indexOf( '}' ) != -1 )
        {
            version = StringUtils.deleteWhitespace( version );
            for ( PropertyVersionsBuilder property : result.values() )
            {
                final String propertyRef = "${" + property.getName() + "}";
                if ( version.contains( propertyRef ) )
                {
                    // Any of these could be defined by a property
                    String groupId = dependency.getGroupId();
                    if ( groupId == null || groupId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        groupId = (String) expressionEvaluator.evaluate( groupId );
                    }
                    String artifactId = dependency.getArtifactId();
                    if ( artifactId == null || artifactId.trim().length() == 0 )
                    {
                        // malformed pom
                        continue;
                    }
                    else
                    {
                        artifactId = (String) expressionEvaluator.evaluate( artifactId );
                    }
                    // might as well capture the current value
                    VersionRange versionRange =
                        VersionRange.createFromVersion( (String) expressionEvaluator.evaluate( dependency.getVersion() ) );
                    property.addAssociation( helper.createDependencyArtifact( groupId, artifactId, versionRange,
                                                                              dependency.getType(),
                                                                              dependency.getClassifier(),
                                                                              dependency.getScope(),
                                                                              dependency.isOptional() ),
                                             usePluginRepositories );
                    if ( !propertyRef.equals( version ) )
                    {
                        addBounds( property, version, propertyRef, versionRange.toString() );
                    }
                }
            }
        }
    }
}
 
Example 19
Source File: UseReleasesMojo.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private void useReleases( ModifiedPomXMLEventReader pom, Collection<Dependency> dependencies )
    throws XMLStreamException, MojoExecutionException, ArtifactMetadataRetrievalException
{
    for ( Dependency dep : dependencies )
    {
        if ( isExcludeReactor() && isProducedByReactor( dep ) )
        {
            getLog().info( "Ignoring reactor dependency: " + toString( dep ) );
            continue;
        }

        if ( isHandledByProperty( dep ) )
        {
            getLog().debug( "Ignoring dependency with property as version: " + toString( dep ) );
            continue;
        }

        String version = dep.getVersion();
        Matcher versionMatcher = matchSnapshotRegex.matcher( version );
        if ( versionMatcher.matches() )
        {
            String releaseVersion = versionMatcher.group( 1 );
            Artifact artifact = this.toArtifact( dep );
            if ( !isIncluded( artifact ) )
            {
                continue;
            }

            getLog().debug( "Looking for a release of " + toString( dep ) );
            // Force releaseVersion version because org.apache.maven.artifact.metadata.MavenMetadataSource does not
            // retrieve release version if provided snapshot version.
            artifact.setVersion( releaseVersion );
            ArtifactVersions versions = getHelper().lookupArtifactVersions( artifact, false );
            if ( !allowRangeMatching ) // standard behaviour
            {
                noRangeMatching( pom, dep, version, releaseVersion, versions );
            }
            else
            {
                rangeMatching( pom, dep, version, releaseVersion, versions );
            }
        }
    }
}
 
Example 20
Source File: ProvisionStateMojo.java    From galleon with Apache License 2.0 4 votes vote down vote up
private Path resolveMaven(ArtifactCoordinate coordinate, MavenRepoManager resolver) throws MavenUniverseException, MojoExecutionException {
    final MavenArtifact artifact = new MavenArtifact();
    artifact.setGroupId(coordinate.getGroupId());
    artifact.setArtifactId(coordinate.getArtifactId());
    String version = coordinate.getVersion();
    if(isEmptyOrNull(version)) {
        // first, we are looking for the artifact among the project deps
        // direct dependencies may override the managed versions
        for(Artifact a : project.getArtifacts()) {
            if(coordinate.getArtifactId().equals(a.getArtifactId())
                    && coordinate.getGroupId().equals(a.getGroupId())
                    && coordinate.getExtension().equals(a.getType())
                    && (coordinate.getClassifier() == null ? "" : coordinate.getClassifier())
                            .equals(a.getClassifier() == null ? "" : a.getClassifier())) {
                version = a.getVersion();
                break;
            }
        }
        if(isEmptyOrNull(version)) {
            // Now we are going to look for for among the managed dependencies
            for (Dependency d : project.getDependencyManagement().getDependencies()) {
                if (coordinate.getArtifactId().equals(d.getArtifactId())
                        && coordinate.getGroupId().equals(d.getGroupId())
                        && coordinate.getExtension().equals(d.getType())
                        && (coordinate.getClassifier() == null ? "" : coordinate.getClassifier())
                                .equals(d.getClassifier() == null ? "" : d.getClassifier())) {
                    version = d.getVersion();
                    break;
                }
            }
            if (isEmptyOrNull(version)) {
                throw new MojoExecutionException(coordinate.getGroupId() + ":" + coordinate.getArtifactId() + ":"
                        + (coordinate.getClassifier() == null ? "" : coordinate.getClassifier()) + ":"
                        + coordinate.getExtension()
                        + " was found among neither the project's dependencies nor the managed dependencies."
                        + " To proceed, please, add the desired version of the feature-pack to the provisioning configuration"
                        + " or the project dependencies, or the dependency management section of the Maven project");
            }
        }
    }
    artifact.setVersion(version);
    artifact.setExtension(coordinate.getExtension());
    artifact.setClassifier(coordinate.getClassifier());

    resolver.resolve(artifact);
    return artifact.getPath();
}