Example usage for org.apache.maven.artifact.versioning Restriction getLowerBound

List of usage examples for org.apache.maven.artifact.versioning Restriction getLowerBound

Introduction

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

Prototype

public ArtifactVersion getLowerBound() 

Source Link

Usage

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()) {/*  w  w  w . ja va2s .c o  m*/
        Artifact snapshotArtifact = artifactWithProjects.getKey();
        Collection<MavenProject> projects = artifactWithProjects.getValue();

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

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

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

From source file:com.puppetlabs.geppetto.forge.maven.plugin.PomMetadataExtractor.java

License:Open Source License

@Override
public Metadata performMetadataExtraction(File existingFile, Diagnostic result) throws IOException {
    Metadata metadata = new Metadata();
    String gid = mavenProject.getGroupId();
    String owner = gid.substring(gid.lastIndexOf('.') + 1);
    metadata.setName(ModuleName.create(owner, mavenProject.getArtifactId(), true));
    metadata.setVersion(Version.create(mavenProject.getVersion()));
    metadata.setSummary(mavenProject.getName());

    Scm scm = mavenProject.getScm();/*from   w  ww .  j a v a  2s.c  o m*/
    if (scm != null)
        metadata.setSource(scm.getUrl());

    metadata.setProjectPage(mavenProject.getUrl());

    List<Dependency> forgeDeps = null;
    for (org.apache.maven.model.Dependency dep : mavenProject.getDependencies()) {
        if ("test".equals(dep.getScope()))
            continue;

        try {
            org.apache.maven.artifact.versioning.VersionRange vr = org.apache.maven.artifact.versioning.VersionRange
                    .createFromVersionSpec(dep.getVersion());
            List<Restriction> restrictions = vr.getRestrictions();
            if (restrictions.size() == 1) {
                Restriction r = restrictions.get(0);
                Version lower = r.getLowerBound() == null ? Version.MIN
                        : Version.create(r.getLowerBound().toString());
                Version upper = r.getUpperBound() == null ? Version.MAX
                        : Version.create(r.getUpperBound().toString());

                Dependency forgeDep = new Dependency();
                String dgid = mavenProject.getGroupId();
                String downer = dgid.substring(dgid.lastIndexOf('.') + 1);
                forgeDep.setName(ModuleName.create(downer, dep.getArtifactId(), true));
                forgeDep.setVersionRequirement(VersionRange.create(lower, r.isLowerBoundInclusive(), upper,
                        r.isUpperBoundInclusive()));

                if (forgeDeps == null)
                    forgeDeps = new ArrayList<Dependency>();
                forgeDeps.add(forgeDep);
            }
        } catch (InvalidVersionSpecificationException e) {
            result.addChild(new FileDiagnostic(Diagnostic.WARNING, ValidationService.GEPPETTO, e.getMessage(),
                    mavenProject.getFile()));
        }
    }
    metadata.setDependencies(forgeDeps);
    return metadata;
}

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

/**
 * Finds a version out of a range/*from   www.  ja  v  a2s.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.cloudsmith.geppetto.forge.maven.plugin.PomMetadataExtractor.java

License:Open Source License

@Override
public Metadata performMetadataExtraction(File existingFile, Diagnostic result) throws IOException {
    Metadata metadata = new Metadata();
    metadata.setName(new ModuleName(mavenProject.getGroupId(), mavenProject.getArtifactId(), true));
    metadata.setVersion(Version.create(mavenProject.getVersion()));
    metadata.setSummary(mavenProject.getName());

    Scm scm = mavenProject.getScm();/*from w  ww  . ja  v  a2  s .  c om*/
    if (scm != null)
        metadata.setSource(scm.getUrl());

    metadata.setProjectPage(mavenProject.getUrl());

    List<Dependency> forgeDeps = null;
    for (org.apache.maven.model.Dependency dep : mavenProject.getDependencies()) {
        if ("test".equals(dep.getScope()))
            continue;

        try {
            org.apache.maven.artifact.versioning.VersionRange vr = org.apache.maven.artifact.versioning.VersionRange
                    .createFromVersionSpec(dep.getVersion());
            List<Restriction> restrictions = vr.getRestrictions();
            if (restrictions.size() == 1) {
                Restriction r = restrictions.get(0);
                Version lower = r.getLowerBound() == null ? Version.MIN
                        : Version.create(r.getLowerBound().toString());
                Version upper = r.getUpperBound() == null ? Version.MAX
                        : Version.create(r.getUpperBound().toString());

                Dependency forgeDep = new Dependency();
                forgeDep.setName(new ModuleName(dep.getGroupId(), dep.getArtifactId(), true));
                forgeDep.setVersionRequirement(VersionRange.create(lower, r.isLowerBoundInclusive(), upper,
                        r.isUpperBoundInclusive()));

                if (forgeDeps == null)
                    forgeDeps = new ArrayList<Dependency>();
                forgeDeps.add(forgeDep);
            }
        } catch (InvalidVersionSpecificationException e) {
            result.addChild(new FileDiagnostic(Diagnostic.WARNING, ValidationService.GEPPETTO, e.getMessage(),
                    mavenProject.getFile()));
        }
    }
    metadata.setDependencies(forgeDeps);
    return metadata;
}

From source file:org.codehaus.mojo.pomtools.wrapper.custom.DependencyWrapper.java

License:Apache License

protected boolean setBoundedVersion(String boundVersionSpec, boolean isLower) throws PomToolsVersionException {
    boolean isUpper = !isLower;

    try {/*w w  w.  java  2 s . c  o  m*/
        ModelVersionRange currentRange = getVersionRange();
        ModelVersionRange newRange = ModelVersionRange.createFromVersionSpec(boundVersionSpec);

        if (currentRange != null && currentRange.hasRestrictions()) {
            Restriction curres = (Restriction) currentRange.getRestrictions().get(0);
            Restriction newres = (Restriction) newRange.getRestrictions().get(0);
            Restriction r = new Restriction(
                    (isLower || curres.getLowerBound() == null) ? newres.getLowerBound()
                            : curres.getLowerBound(),
                    (isLower || curres.getLowerBound() == null) ? newres.isLowerBoundInclusive()
                            : curres.isLowerBoundInclusive(),
                    (isUpper || curres.getUpperBound() == null) ? newres.getUpperBound()
                            : curres.getUpperBound(),
                    (isUpper || curres.getUpperBound() == null) ? newres.isUpperBoundInclusive()
                            : curres.isUpperBoundInclusive());

            currentRange.getRestrictions().clear();
            currentRange.getRestrictions().add(r);
        } else {
            currentRange = newRange;
        }

        String strVersion = currentRange.toString();
        if (ModelHelper.isParsableVersion(strVersion)) {
            setVersion(currentRange.toString());
            return true;
        } else {
            return false;
        }

    } catch (InvalidVersionSpecificationException e) {
        throw new PomToolsVersionException("Unable to parse version: " + boundVersionSpec, e);
    }
}

From source file:org.codehaus.mojo.pomtools.wrapper.custom.ModelVersionRange.java

License:Apache License

/** {@link VersionRange#hasRestrictions()} returns false if it has a recommendedVersion regarless
 * of whether it has restrictions or not.  We actually need to know if it has restrictions,
 * so this function re-implements the hasRestrictions to actually determine if the range has
 * restrictions./*from   www. j a  va  2  s  .c  o m*/
 */
public static boolean hasRestrictions(VersionRange range) {
    if (range == null) {
        return false;
    }

    List restrictions = range.getRestrictions();
    if (restrictions != null && !restrictions.isEmpty()) {
        if (restrictions.size() > 1) {
            return true;
        }

        Restriction restriction = (Restriction) restrictions.get(0);
        return restriction.getLowerBound() != null || restriction.getUpperBound() != null;
    } else {
        return false;
    }
}

From source file:org.codehaus.mojo.pomtools.wrapper.custom.ModelVersionRange.java

License:Apache License

/** {@link VersionRange#toString()} simply returns the recommended version if it has
 * a recommended version; otherwise it builds a proper string based on the restrictions.
 * We need the string build with restrictions if there are any; so this is a copy of the guts
 * of {@link VersionRange#toString()} except we build the string with restrictions regardless 
 * of having a recommendedVersion./*from w w  w  . j ava2s. com*/
 */
public static String toString(VersionRange range) {
    if (range == null) {
        return null;
    }

    if (!hasRestrictions(range)) {
        return range.toString();
    } else {
        StringBuffer buf = new StringBuffer();
        for (Iterator i = range.getRestrictions().iterator(); i.hasNext();) {
            Restriction r = (Restriction) i.next();

            buf.append(r.isLowerBoundInclusive() ? "[" : "(");
            if (r.getLowerBound() != null) {
                buf.append(r.getLowerBound().toString());
            }
            buf.append(",");
            if (r.getUpperBound() != null) {
                buf.append(r.getUpperBound().toString());
            }
            buf.append(r.isUpperBoundInclusive() ? "]" : ")");

            if (i.hasNext()) {
                buf.append(",");
            }
        }
        return buf.toString();
    }
}

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

License:Apache License

/**
 * Checks if the version is in the range (and ensures that the range respects the <code>-!</code> syntax
 * to rule out any qualifiers from range boundaries).
 *
 * @param version the version to check.//from  w ww  . j  a  v a 2  s . c  om
 * @param range   the range to check.
 * @return <code>true</code> if and only if the version is in the range.
 * @since 1.3
 */
public static boolean isVersionInRange(ArtifactVersion version, VersionRange range) {
    if (!range.containsVersion(version)) {
        return false;
    }
    for (Restriction r : ((List<Restriction>) range.getRestrictions())) {
        if (r.containsVersion(version)) {
            // check for the -! syntax
            if (!r.isLowerBoundInclusive() && r.getLowerBound() != null) {
                String s = r.getLowerBound().toString();
                if (s.endsWith("-!") && version.toString().startsWith(s.substring(0, s.length() - 2))) {
                    return false;
                }
            }
            if (!r.isUpperBoundInclusive() && r.getUpperBound() != null) {
                String s = r.getUpperBound().toString();
                if (s.endsWith("-!") && version.toString().startsWith(s.substring(0, s.length() - 2))) {
                    return false;
                }
            }
        }
    }
    return true;
}

From source file:org.commonjava.emb.component.vscheme.SchemeAwareVersionRange.java

License:Apache License

@SuppressWarnings("unchecked")
public static SchemeAwareVersionRange createFromVersionSpec(final String spec, final VersionScheme scheme)
        throws InvalidVersionSpecificationException {
    if (spec == null) {
        return null;
    }/*from  ww  w .  j a v a  2  s .com*/

    final List<Restriction> restrictions = new ArrayList<Restriction>();
    String process = spec;
    ArtifactVersion version = null;
    ArtifactVersion upperBound = null;
    ArtifactVersion lowerBound = null;

    while (process.startsWith("[") || process.startsWith("(")) {
        final int index1 = process.indexOf(")");
        final int index2 = process.indexOf("]");

        int index = index2;
        if (index2 < 0 || index1 < index2) {
            if (index1 >= 0) {
                index = index1;
            }
        }

        if (index < 0) {
            throw new InvalidVersionSpecificationException("Unbounded range: " + spec);
        }

        final Restriction restriction = parseRestriction(process.substring(0, index + 1), scheme);
        if (lowerBound == null) {
            lowerBound = restriction.getLowerBound();
        }
        if (upperBound != null) {
            if (restriction.getLowerBound() == null || restriction.getLowerBound().compareTo(upperBound) < 0) {
                throw new InvalidVersionSpecificationException("Ranges overlap: " + spec);
            }
        }
        restrictions.add(restriction);
        upperBound = restriction.getUpperBound();

        process = process.substring(index + 1).trim();

        if (process.length() > 0 && process.startsWith(",")) {
            process = process.substring(1).trim();
        }
    }

    if (process.length() > 0) {
        if (restrictions.size() > 0) {
            throw new InvalidVersionSpecificationException(
                    "Only fully-qualified sets allowed in multiple set scenario: " + spec);
        } else {
            version = new SchemeAwareArtifactVersion(process, scheme);
            restrictions.add(Restriction.EVERYTHING);
        }
    }

    return new SchemeAwareVersionRange(version, restrictions, scheme);
}

From source file:org.commonjava.emb.component.vscheme.SchemeAwareVersionRange.java

License:Apache License

@SuppressWarnings("unchecked")
private List<Restriction> intersection(final List<Restriction> r1, final List<Restriction> r2) {
    final List<Restriction> restrictions = new ArrayList<Restriction>(r1.size() + r2.size());
    final Iterator<Restriction> i1 = r1.iterator();
    final Iterator<Restriction> i2 = r2.iterator();
    Restriction res1 = i1.next();
    Restriction res2 = i2.next();//from  ww  w. j a v  a 2  s . c om

    boolean done = false;
    while (!done) {
        if (res1.getLowerBound() == null || res2.getUpperBound() == null
                || res1.getLowerBound().compareTo(res2.getUpperBound()) <= 0) {
            if (res1.getUpperBound() == null || res2.getLowerBound() == null
                    || res1.getUpperBound().compareTo(res2.getLowerBound()) >= 0) {
                ArtifactVersion lower;
                ArtifactVersion upper;
                boolean lowerInclusive;
                boolean upperInclusive;

                // overlaps
                if (res1.getLowerBound() == null) {
                    lower = res2.getLowerBound();
                    lowerInclusive = res2.isLowerBoundInclusive();
                } else if (res2.getLowerBound() == null) {
                    lower = res1.getLowerBound();
                    lowerInclusive = res1.isLowerBoundInclusive();
                } else {
                    final int comparison = res1.getLowerBound().compareTo(res2.getLowerBound());
                    if (comparison < 0) {
                        lower = res2.getLowerBound();
                        lowerInclusive = res2.isLowerBoundInclusive();
                    } else if (comparison == 0) {
                        lower = res1.getLowerBound();
                        lowerInclusive = res1.isLowerBoundInclusive() && res2.isLowerBoundInclusive();
                    } else {
                        lower = res1.getLowerBound();
                        lowerInclusive = res1.isLowerBoundInclusive();
                    }
                }

                if (res1.getUpperBound() == null) {
                    upper = res2.getUpperBound();
                    upperInclusive = res2.isUpperBoundInclusive();
                } else if (res2.getUpperBound() == null) {
                    upper = res1.getUpperBound();
                    upperInclusive = res1.isUpperBoundInclusive();
                } else {
                    final int comparison = res1.getUpperBound().compareTo(res2.getUpperBound());
                    if (comparison < 0) {
                        upper = res1.getUpperBound();
                        upperInclusive = res1.isUpperBoundInclusive();
                    } else if (comparison == 0) {
                        upper = res1.getUpperBound();
                        upperInclusive = res1.isUpperBoundInclusive() && res2.isUpperBoundInclusive();
                    } else {
                        upper = res2.getUpperBound();
                        upperInclusive = res2.isUpperBoundInclusive();
                    }
                }

                // don't add if they are equal and one is not inclusive
                if (lower == null || upper == null || lower.compareTo(upper) != 0) {
                    restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive));
                } else if (lowerInclusive && upperInclusive) {
                    restrictions.add(new Restriction(lower, lowerInclusive, upper, upperInclusive));
                }

                // noinspection ObjectEquality
                if (upper == res2.getUpperBound()) {
                    // advance res2
                    if (i2.hasNext()) {
                        res2 = i2.next();
                    } else {
                        done = true;
                    }
                } else {
                    // advance res1
                    if (i1.hasNext()) {
                        res1 = i1.next();
                    } else {
                        done = true;
                    }
                }
            } else {
                // move on to next in r1
                if (i1.hasNext()) {
                    res1 = i1.next();
                } else {
                    done = true;
                }
            }
        } else {
            // move on to next in r2
            if (i2.hasNext()) {
                res2 = i2.next();
            } else {
                done = true;
            }
        }
    }

    return restrictions;
}