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

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

Introduction

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

Prototype

public static VersionRange createFromVersion(String version) 

Source Link

Usage

From source file:org.carlspring.maven.commons.util.ArtifactUtils.java

License:Apache License

public static Artifact convertDependencyToArtifact(Dependency dependency) {
    return new DefaultArtifact(dependency.getGroupId(), dependency.getArtifactId(),
            VersionRange.createFromVersion(dependency.getVersion()), dependency.getScope(),
            dependency.getType(), dependency.getClassifier(), new DefaultArtifactHandler(dependency.getType()));
}

From source file:org.codehaus.mojo.antlr.stubs.DependencyProjectStub.java

License:Apache License

public Artifact getArtifact() {
    if (artifact == null) {
        ArtifactHandler ah = new DefaultArtifactHandlerStub("jar", null);

        VersionRange vr = VersionRange.createFromVersion("1.0");
        Artifact art = new DefaultArtifact("group", "artifact", vr, Artifact.SCOPE_COMPILE, "jar", null, ah,
                false);//  ww  w .  ja  va  2s  . c o  m
        setArtifact(art);
    }
    return artifact;
}

From source file:org.codehaus.mojo.appassembler.CreateRepositoryMojo.java

License:Open Source License

private void installBooterArtifacts(ArtifactRepository artifactRepository) throws MojoExecutionException {
    Artifact artifact = artifactFactory.createDependencyArtifact("org.codehaus.mojo.appassembler",
            "appassembler-booter", VersionRange.createFromVersion(pluginVersion), "jar", null,
            Artifact.SCOPE_RUNTIME);/*from  w  w w  . java  2s .c  om*/
    try {
        Artifact p = artifactFactory.createBuildArtifact("org.codehaus.mojo.appassembler",
                "appassembler-maven-plugin", pluginVersion, "jar");

        ArtifactFilter filter = new ExcludesArtifactFilter(Collections.singletonList("junit:junit"));
        ArtifactResolutionResult result = artifactResolver.resolveTransitively(Collections.singleton(artifact),
                p, localRepository, Collections.EMPTY_LIST, metadataSource, filter);
        for (Iterator i = result.getArtifacts().iterator(); i.hasNext();) {
            Artifact a = (Artifact) i.next();
            installArtifact(a, artifactRepository, this.useTimestampInSnapshotFileName);
        }
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Failed to copy artifact.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Failed to copy artifact.", e);
    }
}

From source file:org.codehaus.mojo.clirr.AbstractClirrMojo.java

License:Apache License

private Artifact resolveArtifact(ArtifactSpecification artifactSpec)
        throws MojoFailureException, MojoExecutionException {
    final String groupId = artifactSpec.getGroupId();
    if (groupId == null) {
        throw new MojoFailureException("An artifacts groupId is required.");
    }/*from w  ww  .  java  2s .  com*/
    final String artifactId = artifactSpec.getArtifactId();
    if (artifactId == null) {
        throw new MojoFailureException("An artifacts artifactId is required.");
    }
    final String version = artifactSpec.getVersion();
    if (version == null) {
        throw new MojoFailureException("An artifacts version number is required.");
    }
    final VersionRange versionRange = VersionRange.createFromVersion(version);
    String type = artifactSpec.getType();
    if (type == null) {
        type = "jar";
    }

    Artifact artifact = factory.createDependencyArtifact(groupId, artifactId, versionRange, type,
            artifactSpec.getClassifier(), Artifact.SCOPE_COMPILE);
    return artifact;
}

From source file:org.codehaus.mojo.javascript.AbstractCompressMojo.java

License:Apache License

private JSCompressor getCompressor() throws MojoExecutionException {
    if (compressors.containsKey(compressor)) {
        return (JSCompressor) compressors.get(compressor);
    }//from   w w  w  .j  ava 2  s . c o  m

    // Inspired by the surefire plugin
    // allows to use multiple compressor that rely on modifier Rhino engines
    // without dependencies/classpath conflicts

    String id = compressor.toLowerCase() + "-compressor";

    // TODO don't have version hardcoded
    Artifact compressorArtifact = artifactFactory.createDependencyArtifact("org.codehaus.mojo.javascript", id,
            VersionRange.createFromVersion("1.0-alpha-1-SNAPSHOT"), "jar", null, Artifact.SCOPE_RUNTIME);

    Artifact originatingArtifact = artifactFactory.createBuildArtifact("dummy", "dummy", "1.0", "jar");

    ArtifactResolutionResult dependencies;
    try {
        dependencies = artifactResolver.resolveTransitively(Collections.singleton(compressorArtifact),
                originatingArtifact, localRepository, remoteRepositories, metadataSource, null);
    } catch (Exception e) {
        getLog().info("Failed to load compressor artifact " + compressorArtifact.toString());
        throw new MojoExecutionException("Failed to load compressor artifact" + compressorArtifact.toString(),
                e);
    }

    IsolatedClassLoader classLoader = new IsolatedClassLoader(dependencies.getArtifacts());

    compressor = StringUtils.capitalize(compressor);
    String compressorClassName = "org.codehaus.mojo.javascript.compress." + compressor + "Compressor";
    Class compressorClass;
    try {
        compressorClass = classLoader.loadClass(compressorClassName);
    } catch (ClassNotFoundException e) {
        getLog().info("Failed to load compressor class " + compressorClassName);
        throw new MojoExecutionException("Failed to load compressor class" + compressorClassName, e);
    }

    JSCompressor jscompressor;
    try {
        jscompressor = new JSCompressorProxy(compressorClass.newInstance());
    } catch (Exception e) {
        getLog().info("Failed to create a isolated-classloader proxy for " + compressorClassName);
        throw new MojoExecutionException(
                "Failed to create a isolated-classloader proxy for " + compressorClassName, e);
    }
    getLog().info("Compressing javascript using " + compressor);

    compressors.put(compressor, jscompressor);
    return jscompressor;
}

From source file:org.codehaus.mojo.javascript.stub.ArtifactStub.java

License:Apache License

/**
 * {@inheritDoc}/*from   w  ww  . j  ava 2 s .co m*/
 * 
 * @see org.apache.maven.plugin.testing.stubs.ArtifactStub#getVersionRange()
 */
public VersionRange getVersionRange() {
    return VersionRange.createFromVersion(getVersion());
}

From source file:org.codehaus.mojo.jsimport.AbstractImportMojo.java

License:Apache License

/**
 * Build up the dependency graph and global symbol table by parsing the project's dependencies.
 * /*from  w  ww.ja  v a  2s .  c  o  m*/
 * @param scope compile or test.
 * @param fileDependencyGraphModificationTime the time that the dependency graph was updated. Used for file time
 *            comparisons to check the age of them.
 * @param processedFiles an insert-ordered set of files that have been processed.
 * @param targetFolder Where the target files live.
 * @param workFolder Where we can create some long lived information that may be useful to subsequent builds.
 * @param compileWorkFolder Ditto but in the case of testing it points to where the compile working folder is.
 * @return true if the dependency graph has been updated.
 * @throws MojoExecutionException if something bad happens.
 */
private boolean buildDependencyGraphForDependencies(Scope scope, long fileDependencyGraphModificationTime,
        LinkedHashSet<File> processedFiles, File targetFolder, File workFolder, File compileWorkFolder)
        throws MojoExecutionException {
    File targetJsFolder = new File(targetFolder, "js");

    boolean fileDependencyGraphUpdated = false;

    // Determine how we need to filter things both for direct filtering and transitive filtering.

    String scopeStr = (scope == Scope.COMPILE ? Artifact.SCOPE_COMPILE : Artifact.SCOPE_TEST);

    AndArtifactFilter jsArtifactFilter = new AndArtifactFilter();
    jsArtifactFilter.add(new ScopeArtifactFilter(scopeStr));
    jsArtifactFilter.add(new TypeArtifactFilter("js"));

    AndArtifactFilter wwwZipArtifactFilter = new AndArtifactFilter();
    wwwZipArtifactFilter.add(new ScopeArtifactFilter(scopeStr));
    wwwZipArtifactFilter.add(new TypeArtifactFilter("zip"));
    wwwZipArtifactFilter.add(new ArtifactFilter() {
        public boolean include(Artifact artifact) {
            return artifact.hasClassifier() && artifact.getClassifier().equals("www");
        }
    });

    // Determine the artifacts to resolve and associate their transitive dependencies.

    Map<Artifact, LinkedHashSet<Artifact>> directArtifactWithTransitives = new HashMap<Artifact, LinkedHashSet<Artifact>>(
            dependencies.size());

    Set<Artifact> directArtifacts = new HashSet<Artifact>(dependencies.size());
    LinkedHashSet<Artifact> transitiveArtifacts = new LinkedHashSet<Artifact>();

    for (Dependency dependency : dependencies) {
        // Process imports and symbols of this dependencies' transitives
        // first.
        Artifact directArtifact = artifactFactory.createDependencyArtifact(dependency.getGroupId(),
                dependency.getArtifactId(), VersionRange.createFromVersion(dependency.getVersion()),
                dependency.getType(), dependency.getClassifier(), dependency.getScope());

        if (!jsArtifactFilter.include(directArtifact) && !wwwZipArtifactFilter.include(directArtifact)) {
            continue;
        }

        Set<Artifact> artifactsToResolve = new HashSet<Artifact>(1);
        artifactsToResolve.add(directArtifact);

        ArtifactResolutionResult result;
        try {
            result = resolver.resolveTransitively(artifactsToResolve, project.getArtifact(), remoteRepositories,
                    localRepository, artifactMetadataSource);
        } catch (ArtifactResolutionException e) {
            throw new MojoExecutionException("Problem resolving dependencies", e);
        } catch (ArtifactNotFoundException e) {
            throw new MojoExecutionException("Problem resolving dependencies", e);
        }

        // Associate the transitive dependencies with the direct dependency and aggregate all transitives for
        // collection later.

        LinkedHashSet<Artifact> directTransitiveArtifacts = new LinkedHashSet<Artifact>(
                result.getArtifacts().size());
        for (Object o : result.getArtifacts()) {
            Artifact resolvedArtifact = (Artifact) o;
            if (jsArtifactFilter.include(resolvedArtifact) && //
                    !resolvedArtifact.equals(directArtifact)) {
                directTransitiveArtifacts.add(resolvedArtifact);
            }
        }

        directArtifacts.add(directArtifact);
        transitiveArtifacts.addAll(directTransitiveArtifacts);
        directArtifactWithTransitives.put(directArtifact, directTransitiveArtifacts);
    }

    // Resolve the best versions of the transitives to use by asking Maven to collect them.

    Set<Artifact> collectedArtifacts = new HashSet<Artifact>(
            directArtifacts.size() + transitiveArtifacts.size());
    Map<ArtifactId, Artifact> indexedCollectedDependencies = new HashMap<ArtifactId, Artifact>(
            collectedArtifacts.size());
    try {
        // Note that we must pass an insert-order set into the collector. The collector appears to assume that order
        // is significant, even though it is undocumented.
        LinkedHashSet<Artifact> collectableArtifacts = new LinkedHashSet<Artifact>(directArtifacts);
        collectableArtifacts.addAll(transitiveArtifacts);

        ArtifactResolutionResult resolutionResult = artifactCollector.collect(collectableArtifacts,
                project.getArtifact(), localRepository, remoteRepositories, artifactMetadataSource, null, //
                Collections.EMPTY_LIST);
        for (Object o : resolutionResult.getArtifacts()) {
            Artifact collectedArtifact = (Artifact) o;
            collectedArtifacts.add(collectedArtifact);

            // Build up an index of of collected transitive dependencies so that we can we refer back to them as we
            // process the direct dependencies.
            ArtifactId collectedArtifactId = new ArtifactId(collectedArtifact.getGroupId(),
                    collectedArtifact.getArtifactId());
            indexedCollectedDependencies.put(collectedArtifactId, collectedArtifact);
        }

        if (getLog().isDebugEnabled()) {
            getLog().debug("Dependencies collected: " + collectedArtifacts.toString());
        }
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Cannot collect dependencies", e);
    }

    // Now go through direct artifacts and process their transitives.

    LocalRepositoryCollector localRepositoryCollector = new LocalRepositoryCollector(project, localRepository,
            new File[] {});

    for (Entry<Artifact, LinkedHashSet<Artifact>> entry : directArtifactWithTransitives.entrySet()) {
        Artifact directArtifact = entry.getKey();
        LinkedHashSet<Artifact> directArtifactTransitives = entry.getValue();

        LinkedHashSet<String> transitivesAsImports = new LinkedHashSet<String>(
                directArtifactTransitives.size());

        for (Object o : directArtifactTransitives) {
            Artifact directTransitiveArtifact = (Artifact) o;

            // Get the transitive artifact that Maven decided was the best to use.

            ArtifactId directTransitiveArtifactId = new ArtifactId(directTransitiveArtifact.getGroupId(),
                    directTransitiveArtifact.getArtifactId());
            Artifact transitiveArtifact = indexedCollectedDependencies.get(directTransitiveArtifactId);

            List<File> transitiveArtifactFiles = getArtifactFiles(transitiveArtifact, targetFolder, workFolder,
                    compileWorkFolder, localRepositoryCollector);

            // Only process this dependency if we've not done so
            // already.
            for (File transitiveArtifactFile : transitiveArtifactFiles) {
                if (!processedFiles.contains(transitiveArtifactFile)) {
                    String localRepository = localRepositoryCollector
                            .findLocalRepository(transitiveArtifactFile.getAbsolutePath());
                    if (localRepository != null) {
                        if (processFileForImportsAndSymbols(new File(localRepository), targetJsFolder,
                                transitiveArtifactFile, fileDependencyGraphModificationTime,
                                directArtifactTransitives)) {

                            processedFiles.add(transitiveArtifactFile);

                            fileDependencyGraphUpdated = true;
                        }
                    } else {
                        throw new MojoExecutionException(
                                "Problem determining local repository for transitive file: "
                                        + transitiveArtifactFile);
                    }
                }

                // Add transitives to the artifacts set of dependencies -
                // as if they were @import statements themselves.
                transitivesAsImports.add(transitiveArtifactFile.getPath());
            }
        }

        // Now deal with the pom specified dependency.
        List<File> artifactFiles = getArtifactFiles(directArtifact, targetFolder, workFolder, compileWorkFolder,
                localRepositoryCollector);
        for (File artifactFile : artifactFiles) {
            String artifactPath = artifactFile.getAbsolutePath();

            // Process imports and symbols of this dependency if we've not
            // already done so.
            if (!processedFiles.contains(artifactFile)) {
                String localRepository = localRepositoryCollector
                        .findLocalRepository(artifactFile.getAbsolutePath());
                if (localRepository != null) {
                    if (processFileForImportsAndSymbols(new File(localRepository), targetJsFolder, artifactFile,
                            fileDependencyGraphModificationTime, null)) {
                        processedFiles.add(artifactFile);

                        fileDependencyGraphUpdated = true;
                    }
                } else {
                    throw new MojoExecutionException(
                            "Problem determining local repository for file: " + artifactFile);
                }
            }

            // Add in our transitives to the dependency graph if they're not
            // already there.
            LinkedHashSet<String> existingImports = fileDependencies.get(artifactPath);
            if (existingImports.addAll(transitivesAsImports)) {
                if (getLog().isDebugEnabled()) {
                    getLog().debug("Using transitives as import: " + transitivesAsImports + " for file: "
                            + artifactPath);
                }
                fileDependencyGraphUpdated = true;
            }
        }

    }

    return fileDependencyGraphUpdated;
}

From source file:org.codehaus.mojo.mrm.maven.ProxyArtifactStore.java

License:Apache License

/**
 * {@inheritDoc}//from ww  w. ja  va 2 s.  c  o  m
 */
public Metadata getMetadata(String path) throws IOException, MetadataNotFoundException {
    path = StringUtils.strip(path, "/");
    int index = path.lastIndexOf('/');
    int index2 = index == -1 ? -1 : path.lastIndexOf('/', index - 1);

    String version = index2 == -1 ? null : path.substring(index + 1);
    String artifactId = index2 == -1 ? null : path.substring(index2 + 1, index);
    String groupId = index2 == -1 ? null : path.substring(0, index2).replace('/', '.');

    Metadata metadata = new Metadata();

    boolean foundSomething = false;

    // is this path a groupId:artifactId pair?
    if (version != null && version.endsWith("-SNAPSHOT") && !StringUtils.isEmpty(artifactId)
            && !StringUtils.isEmpty(groupId)) {
        final org.apache.maven.artifact.Artifact artifact = artifactFactory.createDependencyArtifact(groupId,
                artifactId, VersionRange.createFromVersion(version), "pom", null, "compile");
        final SnapshotArtifactRepositoryMetadata artifactRepositoryMetadata = new SnapshotArtifactRepositoryMetadata(
                artifact);
        try {
            repositoryMetadataManager.resolve(artifactRepositoryMetadata, remoteRepositories, localRepository);

            final Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata();
            if (artifactMetadata.getVersioning() != null
                    && artifactMetadata.getVersioning().getSnapshot() != null) {
                foundSomething = true;
                metadata.setGroupId(groupId);
                metadata.setArtifactId(artifactId);
                metadata.setVersion(version);
                metadata.merge(artifactMetadata);
            }
            try {
                if (artifactMetadata.getVersioning() != null
                        && !artifactMetadata.getVersioning().getSnapshotVersions().isEmpty()) {
                    // TODO up to and including Maven 3.0.3 we do not get a populated SnapshotVersions
                    for (SnapshotVersion v : artifactMetadata.getVersioning().getSnapshotVersions()) {
                        metadata.getVersioning().addSnapshotVersion(v);
                        if (v.getVersion().endsWith("-SNAPSHOT")) {
                            addResolved(new Artifact(groupId, artifactId, version, v.getClassifier(),
                                    v.getExtension()));
                        }
                    }
                }
            } catch (NoSuchMethodError e) {
                // ignore Maven 2.x doesn't give us the info
            }
        } catch (RepositoryMetadataResolutionException e) {
            log.debug(e);
        }
    }

    // is this path a groupId:artifactId pair?
    artifactId = index == -1 ? null : path.substring(index + 1);
    groupId = index == -1 ? null : path.substring(0, index).replace('/', '.');
    if (!StringUtils.isEmpty(artifactId) && !StringUtils.isEmpty(groupId)) {
        final org.apache.maven.artifact.Artifact artifact = artifactFactory.createDependencyArtifact(groupId,
                artifactId, anyVersion, "pom", null, "compile");
        final ArtifactRepositoryMetadata artifactRepositoryMetadata = new ArtifactRepositoryMetadata(artifact);
        try {
            repositoryMetadataManager.resolve(artifactRepositoryMetadata, remoteRepositories, localRepository);

            final Metadata artifactMetadata = artifactRepositoryMetadata.getMetadata();
            if (artifactMetadata.getVersioning() != null) {
                foundSomething = true;
                if (StringUtils.isEmpty(metadata.getGroupId())) {
                    metadata.setGroupId(groupId);
                    metadata.setArtifactId(artifactId);
                }
                metadata.merge(artifactMetadata);
                for (String v : artifactMetadata.getVersioning().getVersions()) {
                    addResolved(path + "/" + v);
                }
            }
        } catch (RepositoryMetadataResolutionException e) {
            log.debug(e);
        }
    }

    // if this path a groupId on its own?
    groupId = path.replace('/', '.');
    final GroupRepositoryMetadata groupRepositoryMetadata = new GroupRepositoryMetadata(groupId);
    try {
        repositoryMetadataManager.resolve(groupRepositoryMetadata, remotePluginRepositories, localRepository);
        foundSomething = true;
        metadata.merge(groupRepositoryMetadata.getMetadata());
        for (Plugin plugin : groupRepositoryMetadata.getMetadata().getPlugins()) {
            addResolved(path + "/" + plugin.getArtifactId());
        }
    } catch (RepositoryMetadataResolutionException e) {
        log.debug(e);
    }

    if (!foundSomething) {
        throw new MetadataNotFoundException(path);
    }
    addResolved(path);
    return metadata;
}

From source file:org.codehaus.mojo.pluginsupport.MojoSupport.java

License:Apache License

protected Set getProjectArtifacts(final MavenProject project, final boolean resolve)
        throws MojoExecutionException {
    Set artifacts = new HashSet();

    Iterator dependencies = project.getDependencies().iterator();
    while (dependencies.hasNext()) {
        Dependency dep = (Dependency) dependencies.next();

        String groupId = dep.getGroupId();
        String artifactId = dep.getArtifactId();
        VersionRange versionRange = VersionRange.createFromVersion(dep.getVersion());
        String type = dep.getType();
        if (type == null) {
            type = "jar";
        }/*ww w. j a  v a 2s. c  om*/

        String classifier = dep.getClassifier();
        boolean optional = dep.isOptional();
        String scope = dep.getScope();
        if (scope == null) {
            scope = Artifact.SCOPE_COMPILE;
        }

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

        if (scope.equalsIgnoreCase(Artifact.SCOPE_SYSTEM)) {
            artifact.setFile(new File(dep.getSystemPath()));
        }

        List exclusions = new ArrayList();
        for (Iterator j = dep.getExclusions().iterator(); j.hasNext();) {
            Exclusion e = (Exclusion) j.next();
            exclusions.add(e.getGroupId() + ":" + e.getArtifactId());
        }

        ArtifactFilter newFilter = new ExcludesArtifactFilter(exclusions);
        artifact.setDependencyFilter(newFilter);

        if (resolve && !artifact.isResolved()) {
            log.debug("Resolving artifact: " + artifact);
            artifact = resolveArtifact(artifact);
        }

        artifacts.add(artifact);
    }

    return artifacts;
}

From source file:org.codehaus.mojo.unzip.UnzipMojo.java

License:Apache License

public void execute() throws MojoExecutionException {
    for (int i = 0; i < dependencies.length; ++i) {
        VersionRange versionRange = VersionRange.createFromVersion(dependencies[i].getVersion());
        ArtifactHandler artifactHandler = new DefaultArtifactHandler(dependencies[i].getType());

        DefaultArtifact artifact = new DefaultArtifact(dependencies[i].getGroupId(),
                dependencies[i].getArtifactId(), versionRange, dependencies[i].getScope(),
                dependencies[i].getType(), dependencies[i].getClassifier(), artifactHandler);

        File artifactFile = new File(localRepository.getBasedir(), localRepository.pathOf(artifact));
        File targetUnCompress = new File(
                this.project.getBuild().getDirectory() + File.separatorChar + this.unzipSource);

        this.getLog().info("Unzip file '" + artifactFile.getAbsolutePath() + "' to directory  '"
                + targetUnCompress.getAbsolutePath() + "'.");
        try {// ww w  .  ja  va 2  s  . c  o  m
            if (!targetUnCompress.exists()) {
                this.getLog().debug("Create directory : " + targetUnCompress.getAbsolutePath());
                targetUnCompress.mkdirs();
            }
            ZipManager.unzip(artifactFile, targetUnCompress.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            this.getLog().error("le fichier  dcompresser : " + artifactFile.getAbsolutePath()
                    + " ne peut pas tre dcomprss");

        }
    }
}