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

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

Introduction

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

Prototype

public Set<ResolutionNode> getArtifactResolutionNodes() 

Source Link

Usage

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

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing.//from   w  ww.  j a  v a2 s  .com
 *
 * @return resolved IDE dependencies, with attached jars for non-reactor dependencies
 * @throws MojoExecutionException if dependencies can't be resolved
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    if (ideDeps == null) {
        if (resolveDependencies) {
            MavenProject project = getProject();
            ArtifactRepository localRepo = getLocalRepository();

            List deps = getProject().getDependencies();

            // Collect the list of resolved IdeDependencies.
            List dependencies = new ArrayList();

            if (deps != null) {
                Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(),
                        project.getDependencyManagement());

                ArtifactResolutionResult artifactResolutionResult = null;

                try {

                    List listeners = new ArrayList();

                    if (logger.isDebugEnabled()) {
                        listeners.add(new DebugResolutionListener(logger));
                    }

                    listeners.add(new WarningResolutionListener(logger));

                    artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(),
                            project.getArtifact(), managedVersions, localRepo,
                            project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null,
                            listeners);
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().error(
                            Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$
                                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

                    // if we are here artifactResolutionResult is null, create a project without dependencies but
                    // don't fail
                    // (this could be a reactor projects, we don't want to fail everything)
                    // Causes MECLIPSE-185. Not sure if it should be handled this way??
                    return new IdeDependency[0];
                }

                // keep track of added reactor projects in order to avoid duplicates
                Set emittedReactorProjectId = new HashSet();

                for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i
                        .hasNext();) {

                    ResolutionNode node = (ResolutionNode) i.next();
                    int dependencyDepth = node.getDepth();
                    Artifact art = node.getArtifact();
                    // don't resolve jars for reactor projects
                    if (hasToResolveJar(art)) {
                        try {
                            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                        } catch (ArtifactNotFoundException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        } catch (ArtifactResolutionException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution",
                                    new Object[] { //$NON-NLS-1$
                                            e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        }
                    }

                    boolean includeArtifact = true;
                    if (getExcludes() != null) {
                        String artifactFullId = art.getGroupId() + ":" + art.getArtifactId();
                        if (getExcludes().contains(artifactFullId)) {
                            getLog().info("excluded: " + artifactFullId);
                            includeArtifact = false;
                        }
                    }

                    if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art))
                            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) {

                        // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar"
                        // also
                        // if the packaging specified in pom.xml is different.

                        // osgi-bundle packaging is provided by the felix osgi plugin
                        // eclipse-plugin packaging is provided by this eclipse plugin
                        // String packaging = art.getArtifactHandler().getPackaging();
                        // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals(
                        // packaging );

                        // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be
                        // considered
                        // an osgi bundle
                        boolean isOsgiBundle = false;
                        String osgiSymbolicName = null;
                        if (art.getFile() != null) {
                            JarFile jarFile = null;
                            try {
                                jarFile = new JarFile(art.getFile(), false, ZipFile.OPEN_READ);

                                Manifest manifest = jarFile.getManifest();
                                if (manifest != null) {
                                    osgiSymbolicName = manifest.getMainAttributes()
                                            .getValue(new Attributes.Name("Bundle-SymbolicName"));
                                }
                            } catch (IOException e) {
                                getLog().info("Unable to read jar manifest from " + art.getFile());
                            } finally {
                                if (jarFile != null) {
                                    try {
                                        jarFile.close();
                                    } catch (IOException e) {
                                        // ignore
                                    }
                                }
                            }
                        }

                        isOsgiBundle = osgiSymbolicName != null;

                        IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(),
                                art.getVersion(), art.getClassifier(), useProjectReference(art),
                                Artifact.SCOPE_TEST.equals(art.getScope()),
                                Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                                Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                                art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(),
                                isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art));
                        // no duplicate entries allowed. System paths can cause this problem.
                        if (!dependencies.contains(dep)) {
                            dependencies.add(dep);
                        }
                    }
                }

                // @todo a final report with the list of
                // missingArtifacts?

            }

            ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]);
        } else {
            ideDeps = new IdeDependency[0];
        }
    }

    return ideDeps;
}

From source file:com.github.veithen.alta.AbstractGenerateMojo.java

License:Apache License

public final void execute() throws MojoExecutionException, MojoFailureException {
    Log log = getLog();//from  w  w w .  j  a v a 2  s.  c o m
    if (skip) {
        log.info("Skipping plugin execution");
        return;
    }
    Template<Context> nameTemplate;
    try {
        nameTemplate = templateCompiler.compile(name);
    } catch (InvalidTemplateException ex) {
        throw new MojoExecutionException("Invalid destination name template", ex);
    }
    Template<Context> valueTemplate;
    try {
        valueTemplate = templateCompiler.compile(value);
    } catch (InvalidTemplateException ex) {
        throw new MojoExecutionException("Invalid value template", ex);
    }
    List<Artifact> resolvedArtifacts = new ArrayList<Artifact>();

    if (dependencySet != null) {
        if (log.isDebugEnabled()) {
            log.debug("Resolving project dependencies in scope " + dependencySet.getScope());
        }
        AndArtifactFilter filter = new AndArtifactFilter();
        filter.add(new ScopeArtifactFilter(dependencySet.getScope()));
        filter.add(new IncludeExcludeArtifactFilter(dependencySet.getIncludes(), dependencySet.getExcludes(),
                null));
        for (Artifact artifact : project.getArtifacts()) {
            if (filter.include(artifact)) {
                resolvedArtifacts.add(artifact);
            }
        }
        if (dependencySet.isUseProjectArtifact()) {
            resolvedArtifacts.add(project.getArtifact());
        }
    }

    if (artifacts != null && artifacts.length != 0) {
        List<ArtifactRepository> pomRepositories = project.getRemoteArtifactRepositories();
        List<ArtifactRepository> effectiveRepositories;
        if (repositories != null && repositories.length > 0) {
            effectiveRepositories = new ArrayList<ArtifactRepository>(
                    pomRepositories.size() + repositories.length);
            effectiveRepositories.addAll(pomRepositories);
            for (Repository repository : repositories) {
                try {
                    effectiveRepositories.add(repositorySystem.buildArtifactRepository(repository));
                } catch (InvalidRepositoryException ex) {
                    throw new MojoExecutionException("Invalid repository", ex);
                }
            }
        } else {
            effectiveRepositories = pomRepositories;
        }
        for (ArtifactItem artifactItem : artifacts) {
            String version = artifactItem.getVersion();
            if (StringUtils.isEmpty(version)) {
                version = getMissingArtifactVersion(artifactItem);
            }
            Dependency dependency = new Dependency();
            dependency.setGroupId(artifactItem.getGroupId());
            dependency.setArtifactId(artifactItem.getArtifactId());
            dependency.setVersion(version);
            dependency.setType(artifactItem.getType());
            dependency.setClassifier(artifactItem.getClassifier());
            dependency.setScope(Artifact.SCOPE_COMPILE);
            Artifact artifact = repositorySystem.createDependencyArtifact(dependency);
            try {
                // Find an appropriate version in the specified version range
                ArtifactResolutionResult artifactResolutionResult = artifactCollector.collect(
                        Collections.singleton(artifact), project.getArtifact(), localRepository,
                        effectiveRepositories, artifactMetadataSource, null, Collections.EMPTY_LIST);
                artifact = ((ResolutionNode) artifactResolutionResult.getArtifactResolutionNodes().iterator()
                        .next()).getArtifact();

                // Download the artifact
                resolver.resolve(artifact, effectiveRepositories, localRepository);
            } catch (ArtifactResolutionException ex) {
                throw new MojoExecutionException("Unable to resolve artifact", ex);
            } catch (ArtifactNotFoundException ex) {
                throw new MojoExecutionException("Artifact not found", ex);
            }
            resolvedArtifacts.add(artifact);
        }
    }

    Map<String, String> result = new HashMap<String, String>();
    for (Artifact artifact : resolvedArtifacts) {
        if (log.isDebugEnabled()) {
            log.debug("Processing artifact " + artifact.getId());
        }
        Context context = new Context(artifact);
        try {
            String name = nameTemplate.evaluate(context);
            if (log.isDebugEnabled()) {
                log.debug("name = " + name);
            }
            if (name == null) {
                continue;
            }
            String value = valueTemplate.evaluate(context);
            if (log.isDebugEnabled()) {
                log.debug("value = " + value);
            }
            if (value == null) {
                continue;
            }
            String currentValue = result.get(name);
            if (currentValue == null) {
                currentValue = value;
            } else if (separator == null) {
                throw new MojoExecutionException("No separator configured");
            } else {
                currentValue = currentValue + separator + value;
            }
            result.put(name, currentValue);
        } catch (EvaluationException ex) {
            throw new MojoExecutionException(
                    "Failed to process artifact " + artifact.getId() + ": " + ex.getMessage(), ex);
        }
    }
    process(result);
}

From source file:com.github.zhve.ideaplugin.ArtifactDependencyResolver.java

License:Apache License

private void tryResolve(MavenProject project, Set<Artifact> reactorArtifacts, List<Artifact> remoteData,
        List<Artifact> reactorData, List<Artifact> remoteUnresolvedList) {
    // search//  ww w.  j  a v a 2 s  .  c o m
    ArtifactResolutionResult resolutionResult;
    log.info("Before:");
    for (Artifact a : remoteUnresolvedList)
        log.info("  " + a.getId() + ":" + a.getScope());
    log.info("");
    try {
        resolutionResult = artifactResolver.resolveTransitively(
                new LinkedHashSet<Artifact>(remoteUnresolvedList), project.getArtifact(),
                project.getManagedVersionMap(), localRepository, project.getRemoteArtifactRepositories(),
                artifactMetadataSource);
        // save search result
        log.info("After:");
        for (Object resolutionNode : resolutionResult.getArtifactResolutionNodes()) {
            Artifact art = ((ResolutionNode) resolutionNode).getArtifact();
            if (reactorArtifacts.contains(art)) {
                if (!reactorData.contains(art)) {
                    reactorData.add(art);
                    log.info("R " + art.getId() + ":" + art.getScope());
                } else {
                    log.info("D " + art.getId() + ":" + art.getScope());
                }
            } else {
                log.info("  " + art.getId() + ":" + art.getScope());
                remoteData.add(art);
            }
        }
        // clear unresolved
        remoteUnresolvedList.clear();
    } catch (ArtifactResolutionException e) {
        log.error(e.getMessage());
        remoteData.addAll(remoteUnresolvedList);
    } catch (ArtifactNotFoundException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:fr.paris.lutece.maven.ExplodedMojo.java

License:Open Source License

/**
 * Use to filter duplicate dependencies in multi project
 *
 * @return a list of artifacts whith no duplicate entry
 *//*  w  w w.  j  a  v a 2s . c  o  m*/
private Set<Artifact> doDependencyResolution() {
    Set<Artifact> artifactsReturn = new HashSet<Artifact>();

    // Collector Filter jar artifacts in scope 'compile' or 'runtime'
    ArtifactFilter thirdPartyFilter = new ArtifactFilter() {
        @Override
        public boolean include(Artifact artifact) {
            return (!LUTECE_CORE_TYPE.equals(artifact.getArtifactId())
                    && !SERVLET_API.equals(artifact.getArtifactId())
                    && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                    && !Artifact.SCOPE_TEST.equals(artifact.getScope()));
        }
    };

    // Collector listener config
    List<ResolutionListener> listeners = new ArrayList<ResolutionListener>();

    if (logger.isDebugEnabled()) {
        listeners.add(new DebugResolutionListener(logger));
    }

    listeners.add(new WarningResolutionListener(logger));

    /*---------------- Resolution-------------*/
    // resolve conflict version artifacts with collector
    ArtifactResolutionResult artifactResolutionResult = null;

    try {
        artifactResolutionResult = artifactCollector.collect(multiProjectArtifacts, project.getArtifact(),
                localRepository, remoteRepositories, metadataSource, thirdPartyFilter, listeners);
    } catch (ArtifactResolutionException e) {
        e.printStackTrace();
    }

    // keep track of added reactor projects in order to avoid duplicates
    Set<String> emittedReactorProjectId = new HashSet<String>();

    for (ResolutionNode node : artifactResolutionResult.getArtifactResolutionNodes()) {
        Artifact art = node.getArtifact();

        try {
            resolver.resolve(art, node.getRemoteRepositories(), localRepository);
        } catch (ArtifactNotFoundException e) {
            e.printStackTrace();
        } catch (ArtifactResolutionException e) {
            e.printStackTrace();
        }

        if (emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) {
            artifactsReturn.add(art);
        }
    }

    return artifactsReturn;
}

From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing./*from  ww  w  .  ja  va 2s .c o m*/
 *
 * @throws MojoExecutionException if dependencies can't be resolved
 * @return resolved IDE dependencies, with attached jars for non-reactor dependencies
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    if (ideDeps == null) {
        if (resolveDependencies) {
            MavenProject project = getProject();
            Set<String> imported = Collections.emptySet();
            try {
                imported = BundleUtil.getImportedPackages(project.getBasedir());
            } catch (IOException e1) {
                throw new MojoExecutionException(e1.getMessage(), e1);
            }
            ArtifactRepository localRepo = getLocalRepository();

            List deps = getProject().getDependencies();

            // Collect the list of resolved IdeDependencies.
            List dependencies = new ArrayList();

            if (deps != null) {
                Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(),
                        project.getDependencyManagement());

                ArtifactResolutionResult artifactResolutionResult = null;

                try {

                    List listeners = new ArrayList();

                    if (logger.isDebugEnabled()) {
                        listeners.add(new DebugResolutionListener(logger));
                    }

                    listeners.add(new WarningResolutionListener(logger));

                    artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(),
                            project.getArtifact(), managedVersions, localRepo,
                            project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null,
                            listeners);
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().error(
                            Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$
                                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

                    // if we are here artifactResolutionResult is null, create a project without dependencies but
                    // don't fail
                    // (this could be a reactor projects, we don't want to fail everything)
                    // Causes MECLIPSE-185. Not sure if it should be handled this way??
                    return new IdeDependency[0];
                }

                // keep track of added reactor projects in order to avoid duplicates
                Set emittedReactorProjectId = new HashSet();

                for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i
                        .hasNext();) {

                    ResolutionNode node = (ResolutionNode) i.next();
                    int dependencyDepth = node.getDepth();
                    Artifact art = node.getArtifact();
                    // don't resolve jars for reactor projects
                    if (hasToResolveJar(art)) {
                        try {
                            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                        } catch (ArtifactNotFoundException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        } catch (ArtifactResolutionException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        }
                    }

                    boolean includeArtifact = true;
                    if (getExcludes() != null) {
                        String artifactFullId = art.getGroupId() + ":" + art.getArtifactId();
                        if (getExcludes().contains(artifactFullId)) {
                            getLog().info("excluded: " + artifactFullId);
                            includeArtifact = false;
                        }
                    }

                    if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art))
                            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) {

                        // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar"
                        // also
                        // if the packaging specified in pom.xml is different.

                        // osgi-bundle packaging is provided by the felix osgi plugin
                        // eclipse-plugin packaging is provided by this eclipse plugin
                        // String packaging = art.getArtifactHandler().getPackaging();
                        // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals(
                        // packaging );

                        // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be
                        // considered
                        // an osgi bundle
                        if ("pom".equals(art.getType())) {
                            continue;
                        }
                        File artifactFile = art.getFile();
                        MavenProject reactorProject = getReactorProject(art);
                        if (reactorProject != null) {
                            artifactFile = reactorProject.getBasedir();
                        }
                        boolean isOsgiBundle = false;
                        String osgiSymbolicName = null;
                        try {
                            osgiSymbolicName = BundleUtil.getBundleSymbolicName(artifactFile);
                        } catch (IOException e) {
                            getLog().error("Unable to read jar manifest from " + artifactFile, e);
                        }
                        isOsgiBundle = osgiSymbolicName != null;

                        IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(),
                                art.getVersion(), art.getClassifier(), useProjectReference(art),
                                Artifact.SCOPE_TEST.equals(art.getScope()),
                                Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                                Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                                art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(),
                                isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art));
                        // no duplicate entries allowed. System paths can cause this problem.
                        if (!dependencies.contains(dep)) {
                            // [rfeng] Do not add compile/provided dependencies
                            if (!(pde && (Artifact.SCOPE_COMPILE.equals(art.getScope())
                                    || Artifact.SCOPE_PROVIDED.equals(art.getScope())))) {
                                dependencies.add(dep);
                            } else {
                                // Check this compile dependency is an OSGi package supplier
                                if (!imported.isEmpty()) {
                                    Set<String> exported = Collections.emptySet();
                                    try {
                                        exported = BundleUtil.getExportedPackages(artifactFile);
                                    } catch (IOException e) {
                                        getLog().error("Unable to read jar manifest from " + art.getFile(), e);
                                    }
                                    boolean matched = false;
                                    for (String p : imported) {
                                        if (exported.contains(p)) {
                                            matched = true;
                                            break;
                                        }
                                    }
                                    if (!matched) {
                                        dependencies.add(dep);
                                    } else {
                                        getLog().debug(
                                                "Compile dependency is skipped as it is added through OSGi dependency: "
                                                        + art);
                                    }
                                } else {
                                    dependencies.add(dep);
                                }
                            }
                        }
                    }

                }

                // @todo a final report with the list of
                // missingArtifacts?

            }

            ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]);
        } else {
            ideDeps = new IdeDependency[0];
        }
    }

    return ideDeps;
}

From source file:org.codehaus.mojo.graphing.model.factory.GraphModelFactory.java

License:Apache License

public GraphModel getGraphModel(String groupId, String artifactId, String version)
        throws MojoExecutionException {
    Artifact pomArtifact = resolveArtifact(groupId, artifactId, version);
    // Model pom = getModel(pomArtifact);

    List listeners = Collections.EMPTY_LIST;
    if (verbose) {
        listeners = Collections.singletonList(new DebugResolutionListener(getLog()));
    }/* ww w .j  av  a  2  s  .  c o m*/

    List remoteArtifactRepositories = getArtifactRepositories();

    // TODO: managed dependencies
    Map managedDependencies = Collections.EMPTY_MAP;

    ArtifactFilter filter = null;
    if (scopeFilter != null) {
        filter = new ScopeArtifactFilter(scopeFilter);
    }
    if (typeFilter != null) {
        TypeArtifactFilter typeArtifactFilter = new TypeArtifactFilter(typeFilter);
        if (filter != null) {
            AndArtifactFilter andFilter = new AndArtifactFilter();
            andFilter.add(filter);
            andFilter.add(typeArtifactFilter);
            filter = andFilter;
        } else {
            filter = typeArtifactFilter;
        }
    }

    ArtifactResolutionResult result;
    Set artifacts;

    GraphModel model = new GraphModel();
    Node centerNode = toNode(pomArtifact);
    model.addNode(centerNode);
    model.setCenterNode(centerNode);

    try {
        artifacts = new HashSet();
        artifacts.add(pomArtifact);

        result = artifactResolver.resolveTransitively(artifacts, pomArtifact, managedDependencies,
                localRepository, remoteArtifactRepositories, mavenMetadataSource, filter, listeners);
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve deps.", e);
    } catch (ArtifactNotFoundException e) {
        throw new MojoExecutionException("Unable to resolve deps.", e);
    }

    getLog().info("Got " + result.getArtifactResolutionNodes().size() + " resolution node(s).");

    Iterator it = result.getArtifactResolutionNodes().iterator();
    while (it.hasNext()) {
        ResolutionNode child = (ResolutionNode) it.next();
        Node childNode = toNode(child.getArtifact());
        Edge edge = new Edge(centerNode, childNode);
        if (model.addEdge(edge)) {
            addChildEdges(model, child);
        }
    }

    return model;
}

From source file:org.codehaus.mojo.pomtools.helpers.MetadataHelper.java

License:Apache License

/** Resolves all transitive dependencies for the current project and returns a list
 * of {@link TransitiveDependencyInfo} objects.  Each object represents a distinct 
 * groupId:artifactId:type dependency.  The {@link TransitiveDependencyInfo#getResolutionNodes()}
 * represent all of the possible ResolutionNodes which resolve to this groupId:artifactId.
 * /*w ww . j  a  v  a  2s .c  o  m*/
 * @return
 * @throws PomToolsException
 */
public List getTransitiveDependencies() throws PomToolsException, ProjectBuildingException {
    // Certain things like groupId or versions for dependencies may be declared in a parent
    // pom so we need to have maven fully resolve the model before walking the tree.
    MavenProject project = PomToolsPluginContext.getInstance().getActiveProject().getTemporaryResolvedProject();

    try {
        project.setDependencyArtifacts(project.createArtifacts(artifactFactory, null, null));
    } catch (InvalidDependencyVersionException e) {
        throw new PomToolsVersionException(
                "Unable to build project due to an invalid dependency version: " + e.getMessage(), e);
    }

    Artifact projectArtifact = project.getArtifact();

    Set artifacts = project.getDependencyArtifacts();

    try {
        List dependencies = new ArrayList();

        ArtifactResolutionResult result;
        result = artifactResolver.resolveTransitively(artifacts, projectArtifact, Collections.EMPTY_MAP,
                localRepository, remoteRepositories, metadataSource, projectArtifact.getDependencyFilter());

        Map dependencyMap = new HashMap();
        Set seen = new HashSet();

        // First build our map of distinct groupId:artifactIds
        for (Iterator iter = result.getArtifactResolutionNodes().iterator(); iter.hasNext();) {
            ResolutionNode node = (ResolutionNode) iter.next();

            TransitiveDependencyInfo info = new TransitiveDependencyInfo(node);

            dependencyMap.put(info.getKey(), info);

            dependencies.add(info);
        }

        // Now populate the map with all children
        recurseNode(dependencyMap, seen, result.getArtifactResolutionNodes().iterator(), 0);

        return dependencies;
    } catch (ArtifactNotFoundException e) {
        throw new PomToolsException(e);
    } catch (ArtifactResolutionException e) {
        throw new PomToolsException(e);
    }

}

From source file:org.codehaus.mojo.sysdeo.ide.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resoltion of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing.//from w w w.j av a 2 s .  c  o  m
 *
 * @throws MojoExecutionException if dependencies can't be resolved
 * @return resoved IDE dependencies, with attached jars for non-reactor dependencies
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {

    if (workspace != null) {
        getLog().info("read available projects in eclipse workspace");
        workspaceProjects = new ReadWorkspaceLocations().readWorkspace(workspace, getLog());
    }

    ArtifactRepository localRepo = getLocalRepository();

    List dependencies = getProject().getDependencies();

    // Collect the list of resolved IdeDependencies.
    List dependencyList = new ArrayList();

    if (dependencies != null) {
        Map managedVersions = createManagedVersionMap(project.getId(), project.getDependencyManagement());

        ArtifactResolutionResult artifactResolutionResult = null;

        try {

            List listeners = new ArrayList();

            if (logger.isDebugEnabled()) {
                listeners.add(new DebugResolutionListener(logger));
            }

            listeners.add(new WarningResolutionListener(logger));

            artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(), project.getArtifact(),
                    managedVersions, localRepo, project.getRemoteArtifactRepositories(),
                    getArtifactMetadataSource(), null, listeners);
        } catch (ArtifactResolutionException e) {
            getLog().debug(e.getMessage(), e);
            getLog().error(Messages.getString("artifactresolution", new Object[] { //$NON-NLS-1$
                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

            // if we are here artifactResolutionResult is null, create a project without dependencies but don't fail
            // (this could be a reactor projects, we don't want to fail everything)
            return new IdeDependency[0];
        }

        // keep track of added reactor projects in order to avoid duplicates
        Set emittedReactorProjectId = new HashSet();

        for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i.hasNext();) {
            ResolutionNode node = (ResolutionNode) i.next();
            Artifact art = node.getArtifact();
            boolean isReactorProject = getUseProjectReferences() && isAvailableAsAReactorProject(art);

            // don't resolve jars for reactor projects
            if (!isReactorProject) {
                try {
                    artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                } catch (ArtifactNotFoundException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().warn(Messages.getString("artifactdownload", new Object[] { //$NON-NLS-1$
                            e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().warn(Messages.getString("artifactresolution", new Object[] { //$NON-NLS-1$
                            e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));
                }
            }

            if (!isReactorProject
                    || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId())) {

                IdeDependency dep = new IdeDependency(art, isReactorProject);
                dep = resolveWorkspaceProject(dep);
                dependencyList.add(dep);

            }

        }

        // @todo a final report with the list of missingArtifacts?

    }

    IdeDependency[] deps = (IdeDependency[]) dependencyList.toArray(new IdeDependency[dependencyList.size()]);

    return deps;
}

From source file:org.eclipse.che.maven.CheArtifactResolver.java

License:Apache License

public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) {
    Artifact rootArtifact = request.getArtifact();
    Set<Artifact> artifacts = request.getArtifactDependencies();
    Map<String, Artifact> managedVersions = request.getManagedVersionMap();
    List<ResolutionListener> listeners = request.getListeners();
    ArtifactFilter collectionFilter = request.getCollectionFilter();
    ArtifactFilter resolutionFilter = request.getResolutionFilter();
    RepositorySystemSession session = getSession(request.getLocalRepository());

    //TODO: hack because metadata isn't generated in m2e correctly and i want to run the maven i have in the workspace
    if (source == null) {
        try {//from w w w. j  av  a2  s. com
            source = container.lookup(ArtifactMetadataSource.class);
        } catch (ComponentLookupException e) {
            // won't happen
        }
    }

    if (listeners == null) {
        listeners = new ArrayList<ResolutionListener>();

        if (logger.isDebugEnabled()) {
            listeners.add(new DebugResolutionListener(logger));
        }

        listeners.add(new WarningResolutionListener(logger));
    }

    ArtifactResolutionResult result = new ArtifactResolutionResult();

    // The root artifact may, or may not be resolved so we need to check before we attempt to resolve.
    // This is often an artifact like a POM that is taken from disk and we already have hold of the
    // file reference. But this may be a Maven Plugin that we need to resolve from a remote repository
    // as well as its dependencies.

    if (request.isResolveRoot() /* && rootArtifact.getFile() == null */) {
        try {
            resolve(rootArtifact, request.getRemoteRepositories(), session);
        } catch (ArtifactResolutionException e) {
            result.addErrorArtifactException(e);
            return result;
        } catch (ArtifactNotFoundException e) {
            result.addMissingArtifact(request.getArtifact());
            return result;
        }
    }

    ArtifactResolutionRequest collectionRequest = request;

    if (request.isResolveTransitively()) {
        MetadataResolutionRequest metadataRequest = new DefaultMetadataResolutionRequest(request);

        metadataRequest.setArtifact(rootArtifact);
        metadataRequest.setResolveManagedVersions(managedVersions == null);

        try {
            ResolutionGroup resolutionGroup = source.retrieve(metadataRequest);

            if (managedVersions == null) {
                managedVersions = resolutionGroup.getManagedVersions();
            }

            Set<Artifact> directArtifacts = resolutionGroup.getArtifacts();

            if (artifacts == null || artifacts.isEmpty()) {
                artifacts = directArtifacts;
            } else {
                List<Artifact> allArtifacts = new ArrayList<Artifact>();
                allArtifacts.addAll(artifacts);
                allArtifacts.addAll(directArtifacts);

                Map<String, Artifact> mergedArtifacts = new LinkedHashMap<String, Artifact>();
                for (Artifact artifact : allArtifacts) {
                    String conflictId = artifact.getDependencyConflictId();
                    if (!mergedArtifacts.containsKey(conflictId)) {
                        mergedArtifacts.put(conflictId, artifact);
                    }
                }

                artifacts = new LinkedHashSet<Artifact>(mergedArtifacts.values());
            }

            collectionRequest = new ArtifactResolutionRequest(request);
            collectionRequest.setServers(request.getServers());
            collectionRequest.setMirrors(request.getMirrors());
            collectionRequest.setProxies(request.getProxies());
            collectionRequest.setRemoteRepositories(resolutionGroup.getResolutionRepositories());
        } catch (ArtifactMetadataRetrievalException e) {
            ArtifactResolutionException are = new ArtifactResolutionException(
                    "Unable to get dependency information for " + rootArtifact.getId() + ": " + e.getMessage(),
                    rootArtifact, metadataRequest.getRemoteRepositories(), e);
            result.addMetadataResolutionException(are);
            return result;
        }
    }

    if (artifacts == null || artifacts.isEmpty()) {
        if (request.isResolveRoot()) {
            result.addArtifact(rootArtifact);
        }
        return result;
    }

    // After the collection we will have the artifact object in the result but they will not be resolved yet.
    result = artifactCollector.collect(artifacts, rootArtifact, managedVersions, collectionRequest, source,
            collectionFilter, listeners, null);

    // We have metadata retrieval problems, or there are cycles that have been detected
    // so we give this back to the calling code and let them deal with this information
    // appropriately.

    if (result.hasMetadataResolutionExceptions() || result.hasVersionRangeViolations()
            || result.hasCircularDependencyExceptions()) {
        return result;
    }

    if (result.getArtifactResolutionNodes() != null) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        CountDownLatch latch = new CountDownLatch(result.getArtifactResolutionNodes().size());

        for (ResolutionNode node : result.getArtifactResolutionNodes()) {
            Artifact artifact = node.getArtifact();

            if (resolutionFilter == null || resolutionFilter.include(artifact)) {
                executor.execute(new ResolveTask(classLoader, latch, artifact, session,
                        node.getRemoteRepositories(), result));
            } else {
                latch.countDown();
            }
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            result.addErrorArtifactException(
                    new ArtifactResolutionException("Resolution interrupted", rootArtifact, e));
        }
    }

    // We want to send the root artifact back in the result but we need to do this after the other dependencies
    // have been resolved.
    if (request.isResolveRoot()) {
        // Add the root artifact (as the first artifact to retain logical order of class path!)
        Set<Artifact> allArtifacts = new LinkedHashSet<Artifact>();
        allArtifacts.add(rootArtifact);
        allArtifacts.addAll(result.getArtifacts());
        result.setArtifacts(allArtifacts);
    }

    return result;
}

From source file:org.jetbrains.idea.maven.server.embedder.CustomMaven32ArtifactResolver.java

License:Apache License

public ArtifactResolutionResult resolve(ArtifactResolutionRequest request) {
    Artifact rootArtifact = request.getArtifact();
    Set<Artifact> artifacts = request.getArtifactDependencies();
    Map<String, Artifact> managedVersions = request.getManagedVersionMap();
    List<ResolutionListener> listeners = request.getListeners();
    ArtifactFilter collectionFilter = request.getCollectionFilter();
    ArtifactFilter resolutionFilter = request.getResolutionFilter();
    RepositorySystemSession session = getSession(request.getLocalRepository());

    //TODO: hack because metadata isn't generated in m2e correctly and i want to run the maven i have in the workspace
    if (source == null) {
        try {/* w  ww .ja  va  2  s. c  o  m*/
            source = container.lookup(ArtifactMetadataSource.class);
        } catch (ComponentLookupException e) {
            // won't happen
        }
    }

    if (listeners == null) {
        listeners = new ArrayList<ResolutionListener>();

        if (logger.isDebugEnabled()) {
            listeners.add(new DebugResolutionListener(logger));
        }

        listeners.add(new WarningResolutionListener(logger));
    }

    ArtifactResolutionResult result = new ArtifactResolutionResult();

    // The root artifact may, or may not be resolved so we need to check before we attempt to resolve.
    // This is often an artifact like a POM that is taken from disk and we already have hold of the
    // file reference. But this may be a Maven Plugin that we need to resolve from a remote repository
    // as well as its dependencies.

    if (request.isResolveRoot() /* && rootArtifact.getFile() == null */ ) {
        try {
            resolve(rootArtifact, request.getRemoteRepositories(), session);
        } catch (ArtifactResolutionException e) {
            result.addErrorArtifactException(e);
            return result;
        } catch (ArtifactNotFoundException e) {
            result.addMissingArtifact(request.getArtifact());
            return result;
        }
    }

    ArtifactResolutionRequest collectionRequest = request;

    if (request.isResolveTransitively()) {
        MetadataResolutionRequest metadataRequest = new DefaultMetadataResolutionRequest(request);

        metadataRequest.setArtifact(rootArtifact);
        metadataRequest.setResolveManagedVersions(managedVersions == null);

        try {
            ResolutionGroup resolutionGroup = source.retrieve(metadataRequest);

            if (managedVersions == null) {
                managedVersions = resolutionGroup.getManagedVersions();
            }

            Set<Artifact> directArtifacts = resolutionGroup.getArtifacts();

            if (artifacts == null || artifacts.isEmpty()) {
                artifacts = directArtifacts;
            } else {
                List<Artifact> allArtifacts = new ArrayList<Artifact>();
                allArtifacts.addAll(artifacts);
                allArtifacts.addAll(directArtifacts);

                Map<String, Artifact> mergedArtifacts = new LinkedHashMap<String, Artifact>();
                for (Artifact artifact : allArtifacts) {
                    String conflictId = artifact.getDependencyConflictId();
                    if (!mergedArtifacts.containsKey(conflictId)) {
                        mergedArtifacts.put(conflictId, artifact);
                    }
                }

                artifacts = new LinkedHashSet<Artifact>(mergedArtifacts.values());
            }

            collectionRequest = new ArtifactResolutionRequest(request);
            collectionRequest.setServers(request.getServers());
            collectionRequest.setMirrors(request.getMirrors());
            collectionRequest.setProxies(request.getProxies());
            collectionRequest.setRemoteRepositories(resolutionGroup.getResolutionRepositories());
        } catch (ArtifactMetadataRetrievalException e) {
            ArtifactResolutionException are = new ArtifactResolutionException(
                    "Unable to get dependency information for " + rootArtifact.getId() + ": " + e.getMessage(),
                    rootArtifact, metadataRequest.getRemoteRepositories(), e);
            result.addMetadataResolutionException(are);
            return result;
        }
    }

    if (artifacts == null || artifacts.isEmpty()) {
        if (request.isResolveRoot()) {
            result.addArtifact(rootArtifact);
        }
        return result;
    }

    // After the collection we will have the artifact object in the result but they will not be resolved yet.
    result = artifactCollector.collect(artifacts, rootArtifact, managedVersions, collectionRequest, source,
            collectionFilter, listeners, null);

    // We have metadata retrieval problems, or there are cycles that have been detected
    // so we give this back to the calling code and let them deal with this information
    // appropriately.

    if (result.hasMetadataResolutionExceptions() || result.hasVersionRangeViolations()
            || result.hasCircularDependencyExceptions()) {
        return result;
    }

    if (result.getArtifactResolutionNodes() != null) {
        ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

        CountDownLatch latch = new CountDownLatch(result.getArtifactResolutionNodes().size());

        for (ResolutionNode node : result.getArtifactResolutionNodes()) {
            Artifact artifact = node.getArtifact();

            if (resolutionFilter == null || resolutionFilter.include(artifact)) {
                executor.execute(new ResolveTask(classLoader, latch, artifact, session,
                        node.getRemoteRepositories(), result));
            } else {
                latch.countDown();
            }
        }
        try {
            latch.await();
        } catch (InterruptedException e) {
            result.addErrorArtifactException(
                    new ArtifactResolutionException("Resolution interrupted", rootArtifact, e));
        }
    }

    // We want to send the root artifact back in the result but we need to do this after the other dependencies
    // have been resolved.
    if (request.isResolveRoot()) {
        // Add the root artifact (as the first artifact to retain logical order of class path!)
        Set<Artifact> allArtifacts = new LinkedHashSet<Artifact>();
        allArtifacts.add(rootArtifact);
        allArtifacts.addAll(result.getArtifacts());
        result.setArtifacts(allArtifacts);
    }

    return result;
}