Example usage for org.apache.maven.artifact.versioning VersionRange getRecommendedVersion

List of usage examples for org.apache.maven.artifact.versioning VersionRange getRecommendedVersion

Introduction

In this page you can find the example usage for org.apache.maven.artifact.versioning VersionRange getRecommendedVersion.

Prototype

public ArtifactVersion getRecommendedVersion() 

Source Link

Usage

From source file:ch.ivyteam.ivy.maven.AbstractEngineMojo.java

License:Apache License

protected final VersionRange getIvyVersionRange() throws MojoExecutionException {
    try {//from  ww w.  ja  v a  2s . c o  m
        VersionRange minimalCompatibleVersionRange = VersionRange
                .createFromVersionSpec("[" + AbstractEngineMojo.MINIMAL_COMPATIBLE_VERSION + ",)");
        VersionRange ivyVersionRange = VersionRange.createFromVersionSpec(ivyVersion);

        if (ivyVersionRange.getRecommendedVersion() != null) {
            ivyVersionRange = VersionRange.createFromVersionSpec("[" + ivyVersion + "]");
        }

        VersionRange restrictedIvyVersionRange = ivyVersionRange.restrict(minimalCompatibleVersionRange);
        if (!restrictedIvyVersionRange.hasRestrictions()) {
            throw new MojoExecutionException(
                    "The ivyVersion '" + ivyVersion + "' is lower than the minimal compatible version" + " '"
                            + MINIMAL_COMPATIBLE_VERSION + "'.");
        }
        return restrictedIvyVersionRange;
    } catch (InvalidVersionSpecificationException ex) {
        throw new MojoExecutionException("Invalid ivyVersion '" + ivyVersion + "'.", ex);
    }
}

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  .jav  a  2  s.co 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.github.klieber.phantomjs.util.VersionUtil.java

License:Open Source License

public static boolean isWithin(String version, VersionRange versionRange) {
    ArtifactVersion artifactVersion = new DefaultArtifactVersion(version);
    ArtifactVersion recommendedVersion = versionRange.getRecommendedVersion();
    // treat recommended version as minimum version
    return recommendedVersion != null ? VersionUtil.isLessThanOrEqualTo(recommendedVersion, artifactVersion)
            : versionRange.containsVersion(artifactVersion);
}

From source file:com.naughtyzombie.calypso.maven.mojo.BuildClasspathMojo.java

License:Apache License

/**
 * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
 * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
 * "[2.0.4,)"//from   w  w w. j  a  v  a  2  s  .c o  m
 *
 * @param allowedRange range of allowed versions.
 * @param theVersion   the version to be checked.
 * @return true if the version is contained by the range.
 */
public static boolean containsVersion(VersionRange allowedRange, ArtifactVersion theVersion) {
    ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
    if (recommendedVersion == null) {
        @SuppressWarnings("unchecked")
        List<Restriction> restrictions = allowedRange.getRestrictions();
        for (Restriction restriction : restrictions) {
            if (restriction.containsVersion(theVersion)) {
                return true;
            }
        }
    }

    // only singular versions ever have a recommendedVersion
    return recommendedVersion.compareTo(theVersion) <= 0;
}

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Create a version resolution for the given dependency and artifact.
 *//*from   www .  ja  v a  2s  . com*/
private VersionResolution resolveVersion(Dependency dependency, Artifact artifact, String artifactName,
        final boolean directArtifact) {
    VersionResolution resolution = null;

    try {
        // Build a version from the artifact that was resolved.
        ArtifactVersion resolvedVersion = artifact.getSelectedVersion();

        if (resolvedVersion == null) {
            resolvedVersion = new DefaultArtifactVersion(artifact.getVersion());
        }

        // versionRange represents the versions that will satisfy the dependency.
        VersionRange versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
        // expectedVersion is the version declared in the dependency.
        ArtifactVersion expectedVersion = versionRange.getRecommendedVersion();

        if (expectedVersion == null) {
            // Fall back to the artifact version if it fits.
            if (versionRange.containsVersion(resolvedVersion)) {
                expectedVersion = resolvedVersion;
            } else {
                LOG.error(
                        "Cannot determine the recommended version of dependency '{}'; its version specification is '{}', and the resolved version is '{}'.",
                        new Object[] { artifactName, dependency.getVersion(), resolvedVersion.toString() });
                return null;
            }
        }

        // Build internal versions
        final Version resolvedVersionObj = new Version(resolvedVersion.toString());
        final Version depVersionObj = new Version(versionRange.toString(), expectedVersion.toString());

        resolution = new VersionResolution(artifactName, artifactName, depVersionObj, resolvedVersionObj,
                directArtifact);

        if (!isExcluded(artifact, depVersionObj, resolvedVersionObj)) {
            final Strategy strategy = findStrategy(resolution);

            if (!(versionRange.containsVersion(resolvedVersion)
                    && strategy.isCompatible(resolvedVersionObj, depVersionObj))) {
                resolution.setConflict(true);
            }
        }
    } catch (InvalidVersionSpecificationException ex) {
        LOG.warn("Could not parse the version specification of an artifact", ex);
    } catch (OverConstrainedVersionException ex) {
        LOG.warn("Could not resolve an artifact", ex);
    }
    return resolution;
}

From source file:de.mytoys.maven.plugins.debug.AbstractDebugMojo.java

License:Apache License

/**
 * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
 * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
 * "[2.0.4,)"//from www . j  av  a 2 s.c  o  m
 *
 * @param allowedRange range of allowed versions.
 * @param theVersion the version to be checked.
 * @return true if the version is contained by the range.
 */
public static boolean containsVersion(VersionRange allowedRange, ArtifactVersion theVersion) {
    ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
    if (recommendedVersion == null) {
        List<Restriction> restrictions = allowedRange.getRestrictions();
        for (Restriction restriction : restrictions) {
            if (restriction.containsVersion(theVersion)) {
                return true;
            }
        }
    }

    // only singular versions ever have a recommendedVersion
    return recommendedVersion.compareTo(theVersion) <= 0;
}

From source file:fr.synchrotron.soleil.ica.ci.maven.plugins.soleildependency.mojo.TreeMojo.java

License:Apache License

/**
 * Copied from Artifact.VersionRange. This is tweaked to handle singular ranges properly. Currently the default
 * containsVersion method assumes a singular version means allow everything. This method assumes that "2.0.4" ==
 * "[2.0.4,)"//ww  w  .  j a v a  2s  .  c o m
 *
 * @param allowedRange range of allowed versions.
 * @param theVersion   the version to be checked.
 * @return true if the version is contained by the range.
 */
public static boolean containsVersion(VersionRange allowedRange, ArtifactVersion theVersion) {
    boolean matched = false;
    ArtifactVersion recommendedVersion = allowedRange.getRecommendedVersion();
    if (recommendedVersion == null) {

        for (Iterator i = allowedRange.getRestrictions().iterator(); i.hasNext() && !matched;) {
            Restriction restriction = (Restriction) i.next();
            if (restriction.containsVersion(theVersion)) {
                matched = true;
            }
        }
    } else {
        // only singular versions ever have a recommendedVersion
        int compareTo = recommendedVersion.compareTo(theVersion);
        matched = (compareTo <= 0);
    }
    return matched;
}

From source file:org.apache.sling.maven.projectsupport.AbstractBundleListMojo.java

License:Apache License

/**
 * Get a resolved Artifact from the coordinates provided
 *
 * @return the artifact, which has been resolved.
 * @throws MojoExecutionException//from  w  ww. j  a v a  2s  . c om
 */
protected Artifact getArtifact(String groupId, String artifactId, String version, String type,
        String classifier) throws MojoExecutionException {
    Artifact artifact;
    VersionRange vr;

    try {
        vr = VersionRange.createFromVersionSpec(version);
    } catch (InvalidVersionSpecificationException e) {
        vr = VersionRange.createFromVersion(version);
    }

    if (StringUtils.isEmpty(classifier)) {
        artifact = factory.createDependencyArtifact(groupId, artifactId, vr, type, null,
                Artifact.SCOPE_COMPILE);
    } else {
        artifact = factory.createDependencyArtifact(groupId, artifactId, vr, type, classifier,
                Artifact.SCOPE_COMPILE);
    }

    // This code kicks in when the version specifier is a range.
    if (vr.getRecommendedVersion() == null) {
        try {
            List<ArtifactVersion> availVersions = metadataSource.retrieveAvailableVersions(artifact, local,
                    remoteRepos);
            ArtifactVersion resolvedVersion = vr.matchVersion(availVersions);
            artifact.setVersion(resolvedVersion.toString());
        } catch (ArtifactMetadataRetrievalException e) {
            throw new MojoExecutionException("Unable to find version for artifact", e);
        }

    }

    try {
        resolver.resolve(artifact, remoteRepos, local);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve artifact.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to find artifact.", e);
    }
    return artifact;
}

From source file:org.axway.grapes.maven.resolver.ArtifactResolver.java

/**
 * Finds a version out of a range// ww w. j  av  a2  s.  c o  m
 *
 * @param range VersionRange
 * @return String
 */
public static String getArtifactVersion(final VersionRange range) {
    if (range.getRecommendedVersion() != null) {
        return range.getRecommendedVersion().toString();
    }

    if (range.hasRestrictions()) {
        for (Restriction restriction : range.getRestrictions()) {
            if (restriction.getLowerBound() != null) {
                return restriction.getLowerBound().toString();
            }
            if (restriction.getUpperBound() != null) {
                return restriction.getLowerBound().toString();
            }
        }
    }

    return range.toString();
}

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

License:Apache License

private static VersionRange createVersionRange(String versionOrRange)
        throws InvalidVersionSpecificationException {
    VersionRange versionRange = VersionRange.createFromVersionSpec(versionOrRange);
    if (versionRange.getRecommendedVersion() != null) {
        versionRange = VersionRange.createFromVersionSpec("[" + versionOrRange + "]");
    }/* w  w w  .ja v  a 2s.c om*/
    return versionRange;
}