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

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

Introduction

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

Prototype

public Set<Artifact> getArtifacts() 

Source Link

Document

All dependencies that this project has, including transitive ones.

Usage

From source file:org.opencredo.maven.plugins.enforcer.AbstractBanDependenciesBase.java

License:Apache License

/**
 * Execute the rule.//from ww  w . j  a v  a  2 s  .  co m
 *
 * @param helper the helper
 * @throws EnforcerRuleException the enforcer rule exception
 */
public void execute(EnforcerRuleHelper helper) throws EnforcerRuleException {
    // get the project
    MavenProject project = null;
    DependencyTreePrinter dependencyTreePrinter = null;
    try {
        project = (MavenProject) helper.evaluate("${project}");
        ArtifactRepository localRepository = (ArtifactRepository) helper.evaluate("${localRepository}");
        ArtifactFactory artifactFactory = (ArtifactFactory) helper.getComponent(ArtifactFactory.class);
        ArtifactCollector artifactCollector = (ArtifactCollector) helper.getComponent(ArtifactCollector.class);
        ArtifactMetadataSource artifactMetadataSource = (ArtifactMetadataSource) helper
                .getComponent(ArtifactMetadataSource.class);
        DependencyTreeBuilder dependencyTreeBuilder = (DependencyTreeBuilder) helper
                .getComponent(DependencyTreeBuilder.class);
        dependencyTreePrinter = new DefaultDependencyTreePrinter(project, localRepository, artifactFactory,
                artifactMetadataSource, artifactCollector, dependencyTreeBuilder);
    } catch (Exception eee) {
        throw new EnforcerRuleException("Unable to retrieve the rule dependencies: ", eee);
    }

    // get the correct list of dependencies
    Set dependencies = null;
    if (searchTransitive) {
        dependencies = project.getArtifacts();
    } else {
        dependencies = project.getDependencyArtifacts();
    }

    executeInternal(new DependencyRuleContext(project, helper, dependencyTreePrinter), dependencies);
}

From source file:org.opendaylight.yangtools.yang2sources.plugin.Util.java

License:Open Source License

static List<File> getClassPath(final MavenProject project) {
    List<File> dependencies = new ArrayList<>();
    for (Artifact element : project.getArtifacts()) {
        File asFile = element.getFile();
        if (isJar(asFile) || asFile.isDirectory()) {
            dependencies.add(asFile);/*  ww w.  j a  v  a 2 s  .  com*/
        }
    }
    return dependencies;
}

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(//from ww  w  .ja va  2 s.  c  om
                    "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.opennms.maven.plugins.tgz.AbstractAssemblyMojo.java

License:Apache License

private void processModules(Archiver archiver, List moduleSets, boolean includeBaseDirectory)
        throws MojoFailureException, MojoExecutionException {
    for (Iterator i = moduleSets.iterator(); i.hasNext();) {
        ModuleSet moduleSet = (ModuleSet) i.next();

        AndArtifactFilter filter = new AndArtifactFilter();

        if (!moduleSet.getIncludes().isEmpty()) {
            filter.add(new AssemblyIncludesArtifactFilter(moduleSet.getIncludes()));
        }//www . j a v a2s.  c om
        if (!moduleSet.getExcludes().isEmpty()) {
            filter.add(new AssemblyExcludesArtifactFilter(moduleSet.getExcludes()));
        }

        Set set = getModulesFromReactor(getExecutedProject());

        List moduleFileSets = new ArrayList();

        for (Iterator j = set.iterator(); j.hasNext();) {
            MavenProject moduleProject = (MavenProject) j.next();

            if (filter.include(moduleProject.getArtifact())) {
                String name = moduleProject.getBuild().getFinalName();

                ModuleSources sources = moduleSet.getSources();

                if (sources != null) {
                    String output = sources.getOutputDirectory();
                    output = getOutputDirectory(output, moduleProject, includeBaseDirectory);

                    FileSet moduleFileSet = new FileSet();

                    moduleFileSet.setDirectory(moduleProject.getBasedir().getAbsolutePath());
                    moduleFileSet.setOutputDirectory(output);

                    List excludesList = new ArrayList();
                    excludesList.add(PathUtils.toRelative(moduleProject.getBasedir(),
                            moduleProject.getBuild().getDirectory()) + "/**");
                    excludesList.add(PathUtils.toRelative(moduleProject.getBasedir(),
                            moduleProject.getBuild().getOutputDirectory()) + "/**");
                    excludesList.add(PathUtils.toRelative(moduleProject.getBasedir(),
                            moduleProject.getBuild().getTestOutputDirectory()) + "/**");
                    excludesList.add(PathUtils.toRelative(moduleProject.getBasedir(),
                            moduleProject.getReporting().getOutputDirectory()) + "/**");
                    moduleFileSet.setExcludes(excludesList);

                    moduleFileSets.add(moduleFileSet);
                }

                ModuleBinaries binaries = moduleSet.getBinaries();

                if (binaries != null) {
                    Artifact artifact = moduleProject.getArtifact();

                    if (artifact.getFile() == null) {
                        throw new MojoExecutionException("Included module: " + moduleProject.getId()
                                + " does not have an artifact with a file. Please ensure the package phase is run before the assembly is generated.");
                    }

                    String output = binaries.getOutputDirectory();
                    output = getOutputDirectory(output, moduleProject, includeBaseDirectory);

                    archiver.setDefaultDirectoryMode(Integer.parseInt(binaries.getDirectoryMode(), 8));

                    archiver.setDefaultFileMode(Integer.parseInt(binaries.getFileMode(), 8));

                    getLog().debug("ModuleSet[" + output + "]" + " dir perms: "
                            + Integer.toString(archiver.getDefaultDirectoryMode(), 8) + " file perms: "
                            + Integer.toString(archiver.getDefaultFileMode(), 8));

                    if (binaries.isUnpack()) {
                        // TODO: something like zipfileset in plexus-archiver
                        //                        archiver.addJar(  )

                        // TODO refactor into the AbstractUnpackMojo
                        File tempLocation = new File(workDirectory, name);
                        boolean process = false;
                        if (!tempLocation.exists()) {
                            tempLocation.mkdirs();
                            process = true;
                        } else if (artifact.getFile().lastModified() > tempLocation.lastModified()) {
                            process = true;
                        }

                        if (process) {
                            try {
                                unpack(artifact.getFile(), tempLocation);

                                if (binaries.isIncludeDependencies()) {
                                    Set artifactSet = moduleProject.getArtifacts();

                                    for (Iterator artifacts = artifactSet.iterator(); artifacts.hasNext();) {
                                        Artifact dependencyArtifact = (Artifact) artifacts.next();

                                        unpack(dependencyArtifact.getFile(), tempLocation);
                                    }
                                }
                            } catch (NoSuchArchiverException e) {
                                throw new MojoExecutionException(
                                        "Unable to obtain unarchiver: " + e.getMessage(), e);
                            }

                            /*
                            * If the assembly is 'jar-with-dependencies', remove the security files in all dependencies
                            * that will prevent the uberjar to execute.  Please see MASSEMBLY-64 for details.
                            */
                            if (archiver instanceof JarArchiver) {
                                String[] securityFiles = { "*.RSA", "*.DSA", "*.SF", "*.rsa", "*.dsa", "*.sf" };
                                org.apache.maven.shared.model.fileset.FileSet securityFileSet = new org.apache.maven.shared.model.fileset.FileSet();
                                securityFileSet.setDirectory(tempLocation.getAbsolutePath() + "/META-INF/");

                                for (int sfsi = 0; sfsi < securityFiles.length; sfsi++) {
                                    securityFileSet.addInclude(securityFiles[sfsi]);
                                }

                                FileSetManager fsm = new FileSetManager(getLog());
                                try {
                                    fsm.delete(securityFileSet);
                                } catch (IOException e) {
                                    throw new MojoExecutionException(
                                            "Failed to delete security files: " + e.getMessage(), e);
                                }
                            }
                        }

                        addDirectory(archiver, tempLocation, output, null,
                                FileUtils.getDefaultExcludesAsList());
                    } else {
                        try {
                            String outputFileNameMapping = binaries.getOutputFileNameMapping();

                            archiver.addFile(artifact.getFile(),
                                    output + evaluateFileNameMapping(artifact, outputFileNameMapping));

                            if (binaries.isIncludeDependencies()) {
                                Set artifactSet = moduleProject.getArtifacts();

                                for (Iterator artifacts = artifactSet.iterator(); artifacts.hasNext();) {
                                    Artifact dependencyArtifact = (Artifact) artifacts.next();

                                    archiver.addFile(dependencyArtifact.getFile(),
                                            output + evaluateFileNameMapping(dependencyArtifact,
                                                    outputFileNameMapping));
                                }
                            }
                        } catch (ArchiverException e) {
                            throw new MojoExecutionException("Error adding file to archive: " + e.getMessage(),
                                    e);
                        }
                    }
                }

            } else {
                // would be better to have a way to find out when a specified include or exclude
                // is never triggered and warn() it.
                getLog().debug("module: " + moduleProject.getId() + " not included");
            }

            if (!moduleFileSets.isEmpty()) {
                // TODO: includes and excludes
                processFileSets(archiver, moduleFileSets, includeBaseDirectory);
            }
        }
    }
}

From source file:org.opennms.maven.plugins.tgz.AbstractUnpackingMojo.java

License:Apache License

/**
 * Retrieves all artifact dependencies./*  w w w  . j  a v  a  2s  .  c  o m*/
 *
 * @return A HashSet of artifacts
 */
protected Set getDependencies() {
    MavenProject project = getExecutedProject();

    Set dependenciesSet = new HashSet();

    if (project.getArtifact() != null && project.getArtifact().getFile() != null
            && shouldIncludeSelfAsDependency) {
        dependenciesSet.add(project.getArtifact());
    }

    Set projectArtifacts = project.getArtifacts();
    if (projectArtifacts != null) {
        dependenciesSet.addAll(projectArtifacts);
    }

    return dependenciesSet;
}

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

License:Apache License

/**
 * Adds any non-optional bundle dependencies to the deploy list
 * /*from w w  w.j a  v  a 2s  . c o  m*/
 * @param project a Maven project
 */
private void addProjectDependencies(MavenProject project) {
    Set artifacts = project.getArtifacts();
    for (Iterator i = artifacts.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();
        if (!artifact.isOptional() && !Artifact.SCOPE_TEST.equals(artifact.getScope())) {
            provisionBundle(artifact);
        }
    }
}

From source file:org.phpmaven.eclipse.core.build.Container.java

License:Open Source License

/**
 * Returns the build path entries for given project
 * //  ww w.ja va  2s . c  om
 * @param project
 * 
 * @return the buildpath entries
 */
public IBuildpathEntry[] getBuildpathEntries(final IScriptProject project) {
    // already cached?
    if (this.buildPathEntries == null) {
        // Fetch the maven project
        final List<IBuildpathEntry> entries = new ArrayList<IBuildpathEntry>();
        final IProgressMonitor monitor = new NullProgressMonitor();
        final IMavenProjectFacade mvnFacade = MavenPluginActivator.getDefault().getMavenProjectManager()
                .create(project.getProject(), monitor);
        final MavenProjectManager projectManager = MavenPluginActivator.getDefault().getMavenProjectManager();
        if (mvnFacade != null) {
            try {
                final MavenProject mavenProject = mvnFacade.getMavenProject(monitor);
                final Set<Artifact> artifacts = mavenProject.getArtifacts();
                for (final Artifact a : artifacts) {
                    if (!Container.SCOPE_FILTER_TEST.include(a)
                            || !a.getArtifactHandler().isAddedToClasspath()) {
                        continue;
                    }

                    // fetch project facade of dependency
                    final IMavenProjectFacade dependency = projectManager.getMavenProject(a.getGroupId(),
                            a.getArtifactId(), a.getVersion());
                    if (dependency != null && dependency.getProject().equals(mvnFacade.getProject())) {
                        continue;
                    }

                    IBuildpathEntry entry = null;
                    if (dependency != null && dependency.getFullPath(a.getFile()) != null) {
                        // local project; set the reference
                        entry = DLTKCore.newProjectEntry(dependency.getFullPath(), false);
                    } else {
                        // file reference within the local repository
                        final File artifactFile = a.getFile();
                        if (artifactFile != null /*
                                                  * &&
                                                  * artifactFile.canRead()
                                                  */) {
                            final IEnvironment env = EnvironmentManager.getEnvironment(project);
                            final IPath path = Path.fromOSString(artifactFile.getAbsolutePath());
                            entry = DLTKCore.newLibraryEntry(EnvironmentPathUtils.getFullPath(env, path),
                                    BuildpathEntry.NO_ACCESS_RULES, BuildpathEntry.NO_EXTRA_ATTRIBUTES,
                                    BuildpathEntry.INCLUDE_ALL, BuildpathEntry.EXCLUDE_NONE, false, true);
                        }
                    }

                    if (entry != null) {
                        // add it; if entry is null there is something wrong
                        // with the package, simply ignore it
                        // other builder (from maven plugin) may report the
                        // missing dependency and set a error marker
                        // at the pom.xml already.
                        entries.add(entry);
                    }
                }
            } catch (final CoreException e) {
                // log and ignore; should not happen. Even if this happens
                // we should not fail
                // with the buildpath container. This may confuse eclipse.
                PhpmavenCorePlugin.logError("Error calculating the maven buildpath", e); //$NON-NLS-1$
            }
        }
        this.buildPathEntries = entries.toArray(new IBuildpathEntry[0]);
    }
    return this.buildPathEntries;
}

From source file:org.phpmaven.project.impl.PhpProject.java

License:Apache License

@Override
public void prepareDependencies(final Log log, File targetDir, String sourceScope)
        throws MojoExecutionException, PhpException {
    DependencyState depState = this.stateDatabase.get(GROUPID, ARTIFACTID, DEPSTATEKEY, DependencyState.class);
    if (depState == null) {
        depState = new DependencyState();
    }//  www.ja v a2s. co  m
    if (!depState.containsKey(sourceScope)
            || !depState.get(sourceScope).getDefaultTargetDir().equals(targetDir)) {
        final DependencyInformation info = new DependencyInformation();
        depState.put(sourceScope, info);
        info.setDefaultTargetDir(targetDir);
    }
    final DependencyInformation info = depState.get(sourceScope);

    final BootstrapInfo bootstrapInfo = new BootstrapInfo();

    try {
        final MavenProject project = this.session.getCurrentProject();
        final Set<Artifact> deps = project.getArtifacts();
        for (final Artifact dep : deps) {
            if (!sourceScope.equals(dep.getScope())) {
                continue;
            }

            final List<String> packedElements = new ArrayList<String>();
            packedElements.add(dep.getFile().getAbsolutePath());
            for (final IAction action : DependencyHelper.getDependencyActions(dep, depConfig, reposSystem,
                    session, mavenProjectBuilder, factory)) {
                switch (action.getType()) {
                case ACTION_BOOTSTRAP:
                    performBootstrap(log, info, dep, bootstrapInfo);
                    break;
                case ACTION_CLASSIC:
                    performClassic(log, targetDir, dep, packedElements, info);
                    break;
                case ACTION_PEAR:
                    performPearInstall(log, dep, info);
                    break;
                case ACTION_IGNORE:
                    // do nothing, isClassic should be false so that it is ignored
                    log.info(dep.getFile().getAbsolutePath() + " will be ignored");
                    break;
                case ACTION_INCLUDE:
                    log.info(dep.getFile().getAbsolutePath() + " will be added on include path");
                    break;
                case ACTION_EXTRACT:
                    performExtraction(log, dep, packedElements, action, info);
                    break;
                case ACTION_EXTRACT_INCLUDE:
                    performExtractAndInclude(log, dep, packedElements, action, info);
                    break;
                }
            }
        }
    } catch (IOException ex) {
        throw new MojoExecutionException("Failed preparing dependencies", ex);
    }

    if (!bootstrapInfo.isEmpty()) {
        // invoke the bootstrap
        invokeBootstrap(log, bootstrapInfo, targetDir, sourceScope, depConfig.getBootstrapFile());
    }

    this.stateDatabase.set(GROUPID, ARTIFACTID, DEPSTATEKEY, depState);
}

From source file:org.phpmaven.project.impl.PhpProject.java

License:Apache License

@Override
public void validateDependencies() throws MojoExecutionException {
    // check if we have a dependency that is not added to dependency section
    final MavenProject project = this.session.getCurrentProject();
    final Set<Artifact> deps = project.getArtifacts();
    for (final IDependency depCfg : depConfig.getDependencies()) {
        for (final IAction action : depCfg.getActions()) {
            if (action.getType() == ActionType.ACTION_BOOTSTRAP
                    && (depConfig.getBootstrapFile() == null || !depConfig.getBootstrapFile().exists())) {
                throw new MojoExecutionException("There are bootstrap actions but bootstrap file '"
                        + depConfig.getBootstrapFile() + "' does not exist or was not set.");
            }//from  w  w w.java 2  s .  c  o  m
        }
        boolean found = false;
        for (final Artifact dep : deps) {
            if (depCfg.getGroupId().equals(dep.getGroupId())
                    && depCfg.getArtifactId().equals(dep.getArtifactId())) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new MojoExecutionException("Dependency " + depCfg.getGroupId() + ":" + depCfg.getArtifactId()
                    + " has a dependency configuration but is not added to dependency section.");
        }
    }
}

From source file:org.phpmaven.project.impl.ProjectPhpExecution.java

License:Apache License

/**
 * Adds additional include paths from dependency config.
 * @param execConfig/*from   w w  w.  j  a v  a  2s  . c o m*/
 * @param project
 * @param targetScope
 * @param depConfig
 * @param depsDir
 * @throws ExpressionEvaluationException 
 */
private void addFromDepConfig(IPhpExecutableConfiguration execConfig, MavenProject project, String targetScope,
        IDependencyConfiguration depConfig, File depsDir)
        throws ExpressionEvaluationException, MojoExecutionException {
    final Set<Artifact> deps = project.getArtifacts();

    for (final Artifact depObject : deps) {
        if (!targetScope.equals(depObject.getScope())) {
            continue;
        }

        MavenProject depProject;
        try {
            depProject = this.getProjectFromArtifact(project, depObject);
        } catch (ProjectBuildingException ex) {
            throw new ExpressionEvaluationException("Problems creating maven project from dependency", ex);
        }

        if (depProject.getFile() != null) {
            // Reference to a local project; should only happen in IDEs or multi-project poms

            for (final IAction action : DependencyHelper.getDependencyActions(depObject, depConfig, reposSystem,
                    session, mavenProjectBuilder, componentFactory)) {
                if (action.getType() == ActionType.ACTION_INCLUDE) {
                    final String includePath = getClassesDirFromProject(depProject) + "/"
                            + ((IActionInclude) action).getPharPath();
                    execConfig.getIncludePath().add(new File(includePath).getAbsolutePath());
                } else if (action.getType() == ActionType.ACTION_EXTRACT_INCLUDE) {
                    final String includePath = getClassesDirFromProject(depProject) + "/"
                            + ((IActionExtractAndInclude) action).getPharPath() + "/"
                            + ((IActionExtractAndInclude) action).getIncludePath();
                    execConfig.getIncludePath().add(new File(includePath).getAbsolutePath());
                } else if (action.getType() == ActionType.ACTION_CLASSIC) {
                    final String includePath = getClassesDirFromProject(depProject);
                    execConfig.getIncludePath().add(new File(includePath).getAbsolutePath());
                }
            }
        }

        if (depObject.getFile() != null) {
            // Reference to a local repository
            for (final IAction action : DependencyHelper.getDependencyActions(depObject, depConfig, reposSystem,
                    session, mavenProjectBuilder, componentFactory)) {
                if (action.getType() == ActionType.ACTION_INCLUDE) {
                    final String includePath = ((IActionInclude) action).getPharPath();
                    execConfig.getIncludePath()
                            .add("phar://" + depObject.getFile().getAbsolutePath().replace("\\", "/") + "/"
                                    + (includePath.startsWith("/") ? includePath.substring(1) : includePath));
                } else if (action.getType() == ActionType.ACTION_EXTRACT_INCLUDE) {
                    final String includePath = ((IActionExtractAndInclude) action).getIncludePath();
                    final String pharPath = ((IActionExtractAndInclude) action).getPharPath();
                    execConfig.getIncludePath()
                            .add("phar://" + depObject.getFile().getAbsolutePath().replace("\\", "/") + "/"
                                    + (pharPath.startsWith("/") ? pharPath.substring(1) : pharPath)
                                    + (pharPath.endsWith("/") || pharPath.length() == 0 ? "" : "/")
                                    + (includePath.startsWith("/") ? includePath.substring(1) : includePath));
                }
            }
        }
    }
}