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.nbheaven.sqe.core.maven.utils.MavenUtilities.java

License:Open Source License

/**
 * try to collect the plugin's dependency artifacts
 * as defined in <dependencies> section within <plugin>. Will only
 * return files currently in local repository
 *
 * @return list of files in local repository
 *///from ww  w.  j av a 2s .com
public static List<File> findDependencyArtifacts(Project project, String pluginGroupId, String pluginArtifactId,
        boolean includePluginArtifact) {
    List<File> cpFiles = new ArrayList<File>();
    final NbMavenProject p = project.getLookup().lookup(NbMavenProject.class);
    final MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    MavenProject mp = p.getMavenProject();
    if (includePluginArtifact) {
        Set<Artifact> arts = new HashSet<Artifact>();
        arts.addAll(mp.getReportArtifacts());
        arts.addAll(mp.getPluginArtifacts());
        for (Artifact a : arts) {
            if (pluginArtifactId.equals(a.getArtifactId()) && pluginGroupId.equals(a.getGroupId())) {
                File f = a.getFile();
                if (f == null) {
                    //somehow the report plugins are not resolved, we need to workaround that..
                    f = FileUtil.normalizeFile(new File(new File(online.getLocalRepository().getBasedir()),
                            online.getLocalRepository().pathOf(a)));
                }
                if (!f.exists()) {
                    try {
                        online.resolve(a, mp.getRemoteArtifactRepositories(), online.getLocalRepository());
                    } catch (ArtifactResolutionException ex) {
                        Exceptions.printStackTrace(ex);
                    } catch (ArtifactNotFoundException ex) {
                        Exceptions.printStackTrace(ex);
                    }
                }
                if (f.exists()) {
                    cpFiles.add(f);
                    try {
                        ProjectBuildingRequest req = new DefaultProjectBuildingRequest();
                        req.setRemoteRepositories(mp.getRemoteArtifactRepositories());
                        req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
                        req.setSystemProperties(online.getSystemProperties());
                        ProjectBuildingResult res = online.buildProject(a, req);
                        MavenProject mp2 = res.getProject();
                        if (mp2 != null) {
                            // XXX this is not really right, but mp.dependencyArtifacts = null for some reason
                            for (Dependency dep : mp2.getDependencies()) {
                                Artifact a2 = online.createArtifact(dep.getGroupId(), dep.getArtifactId(),
                                        dep.getVersion(), "jar");
                                online.resolve(a2, mp.getRemoteArtifactRepositories(),
                                        online.getLocalRepository());
                                File df = a2.getFile();
                                if (df.exists()) {
                                    cpFiles.add(df);
                                }
                            }
                        }
                    } catch (Exception x) {
                        Exceptions.printStackTrace(x);
                    }
                }
            }
        }

    }
    List<Plugin> plugins = mp.getBuildPlugins();
    for (Plugin plug : plugins) {
        if (pluginArtifactId.equals(plug.getArtifactId()) && pluginGroupId.equals(plug.getGroupId())) {
            try {
                List<Dependency> deps = plug.getDependencies();
                ArtifactFactory artifactFactory = online.getPlexus().lookup(ArtifactFactory.class);
                for (Dependency d : deps) {
                    final Artifact projectArtifact = artifactFactory.createArtifactWithClassifier(
                            d.getGroupId(), d.getArtifactId(), d.getVersion(), d.getType(), d.getClassifier());
                    String localPath = online.getLocalRepository().pathOf(projectArtifact);
                    File f = FileUtil
                            .normalizeFile(new File(online.getLocalRepository().getBasedir(), localPath));
                    if (!f.exists()) {
                        try {
                            online.resolve(projectArtifact, mp.getRemoteArtifactRepositories(),
                                    online.getLocalRepository());
                        } catch (ArtifactResolutionException ex) {
                            ex.printStackTrace();
                            //                                        Exceptions.printStackTrace(ex);
                        } catch (ArtifactNotFoundException ex) {
                            ex.printStackTrace();
                            //                            Exceptions.printStackTrace(ex);
                        }
                    }
                    if (f.exists()) {
                        cpFiles.add(f);
                    }
                }
            } catch (ComponentLookupException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return cpFiles;
}

From source file:org.netbeans.modules.android.maven.DalvikPlatformForMavenProvider.java

License:Apache License

@Override
public DalvikPlatform findDalvikPlatform() {
    NbMavenProject mvnApiPrj = p.getLookup().lookup(NbMavenProject.class);
    if (mvnApiPrj == null) {
        // weird but OK
        return null;
    }/*from   w w  w.  ja v a2s  . c  om*/
    MavenProject mavenProject = mvnApiPrj.getMavenProject();
    if (mavenProject == null) {
        LOG.log(Level.FINER, "No MavenProject for {0}", p);
        return null;
    }
    List<Dependency> deps = mavenProject.getDependencies();
    deps = deps != null ? deps : Collections.<Dependency>emptyList();
    for (Dependency d : deps) {
        LOG.log(Level.FINE, "dependency {0}", d);
    }
    Dependency androidDep = Iterables.find(deps, new Predicate<Dependency>() {

        @Override
        public boolean apply(Dependency d) {
            return ANDROID_SDK_ARTIFACT.equals(d.getArtifactId()) && ANDROID_SDK_GROUP_ID.equals(d.getGroupId())
                    && Artifact.SCOPE_PROVIDED.equals(d.getScope());
        }
    }, null);
    if (androidDep == null) {
        return null;
    }
    String version = androidDep.getVersion();
    LOG.log(Level.FINE, "{0} depends on android version {1}", new Object[] { p, version });
    if (version == null) {
        return null;
    }
    for (DalvikPlatform dp : DalvikPlatformManager.getDefault().getPlatforms()) {
        if (dp.getAndroidTarget().getVersionName().equals(version)) {
            LOG.log(Level.FINE, "{0} matches to {1}", new Object[] { p, dp });
            return dp;
        }
    }
    return null;
}

From source file:org.onosproject.yang.compiler.plugin.maven.YangPluginUtils.java

License:Apache License

/**
 * Returns list of jar path.//from   ww w.  j av  a 2 s  .com
 *
 * @param project         maven project
 * @param localRepository local repository
 * @param remoteRepos     remote repository
 * @return list of jar paths
 */
private static List<String> resolveDependencyJarPath(MavenProject project, ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepos) {

    StringBuilder path = new StringBuilder();
    List<String> jarPaths = new ArrayList<>();
    for (Object obj : project.getDependencies()) {

        Dependency dependency = (Dependency) obj;
        path.append(localRepository.getBasedir());
        path.append(SLASH);
        path.append(getPackageDirPathFromJavaJPackage(dependency.getGroupId()));
        path.append(SLASH);
        path.append(dependency.getArtifactId());
        path.append(SLASH);
        path.append(dependency.getVersion());
        path.append(SLASH);
        path.append(dependency.getArtifactId() + HYPHEN + dependency.getVersion() + PERIOD + JAR);
        File jarFile = new File(path.toString());
        if (jarFile.exists()) {
            jarPaths.add(path.toString());
        }
        path.delete(0, path.length());
    }

    for (ArtifactRepository repo : remoteRepos) {
        // TODO: add resolver for remote repo.
    }
    return jarPaths;
}

From source file:org.opennms.maven.plugins.karaf.GenerateFeaturesXmlMojo.java

License:Open Source License

void addLocalDependencies(final FeaturesBuilder featuresBuilder, final FeatureBuilder projectFeatureBuilder,
        final MavenProject project) throws MojoExecutionException {

    for (final Dependency dependency : project.getDependencies()) {
        getLog().debug("getting artifact for dependency " + dependency);

        if (getIgnoredScopes().contains(dependency.getScope())) {
            getLog().debug(//w  ww  .  ja  v  a2 s  . co  m
                    "Dependency " + dependency + " is in scope: " + dependency.getScope() + ", ignoring.");
            continue;
        }

        org.apache.maven.artifact.Artifact matched = null;
        for (final org.apache.maven.artifact.Artifact art : project.getArtifacts()) {
            if (!dependency.getGroupId().equals(art.getGroupId())) {
                continue;
            }
            if (!dependency.getArtifactId().equals(art.getArtifactId())) {
                continue;
            }
            if (!dependency.getVersion().equals(art.getBaseVersion())) {
                continue;
            }
            if (!dependency.getType().equals(art.getType())) {
                continue;
            }
            if (dependency.getClassifier() == null && art.getClassifier() != null) {
                continue;
            }
            if (dependency.getClassifier() != null && !dependency.getClassifier().equals(art.getClassifier())) {
                continue;
            }

            matched = art;
            break;
        }

        if (matched == null) {
            throw new MojoExecutionException("Unable to match artifact for dependency: " + dependency);
        } else {
            getLog().debug("Found match for dependency: " + dependency);
            try {
                addBundleArtifact(featuresBuilder, projectFeatureBuilder, matched);
            } catch (final Exception e) {
                throw new MojoExecutionException(
                        "An error occurred while adding artifact " + matched + " to the features file.", e);
            }
        }
    }

}

From source file:org.ops4j.pax.construct.clone.CloneMojo.java

License:Apache License

/**
 * Analyze project structure to try to deduce if this really is a wrapper
 * /*  www.j  a v  a 2 s .  c o  m*/
 * @param project Maven bundle project
 * @return wrapped artifact, null if it isn't a wrapper project
 */
private Dependency findCustomizedWrappee(MavenProject project) {
    List dependencies = project.getDependencies();
    String sourcePath = project.getBuild().getSourceDirectory();

    // try to find a dependency that relates to the wrapper project
    if (dependencies.size() > 0 && !new File(sourcePath).exists()) {
        for (Iterator i = dependencies.iterator(); i.hasNext();) {
            Dependency dependency = (Dependency) i.next();
            if (project.getArtifactId().indexOf(dependency.getArtifactId()) >= 0) {
                return dependency; // closest match
            }
        }

        return (Dependency) dependencies.get(0);
    }

    return null;
}

From source file:org.ops4j.pax.construct.clone.CloneMojo.java

License:Apache License

/**
 * Attempt to repair bundle imports by replacing them with pax-import-bundle commands
 * //ww  w  .jav a 2s  . c  o m
 * @param script build script
 * @param project Maven project
 * @return customized Maven project model
 */
private Pom repairBundleImports(PaxScript script, MavenProject project) {
    Pom pom;
    try {
        File tempFile = File.createTempFile("pom", ".xml", m_tempdir);
        FileUtils.copyFile(project.getFile(), tempFile);
        pom = PomUtils.readPom(tempFile);
        tempFile.deleteOnExit();
    } catch (IOException e) {
        pom = null;
    }

    for (Iterator i = project.getDependencies().iterator(); i.hasNext();) {
        Dependency dependency = (Dependency) i.next();

        String bundleId = dependency.getGroupId() + ':' + dependency.getArtifactId();
        String bundleName = (String) m_bundleNameMap.get(bundleId);

        // is this a local bundle project?
        if (null != bundleName) {
            PaxCommandBuilder command;

            command = script.call(PaxScript.IMPORT_BUNDLE);
            command.option('a', bundleName);

            // enable overwrite
            command.flag('o');

            // only apply to the importing bundle project
            setTargetDirectory(command, project.getBasedir());

            if (null != pom) {
                pom.removeDependency(dependency);
            }
        }
    }

    try {
        if (null != pom) {
            pom.write();
        }
        return pom;
    } catch (IOException e) {
        return null;
    }
}

From source file:org.ops4j.pax.construct.lifecycle.ProvisionMojo.java

License:Apache License

/**
 * Does this look like a provisioning POM? ie. artifactId of 'provision', packaging type 'pom', with dependencies
 * /*from w w w.  j a  v  a 2s . c  om*/
 * @param project a Maven project
 * @return true if this looks like a provisioning POM, otherwise false
 */
public static boolean isProvisioningPom(MavenProject project) {
    // ignore POMs which don't have provision as their artifactId
    if (!"provision".equals(project.getArtifactId())) {
        return false;
    }

    // ignore POMs that produce actual artifacts
    if (!"pom".equals(project.getPackaging())) {
        return false;
    }

    // ignore POMs with no dependencies at all
    List dependencies = project.getDependencies();
    if (dependencies == null || dependencies.size() == 0) {
        return false;
    }

    return true;
}

From source file:org.phpmaven.test.it.AbstractTestCase.java

License:Apache License

/**
 * Installs a local project into target directory
 * @param reposPath repos path// ww  w  .  j  ava2s . co  m
 * @param root root of the project to be installed
 * @param withModules
 * @throws Exception
 */
private void installLocalProject(final String reposPath, String root, boolean withModules) throws Exception {
    final String projectName = new File(root).getName();
    if (installedProjects.contains(projectName)) {
        return;
    }
    installedProjects.add(projectName);

    if (!projectName.equals("java-parent")) {
        //            this.installLocalProject(reposPath, new File(root).getParentFile().getParentFile().getParent() + "/var", false);
        this.installLocalProject(reposPath, new File(root).getParent() + "/java-parent", false);
    }

    // first install dependencies
    final File projectFile = new File(root, "pom.xml");
    final ProjectBuildingRequest buildingRequest = this.createProjectBuildingRequest().projectBuildingRequest;

    final MavenProject project = lookup(ProjectBuilder.class).build(projectFile, buildingRequest).getProject();

    for (final Dependency dep : project.getDependencies()) {
        if ("org.phpmaven".equals(dep.getGroupId())) {
            this.installLocalProject(reposPath, new File(root).getParent() + "/" + dep.getArtifactId(), false);
        }
    }

    // install the project itself
    final Verifier verifier = new Verifier(root, true);
    verifier.setLocalRepo(reposPath);
    verifier.setAutoclean(false);
    verifier.setForkJvm(true);
    final File target = new File(root, "target");
    if (!target.exists()) {
        target.mkdir();
    }
    verifier.setLogFileName("target/log.txt");
    verifier.addCliOption("-N");
    verifier.addCliOption("-nsu");
    verifier.addCliOption("-Dmaven.test.skip=true");
    verifier.executeGoal("install");
    verifier.verifyErrorFreeLog();
    verifier.resetStreams();

    if (withModules) {
        for (final String module : project.getModules()) {
            this.installLocalProject(reposPath, new File(root) + "/" + module, false);
        }
    }
}

From source file:org.piraso.maven.AbstractWarMojo.java

License:Apache License

/**
 * Builds the webapp for the specified project with the new packaging task
 * thingy//  w ww.  j a v a2s .c om
 * <p/>
 * Classes, libraries and tld files are copied to
 * the <tt>webappDirectory</tt> during this phase.
 *
 * @param project         the maven project
 * @param webappDirectory the target directory
 * @throws org.apache.maven.plugin.MojoExecutionException if an error occurred while packaging the webapp
 * @throws org.apache.maven.plugin.MojoFailureException   if an unexpected error occurred while packaging the webapp
 * @throws java.io.IOException            if an error occurred while copying the files
 */
@SuppressWarnings("unchecked")
public void buildWebapp(MavenProject project, File webappDirectory)
        throws MojoExecutionException, MojoFailureException, IOException {

    WebappStructure cache;
    if (useCache && cacheFile.exists()) {
        cache = new WebappStructure(project.getDependencies(), webappStructureSerialier.fromXml(cacheFile));
    } else {
        cache = new WebappStructure(project.getDependencies(), null);
    }

    final long startTime = System.currentTimeMillis();
    getLog().info("Assembling webapp [" + project.getArtifactId() + "] in [" + webappDirectory + "]");

    final OverlayManager overlayManager = new OverlayManager(overlays, project, dependentWarIncludes,
            dependentWarExcludes, currentProjectOverlay);
    final List<WarPackagingTask> packagingTasks = getPackagingTasks(overlayManager);
    List<FileUtils.FilterWrapper> defaultFilterWrappers = null;
    try {
        MavenResourcesExecution mavenResourcesExecution = new MavenResourcesExecution();
        mavenResourcesExecution.setEscapeString(escapeString);

        defaultFilterWrappers = mavenFileFilter.getDefaultFilterWrappers(project, filters,
                escapedBackslashesInFilePath, this.session, mavenResourcesExecution);

    } catch (MavenFilteringException e) {
        getLog().error("fail to build filering wrappers " + e.getMessage());
        throw new MojoExecutionException(e.getMessage(), e);
    }

    final WarPackagingContext context = new DefaultWarPackagingContext(webappDirectory, cache, overlayManager,
            defaultFilterWrappers, getNonFilteredFileExtensions(), filteringDeploymentDescriptors,
            this.artifactFactory, resourceEncoding);
    for (WarPackagingTask warPackagingTask : packagingTasks) {
        warPackagingTask.performPackaging(context);
    }

    // Post packaging
    final List<WarPostPackagingTask> postPackagingTasks = getPostPackagingTasks();
    for (WarPostPackagingTask task : postPackagingTasks) {
        task.performPostPackaging(context);
    }
    getLog().info("Webapp assembled in [" + (System.currentTimeMillis() - startTime) + " msecs]");

}

From source file:org.sonar.updatecenter.deprecated.UpdateCenter.java

License:Open Source License

private History<Plugin> resolvePluginHistory(String id) throws Exception {
    String groupId = StringUtils.substringBefore(id, ":");
    String artifactId = StringUtils.substringAfter(id, ":");

    Artifact artifact = artifactFactory.createArtifact(groupId, artifactId, Artifact.LATEST_VERSION,
            Artifact.SCOPE_COMPILE, ARTIFACT_JAR_TYPE);

    List<ArtifactVersion> versions = filterSnapshots(
            metadataSource.retrieveAvailableVersions(artifact, localRepository, remoteRepositories));

    History<Plugin> history = new History<Plugin>();
    for (ArtifactVersion version : versions) {
        Plugin plugin = org.sonar.updatecenter.deprecated.Plugin
                .extractMetadata(resolve(artifact.getGroupId(), artifact.getArtifactId(), version.toString()));
        history.addArtifact(version, plugin);

        MavenProject project = mavenProjectBuilder
                .buildFromRepository(//  w ww. jav  a  2s  .co  m
                        artifactFactory.createArtifact(groupId, artifactId, version.toString(),
                                Artifact.SCOPE_COMPILE, ARTIFACT_POM_TYPE),
                        remoteRepositories, localRepository);

        if (plugin.getVersion() == null) {
            // Legacy plugin - set default values
            plugin.setKey(project.getArtifactId());
            plugin.setName(project.getName());
            plugin.setVersion(project.getVersion());

            String sonarVersion = "1.10"; // TODO Is it minimal version for all extension points ?
            for (Dependency dependency : project.getDependencies()) {
                if ("sonar-plugin-api".equals(dependency.getArtifactId())) { // TODO dirty hack
                    sonarVersion = dependency.getVersion();
                }
            }

            plugin.setRequiredSonarVersion(sonarVersion);
            plugin.setHomepage(project.getUrl());
        }
        plugin.setDownloadUrl(getPluginDownloadUrl(groupId, artifactId, plugin.getVersion()));
        // There is no equivalent for following properties in MANIFEST.MF
        if (project.getIssueManagement() != null) {
            plugin.setIssueTracker(project.getIssueManagement().getUrl());
        } else {
            System.out.println("Unknown Issue Management for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getScm() != null) {
            String scmUrl = project.getScm().getUrl();
            if (StringUtils.startsWith(scmUrl, "scm:")) {
                scmUrl = StringUtils.substringAfter(StringUtils.substringAfter(scmUrl, ":"), ":");
            }
            plugin.setSources(scmUrl);
        } else {
            System.out.println("Unknown SCM for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getLicenses() != null && project.getLicenses().size() > 0) {
            plugin.setLicense(project.getLicenses().get(0).getName());
        } else {
            System.out.println("Unknown License for " + plugin.getKey() + ":" + plugin.getVersion());
        }
        if (project.getDevelopers().size() > 0) {
            plugin.setDevelopers(project.getDevelopers());
        } else {
            System.out.println("Unknown Developers for " + plugin.getKey() + ":" + plugin.getVersion());
        }
    }
    return history;
}