Java Code Examples for org.apache.maven.artifact.versioning.ArtifactVersion#compareTo()

The following examples show how to use org.apache.maven.artifact.versioning.ArtifactVersion#compareTo() . 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: RequiredMavenVersionFinder.java    From versions-maven-plugin with Apache License 2.0 6 votes vote down vote up
private ArtifactVersion getHighestArtifactVersion(ArtifactVersion firstMavenVersion, ArtifactVersion secondMavenVersion) {
    if (null == firstMavenVersion && null == secondMavenVersion) {
        return null;
    }

    if (null == firstMavenVersion) {
        return secondMavenVersion;
    }

    if (null == secondMavenVersion) {
        return firstMavenVersion;
    }

    if (firstMavenVersion.compareTo(secondMavenVersion) < 0) {
        return secondMavenVersion;
    }

    return firstMavenVersion;
}
 
Example 2
Source File: FixVersionConflictPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Checks the circumstances of version conflict and offers solution.
 *
 * @return description of found recommended solution
 */
private FixDescription computeRecommendations() {
    FixDescription recs = new FixDescription();

    boolean isDirect = conflictNode.getPrimaryLevel() == 1;
    ArtifactVersion usedVersion = new DefaultArtifactVersion(
            conflictNode.getImpl().getArtifact().getVersion());
    ArtifactVersion newAvailVersion = getClashingVersions().get(0);

    // case: direct dependency to older version -> recommend update to newer
    if (isDirect && usedVersion.compareTo(newAvailVersion) < 0) {
        recs.isSet = true;
        recs.version2Set = newAvailVersion;
    }

    // case: more then one exclusion target, several of them are "good guys"
    // which means they have non conflicting dependency on newer version ->
    // recommend adding dependency exclusion to all but mentioned "good" targets
    Set<Artifact> nonConf = eTargets.getNonConflicting();
    if (!nonConf.isEmpty() && eTargets.getAll().size() > 1) {
        recs.isExclude = true;
        recs.exclusionTargets = eTargets.getConflicting();
    }

    // last try - brute force -> recommend exclude all and add dependency in some cases
    if (!recs.isSet && !recs.isExclude) {
        if (usedVersion.compareTo(newAvailVersion) < 0) {
            recs.isSet = true;
            recs.version2Set = newAvailVersion;
            recs.isExclude = true;
            recs.exclusionTargets = eTargets.getAll();
        }
    }

    return recs;
}
 
Example 3
Source File: LibraryFile.java    From google-cloud-eclipse with Apache License 2.0 5 votes vote down vote up
/**
 * Check Maven Central to find the latest release version of this artifact.
 * This check is made at most once. Subsequent checks are no-ops.
 */
void updateVersion() {
  if (!fixedVersion && !isPinned()) {
    ArtifactVersion remoteVersion = ArtifactRetriever.DEFAULT.getBestVersion(
        mavenCoordinates.getGroupId(), mavenCoordinates.getArtifactId());
    if (remoteVersion != null) {
      DefaultArtifactVersion localVersion = new DefaultArtifactVersion(mavenCoordinates.getVersion());
      if (remoteVersion.compareTo(localVersion) > 0) {
        String updatedVersion = remoteVersion.toString(); 
        mavenCoordinates = mavenCoordinates.toBuilder().setVersion(updatedVersion).build();
      }
    }
    fixedVersion = true;
  }
}
 
Example 4
Source File: VersionUtil.java    From phantomjs-maven-plugin with MIT License 5 votes vote down vote up
private static int compare(ArtifactVersion versionA, ArtifactVersion versionB) {
  if (versionA == versionB) {
    return 0;
  }
  if (versionA == null) {
    return -1;
  }
  if (versionB == null) {
    return 1;
  }
  return versionA.compareTo(versionB);
}
 
Example 5
Source File: UpdateChecker.java    From deadcode4j with 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 6
Source File: MinimumVersionAgentMetadataInspector.java    From genie with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public InspectionReport inspect(@Valid final AgentClientMetadata agentClientMetadata) {

    final String minimumVersionString = this.agentFilterProperties.getMinimumVersion();
    final String agentVersionString = agentClientMetadata.getVersion().orElse(null);

    if (StringUtils.isBlank(minimumVersionString)) {
        return InspectionReport.newAcceptance("Minimum version requirement not set");

    } else if (StringUtils.isBlank(agentVersionString)) {
        return InspectionReport.newRejection("Agent version not set");

    } else {
        final ArtifactVersion minimumVersion = new DefaultArtifactVersion(minimumVersionString);
        final ArtifactVersion agentVersion = new DefaultArtifactVersion(agentVersionString);

        final boolean deprecated = minimumVersion.compareTo(agentVersion) > 0;

        return new InspectionReport(
            deprecated ? InspectionReport.Decision.REJECT : InspectionReport.Decision.ACCEPT,
            String.format(
                "Agent version: %s is %s than minimum: %s",
                agentVersionString,
                deprecated ? "older" : "newer or equal",
                minimumVersionString
            )
        );
    }
}
 
Example 7
Source File: VersionUtil.java    From maven-confluence-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static LinkedList<String> sortAndFilter(Collection<String> versionNameList,
                                               String start,
                                               String end) {

    final ArtifactVersion startVersion = parseArtifactVersion(start);
    final ArtifactVersion endVersion;
    if (end != null && !end.isEmpty()) {
        endVersion = parseArtifactVersion(end);
    } else {
        endVersion = null;
    }


    if (endVersion!=null && startVersion.compareTo(endVersion) > 0) {
        throw new IllegalArgumentException(
                String.format("startVersion %s must be less or equals to endVersion %s",
                        startVersion, endVersion));

    }

    LinkedList<String> linkedList = new LinkedList<String>();

    Map<ArtifactVersion, String> map = new HashMap<ArtifactVersion, String>();

    for (String versionTag : versionNameList) {
        map.put(parseArtifactVersion(versionTag), versionTag);
    }


    List<ArtifactVersion> artifactVersionSet = new ArrayList<ArtifactVersion>(map.keySet());


    CollectionUtils.filter(artifactVersionSet, new Predicate() {
        @Override
        public boolean evaluate(Object o) {
            ArtifactVersion current = (ArtifactVersion) o;
            if (endVersion != null) {
                if (startVersion.compareTo(current) <= 0
                        &&
                        endVersion.compareTo(current) >= 0) {
                    return true;
                }
            } else {
                if (startVersion.compareTo(current) <= 0) {
                    return true;
                }
            }

            return false;
        }
    });

    Collections.sort(artifactVersionSet);
    for (ArtifactVersion artifactVersion : artifactVersionSet) {
        linkedList.add(map.get(artifactVersion));
    }
    return linkedList;

}
 
Example 8
Source File: PropertyVersions.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
private static SortedSet<ArtifactVersion> resolveAssociatedVersions( VersionsHelper helper,
                                                                     Set<ArtifactAssociation> associations,
                                                                     VersionComparator versionComparator )
    throws ArtifactMetadataRetrievalException
{
    SortedSet<ArtifactVersion> versions = null;
    for ( ArtifactAssociation association : associations )
    {
        final ArtifactVersions associatedVersions =
            helper.lookupArtifactVersions( association.getArtifact(), association.isUsePluginRepositories() );
        if ( versions != null )
        {
            final ArtifactVersion[] artifactVersions = associatedVersions.getVersions( true );
            // since ArtifactVersion does not override equals, we have to do this the hard way
            // result.retainAll( Arrays.asList( artifactVersions ) );
            Iterator j = versions.iterator();
            while ( j.hasNext() )
            {
                boolean contains = false;
                ArtifactVersion version = (ArtifactVersion) j.next();
                for ( ArtifactVersion artifactVersion : artifactVersions )
                {
                    if ( version.compareTo( artifactVersion ) == 0 )
                    {
                        contains = true;
                        break;
                    }
                }
                if ( !contains )
                {
                    j.remove();
                }
            }
        }
        else
        {
            versions = new TreeSet<>( versionComparator );
            versions.addAll( Arrays.asList( associatedVersions.getVersions( true ) ) );
        }
    }
    if ( versions == null )
    {
        versions = new TreeSet<>( versionComparator );
    }
    return Collections.unmodifiableSortedSet( versions );
}
 
Example 9
Source File: MavenVersionComparator.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public int compare( ArtifactVersion o1, ArtifactVersion o2 )
{
    return o1.compareTo( o2 );
}
 
Example 10
Source File: DisplayPluginUpdatesMojo.java    From versions-maven-plugin with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings( "unchecked" )
private static int compare( ArtifactVersion a, ArtifactVersion b )
{
    return a.compareTo( b );
}
 
Example 11
Source File: ReleasedVersionMojo.java    From build-helper-maven-plugin with 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 12
Source File: AbstractCompileMojo.java    From sarl with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
private static boolean containsVersion(ArtifactVersion version, ArtifactVersion rangeMin, ArtifactVersion rangeMax) {
	return (version.compareTo(rangeMin) >= 0) && (version.compareTo(rangeMax) < 0);
}
 
Example 13
Source File: AbstractCompileMojo.java    From sarl with 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);
	}
}