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

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

Introduction

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

Prototype

public static VersionRange createFromVersionSpec(String spec) throws InvalidVersionSpecificationException 

Source Link

Document

Create a version range from a string representation

Some spec examples are:
  • 1.0 Version 1.0
  • [1.0,2.0) Versions 1.0 (included) to 2.0 (not included)
  • [1.0,2.0] Versions 1.0 to 2.0 (both included)
  • [1.5,) Versions 1.5 and higher
  • (,1.0],[1.2,) Versions up to 1.0 (included) and 1.2 or higher

Usage

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

License:Apache License

protected final VersionRange getIvyVersionRange() throws MojoExecutionException {
    try {/*w w w . j a  va2 s  .  co 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.adviser.maven.MojoSupport.java

License:Apache License

protected Map createManagedVersionMap(String projectId, DependencyManagement dependencyManagement)
        throws ProjectBuildingException {
    Map map;/* www. ja v  a2 s  .  c o  m*/
    if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
        map = new HashMap();
        for (Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext();) {
            Dependency d = (Dependency) i.next();

            try {
                VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
                Artifact artifact = factory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(),
                        versionRange, d.getType(), d.getClassifier(), d.getScope());
                map.put(d.getManagementKey(), artifact);
            } catch (InvalidVersionSpecificationException e) {
                throw new ProjectBuildingException(projectId, "Unable to parse version '" + d.getVersion()
                        + "' for dependency '" + d.getManagementKey() + "': " + e.getMessage());
            }
        }
    } else {
        map = Collections.EMPTY_MAP;
    }
    return map;
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Returns the list of project artifacts. Also artifacts generated from referenced projects will be added, but with
 * the <code>resolved</code> property set to true.
 *
 * @return list of projects artifacts/*from w ww .  j  av  a  2s .  c o m*/
 * @throws MojoExecutionException if unable to parse dependency versions
 */
private Set getProjectArtifacts() throws MojoExecutionException {
    // [MECLIPSE-388] Don't sort this, the order should be identical to getProject.getDependencies()
    Set artifacts = new LinkedHashSet();

    for (Iterator dependencies = getProject().getDependencies().iterator(); dependencies.hasNext();) {
        Dependency dependency = (Dependency) dependencies.next();

        String groupId = dependency.getGroupId();
        String artifactId = dependency.getArtifactId();
        VersionRange versionRange;
        try {
            versionRange = VersionRange.createFromVersionSpec(dependency.getVersion());
        } catch (InvalidVersionSpecificationException e) {
            throw new MojoExecutionException(Messages.getString("AbstractIdeSupportMojo.unabletoparseversion", //$NON-NLS-1$
                    new Object[] { dependency.getArtifactId(), dependency.getVersion(), dependency.getManagementKey(),
                            e.getMessage() }),
                    e);
        }

        String type = dependency.getType();
        if (type == null) {
            type = Constants.PROJECT_PACKAGING_JAR;
        }
        String classifier = dependency.getClassifier();
        boolean optional = dependency.isOptional();
        String scope = dependency.getScope();
        if (scope == null) {
            scope = Artifact.SCOPE_COMPILE;
        }

        Artifact art = getArtifactFactory().createDependencyArtifact(groupId, artifactId, versionRange, type,
                classifier, scope, optional);

        if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
            art.setFile(new File(dependency.getSystemPath()));
        }

        handleExclusions(art, dependency);

        artifacts.add(art);
    }

    return artifacts;
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

private Map createManagedVersionMap(ArtifactFactory artifactFactory, String projectId,
        DependencyManagement dependencyManagement) throws MojoExecutionException {
    Map map;/* w  w  w.  j  a v  a2  s .c  om*/
    if (dependencyManagement != null && dependencyManagement.getDependencies() != null) {
        map = new HashMap();
        for (Iterator i = dependencyManagement.getDependencies().iterator(); i.hasNext();) {
            Dependency d = (Dependency) i.next();

            try {
                VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion());
                Artifact artifact = artifactFactory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(),
                        versionRange, d.getType(), d.getClassifier(), d.getScope(), d.isOptional());

                handleExclusions(artifact, d);
                map.put(d.getManagementKey(), artifact);
            } catch (InvalidVersionSpecificationException e) {
                throw new MojoExecutionException(
                        Messages.getString("AbstractIdeSupportMojo.unabletoparseversion", new Object[] { //$NON-NLS-1$
                                projectId, d.getVersion(), d.getManagementKey(), e.getMessage() }),
                        e);
            }
        }
    } else {
        map = Collections.EMPTY_MAP;
    }
    return map;
}

From source file:com.alibaba.citrus.maven.eclipse.base.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Checks whether the currently running Maven satisfies the specified version (range).
 *
 * @param version The version range to test for, must not be <code>null</code>.
 * @return <code>true</code> if the current Maven version matches the specified version range, <code>false</code>
 *         otherwise.// w  w  w. j  av a 2 s . c  om
 */
protected boolean isMavenVersion(String version) {
    try {
        VersionRange versionRange = VersionRange.createFromVersionSpec(version);
        ArtifactVersion mavenVersion = runtimeInformation.getApplicationVersion();
        return versionRange.containsVersion(mavenVersion);
    } catch (InvalidVersionSpecificationException e) {
        throw new IllegalArgumentException(e.getMessage());
    }
}

From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java

License:Open Source License

private Artifact getArtifact(BundleInfo bundle) throws MojoExecutionException, MojoFailureException {
    Artifact artifact;//from w ww  . j  a v  a  2s. co  m

    /*
     * Anything in the gav may be interpolated.
     * Version may be "-dependency-" to look for the artifact as a dependency.
     */

    String gav = interpolator.interpolate(bundle.gav);
    String[] pieces = gav.split("/");
    String groupId = pieces[0];
    String artifactId = pieces[1];
    String versionStr;
    String classifier = null;
    if (pieces.length == 3) {
        versionStr = pieces[2];
    } else {
        classifier = pieces[2];
        versionStr = pieces[3];
    }

    if ("-dependency-".equals(versionStr)) {
        versionStr = getArtifactVersionFromDependencies(groupId, artifactId);
        if (versionStr == null) {
            throw new MojoFailureException(String.format(
                    "Request for %s:%s as a dependency, but it is not a dependency", groupId, artifactId));
        }
    }

    VersionRange vr;
    try {
        vr = VersionRange.createFromVersionSpec(versionStr);
    } catch (InvalidVersionSpecificationException e1) {
        throw new MojoExecutionException("Bad version range " + versionStr, e1);
    }

    artifact = factory.createDependencyArtifact(groupId, artifactId, vr, "jar", classifier,
            Artifact.SCOPE_COMPILE);

    // Maven 3 will search the reactor for the artifact but Maven 2 does not
    // to keep consistent behaviour, we search the reactor ourselves.
    Artifact result = getArtifactFomReactor(artifact);
    if (result != null) {
        return result;
    }

    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:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

License:Apache License

protected Artifact getArtifact(ArtifactItem artifactItem)
        throws MojoExecutionException, InvalidVersionSpecificationException {
    Artifact artifact;//from  w w  w  . j a  va 2s  .com

    VersionRange vr = VersionRange.createFromVersionSpec(artifactItem.getVersion());

    if (StringUtils.isEmpty(artifactItem.getClassifier())) {
        artifact = factory.createDependencyArtifact(artifactItem.getGroupId(), artifactItem.getArtifactId(), vr,
                artifactItem.getType(), null, Artifact.SCOPE_COMPILE);
    } else {
        artifact = factory.createDependencyArtifact(artifactItem.getGroupId(), artifactItem.getArtifactId(), vr,
                artifactItem.getType(), artifactItem.getClassifier(), Artifact.SCOPE_COMPILE);
    }

    try {
        resolver.resolve(artifact, remoteRepos, local);
    } catch (ArtifactResolutionException | ArtifactNotFoundException e) {
        throw new MojoExecutionException("Error resolving artifact " + artifact, e);
    }

    return artifact;
}

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()) {/* ww  w . j  ava  2s . 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.github.klieber.phantomjs.util.VersionUtil.java

License:Open Source License

public static boolean isWithin(String version, String versionSpec) {
    boolean within = false;
    try {//ww w. j a  v  a 2 s  . c  om
        return VersionUtil.isWithin(version, VersionRange.createFromVersionSpec(versionSpec));
    } catch (InvalidVersionSpecificationException e) {
        LOGGER.warn("Invalid version specification: {}", versionSpec);
    }
    return within;
}

From source file:com.github.maven_nar.AttachedNarArtifact.java

License:Apache License

public AttachedNarArtifact(final String groupId, final String artifactId, final String version,
        final String scope, final String type, final String classifier, final boolean optional, final File file)
        throws InvalidVersionSpecificationException {
    super(groupId, artifactId, VersionRange.createFromVersionSpec(version), scope, type, classifier, null,
            optional);//from   w  w w .j  a  v a  2 s. co m
    setArtifactHandler(new Handler(classifier));
    setFile(new File(file.getParentFile(),
            artifactId + "-" + VersionRange.createFromVersionSpec(version) + "-" + classifier + "." + type));
}