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:org.bigtester.ate.experimentals.DynamicClassLoader.java

License:Apache License

@Test
public void test3() throws FileNotFoundException, IOException, XmlPullParserException,
        DependencyResolutionRequiredException {
    MavenXpp3Reader reader = new MavenXpp3Reader();

    File pomFile = new File("pom.xml");
    Model model = reader.read(new FileReader(pomFile));
    MavenProject project = new MavenProject(model);
    //      Collection<File> jars = new Classpath(
    //              project,
    //              new File("/home/peidong/.m2/respository"),
    //              "test" // the scope you're interested in
    //            );
    List<Dependency> runtimeClasspathElements = project.getDependencies();
    for (Dependency runtimeClasspathElement : runtimeClasspathElements) {
        System.out.println(runtimeClasspathElement);
    }/*  w  w w .j  av a 2s .  c  om*/
    //      System.out.println("--------- Model -------------");
    //      for (Dependency dependency : modelPom.getDependencies()) {
    //         System.out.println("Model Dependency:" + dependency);
    //      }
}

From source file:org.codehaus.mojo.gwt.AbstractGwtMojo.java

License:Apache License

private Collection<File> getJarFiles(String artifactId) throws MojoExecutionException {
    checkGwtUserVersion();//from   w ww.  j av a  2s.  c  o m
    Artifact rootArtifact = pluginArtifactMap.get(artifactId);

    ArtifactResolutionResult result;
    try {
        // Code shamelessly copied from exec-maven-plugin.
        MavenProject rootProject = this.projectBuilder.buildFromRepository(rootArtifact,
                this.remoteRepositories, this.localRepository);
        List<Dependency> dependencies = rootProject.getDependencies();
        Set<Artifact> dependencyArtifacts = MavenMetadataSource.createArtifacts(artifactFactory, dependencies,
                null, null, null);
        dependencyArtifacts.add(rootProject.getArtifact());
        result = resolver.resolveTransitively(dependencyArtifacts, rootArtifact, Collections.EMPTY_MAP,
                localRepository, remoteRepositories, artifactMetadataSource, null, Collections.EMPTY_LIST);
    } catch (Exception e) {
        throw new MojoExecutionException("Failed to resolve artifact", e);
    }

    Collection<Artifact> resolved = result.getArtifacts();
    Collection<File> files = new ArrayList<File>(resolved.size() + 1);
    files.add(rootArtifact.getFile());
    for (Artifact artifact : resolved) {
        files.add(artifact.getFile());
    }

    return files;
}

From source file:org.codehaus.mojo.javascript.configurator.JsriaProjectConfigurator.java

License:Open Source License

private void ensureImplicitDependencies(MavenProject mavenProject) {
    List<Dependency> dependencies = mavenProject.getDependencies();
    boolean qunitExists = false, jstestRunnerExists = false, junitExists = false;
    for (Dependency d : dependencies) {
        if (!qunitExists && dependencyEquivalent(d, QUNIT_DEPENDENCY)) {
            qunitExists = true;//from w  ww.j a v a  2  s.  c o  m
        } else if (!jstestRunnerExists && dependencyEquivalent(d, JSTESTRUNNER_DEPENDENCY)) {
            jstestRunnerExists = true;
        } else if (!junitExists && dependencyEquivalent(d, JUNIT_DEPENDENCY)) {
            junitExists = true;
        }
    }

    if (!qunitExists) {
        dependencies.add(QUNIT_DEPENDENCY);
    }
    if (!jstestRunnerExists) {
        dependencies.add(JSTESTRUNNER_DEPENDENCY);
    }
    if (!junitExists) {
        dependencies.add(JUNIT_DEPENDENCY);
    }
}

From source file:org.codehaus.mojo.license.api.DefaultDependenciesTool.java

License:Open Source License

/**
 * {@inheritDoc}/*w ww.  ja  v  a2  s  .  co m*/
 */
public void loadProjectArtifacts(ArtifactRepository localRepository, List remoteRepositories,
        MavenProject project) throws DependenciesToolException

{

    if (CollectionUtils.isEmpty(project.getDependencyArtifacts())) {

        Set dependenciesArtifacts;
        try {
            dependenciesArtifacts = MavenMetadataSource.createArtifacts(artifactFactory,
                    project.getDependencies(), null, null, project);
        } catch (InvalidDependencyVersionException e) {
            throw new DependenciesToolException(e);
        }
        project.setDependencyArtifacts(dependenciesArtifacts);

        Artifact artifact = project.getArtifact();

        ArtifactResolutionResult result;
        try {
            result = artifactResolver.resolveTransitively(dependenciesArtifacts, artifact, remoteRepositories,
                    localRepository, artifactMetadataSource);
        } catch (ArtifactResolutionException e) {
            throw new DependenciesToolException(e);
        } catch (ArtifactNotFoundException e) {
            throw new DependenciesToolException(e);
        }

        project.setArtifacts(result.getArtifacts());

    }

}

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

License:Apache License

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

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

        String groupId = dep.getGroupId();
        String artifactId = dep.getArtifactId();
        VersionRange versionRange = VersionRange.createFromVersion(dep.getVersion());
        String type = dep.getType();
        if (type == null) {
            type = "jar";
        }/*from w  w  w.j  ava  2 s .co m*/

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

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

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

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

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

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

        artifacts.add(artifact);
    }

    return artifacts;
}

From source file:org.codehaus.mojo.pom.PomRefactorMojo.java

License:Apache License

/**
 * {@inheritDoc}/*from  w  w  w .j  av a  2s  . com*/
 */
@Override
@SuppressWarnings("unchecked")
public void execute(ProjectContainer projectContainer) throws MojoExecutionException, MojoFailureException {

    if (getNewAttributes().isEmpty()) {
        throw new MojoExecutionException(
                "At least one of the new*-parameters (newVersion, newArtifactId, newGroupId, newScope or newClassifier) have to be configured!");
    }
    super.execute(projectContainer);
    MavenProject project = projectContainer.getProject();
    updateProject(projectContainer, project, false);
    MavenProject parent = project.getParent();
    if (parent != null) {
        updateProject(projectContainer, parent, true);
    }
    updateDependencies(project.getDependencies(), projectContainer, ProjectContainer.XML_TAG_DEPENDENCIES);
    DependencyManagement dependencyManagement = project.getDependencyManagement();
    if (dependencyManagement != null) {
        updateDependencies(dependencyManagement.getDependencies(), projectContainer,
                ProjectContainer.XML_TAG_DEPENDENCY_MANAGEMENT);
    }
}

From source file:org.codehaus.mojo.versions.CompareDependenciesMojo.java

License:Apache License

/**
 * @param pom the pom to update.//from  w  w  w  .j  a  va2s .c  o  m
 * @throws org.apache.maven.plugin.MojoExecutionException
 *          Something wrong with the plugin itself
 * @throws org.apache.maven.plugin.MojoFailureException
 *          The plugin detected an error in the build
 * @throws javax.xml.stream.XMLStreamException
 *          when things go wrong with XML streaming
 * @see AbstractVersionsUpdaterMojo#update(org.codehaus.mojo.versions.rewriting.ModifiedPomXMLEventReader)
 */
protected void update(ModifiedPomXMLEventReader pom)
        throws MojoExecutionException, MojoFailureException, XMLStreamException {
    if (this.ignoreRemoteDependencies && this.ignoreRemoteDependencyManagement) {
        throw new MojoFailureException(" ignoreRemoteDependencies and ignoreRemoteDependencyManagement"
                + "are both set to true.  At least one of these needs to be false ");
    }

    if (updateDependencies) {
        reportMode = false;
    }

    String[] remotePomParts = this.remotePom.split(":");
    if (remotePomParts.length != 3) {
        throw new MojoFailureException(" Invalid format for remotePom: " + remotePom);
    }
    String rGroupId = remotePomParts[0];
    String rArtifactId = remotePomParts[1];
    String rVersion = remotePomParts[2];

    Dependency remoteDependency = new Dependency();
    remoteDependency.setGroupId(rGroupId);
    remoteDependency.setArtifactId(rArtifactId);
    remoteDependency.setVersion(rVersion);

    Artifact remoteArtifact = this.toArtifact(remoteDependency);
    MavenProject remoteMavenProject = null;
    try {
        remoteMavenProject = mavenProjectBuilder.buildFromRepository(remoteArtifact, remoteArtifactRepositories,
                localRepository);
    } catch (ProjectBuildingException e) {
        throw new MojoExecutionException("Unable to build remote project " + remoteArtifact, e);
    }

    Map<String, Dependency> remoteDepsMap = new HashMap<String, Dependency>();
    if (!ignoreRemoteDependencyManagement) {
        List<Dependency> remoteProjectDepMgmtDeps = (remoteMavenProject.getDependencyManagement() == null)
                ? null
                : remoteMavenProject.getDependencyManagement().getDependencies();
        mapDependencies(remoteDepsMap, remoteProjectDepMgmtDeps);
    }
    if (!ignoreRemoteDependencies) {
        List<Dependency> remoteProjectDeps = remoteMavenProject.getDependencies();
        mapDependencies(remoteDepsMap, remoteProjectDeps);
    }

    List<String> totalDiffs = new ArrayList<String>();
    List<String> propertyDiffs = new ArrayList<String>();
    if (getProject().getDependencyManagement() != null && isProcessingDependencyManagement()) {
        List<String> depManDiffs = compareVersions(pom,
                getProject().getDependencyManagement().getDependencies(), remoteDepsMap);
        totalDiffs.addAll(depManDiffs);
    }
    if (isProcessingDependencies()) {
        List<String> depDiffs = compareVersions(pom, getProject().getDependencies(), remoteDepsMap);
        totalDiffs.addAll(depDiffs);
    }
    if (updatePropertyVersions) {
        Map<Property, PropertyVersions> versionProperties = this.getHelper()
                .getVersionPropertiesMap(getProject(), null, null, null, true);
        List<String> diff = updatePropertyVersions(pom, versionProperties, remoteDepsMap);
        propertyDiffs.addAll(diff);
    }

    if (reportMode) {
        getLog().info("The following differences were found:");
        if (totalDiffs.size() == 0) {
            getLog().info("  none");
        } else {
            for (String totalDiff : totalDiffs) {
                getLog().info("  " + totalDiff);
            }
        }
        getLog().info("The following property differences were found:");
        if (propertyDiffs.size() == 0) {
            getLog().info("  none");
        } else {
            for (String propertyDiff : propertyDiffs) {
                getLog().info("  " + propertyDiff);
            }
        }
    }

    if (reportOutputFile != null) {
        writeReportFile(totalDiffs, propertyDiffs);
    }

}

From source file:org.commonjava.emb.project.graph.DependencyGraphResolver.java

License:Apache License

private DependencyGraph accumulate(final ProjectToolsSession session, final RepositorySystemSession rss,
        final Collection<MavenProject> projects, final RemoteRepository... remoteRepositories) {
    final ArtifactTypeRegistry stereotypes = rss.getArtifactTypeRegistry();

    final DependencyGraph depGraph = session.getDependencyGraph();
    final GraphAccumulator accumulator = new GraphAccumulator(depGraph);

    for (final MavenProject project : projects) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Collecting dependencies for: " + project);
        }//from   ww w. j  av a  2  s.c  o  m
        final CollectRequest request = new CollectRequest();
        request.setRequestContext("project");
        request.setRepositories(Arrays.asList(remoteRepositories));

        if (project.getDependencyArtifacts() == null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Adding dependencies to collection request...");
            }
            for (final Dependency dependency : project.getDependencies()) {
                request.addDependency(RepositoryUtils.toDependency(dependency, stereotypes));
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Mapping project dependencies by management key...");
            }
            final Map<String, Dependency> dependencies = new HashMap<String, Dependency>();
            for (final Dependency dependency : project.getDependencies()) {
                final String key = dependency.getManagementKey();
                dependencies.put(key, dependency);
            }

            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Adding dependencies to collection request...");
            }
            for (final org.apache.maven.artifact.Artifact artifact : project.getDependencyArtifacts()) {
                final String key = artifact.getDependencyConflictId();
                final Dependency dependency = dependencies.get(key);
                final Collection<org.apache.maven.model.Exclusion> exclusions = dependency != null
                        ? dependency.getExclusions()
                        : null;

                org.sonatype.aether.graph.Dependency dep = RepositoryUtils.toDependency(artifact, exclusions);
                if (!JavaScopes.SYSTEM.equals(dep.getScope()) && dep.getArtifact().getFile() != null) {
                    // enable re-resolution
                    org.sonatype.aether.artifact.Artifact art = dep.getArtifact();
                    art = art.setFile(null).setVersion(art.getBaseVersion());
                    dep = dep.setArtifact(art);
                }
                request.addDependency(dep);
            }
        }

        final DependencyManagement depMngt = project.getDependencyManagement();
        if (depMngt != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Adding managed dependencies to collection request...");
            }
            for (final Dependency dependency : depMngt.getDependencies()) {
                request.addManagedDependency(RepositoryUtils.toDependency(dependency, stereotypes));
            }
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Collecting dependencies...");
        }
        CollectResult result;
        try {
            result = repositorySystem.collectDependencies(rss, request);
        } catch (final DependencyCollectionException e) {
            // TODO: Handle problem resolving POMs...
            result = e.getResult();

            // result.setDependencyGraph( e.getResult().getRoot() );
            // result.setCollectionErrors( e.getResult().getExceptions() );
            //
            // throw new DependencyResolutionException( result, "Could not resolve dependencies for project "
            // + project.getId() + ": " + e.getMessage(), e );
        }

        final DependencyNode root = result.getRoot();
        final DepGraphRootNode rootNode = depGraph.addRoot(root, project);

        accumulator.resetForNextRun(root, rootNode);

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Adding collected dependencies to consolidated dependency graph...");
        }
        result.getRoot().accept(accumulator);

    }

    return depGraph;
}

From source file:org.commonjava.maven.plugins.betterdep.AbstractDepgraphGoal.java

License:Open Source License

protected void readFromReactorProjects() throws MojoExecutionException {
    getLog().info("Initializing direct graph relationships from reactor projects: " + projects);
    for (final MavenProject project : projects) {
        final List<Profile> activeProfiles = project.getActiveProfiles();
        if (activeProfiles != null) {
            for (final Profile profile : activeProfiles) {
                profiles.add(RelationshipUtils.profileLocation(profile.getId()));
            }// ww w. j ava  2 s  . co  m
        }

        final ProjectVersionRef projectRef = new SimpleProjectVersionRef(project.getGroupId(),
                project.getArtifactId(), project.getVersion());
        roots.add(projectRef);

        final List<Dependency> deps = project.getDependencies();
        //            final List<ProjectVersionRef> roots = new ArrayList<ProjectVersionRef>( deps.size() );

        URI localUri;
        try {
            localUri = new URI(MavenLocationExpander.LOCAL_URI);
        } catch (final URISyntaxException e) {
            throw new MojoExecutionException(
                    "Failed to construct dummy local URI to use as the source of the current project in the depgraph: "
                            + e.getMessage(),
                    e);
        }

        final int index = 0;
        for (final Dependency dep : deps) {
            final ProjectVersionRef depRef = new SimpleProjectVersionRef(dep.getGroupId(), dep.getArtifactId(),
                    dep.getVersion());

            //                roots.add( depRef );

            final List<Exclusion> exclusions = dep.getExclusions();
            final List<ProjectRef> excludes = new ArrayList<ProjectRef>();
            if (exclusions != null && !exclusions.isEmpty()) {
                for (final Exclusion exclusion : exclusions) {
                    excludes.add(new SimpleProjectRef(exclusion.getGroupId(), exclusion.getArtifactId()));
                }
            }

            rootRels.add(new SimpleDependencyRelationship(localUri, projectRef,
                    new SimpleArtifactRef(depRef, dep.getType(), dep.getClassifier(), dep.isOptional()),
                    DependencyScope.getScope(dep.getScope()), index, false,
                    excludes.toArray(new ProjectRef[excludes.size()])));
        }

        final DependencyManagement dm = project.getDependencyManagement();
        if (dm != null) {
            final List<Dependency> managed = dm.getDependencies();
            int i = 0;
            for (final Dependency dep : managed) {
                if ("pom".equals(dep.getType()) && "import".equals(dep.getScope())) {
                    final ProjectVersionRef depRef = new SimpleProjectVersionRef(dep.getGroupId(),
                            dep.getArtifactId(), dep.getVersion());
                    rootRels.add(new SimpleBomRelationship(localUri, projectRef, depRef, i++));
                }
            }
        }

        ProjectVersionRef lastParent = projectRef;
        MavenProject parent = project.getParent();
        while (parent != null) {
            final ProjectVersionRef parentRef = new SimpleProjectVersionRef(parent.getGroupId(),
                    parent.getArtifactId(), parent.getVersion());

            rootRels.add(new SimpleParentRelationship(localUri, projectRef, parentRef));

            lastParent = parentRef;
            parent = parent.getParent();
        }

        rootRels.add(new SimpleParentRelationship(lastParent));
    }

}

From source file:org.deegree.maven.utils.ClasspathHelper.java

License:Open Source License

/**
 * @param project/* w w w . j  a  va2 s  .c o m*/
 * @param artifactResolver
 * @param artifactFactory
 * @param metadataSource
 * @param localRepository
 * @param type
 * @return a list of all (possibly transitive) artifacts of the given type
 * @throws InvalidDependencyVersionException
 * @throws ArtifactResolutionException
 * @throws ArtifactNotFoundException
 */
public static Set<?> getDependencyArtifacts(MavenProject project, ArtifactResolver artifactResolver,
        ArtifactFactory artifactFactory, ArtifactMetadataSource metadataSource,
        ArtifactRepository localRepository, final String type, boolean transitively)
        throws InvalidDependencyVersionException, ArtifactResolutionException, ArtifactNotFoundException {

    List<?> dependencies = project.getDependencies();

    Set<Artifact> dependencyArtifacts = createArtifacts(artifactFactory, dependencies, null,
            new ArtifactFilter() {
                @Override
                public boolean include(Artifact artifact) {
                    return artifact != null && artifact.getType() != null && artifact.getType().equals(type);
                }
            }, null);

    ArtifactResolutionResult result;
    Artifact mainArtifact = project.getArtifact();

    result = artifactResolver.resolveTransitively(dependencyArtifacts, mainArtifact, EMPTY_MAP, localRepository,
            project.getRemoteArtifactRepositories(), metadataSource, null, EMPTY_LIST);

    if (transitively) {
        return result.getArtifacts();
    }

    LinkedHashSet<Artifact> set = new LinkedHashSet<Artifact>();
    if (mainArtifact.getType() != null && mainArtifact.getType().equals(type)) {
        set.add(mainArtifact);
    }
    set.addAll(dependencyArtifacts);

    return set;
}