Example usage for org.apache.maven.project MavenProject getDependencies

List of usage examples for org.apache.maven.project MavenProject getDependencies

Introduction

In this page you can find the example usage for org.apache.maven.project MavenProject getDependencies.

Prototype

public List<Dependency> getDependencies() 

Source Link

Usage

From source file:com.ning.maven.plugins.dependencyversionscheck.AbstractDependencyVersionsMojo.java

License:Apache License

/**
 * Returns a Set of artifacts based off the given project. Artifacts can be filtered and optional dependencies can be excluded.
 *
 * It would be awesome if this method would also use the DependencyTreeBuilder which seems to yield better results (and is much closer to the actual compile tree in some cases)
 * than the artifactResolver. However, due to MNG-3236 the artifact filter is not applied when resolving dependencies and this method relies on the artifact filter to get
 * the scoping right. Well, maybe in maven 3.0 this will be better. Or different. Whatever comes first.
 *///w w  w .j  av  a  2 s.com
private Set resolveDependenciesInItsOwnScope(final MavenProject project, final ArtifactFilter filter,
        final boolean includeOptional)
        throws InvalidDependencyVersionException, ArtifactResolutionException, ArtifactNotFoundException {
    Set dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, project.getDependencies(),
            null, filter, null);

    ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts,
            project.getArtifact(), Collections.EMPTY_MAP, localRepository,
            project.getRemoteArtifactRepositories(), artifactMetadataSource,
            new ArtifactOptionalFilter(includeOptional));

    return result.getArtifacts();
}

From source file:com.pongasoft.maven.ant.tasks.ResolveTask.java

License:Apache License

@SuppressWarnings("unchecked")
private void resolveTransitively(Artifact mainArtifact) {
    try {/* w ww.  ja  v a  2 s .  co  m*/
        Artifact pomArtifact = resolveArtifact("pom", null);
        MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup(MavenProjectBuilder.ROLE);
        MavenProject mavenProject = projectBuilder.buildWithDependencies(pomArtifact.getFile(), _localRepo,
                getProfileManager());

        Set<String> dependencies = new HashSet<String>();

        for (Dependency d : (List<Dependency>) mavenProject.getDependencies()) {
            dependencies.add(d.getGroupId() + ":" + d.getArtifactId() + ":" + d.getVersion() + ":"
                    + d.getClassifier() + ":" + d.getType() + ":" + d.getScope());
        }

        Collection<Artifact> directDependencies = new ArrayList<Artifact>();
        Collection<Artifact> transitiveDependencies = new ArrayList<Artifact>();
        Collection<Artifact> optionalDependencies = new ArrayList<Artifact>();
        Collection<Artifact> classpath = new ArrayList<Artifact>();
        classpath.add(mainArtifact);

        for (org.apache.maven.artifact.Artifact a : (Set<org.apache.maven.artifact.Artifact>) mavenProject
                .getArtifacts()) {
            String scope = a.getScope();
            if ("compile".equals(scope) || "runtime".equals(scope)) {
                Artifact artifact = createArtifact(a);

                if (a.isOptional() && _optional) {
                    classpath.add(artifact);
                    optionalDependencies.add(artifact);
                } else {
                    classpath.add(artifact);

                }
                if (dependencies.contains(a.getGroupId() + ":" + a.getArtifactId() + ":" + a.getVersion() + ":"
                        + a.getClassifier() + ":" + a.getType() + ":" + a.getScope())) {
                    directDependencies.add(artifact);
                } else {
                    transitiveDependencies.add(artifact);
                }
            }
        }

        _result.put("classpath", classpath);
        _result.put("transitiveDependencies", transitiveDependencies);
        _result.put("directDependencies", directDependencies);
        _result.put("optionalDependencies", optionalDependencies);
    } catch (ProjectBuildingException e) {
        throw new BuildException(e);
    } catch (ArtifactNotFoundException e) {
        throw new BuildException(e);
    } catch (ArtifactResolutionException e) {
        throw new BuildException(e);
    }
}

From source file:com.puresoltechnologies.maven.plugins.license.AbstractValidationMojo.java

/**
 * Loads the artifact recursively.//from ww w . j a  v  a 2  s .  c  o  m
 * 
 * @param artifact
 * @param recursive
 *            specified whether all dependencies should be loaded
 *            recursively.
 * @param skipTestScope
 *            specified whether to skip test scoped artifacts or not.
 * @return A {@link DependencyTree} object is returned.
 * @throws MojoExecutionException
 *             is thrown if anything unexpected goes wrong.
 */
private DependencyTree loadArtifacts(int depth, DependencyTree parentDependencyTree, Artifact artifact,
        boolean recursive, boolean skipTestScope, boolean skipProvidedScope, boolean skipOptionals)
        throws MojoExecutionException {
    Log log = getLog();
    MavenProject parentArtifactProject;
    try {
        parentArtifactProject = mavenProjectBuilder.buildFromRepository(artifact, remoteArtifactRepositories,
                localRepository);
    } catch (ProjectBuildingException e) {
        log.warn("Could not load artifacts recursively. For artifact '" + ArtifactUtilities.toString(artifact)
                + "' the project creation failed.", e);
        return null;
    }
    @SuppressWarnings("unchecked")
    List<Dependency> dependencies = parentArtifactProject.getDependencies();
    @SuppressWarnings("unchecked")
    List<License> licenses = parentArtifactProject.getLicenses();
    DependencyTree dependencyTree = new DependencyTree(artifact, licenses);
    if (parentDependencyTree != null) {
        parentDependencyTree.addDependency(dependencyTree);
    }
    if ((dependencies != null) && ((recursive) || (artifact == mavenProject.getArtifact()))) {
        for (Dependency dependency : dependencies) {
            StringBuffer buffer = new StringBuffer();
            if (log.isDebugEnabled()) {
                for (int i = 0; i < depth; i++) {
                    buffer.append("    ");
                }
                buffer.append("\\-> ");
                log.debug(buffer.toString() + ArtifactUtilities.toString(dependency));
            }
            if (skipTestScope && Artifact.SCOPE_TEST.equals(dependency.getScope())) {
                if (log.isDebugEnabled()) {
                    log.debug(buffer.toString() + " >> test scope is skipped");
                }
                continue;
            }
            if (skipProvidedScope && Artifact.SCOPE_PROVIDED.equals(dependency.getScope())) {
                if (log.isDebugEnabled()) {
                    log.debug(buffer.toString() + " >> provided scope is skipped");
                }
                continue;
            }
            if (skipOptionals && dependency.isOptional()) {
                if (log.isDebugEnabled()) {
                    log.debug(buffer.toString() + " >> optional is skipped");
                }
                continue;
            }
            if (hasCycle(dependencyTree, dependency)) {
                if (log.isDebugEnabled()) {
                    log.debug(buffer.toString() + " >> cylce found and needs to be skipped");
                }
                continue;
            }
            Artifact dependencyArtifact = DependencyUtilities.buildArtifact(artifact, dependency);
            loadArtifacts(depth + 1, dependencyTree, dependencyArtifact, recursive, skipTestScope,
                    skipProvidedScope, skipOptionals);
        }
    }
    return dependencyTree;
}

From source file:com.runwaysdk.business.generation.maven.MavenClasspathBuilder.java

License:Open Source License

public static List<String> getClasspathFromMavenProject(File projectPom, File localRepoFolder,
        boolean isRunwayEnvironment) throws DependencyResolutionException, IOException, XmlPullParserException {
    MavenProject proj = loadProject(projectPom);

    PropertyReplacer propReplacer = new PropertyReplacer(proj);

    List<Repository> repos = proj.getRepositories();

    List<String> classpath = new ArrayList<String>();

    RepositorySystem system = Booter.newRepositorySystem();
    RepositorySystemSession session = Booter.newRepositorySystemSession(system, localRepoFolder);
    RemoteRepository centralRepo = Booter.newCentralRepository();
    DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);

    List<org.apache.maven.model.Dependency> dependencies = proj.getDependencies();
    Iterator<org.apache.maven.model.Dependency> it = dependencies.iterator();

    while (it.hasNext()) {
        org.apache.maven.model.Dependency depend = it.next();

        Artifact artifact = new DefaultArtifact(propReplacer.replace(depend.getGroupId()),
                propReplacer.replace(depend.getArtifactId()), propReplacer.replace(depend.getClassifier()),
                propReplacer.replace(depend.getType()), propReplacer.replace(depend.getVersion()));

        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(artifact, JavaScopes.COMPILE));
        collectRequest.addRepository(centralRepo);

        for (Repository repo : repos) {
            collectRequest.addRepository(new RemoteRepository(propReplacer.replace(repo.getId()),
                    propReplacer.replace(repo.getLayout()), propReplacer.replace(repo.getUrl())));
        }//  www .j a  v a 2s.co m

        try {
            DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);

            List<ArtifactResult> artifactResults = system.resolveDependencies(session, dependencyRequest)
                    .getArtifactResults();

            for (ArtifactResult artifactResult : artifactResults) {
                Artifact art = artifactResult.getArtifact();

                if (isRunwayEnvironment && art.getGroupId().equals("com.runwaysdk")
                        && (art.getArtifactId().equals("runwaysdk-client")
                                || art.getArtifactId().equals("runwaysdk-common")
                                || art.getArtifactId().equals("runwaysdk-server"))) {
                    continue;
                }

                classpath.add(art.getFile().getAbsolutePath());
            }
        } catch (DependencyResolutionException e) {
            // Is Maven ignoring this? I'm confused.
            log.error(e);
            e.printStackTrace();
        }
    }

    if (log.isTraceEnabled()) {
        String cpath = "";
        for (Iterator<String> i = classpath.iterator(); i.hasNext();) {
            cpath = cpath + ", " + i.next();
        }

        log.trace("Resolved pom [" + projectPom.getAbsolutePath() + "] classpath to [" + cpath + "]");
    }

    return classpath;
}

From source file:com.simpligility.maven.plugins.android.phase_prebuild.ClasspathModifierLifecycleParticipant.java

License:Open Source License

private Dependency findProvidedDependencies(Dependency dexDependency, MavenProject project) {
    for (Dependency dependency : project.getDependencies()) {
        if (dependency.getScope().equals(Artifact.SCOPE_PROVIDED)) {
            if (dependency.getArtifactId().equals(dexDependency.getArtifactId())
                    && dependency.getGroupId().equals(dexDependency.getGroupId())
                    && dependency.getType().equals(dexDependency.getType())
                    && dependency.getVersion().equals(dexDependency.getVersion())) {
                return dependency;
            }//  w  w w .  j  a  v  a 2  s .c o  m
        }
    }
    return null;

}

From source file:com.sourcesense.maven.dbdep.plugin.parser.POMParser.java

License:Apache License

public List getDependenciesFromPOM(MavenProject project, String projectName, String environment) {
    List dependencies = new ArrayList();
    Iterator i = project.getDependencies().iterator();
    while (i.hasNext()) {
        DependencyDO dependency = new DependencyDO();
        Dependency dep = (Dependency) i.next();
        dependency.setProject(projectName);
        dependency.setEnvironment(environment);
        dependency.setName(dep.getArtifactId());
        dependency.setVersion(dep.getVersion());
        dependencies.add(dependency);//  w w  w. ja  va 2  s  . co  m
    }
    return dependencies;
}

From source file:com.sun.jersey.wadl.AbstractMojoProjectClasspathSupport.java

License:Open Source License

/**
 * Create a list of classpath elements including declared build dependencies, the build
 * output directory and additionally configured dependencies.
 * @param mavenProject/*  w  w  w  . j  ava 2s  .  c o m*/
 * @param additionalDependencies
 * @return a list of classpath elements
 * @throws DependencyResolutionRequiredException
 * @throws ArtifactResolutionException
 * @throws ArtifactNotFoundException
 * @author Martin Grotzke
 */
protected List<String> getClasspathElements(final MavenProject mavenProject,
        final List<com.sun.jersey.wadl.Dependency> additionalDependencies)
        throws DependencyResolutionRequiredException, ArtifactResolutionException, ArtifactNotFoundException {

    final List<String> paths = new ArrayList<String>();

    /* Add maven compile classpath elements
     */
    @SuppressWarnings("unchecked")
    final List<String> compileClasspathElements = mavenProject.getCompileClasspathElements();
    paths.addAll(compileClasspathElements);

    /* Add build dependencies as classpath elements
     */
    @SuppressWarnings("unchecked")
    final Collection<Dependency> dependencies = mavenProject.getDependencies();
    if (dependencies != null) {
        for (Dependency dependency : dependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(),
                        dependency.getArtifactId(), dependency.getVersion(), dependency.getType(),
                        dependency.getClassifier());
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }

    /* Add additional dependencies
     */
    if (additionalDependencies != null) {
        for (com.sun.jersey.wadl.Dependency dependency : additionalDependencies) {
            if (dependency.getSystemPath() != null) {
                getLog().debug("Adding additional dependency with systemPath " + dependency.getSystemPath());
                paths.add(dependency.getSystemPath());
            } else {
                final Artifact artifact = artifactFactory.createArtifactWithClassifier(dependency.getGroupId(),
                        dependency.getArtifactId(), dependency.getVersion(), "jar", null);
                resolver.resolve(artifact, remoteRepositories, localRepository);
                getLog().debug("Adding additional artifact " + artifact.getFile().getPath());
                paths.add(artifact.getFile().getPath());
            }
        }
    }

    return paths;
}

From source file:com.taobao.hsf.jetty.RuntimeDependencyResolver.java

License:Apache License

/**
 * Download (if necessary) a pom, and load it as a MavenProject, transitively resolving any
 * dependencies therein./*w w w .  j a  v  a 2  s .c  o  m*/
 * 
 * @param projectBuilder
 * @param groupId
 * @param artifactId
 * @param versionId
 * @return a Set of Artifacts representing the transitively resolved dependencies.
 * 
 * @throws MalformedURLException
 * @throws ProjectBuildingException
 * @throws InvalidDependencyVersionException
 * @throws ArtifactResolutionException
 * @throws ArtifactNotFoundException
 */
public Set transitivelyResolvePomDependencies(MavenProjectBuilder projectBuilder, String groupId,
        String artifactId, String versionId, boolean resolveProjectArtifact)
        throws MalformedURLException, ProjectBuildingException, InvalidDependencyVersionException,
        ArtifactResolutionException, ArtifactNotFoundException {

    Artifact pomArtifact = getPomArtifact(groupId, artifactId, versionId);
    MavenProject project = loadPomAsProject(projectBuilder, pomArtifact);
    List dependencies = project.getDependencies();

    Set dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null,
            null);
    dependencyArtifacts.add(project.getArtifact());

    List listeners = Collections.EMPTY_LIST;

    if (PluginLog.getLog().isDebugEnabled()) {
        listeners = new ArrayList();
        listeners.add(new RuntimeResolutionListener());
    }

    ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts, pomArtifact,
            Collections.EMPTY_MAP, localRepository, remoteRepositories, metadataSource, null, listeners);

    Set artifacts = result.getArtifacts();

    if (PluginLog.getLog().isDebugEnabled()) {
        PluginLog.getLog().debug("RESOLVED " + artifacts.size() + " ARTIFACTS");
        Iterator itor = artifacts.iterator();
        while (itor.hasNext()) {
            Artifact a = (Artifact) itor.next();
            PluginLog.getLog().debug(a.getFile().toURL().toString());
        }
    }
    return artifacts;
}

From source file:com.technophobia.substeps.runner.CoreVersionChecker.java

License:Open Source License

public void checkVersion(MavenProject runningProject, List<Artifact> pluginsDependencies)
        throws MojoExecutionException {

    Dependency substepsCoreDependency = Iterables.find((List<Dependency>) runningProject.getTestDependencies(),
            IS_SUBSTEPS_CORE, null);/*from  ww  w  .j a va  2s  . c o  m*/

    if (substepsCoreDependency == null) {

        log.warn("Invalid plugin configuration, no version of " + CORE_ARTIFACT_ID + " found");

    } else {
        MavenProject coreProject = loadProject(substepsCoreDependency);

        Dependency apiDependencyInCore = Iterables.find((List<Dependency>) coreProject.getDependencies(),
                IS_SUBSTEPS_API, null);

        Artifact apiArtifactInPlugin = Iterables.find(pluginsDependencies, ARTIFACT_IS_SUBSTEPS_API, null);

        assertSameVersion(apiDependencyInCore, apiArtifactInPlugin);
    }
}

From source file:de.jiac.micro.mojo.ConfiguratorMojo.java

License:Open Source License

private Set transitivelyResolvePomDependencies(String groupId, String artifactId, String version)
        throws ProjectBuildingException, InvalidDependencyVersionException, ArtifactResolutionException,
        ArtifactNotFoundException {/*  w w  w . ja  v  a 2  s . c om*/
    //get the pom as an Artifact 
    Artifact pomArtifact = artifactFactory.createPluginArtifact(groupId, artifactId,
            VersionRange.createFromVersion(version));

    //load the pom as a MavenProject
    MavenProject tempProject = mavenProjectBuilder.buildFromRepository(pomArtifact, remoteRepositories,
            localRepository);

    //get all of the dependencies for the project
    List dependencies = tempProject.getDependencies();

    //make Artifacts of all the dependencies
    Set dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, dependencies, null, null,
            null);

    //not forgetting the Artifact of the project itself
    dependencyArtifacts.add(tempProject.getArtifact());

    //resolve all dependencies transitively to obtain a comprehensive list of jars        
    ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts, pomArtifact,
            Collections.EMPTY_MAP, localRepository, remoteRepositories, metadataSource, null,
            Collections.EMPTY_LIST);

    return result.getArtifacts();
}