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

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

Introduction

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

Prototype

public String toString() 

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()) {//ww  w . ja va 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.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Create a version resolution for the given dependency and artifact.
 *//*  ww  w  .j  a va 2 s .  c om*/
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:org.axway.grapes.maven.resolver.ArtifactResolver.java

/**
 * Finds a version out of a range//  w  ww  . j  a  va2  s. c om
 *
 * @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.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  a v a  2  s  .c o m
 */
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.PomHelper.java

License:Apache License

/**
 * Takes a list of {@link org.apache.maven.model.Plugin} instances and adds associations to properties used to
 * define versions of the plugin artifact or any of the plugin dependencies specified in the pom.
 *
 * @param helper              Our helper.
 * @param expressionEvaluator Our expression evaluator.
 * @param result              The map of {@link org.codehaus.mojo.versions.api.PropertyVersionsBuilder} keyed by property name.
 * @param plugins             The list of {@link org.apache.maven.model.Plugin}.
 * @throws ExpressionEvaluationException if an expression cannot be evaluated.
 *///from   w w w .j  a v  a2  s  .  c om
private static void addPluginAssociations(VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
        Map<String, PropertyVersionsBuilder> result, List<Plugin> plugins)
        throws ExpressionEvaluationException {
    if (plugins == null) {
        return;
    }
    for (Plugin plugin : plugins) {
        String version = plugin.getVersion();
        if (version != null && version.contains("${") && version.indexOf('}') != -1) {
            version = StringUtils.deleteWhitespace(version);
            for (PropertyVersionsBuilder property : result.values()) {
                // any of these could be defined by a property
                final String propertyRef = "${" + property.getName() + "}";
                if (version.contains(propertyRef)) {
                    String groupId = plugin.getGroupId();
                    if (groupId == null || groupId.trim().length() == 0) {
                        // group Id has a special default
                        groupId = APACHE_MAVEN_PLUGINS_GROUPID;
                    } else {
                        groupId = (String) expressionEvaluator.evaluate(groupId);
                    }
                    String artifactId = plugin.getArtifactId();
                    if (artifactId == null || artifactId.trim().length() == 0) {
                        // malformed pom
                        continue;
                    } else {
                        artifactId = (String) expressionEvaluator.evaluate(artifactId);
                    }
                    // might as well capture the current value
                    VersionRange versionRange = VersionRange
                            .createFromVersion((String) expressionEvaluator.evaluate(plugin.getVersion()));
                    property.addAssociation(helper.createPluginArtifact(groupId, artifactId, versionRange),
                            true);
                    if (!propertyRef.equals(version)) {
                        addBounds(property, version, propertyRef, versionRange.toString());
                    }
                }
            }
        }
        addDependencyAssocations(helper, expressionEvaluator, result, plugin.getDependencies(), true);
    }
}

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

License:Apache License

private static void addReportPluginAssociations(VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
        Map<String, PropertyVersionsBuilder> result, List<ReportPlugin> reportPlugins)
        throws ExpressionEvaluationException {
    if (reportPlugins == null) {
        return;/* w ww .  ja v a2s .c om*/
    }
    for (ReportPlugin plugin : reportPlugins) {
        String version = plugin.getVersion();
        if (version != null && version.contains("${") && version.indexOf('}') != -1) {
            version = StringUtils.deleteWhitespace(version);
            for (PropertyVersionsBuilder property : result.values()) {
                final String propertyRef = "${" + property.getName() + "}";
                if (version.contains(propertyRef)) {
                    // any of these could be defined by a property
                    String groupId = plugin.getGroupId();
                    if (groupId == null || groupId.trim().length() == 0) {
                        // group Id has a special default
                        groupId = APACHE_MAVEN_PLUGINS_GROUPID;
                    } else {
                        groupId = (String) expressionEvaluator.evaluate(groupId);
                    }
                    String artifactId = plugin.getArtifactId();
                    if (artifactId == null || artifactId.trim().length() == 0) {
                        // malformed pom
                        continue;
                    } else {
                        artifactId = (String) expressionEvaluator.evaluate(artifactId);
                    }
                    // might as well capture the current value
                    VersionRange versionRange = VersionRange
                            .createFromVersion((String) expressionEvaluator.evaluate(plugin.getVersion()));
                    property.addAssociation(helper.createPluginArtifact(groupId, artifactId, versionRange),
                            true);
                    if (!propertyRef.equals(version)) {
                        addBounds(property, version, propertyRef, versionRange.toString());
                    }
                }
            }
        }
    }
}

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

License:Apache License

private static void addDependencyAssocations(VersionsHelper helper, ExpressionEvaluator expressionEvaluator,
        Map<String, PropertyVersionsBuilder> result, List<Dependency> dependencies,
        boolean usePluginRepositories) throws ExpressionEvaluationException {
    if (dependencies == null) {
        return;//from   w  w w . j a  v  a 2 s . c om
    }
    for (Dependency dependency : dependencies) {
        String version = dependency.getVersion();
        if (version != null && version.contains("${") && version.indexOf('}') != -1) {
            version = StringUtils.deleteWhitespace(version);
            for (PropertyVersionsBuilder property : result.values()) {
                final String propertyRef = "${" + property.getName() + "}";
                if (version.contains(propertyRef)) {
                    // Any of these could be defined by a property
                    String groupId = dependency.getGroupId();
                    if (groupId == null || groupId.trim().length() == 0) {
                        // malformed pom
                        continue;
                    } else {
                        groupId = (String) expressionEvaluator.evaluate(groupId);
                    }
                    String artifactId = dependency.getArtifactId();
                    if (artifactId == null || artifactId.trim().length() == 0) {
                        // malformed pom
                        continue;
                    } else {
                        artifactId = (String) expressionEvaluator.evaluate(artifactId);
                    }
                    // might as well capture the current value
                    VersionRange versionRange = VersionRange
                            .createFromVersion((String) expressionEvaluator.evaluate(dependency.getVersion()));
                    property.addAssociation(helper.createDependencyArtifact(groupId, artifactId, versionRange,
                            dependency.getType(), dependency.getClassifier(), dependency.getScope(),
                            dependency.isOptional()), usePluginRepositories);
                    if (!propertyRef.equals(version)) {
                        addBounds(property, version, propertyRef, versionRange.toString());
                    }
                }
            }
        }
    }
}

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

License:Apache License

public static SchemeAwareVersionRange from(final VersionRange range, final VersionScheme scheme) {
    try {/* www .ja  v a  2  s .co m*/
        return createFromVersionSpec(range.toString(), scheme);
    } catch (final InvalidVersionSpecificationException e) {
        // cannot happen...
    }

    return null;
}

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

License:Apache License

public static SchemeAwareVersionRange from(final VersionRange range, final String scheme) {
    try {/*from w  w w.  ja  v a 2 s .c  om*/
        return createFromVersionSpec(range.toString(), scheme);
    } catch (final InvalidVersionSpecificationException e) {
        // cannot happen...
    }

    return null;
}

From source file:org.fluidity.deployment.maven.DependenciesSupportImpl.java

License:Apache License

/**
 * Converts a Aether artifact to a Maven artifact.
 *
 * @param original the Maven artifact.// w w w  .j ava2  s  . co  m
 *
 * @return the Aether artifact.
 */
private static org.eclipse.aether.artifact.Artifact aetherArtifact(final Artifact original) {
    final String explicitVersion = original.getVersion();
    final VersionRange versionRange = original.getVersionRange();
    final String version = explicitVersion == null && versionRange != null ? versionRange.toString()
            : explicitVersion;

    final boolean isSystem = Artifact.SCOPE_SYSTEM.equals(original.getScope());
    final String path = (original.getFile() != null) ? original.getFile().getPath() : "";
    final Map<String, String> properties = isSystem
            ? Collections.singletonMap(ArtifactProperties.LOCAL_PATH, path)
            : null;

    final ArtifactHandler handler = original.getArtifactHandler();

    final String extension = handler.getExtension();
    final DefaultArtifactType type = new DefaultArtifactType(original.getType(), extension,
            handler.getClassifier(), handler.getLanguage(), handler.isAddedToClasspath(),
            handler.isIncludesDependencies());

    final org.eclipse.aether.artifact.Artifact artifact = new org.eclipse.aether.artifact.DefaultArtifact(
            original.getGroupId(), original.getArtifactId(), original.getClassifier(), extension, version,
            properties, type);
    return artifact.setFile(original.getFile());
}