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.hardisonbrewing.maven.core.DependencyService.java

License:Open Source License

/**
 * Extract the contents of all {@link Dependency} {@link Artifact}s to the specified destination directory.
 * @param mavenProject//  w w  w .jav  a2s .  c om
 * @param dest The destination directory.
 * @throws ArchiverException
 * @throws ProjectBuildingException
 * @throws ArtifactResolutionException
 * @throws ArtifactNotFoundException
 */
@SuppressWarnings("unchecked")
public static final void extractDependencies(MavenProject mavenProject, File dest) throws Exception {

    List<Dependency> dependencies = mavenProject.getDependencies();
    Iterator<Dependency> iterator = dependencies.iterator();

    while (iterator.hasNext()) {
        extractDependency(iterator.next(), dest);
    }
}

From source file:org.janus_project.janus_maven_plugin.mojo.AbstractDistributionMojo.java

License:Open Source License

@SuppressWarnings("unchecked")
private void detectEmbeddedArtifacts(Set<File> inputDirs) throws MojoExecutionException {
    MavenProject p = this.getMavenSession().getCurrentProject();

    List<Dependency> odeps = p.getDependencies();
    List<Dependency> deps = new ArrayList<Dependency>(
            odeps == null ? Collections.<Dependency>emptyList() : odeps);
    File artifactFile;// w  ww.j a v a2  s. c o m
    Dependency dep;
    Artifact depArtifact;
    Iterator<Dependency> iterator;
    while (!deps.isEmpty()) {
        iterator = deps.iterator();
        dep = iterator.next();
        iterator.remove();
        if (dep != null) {
            depArtifact = resolveArtifact(dep.getGroupId(), dep.getArtifactId(), dep.getVersion());

            artifactFile = depArtifact.getFile();
            if (!Utils.isOSGiExplodedBundle(artifactFile) && !Utils.isOSGiBundle(artifactFile)) {
                // The dependency artifact should be embedded in the top artifact
                inputDirs.add(artifactFile);

                p = this.getMavenSession().getCurrentProject();
                odeps = p.getDependencies();
                if (odeps != null)
                    deps.addAll(odeps);
            }
        }
    }
}

From source file:org.jboss.maven.plugins.qstools.checkers.MavenCentralRepositoryChecker.java

License:Apache License

@Override
public void checkProject(MavenProject project, Document doc, Map<String, List<Violation>> results)
        throws Exception {
    for (Dependency dependency : project.getDependencies()) {
        Artifact dependencyArtifact = repositorySystem.createProjectArtifact(dependency.getGroupId(),
                dependency.getArtifactId(), dependency.getVersion());
        ArtifactResolutionRequest arr = new ArtifactResolutionRequest();

        List<ArtifactRepository> remoteRepositories = new ArrayList<ArtifactRepository>();
        remoteRepositories.add(repositorySystem.createDefaultRemoteRepository());

        arr.setArtifact(dependencyArtifact).setRemoteRepositories(remoteRepositories)
                .setLocalRepository(getMavenSession().getLocalRepository());
        ArtifactResolutionResult result = repositorySystem.resolve(arr);
        Node dependencyNode = (Node) getxPath().evaluate(
                "//artifactId[text() ='" + dependency.getArtifactId() + "']", doc, XPathConstants.NODE);
        int lineNumber = XMLUtil.getLineNumberFromNode(dependencyNode);
        if (!result.isSuccess()) {
            addViolation(project.getFile(), results, lineNumber,
                    dependency + " doesn't comes from Maven Central Repository");
        }/*w ww. java  2  s. c om*/
    }
}

From source file:org.jboss.shrinkwrap.resolver.plugin.DependencyTreeMojo.java

License:Apache License

@Override
public void execute() throws MojoExecutionException {

    // first, we need to propagate environment settings
    PropagateExecutionContextMojo mojo = new PropagateExecutionContextMojo();
    mojo.setNamespace("maven.execution.");
    mojo.setSession(session);/*from ww  w .ja va 2 s  .  c o m*/
    mojo.execute();

    // propagate into current environment
    SecurityActions.addProperties(session.getUserProperties());

    MavenProject project = session.getCurrentProject();

    // set scope
    ScopeType[] scopes = ScopeType.values();
    if (scope != null && !"".equals(scope)) {
        scopes = new ScopeType[] { ScopeType.fromScopeType(scope) };
    }

    // get ClassLoader that contains both Maven and plugin class path
    ClassLoader cls = getCombinedClassLoader(classRealmManager);

    // skip resolution if no dependencies are in the project (e.g. parent agreggator)
    MavenResolvedArtifact[] artifacts;

    if (project.getDependencies() == null || project.getDependencies().size() == 0) {
        artifacts = new MavenResolvedArtifact[0];
    } else {
        artifacts = Maven.configureResolverViaPlugin(cls).importDependencies(scopes).resolve()
                .withTransitivity().asResolvedArtifact();
    }

    StringBuilder projectGAV = new StringBuilder();
    projectGAV.append(project.getGroupId()).append(":").append(project.getArtifactId()).append(":")
            .append(project.getPackaging()).append(":").append(project.getVersion()).append("\n");

    String dependencyTree = buildDependencyTree(projectGAV, "+- ", artifacts);

    // write output to file if specified
    if (outputFile != null) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(outputFile);
            writer.write(dependencyTree);
            getLog().info("Dependency tree output was writen into: " + outputFile.getAbsolutePath());
        } catch (IOException e) {

        } finally {
            try {
                if (writer != null) {
                    writer.close();
                }
            } catch (IOException e) {
            }
        }
    }
    // write an output to console
    else {
        StringBuilder outputBuffer = new StringBuilder();
        outputBuffer.append(OUTPUT_DELIMITER).append("\nShrinkWrap Maven: Dependency Tree\n")
                .append(OUTPUT_DELIMITER).append("\n").append(dependencyTree).append(OUTPUT_DELIMITER);

        getLog().info(outputBuffer.toString());
    }

}

From source file:org.jszip.maven.RunMojo.java

License:Apache License

private boolean buildPlanEqual(List<MavenProject> newPlan, List<MavenProject> oldPlan) {
    if (newPlan.size() != oldPlan.size()) {
        return false;
    }//from  w w w  .j av a  2s  .c om
    int seq = 0;
    for (Iterator<MavenProject> i = newPlan.iterator(), j = oldPlan.iterator(); i.hasNext() && j.hasNext();) {
        MavenProject left = i.next();
        MavenProject right = j.next();
        getLog().debug("[" + (seq++) + "] = " + left.equals(right) + (left == right ? " same" : " diff") + " : "
                + left.getName() + "[" + left.getDependencies().size() + "], " + right.getName() + "["
                + right.getDependencies().size() + "]");
        if (!left.equals(right)) {
            return false;
        }
        if (left.getDependencies().size() != right.getDependencies().size()) {
            getLog().info("Dependency tree of " + left.getId() + " has been modified");
        }
    }
    return true;
}

From source file:org.kloeckner.maven.plugin.VersionRange.java

License:Apache License

private Map<String, String> getOriginalVersionMap(MavenProject projects) {
    HashMap<String, String> hashMap = new HashMap<String, String>();

    // TODO depmgmt, parent ...
    if (projects.getParentArtifact() != null) {
        hashMap.put(/*ww w. ja v a2  s .co  m*/
                ArtifactUtils.versionlessKey(projects.getParentArtifact().getGroupId(),
                        projects.getParentArtifact().getArtifactId()),
                projects.getParentArtifact().getArtifactId());
    }
    hashMap.putAll(buildVersionsMap(projects.getDependencies()));
    if (projects.getDependencyManagement() != null) {
        hashMap.putAll(buildVersionsMap(projects.getDependencyManagement().getDependencies()));
    }

    for (Profile profile : projects.getActiveProfiles()) {
        hashMap.putAll(buildVersionsMap(profile.getDependencies()));
        if (profile.getDependencyManagement() != null) {
            hashMap.putAll(buildVersionsMap(profile.getDependencyManagement().getDependencies()));
        }
    }

    return hashMap;
}

From source file:org.l2x6.maven.srcdeps.SrcdepsLifecycleParticipant.java

License:Apache License

@Override
public void afterProjectsRead(MavenSession session) throws MavenExecutionException {
    boolean globalSkip = Boolean
            .valueOf(session.getUserProperties().getProperty(Element.skip.toSrcDepsProperty(), "false"));
    if (globalSkip) {
        logger.info("srcdeps-maven-plugin skipped");
        return;/*from   www  . j  a va2 s  .  c o  m*/
    }

    List<String> goals = session.getGoals();
    if (goals != null && shouldTriggerSrcdepsBuild(goals)) {
        List<MavenProject> projects = session.getProjects();
        logger.debug("SrcdepsLifecycleParticipant projects = " + projects);

        Set<Gav> projectGavs = new HashSet<SrcdepsLifecycleParticipant.Gav>();
        for (MavenProject project : projects) {
            projectGavs.add(Gav.ofModel(project.getModel()));
        }

        boolean builtSomething = false;

        for (MavenProject project : projects) {
            logger.info("srcdeps-maven-plugin scanning project " + project.getGroupId() + ":"
                    + project.getArtifactId());

            Optional<Plugin> plugin = findPlugin(project,
                    SrcdepsPluginConstants.ORG_L2X6_MAVEN_SRCDEPS_GROUP_ID,
                    SrcdepsPluginConstants.SRCDEPS_MAVEN_PLUGIN_ADRTIFACT_ID);
            if (plugin.isPresent() && project.getDependencies() != null) {

                Optional<Xpp3Dom> conf = plugin.map(Mapper.TO_DOM);
                if (conf.isPresent()) {

                    MojoExecution mojoExecution = new MojoExecution(plugin.value(), "install", "whatever");
                    PropsEvaluator evaluator = new PropsEvaluator(
                            new PluginParameterExpressionEvaluator(session, mojoExecution));
                    SrcdepsConfiguration srcdepsConfiguration = new SrcdepsConfiguration.Builder(evaluator,
                            conf.value(), session, logger).build();
                    if (srcdepsConfiguration.isSkip()) {
                        logger.info("srcdeps-maven-plugin skipped for project " + project.getGroupId() + ":"
                                + project.getArtifactId());
                    } else {
                        @SuppressWarnings("unchecked")
                        Map<Dependency, SrcVersion> revisions = filterSrcdeps(project.getDependencies(),
                                projectGavs);
                        if (!revisions.isEmpty()) {
                            assertFailWithProfiles(session, srcdepsConfiguration);
                            new SrcdepsInstaller(session, logger, artifactHandlerManager, srcdepsConfiguration,
                                    revisions, buildService).install();
                            builtSomething = true;
                        }
                    }
                }
            }
        }

        if (builtSomething) {
            Optional<Plugin> plugin = findPlugin(session.getTopLevelProject(), "org.apache.maven.plugins",
                    "maven-clean-plugin");
            if (plugin.isPresent()) {
                addCleanExclude(session.getTopLevelProject(), plugin.value());
            }
        }

    }
}

From source file:org.maven.ide.querydsl.AptConfigurator.java

License:Open Source License

private QueryDslConfiguration getQueryDslConfiguration(final MavenFacade p_mavenFacade) throws CoreException {
    MavenProject mavenProject = p_mavenFacade.getMavenProject();

    // find querydsl version so we can resolve matching one-jar from repo
    String queryDslVersion = "0.0.0";
    List<Dependency> dependencies = mavenProject.getDependencies();
    for (Dependency dependency : dependencies) {
        if ("com.mysema.querydsl".equals(dependency.getGroupId())) {
            queryDslVersion = dependency.getVersion();
            break;
        }/*w  w  w.  ja  v  a 2  s  .  c o  m*/
    }

    Plugin queryDslPlugin = mavenProject.getPlugin("com.mysema.maven:maven-apt-plugin");
    QueryDslConfiguration queryDslConfiguration = new QueryDslConfiguration(queryDslPlugin, queryDslVersion,
            p_mavenFacade);

    return queryDslConfiguration;
}

From source file:org.mimacom.maven.plugins.liferay.CreatePortalMojo.java

License:Apache License

protected void createWar() throws MojoExecutionException {
    setArtifactType(artifactWarFile(), "war");

    log("extracting " + liferayWar + " to " + explodedDir());
    unpackLiferayWarArtifact(explodedDir(), null, "war");

    final File exploded = new File(basedir, explodedDir());
    final File libDir = new File(basedir, libDir());

    if (finalNameDir().exists()) {
        log("copying target/" + finalName + " to " + explodedDir());
        copy(////w w w.jav a 2s  .com
                fileset(//
                        dir(finalNameDir()), //
                        excludes(prefixedOriginalConfigs("WEB-INF/classes/"))), //
                todir(exploded), //
                overwrite(true)//
        );
    }

    log("copying " + ORIGINAL_CONFIGS + " to " + CONFIG_DIR);
    try {
        expand(//
                src(libDir, "portal-impl.jar"), //
                dest(basedir, CONFIG_DIR), //
                patternset(includes(ORIGINAL_CONFIGS))//
        );
    } catch (Exception e) {
        getLog().info("could not extract " + ORIGINAL_CONFIGS + ": " + e.getMessage());
    }

    String allCommonArtifactIds = "";
    if (commonArtifactIds != null) {
        allCommonArtifactIds = StringUtils.join(getNonProvidedDependencies(commonArtifactIds), ",");
    }
    log("copying project dependencies (without 'provided' scoped dependencies and (" + allCommonArtifactIds
            + ")) to " + libDir());
    executeMojo(//
            DEPENDENCY_PLUGIN, //
            goal("copy-dependencies"), //
            configuration(//
                    element("outputDirectory", libDir()), //
                    element("excludeScope", "provided"), //
                    element("excludeArtifactIds", allCommonArtifactIds)//
            ), //
            executionEnvironment(project, session, pluginManager)//
    );

    if (allCommonArtifactIds.length() > 0) {
        log("copying common artifacts ((" + allCommonArtifactIds + ") without 'provided' scoped ones) to "
                + commonLibDir());
        executeMojo(//
                DEPENDENCY_PLUGIN, //
                goal("copy-dependencies"), //
                configuration(//
                        element("outputDirectory", commonLibDir()), //
                        element("excludeScope", "provided"), //
                        element("includeArtifactIds", allCommonArtifactIds)//
                ), //
                executionEnvironment(project, session, pluginManager)//
        );
    }

    if (moveLibsToCommon != null && moveLibsToCommon.hasInclude()) {
        String moveInclude = moveLibsToCommon.getIncludeWithSuffixes(".jar");
        String moveExclude = moveLibsToCommon.getExcludeWithSuffixes(".jar");
        log("moving (" + moveInclude + ") without (" + moveExclude + ") from " + libDir() + " to "
                + commonLibDir());
        move(//
                fileset(//
                        dir(libDir), //
                        includes(moveInclude), //
                        excludes(moveExclude)), //
                todir(basedir, commonLibDir()), //
                failOnError(false)//
        );
    }

    if (copyLibsToCommon != null && copyLibsToCommon.hasInclude()) {
        String copyInclude = copyLibsToCommon.getIncludeWithSuffixes(".jar");
        String copyExclude = copyLibsToCommon.getExcludeWithSuffixes(".jar");
        log("copying (" + copyInclude + ") without (" + copyExclude + ") from " + libDir() + " to "
                + commonLibDir());
        copy(//
                fileset(//
                        dir(libDir), //
                        includes(copyInclude), //
                        excludes(copyExclude)), //
                todir(basedir, commonLibDir()), //
                failOnError(false)//
        );
    }

    if (defaultCommonLibs != null && defaultCommonLibs) {
        try {
            MavenProject liferayCommonLibs = resolveArtifact(serverType().commonLibsGroupId(), "all",
                    liferayWar.getVersion());
            List<Element> artifacts = new ArrayList<Element>();
            @SuppressWarnings({ "unchecked" })
            List<Dependency> dependencies = liferayCommonLibs.getDependencies();
            for (Dependency dep : dependencies) {
                artifacts.add(element("artifactItem", //
                        element("groupId", dep.getGroupId()), //
                        element("artifactId", dep.getArtifactId()), //
                        element("version", dep.getVersion())));
            }

            log("copying default common libs from to" + commonLibDir());
            executeMojo(//
                    DEPENDENCY_PLUGIN, //
                    goal("copy"), //
                    configuration(//
                            element("outputDirectory", commonLibDir()), //
                            element("artifactItems", artifacts.toArray(new Element[artifacts.size()]))//
                    ), //
                    executionEnvironment(project, session, pluginManager)//
            );
        } catch (Exception e) {
            log("Could not copy default common libs", e);
        }
    }

    if (deleteLibs != null && deleteLibs.hasInclude()) {
        String deleteInclude = deleteLibs.getIncludeWithSuffixes(".jar");
        String deleteExclude = deleteLibs.getExcludeWithSuffixes(".jar");
        log("deleting (" + deleteInclude + ") without (" + deleteExclude + ") from " + libDir());
        delete(//
                dir(libDir), //
                includes(deleteInclude), //
                excludes(deleteExclude)//
        );
    }

    if (deleteFiles != null && deleteFiles.hasInclude()) {
        String deleteInclude = deleteFiles.getIncludeWithSuffixes("");
        String deleteExclude = deleteFiles.getExcludeWithSuffixes("");
        log("deleting (" + deleteInclude + ") without (" + deleteExclude + ") from " + explodedDir());
        delete(//
                dir(exploded), //
                includes(deleteInclude), //
                excludes(deleteExclude)//
        );
    }

    createWar(exploded, serverType().additionalManifest(this));
}

From source file:org.nanoko.coffee.mill.utils.JasmineUtils.java

License:Apache License

public static void prepareJasmineMojo(AbstractCoffeeMillMojo mill, AbstractJasmineMojo mojo,
        List<String> aggregation) {
    MavenProject project = mill.project;
    mojo.setLog(mill.getLog());/*from ww  w  .ja v a  2 s. c  o  m*/
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "jsSrcDir",
            new File(project.getBasedir(), "src/main/coffee")); //TODO This should be configurable.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "jsTestSrcDir",
            new File(project.getBasedir(), "src/test/js")); //TODO This should be configurable.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "webDriverClassName",
            "org.openqa.selenium.htmlunit.HtmlUnitDriver"); //TODO This should be configurable.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "browserVersion", "FIREFOX_3"); //TODO This should be configurable.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "format", "documentation"); //TODO This should be configurable.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "jasmineTargetDir",
            new File(project.getBuild().getDirectory(), "jasmine"));
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "specDirectoryName", "spec");
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "srcDirectoryName", "src");
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "manualSpecRunnerHtmlFileName",
            "ManualSpecRunner.html");
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "specRunnerHtmlFileName", "SpecRunner.html");
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "junitXmlReportFileName", TEST_JASMINE_XML);
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "mavenProject", project);
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "specRunnerTemplate", "DEFAULT");
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "haltOnFailure", true);

    List<String> deps = new ArrayList<String>();
    for (Dependency dep : (Collection<Dependency>) project.getDependencies()) {
        if ("js".equals(dep.getType())) {
            String filename = dep.getArtifactId() + ".js";
            if (dep.getClassifier() != null && !dep.getClassifier().equals("min")) {
                filename = dep.getArtifactId() + "-" + dep.getClassifier() + ".js";
            }
            File file = new File(mill.getLibDirectory(), filename);

            if (!file.exists()) {
                mill.getLog().error("Cannot preload " + dep.getArtifactId() + ":" + dep.getVersion() + " : "
                        + file.getAbsolutePath() + " not found");
            } else {
                try {
                    FileUtils.copyFileToDirectory(file, getJasmineDirectory(project));
                } catch (IOException e) {
                    e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
                }
                deps.add(filename);
            }
        }
    }
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "preloadSources", deps);

    // If javaScriptAggregation is set, use the right order.
    if (aggregation != null) {
        InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "sourceIncludes", aggregation);
    }

    // TODO Parameter.
    InjectionHelper.inject(mojo, AbstractJasmineMojo.class, "timeout", 300);

}