Example usage for org.apache.maven.artifact.resolver ResolutionNode getArtifact

List of usage examples for org.apache.maven.artifact.resolver ResolutionNode getArtifact

Introduction

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

Prototype

public Artifact getArtifact() 

Source Link

Usage

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

public ArtifactResolutionResult collect(Set<Artifact> artifacts, Artifact originatingArtifact,
        Map managedVersions, ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories,
        ArtifactMetadataSource source, ArtifactFilter filter, List<ResolutionListener> listeners) {
    Map resolvedArtifacts = new HashMap();

    ResolutionNode root = new ResolutionNode(originatingArtifact, remoteRepositories);
    try {/*w w  w  .  j ava 2  s.  c  om*/
        root.addDependencies(artifacts, remoteRepositories, filter);
        recurse(root, resolvedArtifacts, managedVersions, localRepository, remoteRepositories, source, filter,
                listeners);
    } catch (CyclicDependencyException e) {
        e.printStackTrace();
    } catch (OverConstrainedVersionException e) {
        e.printStackTrace();
    } catch (ArtifactResolutionException e) {
        e.printStackTrace();
    }

    Set set = new HashSet();
    for (Iterator i = resolvedArtifacts.values().iterator(); i.hasNext();) {
        List nodes = (List) i.next();
        for (Iterator j = nodes.iterator(); j.hasNext();) {
            ResolutionNode node = (ResolutionNode) j.next();
            Artifact artifact = node.getArtifact();
            try {
                if (!node.equals(root) && node.isActive() && node.filterTrail(filter)
                // If it was optional and not a direct dependency,
                // we don't add it or its children, just allow the
                // update of the version and scope
                        && (node.isChildOfRootNode() || !artifact.isOptional())) {
                    artifact.setDependencyTrail(node.getDependencyTrail());
                    set.add(node);
                }
            } catch (OverConstrainedVersionException e) {
                e.printStackTrace();
            }
        }
    }

    ArtifactResolutionResult result = new ArtifactResolutionResult();
    result.setArtifactResolutionNodes(set);
    return result;
}

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private void recurse(ResolutionNode node, Map resolvedArtifacts, Map managedVersions,
        ArtifactRepository localRepository, List remoteRepositories, ArtifactMetadataSource source,
        ArtifactFilter filter, List listeners)
        throws CyclicDependencyException, ArtifactResolutionException, OverConstrainedVersionException {
    fireEvent(ResolutionListener.TEST_ARTIFACT, listeners, node);

    // TODO: use as a conflict resolver
    Object key = node.getKey();//from  www .  j  ava 2 s .co  m
    if (managedVersions.containsKey(key)) {
        Artifact artifact = (Artifact) managedVersions.get(key);
        fireEvent(ResolutionListener.MANAGE_ARTIFACT, listeners, node, artifact);
        if (artifact.getVersion() != null) {
            node.getArtifact().setVersion(artifact.getVersion());
        }
        if (artifact.getScope() != null) {
            node.getArtifact().setScope(artifact.getScope());
        }
    }

    List previousNodes = (List) resolvedArtifacts.get(key);
    if (previousNodes != null) {
        node = checkPreviousNodes(node, listeners, previousNodes);
    } else {
        previousNodes = new ArrayList();
        resolvedArtifacts.put(key, previousNodes);
    }
    previousNodes.add(node);

    if (node.isActive()) {
        fireEvent(ResolutionListener.INCLUDE_ARTIFACT, listeners, node);
    }

    // don't pull in the transitive deps of a system-scoped dependency.
    if (node.isActive() && !Artifact.SCOPE_SYSTEM.equals(node.getArtifact().getScope())) {
        fireEvent(ResolutionListener.PROCESS_CHILDREN, listeners, node);
        for (Iterator i = node.getChildrenIterator(); i.hasNext();) {
            ResolutionNode child = (ResolutionNode) i.next();
            // We leave in optional ones, but don't pick up its dependencies
            if (!child.isResolved() && (!child.getArtifact().isOptional() || child.isChildOfRootNode())) {
                Artifact artifact = child.getArtifact();
                try {
                    if (artifact.getVersion() == null) {
                        // set the recommended version
                        // TODO: maybe its better to just pass the range
                        // through to retrieval and use a transformation?
                        ArtifactVersion version;
                        version = getArtifactVersion(localRepository, remoteRepositories, source, artifact);

                        artifact.selectVersion(version.toString());
                        fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, child);
                    }

                    ResolutionGroup rGroup = source.retrieve(artifact, localRepository, remoteRepositories);

                    // TODO might be better to have source.retreive() throw
                    // a specific exception for this situation
                    // and catch here rather than have it return null
                    if (rGroup == null) {
                        // relocated dependency artifact is declared
                        // excluded, no need to add and recurse further
                        continue;
                    }

                    child.addDependencies(rGroup.getArtifacts(), rGroup.getResolutionRepositories(), filter);
                } catch (CyclicDependencyException e) {
                    // would like to throw this, but we have crappy stuff in
                    // the repo

                    fireEvent(ResolutionListener.OMIT_FOR_CYCLE, listeners,
                            new ResolutionNode(e.getArtifact(), remoteRepositories, child));
                } catch (ArtifactMetadataRetrievalException e) {
                    artifact.setDependencyTrail(node.getDependencyTrail());
                    throw new ArtifactResolutionException(
                            "Unable to get dependency information: " + e.getMessage(), artifact, e);
                }

                recurse(child, resolvedArtifacts, managedVersions, localRepository, remoteRepositories, source,
                        filter, listeners);
            }
        }
        fireEvent(ResolutionListener.FINISH_PROCESSING_CHILDREN, listeners, node);
    }
}

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private ResolutionNode checkPreviousNodes(ResolutionNode node, List listeners, List previousNodes)
        throws OverConstrainedVersionException {
    for (Iterator i = previousNodes.iterator(); i.hasNext();) {
        ResolutionNode previous = (ResolutionNode) i.next();
        if (previous.isActive()) {
            // Version mediation
            VersionRange previousRange = previous.getArtifact().getVersionRange();
            VersionRange currentRange = node.getArtifact().getVersionRange();
            // TODO: why do we force the version on it? what if they
            // don't match?
            if (previousRange == null) {
                // version was already resolved
                node.getArtifact().setVersion(previous.getArtifact().getVersion());
            } else if (currentRange == null) {
                // version was already resolved
                previous.getArtifact().setVersion(node.getArtifact().getVersion());
            } else {
                // TODO: shouldn't need to double up on this work, only
                // done for simplicity of handling recommended
                // version but the restriction is identical
                VersionRange newRange = previousRange.restrict(currentRange);
                // TODO: ick. this forces the OCE that should have come
                // from the previous call. It is still correct
                if (newRange.isSelectedVersionKnown(previous.getArtifact())) {
                    fireEvent(ResolutionListener.RESTRICT_RANGE, listeners, node, previous.getArtifact(),
                            newRange);/*from w  w w . j  av a 2 s.co m*/
                }
                previous.getArtifact().setVersionRange(newRange);
                node.getArtifact().setVersionRange(currentRange.restrict(previousRange));

                // Select an appropriate available version from the (now
                // restricted) range
                // Note this version was selected before to get the
                // appropriate POM
                // But it was reset by the call to setVersionRange on
                // restricting the version
                ResolutionNode[] resetNodes = { previous, node };
                for (int j = 0; j < 2; j++) {
                    Artifact resetArtifact = resetNodes[j].getArtifact();
                    if (resetArtifact.getVersion() == null && resetArtifact.getVersionRange() != null
                            && resetArtifact.getAvailableVersions() != null) {

                        resetArtifact.selectVersion(resetArtifact.getVersionRange()
                                .matchVersion(resetArtifact.getAvailableVersions()).toString());
                        fireEvent(ResolutionListener.SELECT_VERSION_FROM_RANGE, listeners, resetNodes[j]);
                    }
                }
            }

            // Conflict Resolution
            // TODO: use as conflict resolver(s), chain

            // TODO: should this be part of mediation?
            // previous one is more dominant
            if (previous.getDepth() <= node.getDepth()) {
                checkScopeUpdate(node, previous, listeners);
            } else {
                checkScopeUpdate(previous, node, listeners);
            }

            if (previous.getDepth() <= node.getDepth()) {
                // previous was nearer
                fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, node, previous.getArtifact());
                node.disable();
                node = previous;
            } else {
                fireEvent(ResolutionListener.OMIT_FOR_NEARER, listeners, previous, node.getArtifact());
                previous.disable();
            }
        }
    }
    return node;
}

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private void checkScopeUpdate(ResolutionNode farthest, ResolutionNode nearest, List listeners) {
    boolean updateScope = false;
    Artifact farthestArtifact = farthest.getArtifact();
    Artifact nearestArtifact = nearest.getArtifact();

    if (Artifact.SCOPE_RUNTIME.equals(farthestArtifact.getScope())
            && (Artifact.SCOPE_TEST.equals(nearestArtifact.getScope())
                    || Artifact.SCOPE_PROVIDED.equals(nearestArtifact.getScope()))) {
        updateScope = true;/*from ww w .  j ava2s .c o  m*/
    }

    if (Artifact.SCOPE_COMPILE.equals(farthestArtifact.getScope())
            && !Artifact.SCOPE_COMPILE.equals(nearestArtifact.getScope())) {
        updateScope = true;
    }

    // current POM rules all
    if (nearest.getDepth() < 2 && updateScope) {
        updateScope = false;

        fireEvent(ResolutionListener.UPDATE_SCOPE_CURRENT_POM, listeners, nearest, farthestArtifact);
    }

    if (updateScope) {
        fireEvent(ResolutionListener.UPDATE_SCOPE, listeners, nearest, farthestArtifact);

        // previously we cloned the artifact, but it is more effecient to
        // just update the scope
        // if problems are later discovered that the original object needs
        // its original scope value, cloning may
        // again be appropriate
        nearestArtifact.setScope(farthestArtifact.getScope());
    }
}

From source file:com.adviser.maven.GraphArtifactCollector.java

License:Apache License

private void fireEvent(int event, List listeners, ResolutionNode node, Artifact replacement,
        VersionRange newRange) {//from  ww w .j  av  a2 s .c om
    for (Iterator i = listeners.iterator(); i.hasNext();) {
        ResolutionListener listener = (ResolutionListener) i.next();

        switch (event) {
        case ResolutionListener.TEST_ARTIFACT:
            listener.testArtifact(node.getArtifact());
            break;
        case ResolutionListener.PROCESS_CHILDREN:
            listener.startProcessChildren(node.getArtifact());
            break;
        case ResolutionListener.FINISH_PROCESSING_CHILDREN:
            listener.endProcessChildren(node.getArtifact());
            break;
        case ResolutionListener.INCLUDE_ARTIFACT:
            listener.includeArtifact(node.getArtifact());
            break;
        case ResolutionListener.OMIT_FOR_NEARER:
            String version = node.getArtifact().getVersion();
            String replacementVersion = replacement.getVersion();
            if (version != null ? !version.equals(replacementVersion) : replacementVersion != null) {
                listener.omitForNearer(node.getArtifact(), replacement);
            }
            break;
        case ResolutionListener.OMIT_FOR_CYCLE:
            listener.omitForCycle(node.getArtifact());
            break;
        case ResolutionListener.UPDATE_SCOPE:
            listener.updateScope(node.getArtifact(), replacement.getScope());
            break;
        case ResolutionListener.UPDATE_SCOPE_CURRENT_POM:
            listener.updateScopeCurrentPom(node.getArtifact(), replacement.getScope());
            break;
        case ResolutionListener.MANAGE_ARTIFACT:
            listener.manageArtifact(node.getArtifact(), replacement);
            break;
        case ResolutionListener.SELECT_VERSION_FROM_RANGE:
            listener.selectVersionFromRange(node.getArtifact());
            break;
        case ResolutionListener.RESTRICT_RANGE:
            if (node.getArtifact().getVersionRange().hasRestrictions()
                    || replacement.getVersionRange().hasRestrictions()) {
                listener.restrictRange(node.getArtifact(), replacement, newRange);
            }
            break;
        default:
            throw new IllegalStateException("Unknown event: " + event);
        }
    }
}

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.// w  w  w  .  ja  v  a  2  s . co  m
 *
 * @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: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
 *//*ww w. jav  a2 s  . c  om*/
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.felix.karaf.tooling.features.GraphArtifactCollector.java

License:Apache License

public ArtifactResolutionResult collect(Set artifacts, Artifact originatingArtifact, Map managedVersions,
        ArtifactRepository localRepository, List remoteRepositories, ArtifactMetadataSource source,
        ArtifactFilter filter, List listeners) throws ArtifactResolutionException {
    Map resolvedArtifacts = new HashMap();

    ResolutionNode root = new ResolutionNode(originatingArtifact, remoteRepositories);
    root.addDependencies(artifacts, remoteRepositories, filter);
    recurse(root, resolvedArtifacts, managedVersions, localRepository, remoteRepositories, source, filter,
            listeners);//from w ww.  j a  v  a2  s.c o  m

    Set set = new HashSet();
    for (Iterator i = resolvedArtifacts.values().iterator(); i.hasNext();) {
        List nodes = (List) i.next();
        for (Iterator j = nodes.iterator(); j.hasNext();) {
            ResolutionNode node = (ResolutionNode) j.next();
            Artifact artifact = node.getArtifact();
            if (!node.equals(root) && node.isActive() && node.filterTrail(filter)
            // If it was optional and not a direct dependency,
            // we don't add it or its children, just allow the
            // update of the version and scope
                    && (node.isChildOfRootNode() || !artifact.isOptional())) {
                artifact.setDependencyTrail(node.getDependencyTrail());
                set.add(node);
            }
        }
    }

    ArtifactResolutionResult result = new ArtifactResolutionResult();
    result.setArtifactResolutionNodes(set);
    return result;
}

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.//  ww w  . j  av a 2  s.c  om
 *
 * @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()));
    }//from   w  w w  . ja  va2s  .  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;
}