Java Code Examples for org.apache.maven.artifact.ArtifactUtils

The following examples show how to use org.apache.maven.artifact.ArtifactUtils. These examples are extracted from open source projects. 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 Project: versions-maven-plugin   Source File: PropertyVersions.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Uses the {@link DefaultVersionsHelper} to find all available versions that match all the associations with this
 * property.
 *
 * @param includeSnapshots Whether to include snapshot versions in our search.
 * @return The (possibly empty) array of versions.
 */
public synchronized ArtifactVersion[] getVersions( boolean includeSnapshots )
{
    Set<ArtifactVersion> result;
    if ( includeSnapshots )
    {
        result = versions;
    }
    else
    {
        result = new TreeSet<>( getVersionComparator() );
        for ( ArtifactVersion candidate : versions )
        {
            if ( ArtifactUtils.isSnapshot( candidate.toString() ) )
            {
                continue;
            }
            result.add( candidate );
        }
    }
    return asArtifactVersionArray( result );
}
 
Example 2
Source Project: versions-maven-plugin   Source File: ArtifactVersions.java    License: Apache License 2.0 6 votes vote down vote up
public ArtifactVersion[] getVersions( boolean includeSnapshots )
{
    Set<ArtifactVersion> result;
    if ( includeSnapshots )
    {
        result = versions;
    }
    else
    {
        result = new TreeSet<>( versionComparator );
        for ( ArtifactVersion candidate : versions )
        {
            if ( ArtifactUtils.isSnapshot( candidate.toString() ) )
            {
                continue;
            }
            result.add( candidate );
        }
    }
    return result.toArray( new ArtifactVersion[result.size()] );
}
 
Example 3
private String getNewVersion( ExternalVersionStrategy strategy, MavenProject mavenProject )
    throws ExternalVersionException
{

    // snapshot detection against the old version.
    boolean isSnapshot = ArtifactUtils.isSnapshot( mavenProject.getVersion() );

    // lookup the new version
    String newVersion = strategy.getVersion( mavenProject );

    if ( newVersion != null )
    {
        newVersion = newVersion.trim();
    }

    boolean isNewSnapshot = ArtifactUtils.isSnapshot( newVersion );
    // make sure we still have a SNAPSHOT if we had one previously.
    if ( isSnapshot && !isNewSnapshot )
    {
        newVersion = newVersion + "-SNAPSHOT";
    }
    return newVersion;
}
 
Example 4
Source Project: sarl   Source File: MavenHelper.java    License: Apache License 2.0 6 votes vote down vote up
/** Build the map of dependencies for the current plugin.
 *
 * @return the artifact.
 * @throws MojoExecutionException if the current plugin cannot be determined.
 */
public synchronized Map<String, Dependency> getPluginDependencies() throws MojoExecutionException {
	if (this.pluginDependencies == null) {
		final String groupId = getConfig("plugin.groupId"); //$NON-NLS-1$
		final String artifactId = getConfig("plugin.artifactId"); //$NON-NLS-1$
		final String pluginArtifactKey = ArtifactUtils.versionlessKey(groupId, artifactId);

		final Set<Artifact> dependencies = resolveDependencies(pluginArtifactKey, true);

		final Map<String, Dependency> deps = new TreeMap<>();

		for (final Artifact artifact : dependencies) {
			final Dependency dep = toDependency(artifact);
			deps.put(ArtifactUtils.versionlessKey(artifact), dep);
		}

		this.pluginDependencies = deps;
	}
	return this.pluginDependencies;
}
 
Example 5
Source Project: sarl   Source File: MavenHelper.java    License: 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 6
private SimpleReactorReader(Collection<MavenProject> projects, Collection<Artifact> artifacts) {
  repository = new WorkspaceRepository("reactor", new Object());

  Map<String, MavenProject> projectsByGAV = new LinkedHashMap<>();
  for (MavenProject project : projects) {
    String projectKey = ArtifactUtils.key(project.getGroupId(), project.getArtifactId(), project.getVersion());
    projectsByGAV.put(projectKey, project);
  }
  this.projectsByGAV = ImmutableMap.copyOf(projectsByGAV);

  Map<String, Artifact> artifactsByGAVCE = new LinkedHashMap<>();
  for (Artifact artifact : artifacts) {
    artifactsByGAVCE.put(keyGAVCE(artifact), artifact);
  }
  this.artifactsByGAVCE = ImmutableMap.copyOf(artifactsByGAVCE);
}
 
Example 7
Source Project: netbeans   Source File: DependencyNode.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public String getHtmlDisplayName() {
    StringBuilder n = new StringBuilder("<html>");
    n.append(getDisplayName());
    if (ArtifactUtils.isSnapshot(data.art.getVersion()) && data.art.getVersion().indexOf("SNAPSHOT") < 0) { //NOI18N
        n.append(" <b>[").append(data.art.getVersion()).append("]</b>");
    }
    if (!data.art.getArtifactHandler().isAddedToClasspath() && !Artifact.SCOPE_COMPILE.equals(data.art.getScope())) {
        n.append("  <i>[").append(data.art.getScope()).append("]</i>");
    }
    n.append("</html>");
    return n.toString();
}
 
Example 8
/**
 * {@inheritDoc}
 */
public ArtifactVersions lookupDependencyUpdates( Dependency dependency, boolean usePluginRepositories )
    throws ArtifactMetadataRetrievalException, InvalidVersionSpecificationException
{
    getLog().debug( "Checking "
        + ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() )
        + " for updates newer than " + dependency.getVersion() );
    VersionRange versionRange = VersionRange.createFromVersionSpec( dependency.getVersion() );

    return lookupArtifactVersions( createDependencyArtifact( dependency.getGroupId(), dependency.getArtifactId(),
                                                             versionRange, dependency.getType(),
                                                             dependency.getClassifier(), dependency.getScope() ),
                                   usePluginRepositories );
}
 
Example 9
/**
 * {@inheritDoc}
 */
public PluginUpdatesDetails lookupPluginUpdates( Plugin plugin, boolean allowSnapshots )
    throws ArtifactMetadataRetrievalException, InvalidVersionSpecificationException
{
    String version = plugin.getVersion();
    version = version == null ? "LATEST" : version;
    getLog().debug( "Checking " + ArtifactUtils.versionlessKey( plugin.getGroupId(), plugin.getArtifactId() )
        + " for updates newer than " + version );

    VersionRange versionRange = VersionRange.createFromVersion( version );

    final boolean includeSnapshots = allowSnapshots;

    final ArtifactVersions pluginArtifactVersions =
        lookupArtifactVersions( createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ),
                                true );

    Set<Dependency> pluginDependencies = new TreeSet<Dependency>( new DependencyComparator() );
    if ( plugin.getDependencies() != null )
    {
        pluginDependencies.addAll( plugin.getDependencies() );
    }
    Map<Dependency, ArtifactVersions> pluginDependencyDetails =
        lookupDependenciesUpdates( pluginDependencies, false );

    return new PluginUpdatesDetails( pluginArtifactVersions, pluginDependencyDetails, includeSnapshots );
}
 
Example 10
public final ArtifactVersion getNewestVersion( VersionRange versionRange, ArtifactVersion lowerBound,
                                               ArtifactVersion upperBound, boolean includeSnapshots,
                                               boolean includeLower, boolean includeUpper )
{
    ArtifactVersion latest = null;
    final VersionComparator versionComparator = getVersionComparator();
    for ( ArtifactVersion candidate : getVersions( includeSnapshots ) )
    {
        if ( versionRange != null && !ArtifactVersions.isVersionInRange( candidate, versionRange ) )
        {
            continue;
        }
        int lower = lowerBound == null ? -1 : versionComparator.compare( lowerBound, candidate );
        int upper = upperBound == null ? +1 : versionComparator.compare( upperBound, candidate );
        if ( lower > 0 || upper < 0 )
        {
            continue;
        }
        if ( ( !includeLower && lower == 0 ) || ( !includeUpper && upper == 0 ) )
        {
            continue;
        }
        if ( !includeSnapshots && ArtifactUtils.isSnapshot( candidate.toString() ) )
        {
            continue;
        }
        if ( latest == null )
        {
            latest = candidate;
        }
        else if ( versionComparator.compare( latest, candidate ) < 0 )
        {
            latest = candidate;
        }

    }
    return latest;
}
 
Example 11
public final ArtifactVersion getOldestVersion( VersionRange versionRange, ArtifactVersion lowerBound,
                                               ArtifactVersion upperBound, boolean includeSnapshots,
                                               boolean includeLower, boolean includeUpper )
{
    ArtifactVersion oldest = null;
    final VersionComparator versionComparator = getVersionComparator();
    for ( ArtifactVersion candidate : getVersions( includeSnapshots ) )
    {
        if ( versionRange != null && !ArtifactVersions.isVersionInRange( candidate, versionRange ) )
        {
            continue;
        }
        int lower = lowerBound == null ? -1 : versionComparator.compare( lowerBound, candidate );
        int upper = upperBound == null ? +1 : versionComparator.compare( upperBound, candidate );
        if ( lower > 0 || upper < 0 )
        {
            continue;
        }
        if ( ( !includeLower && lower == 0 ) || ( !includeUpper && upper == 0 ) )
        {
            continue;
        }
        if ( !includeSnapshots && ArtifactUtils.isSnapshot( candidate.toString() ) )
        {
            continue;
        }
        if ( oldest == null )
        {
            oldest = candidate;
        }
        else if ( versionComparator.compare( oldest, candidate ) > 0 )
        {
            oldest = candidate;
        }
    }
    return oldest;
}
 
Example 12
public final ArtifactVersion[] getVersions( VersionRange versionRange, ArtifactVersion lowerBound,
                                            ArtifactVersion upperBound, boolean includeSnapshots,
                                            boolean includeLower, boolean includeUpper )
{
    final VersionComparator versionComparator = getVersionComparator();
    Set<ArtifactVersion> result = new TreeSet<>( versionComparator );
    for ( ArtifactVersion candidate : Arrays.asList( getVersions( includeSnapshots ) ) )
    {
        if ( versionRange != null && !ArtifactVersions.isVersionInRange( candidate, versionRange ) )
        {
            continue;
        }
        int lower = lowerBound == null ? -1 : versionComparator.compare( lowerBound, candidate );
        int upper = upperBound == null ? +1 : versionComparator.compare( upperBound, candidate );
        if ( lower > 0 || upper < 0 )
        {
            continue;
        }
        if ( ( !includeLower && lower == 0 ) || ( !includeUpper && upper == 0 ) )
        {
            continue;
        }
        if ( !includeSnapshots && ArtifactUtils.isSnapshot( candidate.toString() ) )
        {
            continue;
        }
        result.add( candidate );
    }
    return result.toArray( new ArtifactVersion[result.size()] );
}
 
Example 13
private void renderDependencyDetail( Dependency dependency, ArtifactVersions details )
{
    sink.section2();
    sink.sectionTitle2();
    sink.text( ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() ) );
    sink.sectionTitle2_();
    renderDependencyDetailTable( dependency, details );
    sink.section2_();
}
 
Example 14
private void renderDependencyDetail( Dependency dependency, ArtifactVersions details )
{
    sink.section3();
    sink.sectionTitle3();
    sink.text( MessageFormat.format( getText( "report.pluginDependency" ), new Object[] {
        ArtifactUtils.versionlessKey( dependency.getGroupId(), dependency.getArtifactId() ) } ) );
    sink.sectionTitle3_();
    renderDependencyDetailTable( dependency, details, false, true, true );
    sink.section3_();
}
 
Example 15
@Override
protected void execute(final GitBranchInfo branchInfo) throws MojoExecutionException, MojoFailureException {
    if (branchInfo.isVersioned()) {
        getLog().debug("Versioned Branch: " + branchInfo);
        Matcher gitMatcher = Pattern.compile(branchInfo.getPattern()).matcher(branchInfo.getName());

        // We're in a versioned branch, we expect a non-SNAPSHOT version in the POM.
        if (gitMatcher.matches()) {
            // Always assert that pom versions match our expectations.
            if (hasSnapshotInModel(project)) {
                throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] is defined as a release branch. The maven project or one of its parents is currently a snapshot version.");
            }

            // Non-master version branches require a pom version match of some kind to the branch subgroups.
            if (gitMatcher.groupCount() > 0 && gitMatcher.group(gitMatcher.groupCount()) != null) {
                checkReleaseTypeBranchVersion(branchInfo, gitMatcher);
            }

            // Optionally (default true) reinforce that no dependencies may be snapshots.
            if (enforceNonSnapshots) {
                Set<String> snapshotDeps = getSnapshotDeps();
                if (!snapshotDeps.isEmpty()) {
                    throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] is defined as a release branch. The maven project has the following SNAPSHOT dependencies: " + snapshotDeps.toString());
                }

                Set<String> snapshotPluginDeps = getSnapshotPluginDeps();
                if (!snapshotPluginDeps.isEmpty()) {
                    throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] is defined as a release branch. The maven project has the following SNAPSHOT plugin dependencies: " + snapshotPluginDeps.toString());
                }
            }
        }
    } else if (branchInfo.isSnapshot() && !ArtifactUtils.isSnapshot(project.getVersion())) {
        throw new MojoFailureException("The current git branch: [" + branchInfo.getName() + "] is detected as a SNAPSHOT-type branch, and expects a maven project version ending with -SNAPSHOT. The maven project version found was: [" + project.getVersion() + "]");
    }
}
 
Example 16
private boolean hasSnapshotInModel(final MavenProject project) {
    MavenProject parent = project.getParent();

    boolean projectIsSnapshot = ArtifactUtils.isSnapshot(project.getVersion());
    boolean parentIsSnapshot = parent != null && hasSnapshotInModel(parent);

    return projectIsSnapshot || parentIsSnapshot;
}
 
Example 17
private Set<String> getSnapshotDeps() {
    Set<String> snapshotDeps = new HashSet<>();
    for (Artifact dep : project.getArtifacts()) {
        if (ArtifactUtils.isSnapshot(dep.getVersion())) {
            getLog().debug("SNAPSHOT dependency found: " + dep.toString());
            snapshotDeps.add(dep.toString());
        }
    }

    return snapshotDeps;
}
 
Example 18
Source Project: sarl   Source File: SARLProjectConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
/** Validate the version of the SARL library in the dependencies.
 *
 * <p>The test works for standard Java or Maven projects.
 *
 * <p>Caution: This function should not be called for Eclipse plugins.
 *
 * @throws CoreException if internal error occurs.
 */
protected void validateSARLLibraryVersion() throws CoreException {
	final Map<String, Artifact> artifacts = getMavenProjectFacade().getMavenProject().getArtifactMap();
	final Artifact artifact = artifacts.get(ArtifactUtils.versionlessKey(SARL_GROUP_ID, SARL_ARTIFACT_ID));
	if (artifact != null) {
		validateSARLVersion(SARL_GROUP_ID, SARL_ARTIFACT_ID, artifact.getVersion());
	} else {
		getBuildContext().addMessage(
				getMavenProjectFacade().getPomFile(),
				-1, -1,
				Messages.SARLProjectConfigurator_6,
				BuildContext.SEVERITY_ERROR,
				null);
	}
}
 
Example 19
Source Project: sarl   Source File: SARLProjectConfigurator.java    License: Apache License 2.0 5 votes vote down vote up
/** Validate the version of the SARL compiler in the Maven configuration.
 *
 * @return the SARL bundle.
 * @throws CoreException if internal error occurs.
 */
protected Bundle validateSARLCompilerPlugin() throws CoreException {
	final Map<String, Artifact> plugins = getMavenProjectFacade().getMavenProject().getPluginArtifactMap();
	final Artifact pluginArtifact = plugins.get(ArtifactUtils.versionlessKey(SARL_PLUGIN_GROUP_ID,
			SARL_PLUGIN_ARTIFACT_ID));
	if (pluginArtifact == null) {
		getBuildContext().addMessage(
				getMavenProjectFacade().getPomFile(),
				-1, -1,
				Messages.SARLProjectConfigurator_5,
				BuildContext.SEVERITY_ERROR,
				null);
	} else {
		final String version = pluginArtifact.getVersion();
		if (Strings.isNullOrEmpty(version)) {
			getBuildContext().addMessage(
					getMavenProjectFacade().getPomFile(),
					-1, -1,
					Messages.SARLProjectConfigurator_5,
					BuildContext.SEVERITY_ERROR,
					null);
		} else {
			return validateSARLVersion(
					SARL_PLUGIN_GROUP_ID, SARL_PLUGIN_ARTIFACT_ID,
					version);
		}
	}
	return null;
}
 
Example 20
Source Project: sarl   Source File: AbstractSarlMojo.java    License: Apache License 2.0 5 votes vote down vote up
/** Extract the dependencies that are declared for a Maven plugin.
 * This function reads the list of the dependencies in the configuration
 * resource file with {@link MavenHelper#getConfig(String)}.
 * The key given to {@link MavenHelper#getConfig(String)} is
 * <code>&lt;configurationKeyPrefix&gt;.dependencies</code>.
 *
 * @param configurationKeyPrefix the string that is the prefix in the configuration file.
 * @return the list of the dependencies.
 * @throws MojoExecutionException if something cannot be done when extracting the dependencies.
 */
protected Dependency[] getDependenciesFor(String configurationKeyPrefix) throws MojoExecutionException {
	final List<Dependency> dependencies = new ArrayList<>();
	final Pattern pattern = Pattern.compile(
			"^[ \t\n\r]*([^: \t\n\t]+)[ \t\n\r]*:[ \t\n\r]*([^: \t\n\t]+)[ \t\n\r]*$"); //$NON-NLS-1$
	final String rawDependencies = this.mavenHelper.getConfig(configurationKeyPrefix + ".dependencies"); //$NON-NLS-1$

	final Map<String, Dependency> pomDependencies = this.mavenHelper.getPluginDependencies();

	for (final String dependencyId : rawDependencies.split("\\s*[;|,]+\\s*")) { //$NON-NLS-1$
		final Matcher matcher = pattern.matcher(dependencyId);
		if (matcher != null && matcher.matches()) {
			final String dependencyGroupId = matcher.group(1);
			final String dependencyArtifactId = matcher.group(2);
			final String dependencyKey = ArtifactUtils.versionlessKey(dependencyGroupId, dependencyArtifactId);
			final Dependency dependencyObject = pomDependencies.get(dependencyKey);
			if (dependencyObject == null) {
				throw new MojoExecutionException(MessageFormat.format(
						Messages.AbstractSarlMojo_4, dependencyKey));
			}
			dependencies.add(dependencyObject);
		}
	}

	final Dependency[] dependencyArray = new Dependency[dependencies.size()];
	dependencies.toArray(dependencyArray);
	return dependencyArray;
}
 
Example 21
Source Project: gitflow-maven-plugin   Source File: AbstractGitFlowMojo.java    License: Apache License 2.0 5 votes vote down vote up
protected void checkSnapshotDependencies() throws MojoFailureException {
    getLog().info("Checking for SNAPSHOT versions in dependencies.");

    List<String> snapshots = new ArrayList<String>();
    List<String> builtArtifacts = new ArrayList<String>();

    List<MavenProject> projects = mavenSession.getProjects();
    for (MavenProject project : projects) {
        final MavenProject reloadedProject = reloadProject(project);

        builtArtifacts.add(reloadedProject.getGroupId() + ":" + reloadedProject.getArtifactId() + ":" + reloadedProject.getVersion());

        List<Dependency> dependencies = reloadedProject.getDependencies();
        for (Dependency d : dependencies) {
            String id = d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion();
            if (!builtArtifacts.contains(id) && ArtifactUtils.isSnapshot(d.getVersion())) {
                snapshots.add(reloadedProject + " -> " + d);
            }
        }
    }

    if (!snapshots.isEmpty()) {
        for (String s : snapshots) {
            getLog().warn(s);
        }
        throw new MojoFailureException(
                "There is some SNAPSHOT dependencies in the project, see warnings above. Change them or ignore with `allowSnapshots` property.");
    }
}
 
Example 22
Source Project: deadcode4j   Source File: UpdateChecker.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks if a new version is available for the currently executed plugin.
 *
 * @return the most recent version available or nothing if the running plugin is of newer or equal version
 * @since 2.0.0
 */
@Nonnull
public Optional<ArtifactVersion> checkForUpdate(@Nonnull MojoExecution mojoExecution) {
    Logger logger = LoggerFactory.getLogger(getClass());
    try {
        if (legacySupport.getSession().isOffline()) {
            logger.info("Running in offline mode; skipping update check.");
            return absent();
        }
        Artifact artifact = ArtifactUtils.copyArtifact(
                mojoExecution.getMojoDescriptor().getPluginDescriptor().getPluginArtifact());
        ArtifactVersion versionInUse = artifact.getVersionRange().getRecommendedVersion();
        ArtifactRepositoryMetadata repositoryMetadata = new ArtifactRepositoryMetadata(artifact);
        repositoryMetadataManager.resolve(repositoryMetadata, legacySupport.getSession().getCurrentProject().getPluginArtifactRepositories(), legacySupport.getSession().getLocalRepository());
        ArtifactVersion newestVersion = versionInUse;
        for (String version : repositoryMetadata.getMetadata().getVersioning().getVersions()) {
            ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
            if ("SNAPSHOT".equals(artifactVersion.getQualifier())) {
                continue;
            }
            if (artifactVersion.compareTo(newestVersion) > 0) {
                newestVersion = artifactVersion;
            }
        }
        if (versionInUse.compareTo(newestVersion) >= 0) {
            logger.debug("Running latest version.");
        } else {
            logger.debug("New plugin version [{}] is available.", newestVersion);
            return Optional.of(newestVersion);
        }
    } catch (Exception e) {
        logger.debug("Update check failed!", e);
        logger.warn("Update check failed: {}", e.getMessage());
    }
    return absent();
}
 
Example 23
Source Project: galleon   Source File: ArtifactItem.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * @return Returns the base version.
 */
public String getBaseVersion() {
    return ArtifactUtils.toSnapshotVersion(version);
}
 
Example 24
/**
 * {@inheritDoc}
 */
public ArtifactVersions lookupArtifactVersions( Artifact artifact, boolean usePluginRepositories )
    throws ArtifactMetadataRetrievalException
{
    List remoteRepositories = usePluginRepositories ? remotePluginRepositories : remoteArtifactRepositories;
    final List<ArtifactVersion> versions =
        artifactMetadataSource.retrieveAvailableVersions( artifact, localRepository, remoteRepositories );
    final List<IgnoreVersion> ignoredVersions = getIgnoredVersions( artifact );
    if ( !ignoredVersions.isEmpty() )
    {
        if ( getLog().isDebugEnabled() )
        {
            getLog().debug( "Found ignored versions: " + showIgnoredVersions( ignoredVersions ) );
        }

        final Iterator<ArtifactVersion> i = versions.iterator();
        while ( i.hasNext() )
        {
            final String version = i.next().toString();
            for ( final IgnoreVersion ignoreVersion : ignoredVersions )
            {
                if ( TYPE_REGEX.equals( ignoreVersion.getType() ) )
                {
                    Pattern p = Pattern.compile( ignoreVersion.getVersion() );
                    if ( p.matcher( version ).matches() )
                    {
                        if ( getLog().isDebugEnabled() )
                        {
                            getLog().debug( "Version " + version + " for artifact "
                                + ArtifactUtils.versionlessKey( artifact ) + " found on ignore list: "
                                + ignoreVersion );
                        }
                        i.remove();
                        break;
                    }
                }
                else if ( TYPE_EXACT.equals( ignoreVersion.getType() ) )
                {
                    if ( version.equals( ignoreVersion.getVersion() ) )
                    {
                        if ( getLog().isDebugEnabled() )
                        {
                            getLog().debug( "Version " + version + " for artifact "
                                + ArtifactUtils.versionlessKey( artifact ) + " found on ignore list: "
                                + ignoreVersion );
                        }
                        i.remove();
                        break;
                    }
                }
            }
        }
    }
    return new ArtifactVersions( artifact, versions, getVersionComparator( artifact ) );
}
 
Example 25
public String toString()
{
    return ( usePluginRepositories ? "plugin:" : "artifact:" ) + ArtifactUtils.versionlessKey( artifact );
}
 
Example 26
private void logUpdates( Map<Dependency, ArtifactVersions> updates, String section )
{
    List<String> withUpdates = new ArrayList<>();
    List<String> usingCurrent = new ArrayList<>();
    Iterator i = updates.values().iterator();
    while ( i.hasNext() )
    {
        ArtifactVersions versions = (ArtifactVersions) i.next();
        String left = "  " + ArtifactUtils.versionlessKey( versions.getArtifact() ) + " ";
        final String current;
        ArtifactVersion latest;
        if ( versions.isCurrentVersionDefined() )
        {
            current = versions.getCurrentVersion().toString();
            latest = versions.getNewestUpdate( calculateUpdateScope(), allowSnapshots );
        }
        else
        {
            ArtifactVersion newestVersion =
                versions.getNewestVersion( versions.getArtifact().getVersionRange(), allowSnapshots );
            current = versions.getArtifact().getVersionRange().toString();
            latest = newestVersion == null ? null
                            : versions.getNewestUpdate( newestVersion, calculateUpdateScope(), allowSnapshots );
            if ( latest != null
                && ArtifactVersions.isVersionInRange( latest, versions.getArtifact().getVersionRange() ) )
            {
                latest = null;
            }
        }
        String right = " " + ( latest == null ? current : current + " -> " + latest.toString() );
        List<String> t = latest == null ? usingCurrent : withUpdates;
        if ( right.length() + left.length() + 3 > INFO_PAD_SIZE )
        {
            t.add( left + "..." );
            t.add( StringUtils.leftPad( right, INFO_PAD_SIZE ) );

        }
        else
        {
            t.add( StringUtils.rightPad( left, INFO_PAD_SIZE - right.length(), "." ) + right );
        }
    }

    if ( isVerbose() )
    {
        if ( usingCurrent.isEmpty() )
        {
            if ( !withUpdates.isEmpty() )
            {
                logLine( false, "No dependencies in " + section + " are using the newest version." );
                logLine( false, "" );
            }
        }
        else
        {
            logLine( false, "The following dependencies in " + section + " are using the newest version:" );
            i = usingCurrent.iterator();
            while ( i.hasNext() )
            {
                logLine( false, (String) i.next() );
            }
            logLine( false, "" );
        }
    }        
    
    
    if ( withUpdates.isEmpty() )
    {
        if ( !usingCurrent.isEmpty() )
        {
            logLine( false, "No dependencies in " + section + " have newer versions." );
            logLine( false, "" );
        }
    }
    else
    {
        logLine( false, "The following dependencies in " + section + " have newer versions:" );
        i = withUpdates.iterator();
        while ( i.hasNext() )
        {
            logLine( false, (String) i.next() );
        }
        logLine( false, "" );
    }
}
 
Example 27
Source Project: versions-maven-plugin   Source File: SetMojo.java    License: Apache License 2.0 4 votes vote down vote up
private void applyChange( MavenProject project, SortedMap<String, Model> reactor, Set<File> files, String groupId,
                          String artifactId, String oldVersion )
{

    getLog().debug( "Applying change " + groupId + ":" + artifactId + ":" + oldVersion + " -> " + newVersion );
    // this is a triggering change
    addChange( groupId, artifactId, oldVersion, newVersion );
    // now fake out the triggering change

    final Map.Entry<String, Model> current = PomHelper.getModelEntry( reactor, groupId, artifactId );
    current.getValue().setVersion( newVersion );

    addFile( files, project, current.getKey() );

    for ( Map.Entry<String, Model> sourceEntry : reactor.entrySet() )
    {
        final String sourcePath = sourceEntry.getKey();
        final Model sourceModel = sourceEntry.getValue();

        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;
        }

        addFile( files, project, sourcePath );

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

        for ( Map.Entry<String, Model> stringModelEntry : processAllModules ? reactor.entrySet() : //
                                                                PomHelper.getChildModels( reactor, sourceGroupId,
                                                                                    sourceArtifactId ).entrySet() )
        {
            final Model targetModel = stringModelEntry.getValue();
            final Parent parent = targetModel.getParent();
            getLog().debug( "Module: " + stringModelEntry.getKey() );
            if ( parent != null && sourceVersion.equals( parent.getVersion() ) )
            {
                getLog().debug( "    parent already is "
                    + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId ) + ":" + sourceVersion );
            }
            else
            {
                getLog().debug( "    parent is " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId )
                    + ":" + ( parent == null ? "" : parent.getVersion() ));
                getLog().debug( "    will become " + ArtifactUtils.versionlessKey( sourceGroupId, sourceArtifactId )
                    + ":" + sourceVersion );
            }
            final boolean targetExplicit = PomHelper.isExplicitVersion( targetModel );
            if ( ( updateMatchingVersions || !targetExplicit ) //
                && ( parent != null && 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 ) );
            }
        }
    }
}
 
Example 28
Source Project: build-helper-maven-plugin   Source File: ReleasedVersionMojo.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
public void execute()
{
    org.apache.maven.artifact.Artifact artifact =
        artifactFactory.createArtifact( getProject().getGroupId(), getProject().getArtifactId(), getProject().getVersion(), "", "" );
    try
    {
        ArtifactVersion releasedVersion = null;
        List<ArtifactVersion> versions =
            artifactMetadataSource.retrieveAvailableVersions( artifact, localRepository,
                                                              remoteArtifactRepositories );
        for ( ArtifactVersion version : versions )
        {
            if ( !ArtifactUtils.isSnapshot( version.toString() )
                && ( releasedVersion == null || version.compareTo( releasedVersion ) > 0 ) )
            {
                releasedVersion = version;
            }
        }

        if ( releasedVersion != null )
        {
            // Use ArtifactVersion.toString(), the major, minor and incrementalVersion return all an int.
            String releasedVersionValue = releasedVersion.toString();

            // This would not always reflect the expected version.
            int dashIndex = releasedVersionValue.indexOf( '-' );
            if ( dashIndex >= 0 )
            {
                releasedVersionValue = releasedVersionValue.substring( 0, dashIndex );
            }

            defineVersionProperty( "version", releasedVersionValue );
            defineVersionProperty( "majorVersion", releasedVersion.getMajorVersion() );
            defineVersionProperty( "minorVersion", releasedVersion.getMinorVersion() );
            defineVersionProperty( "incrementalVersion", releasedVersion.getIncrementalVersion() );
            defineVersionProperty( "buildNumber", releasedVersion.getBuildNumber() );
            defineVersionProperty( "qualifier", releasedVersion.getQualifier() );
        }
        else {
            getLog().debug("No released version found.");
        }

    }
    catch ( ArtifactMetadataRetrievalException e )
    {
        if ( getLog().isWarnEnabled() )
        {
            getLog().warn( "Failed to retrieve artifacts metadata, cannot resolve the released version" );
        }
    }
}
 
Example 29
Source Project: sarl   Source File: AbstractCompileMojo.java    License: Apache License 2.0 4 votes vote down vote up
private Set<String> findSARLLibrary(ArtifactVersion compilerVersion, ArtifactVersion maxCompilerVersion,
		StringBuilder classpath, boolean enableTycho) throws MojoExecutionException, MojoFailureException {
	final String sarlLibGroupId = this.mavenHelper.getConfig("sarl-lib.groupId"); //$NON-NLS-1$
	final String sarlLibArtifactId = this.mavenHelper.getConfig("sarl-lib.artifactId"); //$NON-NLS-1$
	final String sarlLibGroupIdTycho = "p2.eclipse-plugin"; //$NON-NLS-1$
	final String sarlLibArtifactIdTycho = this.mavenHelper.getConfig("sarl-lib.osgiBundleId"); //$NON-NLS-1$
	final Set<String> foundVersions = new TreeSet<>();
	for (final Artifact dep : this.mavenHelper.getSession().getCurrentProject().getArtifacts()) {
		getLog().debug(MessageFormat.format(Messages.CompileMojo_4, dep.getGroupId(), dep.getArtifactId(), dep.getVersion()));
		if (classpath.length() > 0) {
			classpath.append(":"); //$NON-NLS-1$
		}
		classpath.append("{"); //$NON-NLS-1$
		classpath.append(ArtifactUtils.versionlessKey(dep));
		classpath.append("}"); //$NON-NLS-1$
		String gid = null;
		String aid = null;
		if (sarlLibGroupId.equals(dep.getGroupId())
				&& sarlLibArtifactId.equals(dep.getArtifactId())) {
			gid = sarlLibGroupId;
			aid = sarlLibArtifactId;
		} else if (enableTycho
				&& sarlLibGroupIdTycho.equals(dep.getGroupId())
				&& sarlLibArtifactIdTycho.equals(dep.getArtifactId())) {
			gid = sarlLibGroupIdTycho;
			aid = sarlLibArtifactIdTycho;
		}
		if (gid != null && aid != null) {
			final ArtifactVersion dependencyVersion = new DefaultArtifactVersion(dep.getVersion());
			if (!containsVersion(dependencyVersion, compilerVersion, maxCompilerVersion)) {
				final String shortMessage = MessageFormat.format(Messages.CompileMojo_5,
						gid, aid, dependencyVersion.toString(),
						compilerVersion.toString(), maxCompilerVersion.toString());
				final String longMessage = MessageFormat.format(Messages.CompileMojo_6,
						sarlLibGroupId, sarlLibArtifactId, dependencyVersion.toString(),
						compilerVersion.toString(), maxCompilerVersion.toString());
				throw new MojoFailureException(this, shortMessage, longMessage);
			}
			foundVersions.add(dep.getVersion());
		}
	}
	return foundVersions;
}
 
Example 30
Source Project: sarl   Source File: AbstractCompileMojo.java    License: Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private void validateDependencyVersions() throws MojoExecutionException, MojoFailureException {
	getLog().info(Messages.CompileMojo_7);
	final String sarlSdkGroupId = this.mavenHelper.getConfig("sarl-sdk.groupId"); //$NON-NLS-1$
	final String sarlSdkArtifactId = this.mavenHelper.getConfig("sarl-sdk.artifactId"); //$NON-NLS-1$

	boolean hasError = false;

	final Map<String, Artifact> projectDependencyTree = this.mavenHelper.getSession().getCurrentProject().getArtifactMap();
	final String sdkArtifactKey = ArtifactUtils.versionlessKey(sarlSdkGroupId, sarlSdkArtifactId);
	final Artifact sdkArtifact = projectDependencyTree.get(sdkArtifactKey);
	if (sdkArtifact != null) {
		final Map<String, ArtifactVersion> pluginDependencyTree = new TreeMap<>();
		final Set<Artifact> pluginScopeDependencies = this.mavenHelper.resolveDependencies(sdkArtifactKey, false);
		for (final Artifact pluginScopeDependency : pluginScopeDependencies) {
			final ArtifactVersion pluginScopeDependencyVersion = new DefaultArtifactVersion(pluginScopeDependency.getVersion());
			final String pluginScopeDependencyKey = ArtifactUtils.versionlessKey(pluginScopeDependency);
			final ArtifactVersion currentVersion = pluginDependencyTree.get(pluginScopeDependencyKey);
			if (currentVersion == null || pluginScopeDependencyVersion.compareTo(currentVersion) > 0) {
				pluginDependencyTree.put(pluginScopeDependencyKey, pluginScopeDependencyVersion);
			}
		}

		for (final Entry<String, Artifact> projectDependency : projectDependencyTree.entrySet()) {
			final ArtifactVersion pluginDependencyArtifactVersion = pluginDependencyTree.get(projectDependency.getKey());
			if (pluginDependencyArtifactVersion != null) {
				final Artifact projectArtifact = projectDependency.getValue();
				final ArtifactVersion projectDependencyVersion = new DefaultArtifactVersion(projectArtifact.getVersion());
				if (Utils.compareMajorMinorVersions(pluginDependencyArtifactVersion, projectDependencyVersion) != 0) {
					final String message = MessageFormat.format(Messages.CompileMojo_8,
							projectArtifact.getGroupId(), projectArtifact.getArtifactId(),
							pluginDependencyArtifactVersion.toString(), projectDependencyVersion.toString());
					getLog().error(message);
					hasError = true;
				}
			}
		}
	}

	if (hasError) {
		throw new MojoFailureException(Messages.CompileMojo_10);
	}
}