Example usage for org.apache.maven.artifact.resolver ArtifactResolutionResult isSuccess

List of usage examples for org.apache.maven.artifact.resolver ArtifactResolutionResult isSuccess

Introduction

In this page you can find the example usage for org.apache.maven.artifact.resolver ArtifactResolutionResult isSuccess.

Prototype

public boolean isSuccess() 

Source Link

Usage

From source file:com.bugvm.maven.plugin.AbstractBugVMMojo.java

License:Apache License

protected Artifact resolveArtifact(Artifact artifact) throws MojoExecutionException {

    ArtifactResolutionRequest request = new ArtifactResolutionRequest();
    request.setArtifact(artifact);/*from   w w w .j  a  va2 s .c  o m*/
    if (artifact.isSnapshot()) {
        request.setForceUpdate(true);
    }
    request.setLocalRepository(localRepository);
    final List<ArtifactRepository> remoteRepositories = project.getRemoteArtifactRepositories();
    request.setRemoteRepositories(remoteRepositories);

    getLog().debug("Resolving artifact " + artifact);

    ArtifactResolutionResult result = artifactResolver.resolve(request);
    if (!result.isSuccess()) {
        throw new MojoExecutionException("Unable to resolve artifact: " + artifact);
    }
    Collection<Artifact> resolvedArtifacts = result.getArtifacts();
    artifact = (Artifact) resolvedArtifacts.iterator().next();
    return artifact;
}

From source file:com.comoyo.maven.plugins.emjar.EmJarMojo.java

License:Apache License

/**
 * Get artifact containing the EmJar class loader itself.
 */// w ww  . ja  v  a  2s  . c o  m
private Artifact getEmJarArtifact() throws MojoExecutionException {
    final Artifact artifact = repositorySystem.createArtifact(pluginDescriptor.getGroupId(), "emjar",
            pluginDescriptor.getVersion(), "jar");

    getLog().info("Using emjar " + artifact);
    ArtifactResolutionRequest request = new ArtifactResolutionRequest().setArtifact(artifact)
            .setRemoteRepositories(remoteRepositories);
    ArtifactResolutionResult result = repositorySystem.resolve(request);
    if (!result.isSuccess()) {
        throw new MojoExecutionException(
                "Unable to resolve dependency on EmJar loader artifact, sorry: " + result.toString());
    }

    Set<Artifact> artifacts = result.getArtifacts();
    if (artifacts.size() != 1) {
        throw new MojoExecutionException("Unexpected number of artifacts returned when resolving EmJar loader ("
                + artifacts.size() + ")");
    }
    return artifacts.iterator().next();
}

From source file:com.edugility.maven.Artifacts.java

License:Open Source License

/**
 * Returns an unmodifiable, non-{@code null} {@link Collection} of
 * {@link Artifact}s, each element of which is a non-{@code null}
 * {@link Artifact} that represents either the supplied {@link
 * MavenProject} itself or a {@linkplain MavenProject#getArtifacts()
 * dependency of it}.// ww  w  .  j  a v a  2 s. c  o m
 *
 * <p>The returned {@link Artifact} {@link Collection} will be
 * sorted in topological order, from an {@link Artifact} with no
 * dependencies as the first element, to the {@link Artifact}
 * representing the {@link MavenProject} itself as the last.</p>
 *
 * <p>All {@link Artifact}s that are not {@linkplain
 * Object#equals(Object) equal to} the return value of {@link
 * MavenProject#getArtifact() project.getArtifact()} will be
 * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest)
 * resolved} if they are not already {@linkplain
 * Artifact#isResolved() resolved}.  No guarantee of {@linkplain
 * Artifact#isResolved() resolution status} is made of the
 * {@linkplain MavenProject#getArtifact() project
 * <code>Artifact</code>}, which in normal&mdash;possibly
 * all?&mdash;cases will be unresolved.</p>
 *
 * @param project the {@link MavenProject} for which resolved {@link
 * Artifact}s should be returned; must not be {@code null}
 *
 * @param dependencyGraphBuilder the {@link DependencyGraphBuilder}
 * instance that will calculate the dependency graph whose postorder
 * traversal will yield the {@link Artifact}s to be resolved; must
 * not be {@code null}
 *
 * @param filter an {@link ArtifactFilter} used during {@linkplain
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter) dependency graph assembly}; may be {@code null}
 *
 * @param resolver an {@link ArtifactResolver} that will use the <a
 * href="http://maven.apache.org/ref/3.0.5/maven-compat/apidocs/src-html/org/apache/maven/artifact/resolver/DefaultArtifactResolver.html#line.335">Maven
 * 3.0.5 <code>Artifact</code> resolution algorithm</a> to resolve
 * {@link Artifact}s returned by the {@link
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter)} method; must not be {@code null}
 *
 * @param localRepository an {@link ArtifactRepository} representing
 * the local Maven repository in effect; may be {@code null}
 *
 * @return a non-{@code null}, {@linkplain
 * Collections#unmodifiableCollection(Collection) unmodifiable}
 * {@link Collection} of non-{@code null} {@link Artifact} instances
 *
 * @exception IllegalArgumentException if {@code project}, {@code
 * dependencyGraphBuilder} or {@code resolver} is {@code null}
 *
 * @exception ArtifactResolutionException if there were problems
 * {@linkplain ArtifactResolver#resolve(ArtifactResolutionRequest)
 * resolving} {@link Artifact} instances
 *
 * @exception DependencyGraphBuilderException if there were problems
 * {@linkplain
 * DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter) building the dependency graph}
 *
 * @see ArtifactResolver#resolve(ArtifactResolutionRequest)
 *
 * @see DependencyGraphBuilder#buildDependencyGraph(MavenProject,
 * ArtifactFilter)
 */
public Collection<? extends Artifact> getArtifactsInTopologicalOrder(final MavenProject project,
        final DependencyGraphBuilder dependencyGraphBuilder, final ArtifactFilter filter,
        final ArtifactResolver resolver, final ArtifactRepository localRepository)
        throws DependencyGraphBuilderException, ArtifactResolutionException {
    final Logger logger = this.getLogger();
    if (logger != null && logger.isLoggable(Level.FINER)) {
        logger.entering(this.getClass().getName(), "getArtifactsInTopologicalOrder",
                new Object[] { project, dependencyGraphBuilder, filter, resolver, localRepository });
    }
    if (project == null) {
        throw new IllegalArgumentException("project", new NullPointerException("project"));
    }
    if (dependencyGraphBuilder == null) {
        throw new IllegalArgumentException("dependencyGraphBuilder",
                new NullPointerException("dependencyGraphBuilder"));
    }
    if (resolver == null) {
        throw new IllegalArgumentException("resolver", new NullPointerException("resolver"));
    }

    List<Artifact> returnValue = null;

    final DependencyNode projectNode = dependencyGraphBuilder.buildDependencyGraph(project, filter);
    assert projectNode != null;
    final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
    projectNode.accept(visitor);
    final Collection<? extends DependencyNode> nodes = visitor.getNodes();

    if (nodes == null || nodes.isEmpty()) {
        if (logger != null && logger.isLoggable(Level.FINE)) {
            logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder",
                    "No dependency nodes encountered");
        }

    } else {
        final Artifact projectArtifact = project.getArtifact();

        returnValue = new ArrayList<Artifact>();

        for (final DependencyNode node : nodes) {
            if (node != null) {
                Artifact artifact = node.getArtifact();
                if (artifact != null) {

                    if (!artifact.isResolved()) {
                        if (logger != null && logger.isLoggable(Level.FINE)) {
                            logger.logp(Level.FINE, this.getClass().getName(), "getArtifactsInTopologicalOrder",
                                    "Artifact {0} is unresolved", artifact);
                        }

                        if (artifact.equals(projectArtifact)) {
                            // First see if the artifact is the project artifact.
                            // If so, then it by definition won't be able to be
                            // resolved, because it's being built.
                            if (logger != null && logger.isLoggable(Level.FINE)) {
                                logger.logp(Level.FINE, this.getClass().getName(),
                                        "getArtifactsInTopologicalOrder",
                                        "Artifact {0} resolved to project artifact: {1}",
                                        new Object[] { artifact, projectArtifact });
                            }
                            artifact = projectArtifact;

                        } else {
                            // See if the project's associated artifact map
                            // contains a resolved version of this artifact.  The
                            // artifact map contains all transitive dependency
                            // artifacts of the project.  Each artifact in the map
                            // is guaranteed to be resolved.
                            @SuppressWarnings("unchecked")
                            final Map<String, Artifact> artifactMap = project.getArtifactMap();
                            if (artifactMap != null && !artifactMap.isEmpty()) {
                                final Artifact mapArtifact = artifactMap
                                        .get(new StringBuilder(artifact.getGroupId()).append(":")
                                                .append(artifact.getArtifactId()).toString());
                                if (mapArtifact != null) {
                                    if (logger != null && logger.isLoggable(Level.FINE)) {
                                        logger.logp(Level.FINE, this.getClass().getName(),
                                                "getArtifactsInTopologicalOrder",
                                                "Artifact {0} resolved from project artifact map: {1}",
                                                new Object[] { artifact, mapArtifact });
                                    }
                                    artifact = mapArtifact;
                                }
                            }

                            if (!artifact.isResolved()) {
                                // Finally, perform manual artifact resolution.
                                final ArtifactResolutionRequest request = new ArtifactResolutionRequest();
                                request.setArtifact(artifact);
                                request.setLocalRepository(localRepository);
                                @SuppressWarnings("unchecked")
                                final List<ArtifactRepository> remoteRepositories = project
                                        .getRemoteArtifactRepositories();
                                request.setRemoteRepositories(remoteRepositories);

                                if (logger != null && logger.isLoggable(Level.FINE)) {
                                    logger.logp(Level.FINE, this.getClass().getName(),
                                            "getArtifactsInTopologicalOrder",
                                            "Resolving artifact {0} using ArtifactResolutionRequest {1}",
                                            new Object[] { artifact, request });
                                }

                                final ArtifactResolutionResult result = resolver.resolve(request);
                                if (result == null || !result.isSuccess()) {
                                    this.handleArtifactResolutionError(request, result);
                                } else {
                                    @SuppressWarnings("unchecked")
                                    final Collection<? extends Artifact> resolvedArtifacts = (Set<? extends Artifact>) result
                                            .getArtifacts();
                                    if (resolvedArtifacts == null || resolvedArtifacts.isEmpty()) {
                                        if (logger != null && logger.isLoggable(Level.WARNING)) {
                                            logger.logp(Level.WARNING, this.getClass().getName(),
                                                    "getArtifactsInTopologicalOrder",
                                                    "Artifact resolution failed silently for artifact {0}",
                                                    artifact);
                                        }
                                    } else {
                                        final Artifact resolvedArtifact = resolvedArtifacts.iterator().next();
                                        if (resolvedArtifact != null) {
                                            assert resolvedArtifact.isResolved();
                                            artifact = resolvedArtifact;
                                        } else if (logger != null && logger.isLoggable(Level.WARNING)) {
                                            logger.logp(Level.WARNING, this.getClass().getName(),
                                                    "getArtifactsInTopologicalOrder",
                                                    "Artifact resolution failed silently for artifact {0}",
                                                    artifact);
                                        }
                                    }
                                }
                            }

                        }
                    }

                    if (artifact != null) {
                        returnValue.add(artifact);
                    }
                }
            }
        }
        if (!returnValue.isEmpty()) {
            Collections.reverse(returnValue);
            Collections.sort(returnValue, scopeComparator);
        }
    }
    if (returnValue == null) {
        returnValue = Collections.emptyList();
    } else {
        returnValue = Collections.unmodifiableList(returnValue);
    }
    if (logger != null && logger.isLoggable(Level.FINER)) {
        logger.exiting(this.getClass().getName(), "getArtifactsInTopologicalOrder", returnValue);
    }
    return returnValue;
}

From source file:com.github.s4u.plugins.PGPVerifyMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException, MojoFailureException {

    prepareForKeys();/*from   w  ww . j a  va2  s.  c  o  m*/

    try {
        Set<Artifact> resolve = resolver.resolve(project, Arrays.asList(scope.split(",")), session);
        if (verifyPomFiles) {
            resolve.addAll(getPomArtifacts(resolve));
        }

        Map<Artifact, Artifact> artifactToAsc = new HashMap<>();

        getLog().debug("Start resolving ASC files");
        for (Artifact a : resolve) {

            if (a.isSnapshot()) {
                continue;
            }

            ArtifactResolutionRequest rreq = getArtifactResolutionRequestForAsc(a);
            ArtifactResolutionResult result = repositorySystem.resolve(rreq);
            if (result.isSuccess()) {
                Artifact aAsc = rreq.getArtifact();
                getLog().debug(aAsc.toString() + " " + aAsc.getFile());
                artifactToAsc.put(a, aAsc);
            } else {
                if (failNoSignature) {
                    getLog().error("No signature for " + a.getId());
                    throw new MojoExecutionException("No signature for " + a.getId());
                } else {
                    getLog().warn("No signature for " + a.getId());
                }
            }
        }

        boolean isAllSigOk = true;
        for (Map.Entry<Artifact, Artifact> artifactEntry : artifactToAsc.entrySet()) {

            boolean isLastOk = verifyPGPSignature(artifactEntry.getKey(), artifactEntry.getKey().getFile(),
                    artifactEntry.getValue().getFile());
            isAllSigOk = isAllSigOk && isLastOk;
        }

        if (!isAllSigOk) {
            throw new MojoExecutionException("PGP signature error");
        }
    } catch (ArtifactResolutionException | ArtifactNotFoundException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }
}

From source file:com.github.s4u.plugins.PGPVerifyMojo.java

License:Apache License

/**
 * Create Artifact objects for all pom files corresponding to the artifacts that you send in.
 *
 * @param resolve Set of artifacts to obtain pom's for
 * @return Artifacts for all the pom files
 *//*w w w  .ja v  a  2 s  .  c o  m*/
private Set<Artifact> getPomArtifacts(Set<Artifact> resolve) throws MojoExecutionException {
    Set<Artifact> poms = new HashSet<>();

    for (Artifact a : resolve) {
        if (a.isSnapshot()) {
            continue;
        }

        ArtifactResolutionRequest rreq = getArtifactResolutionRequestForPom(a);
        ArtifactResolutionResult result = repositorySystem.resolve(rreq);
        if (result.isSuccess()) {
            poms.add(rreq.getArtifact());
        } else {
            getLog().error("No pom for " + a.getId());
            throw new MojoExecutionException("No pom for " + a.getId());
        }
    }
    return poms;
}

From source file:com.tenderowls.opensource.haxemojos.components.NativeBootstrap.java

License:Apache License

private Artifact resolveArtifact(Artifact artifact, List<ArtifactRepository> artifactRepositories)
        throws Exception {
    if (artifact.isResolved() || artifact.getFile() != null)
        return artifact;

    ArtifactResolutionRequest request = new ArtifactResolutionRequest();

    request.setArtifact(artifact);/*from   w w  w.j  a  v  a2 s.  c  om*/
    request.setLocalRepository(localRepository);
    request.setRemoteRepositories(artifactRepositories);
    ArtifactResolutionResult resolutionResult = repositorySystem.resolve(request);

    if (!resolutionResult.isSuccess()) {
        if (artifact.getType().equals(TGZ)) {
            artifact = repositorySystem.createArtifactWithClassifier(artifact.getGroupId(),
                    artifact.getArtifactId(), artifact.getVersion(), TARGZ, artifact.getClassifier());
            request = new ArtifactResolutionRequest();
            request.setArtifact(artifact);
            request.setLocalRepository(localRepository);
            request.setRemoteRepositories(project.getRemoteArtifactRepositories());
            resolutionResult = repositorySystem.resolve(request);
            if (resolutionResult.isSuccess()) {
                return artifact;
            }
        }
        String message = "Failed to resolve artifact " + artifact;
        throw new Exception(message);
    }

    return artifact;
}

From source file:com.yelbota.plugins.nd.DependencyHelper.java

License:Apache License

/**
 * Resolves native dependency artifact. First it checks plugin dependencies
 * compares they with getDefaultArtifactId() and getDefaultGroupId(), then method
 * tries to resolve from repositories using also getDefaultVersion(), getDefaultPackaging()
 * and getDefaultClassifier().// www . j a va2 s .  co m
 *
 * @param pluginArtifacts    list of plugin dependencies (inject this with @parameter)
 * @param repositorySystem   inject this with @parameter
 * @param localRepository    inject this with @parameter
 * @param remoteRepositories inject this with @parameter
 * @return Native dependency artifact
 * @throws MojoFailureException
 */
public Artifact resolve(List<Artifact> pluginArtifacts, RepositorySystem repositorySystem,
        ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories)
        throws MojoFailureException {

    Artifact artifact = null;

    if (pluginArtifacts != null) {

        // Lookup plugin artifacts.
        for (Artifact pluginArtifact : pluginArtifacts) {

            boolean eqGroupId = pluginArtifact.getGroupId().equals(getDefaultGroupId());
            boolean eqArtifactId = pluginArtifact.getArtifactId().equals(getDefaultArtifactId());

            if (eqGroupId && eqArtifactId) {

                artifact = pluginArtifact;
                break;
            }
        }
    }

    if (artifact != null) {
        return artifact;
    } else {
        // Okay. Lets download sdk
        if (repositorySystem != null) {
            artifact = repositorySystem.createArtifactWithClassifier(

                    getDefaultGroupId(), getDefaultArtifactId(), getDefaultVersion(), getDefaultPackaging(),
                    getDefaultClassifier());

            ArtifactResolutionRequest request = new ArtifactResolutionRequest();

            request.setArtifact(artifact);
            request.setLocalRepository(localRepository);
            request.setRemoteRepositories(remoteRepositories);

            ArtifactResolutionResult resolutionResult = repositorySystem.resolve(request);

            if (!resolutionResult.isSuccess()) {

                String message = "Failed to resolve artifact " + artifact;
                throw new ArtifactResolutionException(message, resolutionResult);
            }
        }

        return artifact;
    }
}

From source file:io.fabric8.jube.maven.BuildMojo.java

License:Apache License

protected void unpackBaseImage(File buildDir, boolean useDefaultPrefix) throws Exception {
    String imageName = project.getProperties().getProperty(DOCKER_BASE_IMAGE_PROPERTY);
    Objects.notNull(imageName, DOCKER_BASE_IMAGE_PROPERTY);

    ImageMavenCoords baseImageCoords = ImageMavenCoords.parse(imageName, useDefaultPrefix);
    String coords = baseImageCoords.getAetherCoords();

    Artifact artifact = repositorySystem.createArtifactWithClassifier(baseImageCoords.getGroupId(),
            baseImageCoords.getArtifactId(), baseImageCoords.getVersion(), baseImageCoords.getType(),
            baseImageCoords.getClassifier());
    getLog().info("Resolving Jube image: " + artifact);

    ArtifactResolutionRequest request = new ArtifactResolutionRequest();
    request.setArtifact(artifact);//from   w  w  w.j  a va 2s. c  o  m
    request.setLocalRepository(localRepository);
    request.setRemoteRepositories(pomRemoteRepositories);

    ArtifactResolutionResult result = artifactResolver.resolve(request);
    if (!result.isSuccess()) {
        throw new ArtifactNotFoundException("Cannot download Jube image", artifact);
    }

    getLog().info("Resolved Jube image: " + artifact);

    if (artifact.getFile() != null) {
        File file = artifact.getFile();
        getLog().info("File: " + file);

        if (!file.exists() || file.isDirectory()) {
            throw new MojoExecutionException(
                    "Resolved file for " + coords + " is not a valid file: " + file.getAbsolutePath());
        }
        getLog().info("Unpacking base image " + file.getAbsolutePath() + " to build dir: " + buildDir);
        Zips.unzip(new FileInputStream(file), buildDir);
    }
}

From source file:io.fabric8.maven.core.service.ArtifactResolverServiceMavenImpl.java

License:Apache License

@Override
public File resolveArtifact(String groupId, String artifactId, String version, String type) {
    String canonicalString = groupId + ":" + artifactId + ":" + type + ":" + version;
    Artifact art = repositorySystem.createArtifact(groupId, artifactId, version, type);
    ArtifactResolutionRequest request = new ArtifactResolutionRequest().setArtifact(art).setResolveRoot(true)
            .setOffline(false).setRemoteRepositories(project.getRemoteArtifactRepositories())
            .setResolveTransitively(false);

    ArtifactResolutionResult res = repositorySystem.resolve(request);

    if (!res.isSuccess()) {
        throw new IllegalStateException("Cannot resolve artifact " + canonicalString);
    }//  ww  w .  j a  va 2 s  . co m

    for (Artifact artifact : res.getArtifacts()) {
        if (artifact.getGroupId().equals(groupId) && artifact.getArtifactId().equals(artifactId)
                && artifact.getVersion().equals(version) && artifact.getType().equals(type)) {
            return artifact.getFile();
        }
    }

    throw new IllegalStateException(
            "Cannot find artifact " + canonicalString + " within the resolved resources");
}

From source file:io.github.divinespear.maven.plugin.JpaSchemaGeneratorMojo.java

License:Apache License

private ClassLoader getProjectClassLoader() throws MojoExecutionException {
    try {//from  w w  w  . j a v a  2  s .  c o  m
        // compiled classes
        List<String> classfiles = this.project.getCompileClasspathElements();
        if (this.scanTestClasses) {
            classfiles.addAll(this.project.getTestClasspathElements());
        }
        // classpath to url
        List<URL> classURLs = new ArrayList<URL>(classfiles.size());
        for (String classfile : classfiles) {
            classURLs.add(new File(classfile).toURI().toURL());
        }

        // dependency artifacts to url
        ArtifactResolutionRequest sharedreq = new ArtifactResolutionRequest().setResolveRoot(true)
                .setResolveTransitively(true).setLocalRepository(this.session.getLocalRepository())
                .setRemoteRepositories(this.project.getRemoteArtifactRepositories());

        ArtifactRepository repository = this.session.getLocalRepository();
        Set<Artifact> artifacts = this.project.getDependencyArtifacts();
        for (Artifact artifact : artifacts) {
            if (!Artifact.SCOPE_TEST.equalsIgnoreCase(artifact.getScope())) {
                ArtifactResolutionRequest request = new ArtifactResolutionRequest(sharedreq)
                        .setArtifact(artifact);
                ArtifactResolutionResult result = this.resolver.resolve(request);
                if (result.isSuccess()) {
                    File file = repository.find(artifact).getFile();
                    if (file != null) {
                        classURLs.add(file.toURI().toURL());
                    }
                }
            }
        }

        for (URL url : classURLs) {
            this.log.info("  * classpath: " + url);
        }

        return new URLClassLoader(classURLs.toArray(EMPTY_URLS), this.getClass().getClassLoader());
    } catch (Exception e) {
        this.log.error(e);
        throw new MojoExecutionException("Error while creating classloader", e);
    }
}