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:org.metaeffekt.core.maven.inventory.mojo.AggregateSourceArchivesMojo.java

License:Apache License

private org.apache.maven.artifact.Artifact resolveSourceArtifact(
        org.metaeffekt.core.inventory.processor.model.Artifact artifact) throws MojoFailureException {
    try {/*from  w w  w.  j ava 2s. c  o  m*/
        artifact.deriveArtifactId();

        // preset for default source resolving
        String groupId = artifact.getGroupId();
        String artifactId = artifact.getArtifactId();
        String version = artifact.getVersion();
        String classifier = "sources";
        String type = artifact.getType();

        // enable mapping (by filename)
        if (alternativeArtifactSourceMapping != null
                && alternativeArtifactSourceMapping.getMap().containsKey(artifact.getId())) {
            String mappedSource = alternativeArtifactSourceMapping.getMap().get(artifact.getId());
            // FIXME: for uniqueness a checksum may be required here

            String[] mappedSourceParts = mappedSource.split(":");
            groupId = extractPart(mappedSourceParts, 0, groupId);
            artifactId = extractPart(mappedSourceParts, 1, artifactId);
            version = extractPart(mappedSourceParts, 2, version);
            classifier = extractPart(mappedSourceParts, 3, classifier);
            type = extractPart(mappedSourceParts, 4, type);
        }

        StringBuilder sourceCoordinates = new StringBuilder();
        appendPart(sourceCoordinates, groupId);
        appendPart(sourceCoordinates, artifactId);
        appendPart(sourceCoordinates, version);
        appendPart(sourceCoordinates, classifier);
        appendPart(sourceCoordinates, type);

        DefaultArtifactHandler handler = new DefaultArtifactHandler(type);
        DefaultArtifact sourceArtifact = new DefaultArtifact(groupId, artifactId,
                VersionRange.createFromVersionSpec(version), "runtime", type, classifier, handler);
        getLog().info("Resolving " + sourceArtifact);

        ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        request.setArtifact(sourceArtifact);
        request.setLocalRepository(localRepository);
        request.setRemoteRepositories(remoteRepositories);
        ArtifactResolutionResult result = resolver.resolve(request);
        if (result != null && result.isSuccess()) {
            return result.getArtifacts().iterator().next();
        } else {
            return null;
        }
    } catch (InvalidVersionSpecificationException e) {
        return null;
    }
}

From source file:org.metaeffekt.core.maven.inventory.mojo.DownloadSourcesMojo.java

License:Apache License

private org.apache.maven.artifact.Artifact resolveSourceArtifact(
        org.metaeffekt.core.inventory.processor.model.Artifact artifact) throws MojoFailureException {
    try {/*from w ww . jav  a2 s. co  m*/
        artifact.deriveArtifactId();

        // preset for default source resolving
        String groupId = artifact.getGroupId();
        String artifactId = artifact.getArtifactId();
        String version = artifact.getVersion();
        String classifier = "sources";
        String type = artifact.getType();

        // enable mapping (by filename)
        if (alternativeArtifactSourceMapping != null
                && alternativeArtifactSourceMapping.getMap().containsKey(artifact.getId())) {
            String mappedSource = alternativeArtifactSourceMapping.getMap().get(artifact.getId());
            // FIXME: for uniqueness a checksum may be required here

            String[] mappedSourceParts = mappedSource.split(":");
            groupId = extractPart(mappedSourceParts, 0, groupId);
            artifactId = extractPart(mappedSourceParts, 1, artifactId);
            version = extractPart(mappedSourceParts, 2, version);
            classifier = extractPart(mappedSourceParts, 3, classifier);
            type = extractPart(mappedSourceParts, 4, type);
        }

        StringBuilder sourceCoordinates = new StringBuilder();
        appendPart(sourceCoordinates, groupId);
        appendPart(sourceCoordinates, artifactId);
        appendPart(sourceCoordinates, version);
        appendPart(sourceCoordinates, classifier);
        appendPart(sourceCoordinates, type);

        DefaultArtifactHandler handler = new DefaultArtifactHandler(type);
        DefaultArtifact sourceArtifact = new DefaultArtifact(groupId, artifactId,
                VersionRange.createFromVersionSpec(version), "runtime", type, classifier, handler);
        getLog().info("Resolving " + sourceArtifact);

        ArtifactResolutionRequest request = new ArtifactResolutionRequest();
        request.setArtifact(sourceArtifact);
        request.setLocalRepository(localRepository);
        request.setRemoteRepositories(remoteRepositories);
        ArtifactResolutionResult result = resolver.resolve(request);
        if (result != null && result.isSuccess()) {
            return result.getArtifacts().iterator().next();
        } else {
            logOrFailOn(String.format("Cannot resolve sources for [%s] with source parameters [%s].",
                    artifact.createStringRepresentation(), sourceCoordinates.toString()));
            return null;

        }
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoFailureException(e.getMessage(), e);
    }
}

From source file:org.ops4j.pax.construct.archetype.AbstractPaxArchetypeMojo.java

License:Apache License

/**
 * @return acceptable version range of Pax-Construct archetypes
 *//*from   w  w w .j  a  va2s .com*/
private VersionRange getArchetypeVersionRange() {
    ArtifactVersion version = new DefaultArtifactVersion(pluginVersion);
    int thisRelease = version.getMajorVersion();

    int prevRelease = thisRelease - 1;
    int nextRelease = thisRelease + 1;

    String spec;
    if (false == ArtifactUtils.isSnapshot(pluginVersion)) {
        // keep to same release to avoid potential borkage
        spec = "[" + thisRelease + ',' + nextRelease + ')';
    } else {
        // allow use of previous release during development
        spec = "[" + prevRelease + ',' + nextRelease + ')';
    }

    try {
        return VersionRange.createFromVersionSpec(spec);
    } catch (InvalidVersionSpecificationException e) {
        return null;
    }
}

From source file:org.sakaiproject.nakamura.maven.DroolsCompilerMojo.java

License:Apache License

/**
 * Get a resolved Artifact from the coordinates provided
 * /*  ww w . j a  va  2 s  . c o m*/
 * @return the artifact, which has been resolved.
 * @throws MojoExecutionException
 */
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);
    }
    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.universAAL.maven.treebuilder.DependencyTreeBuilder.java

License:Apache License

/**
 * Method builds dependency tree for a list of maven projects. All artifacts
 * in the tree are crosschecked against duplications and conflicts. In each
 * case of duplication, conflict, the case is resolved by omitting artifact
 * which is lower in the tree and keeping artifact which is higher in the
 * tree. If artifacts are on the same level then the one occuring first in
 * the tree is kept.//from  w ww  . j a v  a  2 s  . com
 * 
 * @param repository
 *            Maven repository.
 * @param factory
 *            Factory used for creating artifacts.
 * @param metadataSource
 *            ArtifactMetadataSource provided by maven.
 * @param projectDescs
 *            list of maven project descriptors. Each descriptor contains
 *            MavenProject, a list of project's remote repositories and a
 *            boolean indicator if the project needs to be resolved
 *            transitively or not.
 * @return a dependency tree as a list of rootnodes (instances of
 *         DependencyNode class) which contain their own subtrees. Each
 *         rootnode corresponds to one maven project provided as argument.
 *         The order of rootnodes list is the same as order of provided
 *         maven projects list.
 * @throws DependencyTreeBuilderException
 *             Notifies about a problem during building the dependency tree.
 * @throws ArtifactMetadataRetrievalException
 *             Signals problem with metadata retieval.
 * @throws InvalidVersionSpecificationException
 *             Informs about invalid version specifications.
 * @throws NoSuchFieldException
 *             Exception related to reflection.
 * @throws SecurityException
 *             Exception thrown by security manager.
 * @throws IllegalAccessException
 *             Illegal access during usage of java reflection.
 * @throws IllegalArgumentException
 *             Illegal argument was passed.
 */
public List<RootNode> buildDependencyTree(final ArtifactRepository repository, final ArtifactFactory factory,
        final ArtifactMetadataSource metadataSource, final MavenProjectDescriptor... projectDescs)
        throws DependencyTreeBuilderException, ArtifactMetadataRetrievalException,
        InvalidVersionSpecificationException, SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException {
    ArtifactFilter filter = new ScopeArtifactFilter();
    DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(filter);
    Map resolvedArtifacts = new LinkedHashMap();
    for (MavenProjectDescriptor projectDesc : projectDescs) {
        MavenProject project = projectDesc.project;
        try {
            List<String> separatedGroupId = extractSeparatedGroupIds(project);

            // Here you can simply add to create a new list
            List remoteRepositories = projectDesc.remoteRepositories;

            // If artifact is marked in pom as a bundle then it is changed
            // to jar. Retaining bundle can impose problems when the
            // artifact is duplicated or conflicted with other artifact
            // specified as a dependency, because in the
            // dependency there is only jar type specified.
            Artifact originatingArtifact = project.getArtifact();
            this.stringifiedRoot = FilteringVisitorSupport.stringify(originatingArtifact);
            if ("bundle".equals(originatingArtifact.getType())) {
                Artifact changeArtifact = artifactFactory.createArtifact(originatingArtifact.getGroupId(),
                        originatingArtifact.getArtifactId(), originatingArtifact.getVersion(),
                        originatingArtifact.getScope(), "jar");
                originatingArtifact = changeArtifact;
            }
            ResolutionNode root = new ResolutionNode(originatingArtifact, remoteRepositories);

            // If the project is not supposed to be transitively resolved
            // then its dependencies are not added to the root. Moreover the
            // parameter is passed to the recurse method. Thanks to than
            // when transitive is false, resolving of runtime dependencies
            // is not performed.
            if (projectDesc.transitive) {
                Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();

                if (dependencyArtifacts == null) {
                    dependencyArtifacts = new LinkedHashSet();
                    List dependencies = project.getDependencies();
                    for (Object depObj : dependencies) {
                        Dependency dep = (Dependency) depObj;
                        if (dep.isOptional()) {
                            // filtering optional dependencies
                            continue;
                        }
                        Artifact dependencyArtifact;
                        VersionRange versionRange = VersionRange.createFromVersionSpec(dep.getVersion());
                        dependencyArtifact = factory.createDependencyArtifact(dep.getGroupId(),
                                dep.getArtifactId(), versionRange, dep.getType(), dep.getClassifier(),
                                dep.getScope());
                        if (dep.getExclusions() != null) {
                            if (!dep.getExclusions().isEmpty()) {
                                List<String> patterns = new ArrayList<String>();
                                for (Exclusion exclusion : dep.getExclusions()) {
                                    patterns.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
                                }
                                dependencyArtifact.setDependencyFilter(new ExcludesArtifactFilter(patterns));
                            }
                        }
                        dependencyArtifacts.add(dependencyArtifact);
                    }
                } else {
                    // filtering optional dependencies
                    Set<Artifact> filteredArtifacts = new LinkedHashSet();
                    for (Artifact a : dependencyArtifacts) {
                        if (!a.isOptional()) {
                            filteredArtifacts.add(a);
                        }
                    }
                    dependencyArtifacts = filteredArtifacts;
                }

                for (Artifact depArtifact : dependencyArtifacts) {
                    if (depArtifact.getVersion() != null) {
                        if (!depArtifact.getVersion().equals(depArtifact.getBaseVersion())) {
                            if (depArtifact.isSnapshot()) {
                                depArtifact.setVersion(depArtifact.getBaseVersion());
                            }
                        }
                    }
                }

                root.addDependencies(dependencyArtifacts, remoteRepositories, filter);
            }

            // Information about managed versions is extracted from the
            // artifact's pom (but also from parent poms and settings.xml
            // file).
            ManagedVersionMap versionMap = getManagedVersionsMap(originatingArtifact,
                    project.getManagedVersionMap());

            recurse(originatingArtifact, root, resolvedArtifacts, versionMap, localRepository,
                    remoteRepositories, metadataSource, filter, listener, projectDesc.transitive,
                    new HashSet<String>(separatedGroupId));
        } catch (ArtifactResolutionException exception) {
            throw new DependencyTreeBuilderException("Cannot build project dependency tree", exception);
        }
    }
    return listener.getRootNodes();
}

From source file:org.xolstice.maven.plugin.protobuf.AbstractProtocMojo.java

License:Open Source License

protected Artifact createDependencyArtifact(final String groupId, final String artifactId, final String version,
        final String type, final String classifier) throws MojoExecutionException {
    final VersionRange versionSpec;
    try {/*from  www  .ja va2  s.  c  om*/
        versionSpec = VersionRange.createFromVersionSpec(version);
    } catch (final InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Invalid version specification", e);
    }
    return artifactFactory.createDependencyArtifact(groupId, artifactId, versionSpec, type, classifier,
            Artifact.SCOPE_RUNTIME);
}

From source file:org.xolstice.maven.plugin.protobuf.ProtocPluginAssembler.java

License:Open Source License

private void resolvePluginDependencies() throws MojoExecutionException {

    final VersionRange versionSpec;
    try {//w  w  w  .  j  a v a 2  s  .  c om
        versionSpec = VersionRange.createFromVersionSpec(pluginDefinition.getVersion());
    } catch (InvalidVersionSpecificationException e) {
        throw new MojoExecutionException("Invalid plugin version specification", e);
    }
    final Artifact protocPluginArtifact = artifactFactory.createDependencyArtifact(
            pluginDefinition.getGroupId(), pluginDefinition.getArtifactId(), versionSpec, "jar",
            pluginDefinition.getClassifier(), Artifact.SCOPE_RUNTIME);

    try {
        final ArtifactResolutionRequest request = new ArtifactResolutionRequest()
                .setArtifact(rootResolutionArtifact).setResolveRoot(false)
                .setArtifactDependencies(Collections.singleton(protocPluginArtifact))
                .setManagedVersionMap(Collections.emptyMap()).setLocalRepository(localRepository)
                .setRemoteRepositories(remoteRepositories).setOffline(session.isOffline())
                .setForceUpdate(session.getRequest().isUpdateSnapshots())
                .setServers(session.getRequest().getServers()).setMirrors(session.getRequest().getMirrors())
                .setProxies(session.getRequest().getProxies());

        final ArtifactResolutionResult result = repositorySystem.resolve(request);

        resolutionErrorHandler.throwErrors(request, result);

        final Set<Artifact> artifacts = result.getArtifacts();

        if (artifacts == null || artifacts.isEmpty()) {
            throw new MojoExecutionException("Unable to resolve plugin artifact");
        }

        for (final Artifact artifact : artifacts) {
            resolvedJars.add(artifact.getFile());
        }

        if (log.isDebugEnabled()) {
            log.debug("Resolved jars: " + resolvedJars);
        }
    } catch (final ArtifactResolutionException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:org.xwiki.tool.enforcer.XWikiBannedDependencies.java

License:Open Source License

@Override
protected boolean compareDependency(String[] pattern, Artifact artifact) throws EnforcerRuleException {
    boolean result = false;
    if (pattern.length > 0) {
        result = artifact.getGroupId().matches(pattern[0]);
    }//w  ww  .j  av  a  2  s  .  co  m

    if (result && pattern.length > 1) {
        result = artifact.getArtifactId().matches(pattern[1]);
    }

    if (result && pattern.length > 2) {
        // short circuit if the versions are exactly the same
        if (pattern[2].equals("*") || artifact.getVersion().equals(pattern[2])) {
            result = true;
        } else {
            try {
                result = AbstractVersionEnforcer.containsVersion(VersionRange.createFromVersionSpec(pattern[2]),
                        new DefaultArtifactVersion(artifact.getBaseVersion()));
            } catch (InvalidVersionSpecificationException e) {
                throw new EnforcerRuleException("Invalid Version Range: ", e);
            }
        }
    }

    if (result && pattern.length > 3) {
        String type = artifact.getType();
        if (type == null || type.equals("")) {
            type = "jar";
        }
        result = pattern[3].equals("*") || type.equals(pattern[3]);
    }

    if (result && pattern.length > 4) {
        String scope = artifact.getScope();
        if (scope == null || scope.equals("")) {
            scope = "compile";
        }
        result = pattern[4].equals("*") || scope.equals(pattern[4]);
    }

    return result;
}