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

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

Introduction

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

Prototype

public Artifact getArtifact() 

Source Link

Usage

From source file:org.apache.hyracks.maven.license.SourcePointerResolver.java

License:Apache License

private void ensureCDDLSourcesPointer(Collection<Project> projects, ArtifactRepository central,
        ArtifactResolutionRequest request) throws ProjectBuildingException, IOException {
    for (Project p : projects) {
        if (p.getSourcePointer() != null) {
            continue;
        }/* ww  w.ja v  a 2 s . com*/
        mojo.getLog().debug("finding sources for artifact: " + p);
        Artifact sourcesArtifact = new DefaultArtifact(p.getGroupId(), p.getArtifactId(), p.getVersion(),
                Artifact.SCOPE_COMPILE, "jar", "sources", null);
        MavenProject mavenProject = mojo.resolveDependency(sourcesArtifact);
        sourcesArtifact.setArtifactHandler(mavenProject.getArtifact().getArtifactHandler());
        final ArtifactRepository localRepo = mojo.getSession().getLocalRepository();
        final File marker = new File(localRepo.getBasedir(), localRepo.pathOf(sourcesArtifact) + ".oncentral");
        final File antimarker = new File(localRepo.getBasedir(),
                localRepo.pathOf(sourcesArtifact) + ".nocentral");
        boolean onCentral;
        if (marker.exists() || antimarker.exists()) {
            onCentral = marker.exists();
        } else {
            request.setArtifact(sourcesArtifact);
            ArtifactResolutionResult result = mojo.getArtifactResolver().resolve(request);
            mojo.getLog().debug("result: " + result);
            onCentral = result.isSuccess();
            if (onCentral) {
                FileUtils.touch(marker);
            } else {
                FileUtils.touch(antimarker);
            }
        }
        StringBuilder noticeBuilder = new StringBuilder("You may obtain ");
        noticeBuilder.append(p.getName()).append(" in Source Code form code here:\n");
        if (onCentral) {
            noticeBuilder.append(central.getUrl()).append("/").append(central.pathOf(sourcesArtifact));
        } else {
            mojo.getLog().warn("Unable to find sources in 'central' for " + p
                    + ", falling back to project url: " + p.getUrl());
            noticeBuilder.append(p.getUrl() != null ? p.getUrl() : "MISSING SOURCE POINTER");
        }
        p.setSourcePointer(noticeBuilder.toString());
    }
}

From source file:org.apache.karaf.tooling.features.Dependency30Helper.java

License:Apache License

@Override
public void getDependencies(MavenProject project, boolean useTransitiveDependencies)
        throws MojoExecutionException {
    DependencyNode rootNode = getDependencyTree(RepositoryUtils.toArtifact(project.getArtifact()));
    Scanner scanner = new Scanner();
    scanner.scan(rootNode, useTransitiveDependencies);
    localDependencies = scanner.localDependencies;
    treeListing = scanner.getLog();/*w  w  w .j av a  2s  .c om*/
}

From source file:org.apache.karaf.tooling.features.Dependency31Helper.java

License:Apache License

@Override
public void getDependencies(MavenProject project, boolean useTransitiveDependencies)
        throws MojoExecutionException {
    DependencyNode rootNode = getDependencyTree(toArtifact(project.getArtifact()));

    Scanner scanner = new Scanner();
    scanner.scan(rootNode, useTransitiveDependencies);
    localDependencies = scanner.localDependencies;
    treeListing = scanner.getLog();/*w  ww.java 2s  .com*/
}

From source file:org.apache.myfaces.trinidadbuild.plugin.jdeveloper.JDeveloperMojo.java

License:Apache License

private MavenProject findDependentProject(String dependencyManagementKey) {
    for (Iterator i = reactorProjects.iterator(); i.hasNext();) {
        MavenProject reactorProject = (MavenProject) i.next();
        String ident = reactorProject.getArtifact().getDependencyConflictId();
        if (ident.equals(dependencyManagementKey))
            return reactorProject.getExecutionProject();
    }/*w w  w.ja  v a  2  s .  co  m*/

    return null;
}

From source file:org.apache.sis.internal.maven.Assembler.java

License:Apache License

/**
 * Returns all files to include for the given Maven project.
 *//*from ww  w .  j  a v  a2 s.c o m*/
private static Set<File> files(final MavenProject project) throws MojoExecutionException {
    final Set<File> files = new LinkedHashSet<>();
    files.add(project.getArtifact().getFile());
    for (final Artifact dep : project.getArtifacts()) {
        final String scope = dep.getScope();
        if (Artifact.SCOPE_COMPILE.equalsIgnoreCase(scope) || Artifact.SCOPE_RUNTIME.equalsIgnoreCase(scope)) {
            files.add(dep.getFile());
        }
    }
    if (files.remove(null)) {
        throw new MojoExecutionException(
                "Invocation of this MOJO shall be done together with a \"package\" Maven phase.");
    }
    return files;
}

From source file:org.apache.synapse.maven.xar.AbstractXarMojo.java

License:Apache License

/**
 * Get the set of artifacts that are provided by Synapse at runtime.
 * //  w  ww .  j  av a  2s  .c  o m
 * @return
 * @throws MojoExecutionException
 */
private Set<Artifact> getSynapseRuntimeArtifacts() throws MojoExecutionException {
    Log log = getLog();
    log.debug("Looking for synapse-core artifact in XAR project dependencies ...");
    Artifact synapseCore = null;
    for (Iterator<?> it = project.getDependencyArtifacts().iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();
        if (artifact.getGroupId().equals("org.apache.synapse")
                && artifact.getArtifactId().equals("synapse-core")) {
            synapseCore = artifact;
            break;
        }
    }
    if (synapseCore == null) {
        throw new MojoExecutionException("Could not locate dependency on synapse-core");
    }

    log.debug("Loading project data for " + synapseCore + " ...");
    MavenProject synapseCoreProject;
    try {
        synapseCoreProject = projectBuilder.buildFromRepository(synapseCore, remoteArtifactRepositories,
                localRepository);
    } catch (ProjectBuildingException e) {
        throw new MojoExecutionException("Unable to retrieve project information for " + synapseCore, e);
    }
    Set<Artifact> synapseRuntimeDeps;
    try {
        synapseRuntimeDeps = synapseCoreProject.createArtifacts(artifactFactory, Artifact.SCOPE_RUNTIME,
                new TypeArtifactFilter("jar"));
    } catch (InvalidDependencyVersionException e) {
        throw new MojoExecutionException("Unable to get project dependencies for " + synapseCore, e);
    }
    log.debug("Direct runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    log.debug("Resolving transitive dependencies for " + synapseCore + " ...");
    try {
        synapseRuntimeDeps = artifactCollector.collect(synapseRuntimeDeps, synapseCoreProject.getArtifact(),
                synapseCoreProject.getManagedVersionMap(), localRepository, remoteArtifactRepositories,
                artifactMetadataSource, null, Collections.singletonList(new DebugResolutionListener(logger)))
                .getArtifacts();
    } catch (ArtifactResolutionException e) {
        throw new MojoExecutionException("Unable to resolve transitive dependencies for " + synapseCore);
    }
    log.debug("All runtime dependencies for " + synapseCore + " :");
    logArtifacts(synapseRuntimeDeps);

    return synapseRuntimeDeps;
}

From source file:org.apache.tuscany.maven.bundle.plugin.BundlesMetaDataBuildMojo.java

License:Apache License

private Set<Artifact> getDependencyArtifacts(MavenProject project)
        throws DependencyTreeBuilderException, ArtifactResolutionException, ArtifactNotFoundException {
    Log log = getLog();/*w  w  w.  j a  v a  2s  . c  om*/
    Set<Artifact> artifacts = new HashSet<Artifact>();
    ArtifactFilter artifactFilter = createResolvingArtifactFilter(Artifact.SCOPE_RUNTIME);

    // TODO: note that filter does not get applied due to MNG-3236

    DependencyNode rootNode = dependencyTreeBuilder.buildDependencyTree(project, local, factory,
            artifactMetadataSource, artifactFilter, artifactCollector);
    CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
    rootNode.accept(visitor);

    // Add included artifacts
    for (Object node : visitor.getNodes()) {
        DependencyNode depNode = (DependencyNode) node;
        int state = depNode.getState();
        if (state == DependencyNode.INCLUDED) {
            Artifact artifact = depNode.getArtifact();
            // Exclude the project artifact to avoid offline resolution failure
            if (!artifact.equals(project.getArtifact())) {
                resolver.resolve(artifact, remoteRepos, local);
                artifacts.add(artifact);
            }
        }
    }
    // Scan for newer versions that are omitted
    for (Object node : visitor.getNodes()) {
        DependencyNode depNode = (DependencyNode) node;
        int state = depNode.getState();
        if (state == DependencyNode.OMITTED_FOR_CONFLICT) {
            Artifact artifact = depNode.getArtifact();
            resolver.resolve(artifact, remoteRepos, local);
            if (state == DependencyNode.OMITTED_FOR_CONFLICT) {
                Artifact related = depNode.getRelatedArtifact();
                if (log.isDebugEnabled()) {
                    log.debug("Dependency node: " + depNode);
                }
                // Compare the version
                ArtifactVersion v1 = new DefaultArtifactVersion(artifact.getVersion());
                ArtifactVersion v2 = new DefaultArtifactVersion(related.getVersion());
                if (v1.compareTo(v2) > 0) {
                    // Only add newer version if it is omitted for conflict
                    if (artifacts.add(artifact)) {
                        log.info("Dependency node added: " + depNode);
                    }
                }
            }
        }
    }
    return artifacts;
}

From source file:org.apache.tuscany.maven.bundle.plugin.BundlesMetaDataBuildMojo.java

License:Apache License

private MavenProject buildProject(Artifact artifact)
        throws ProjectBuildingException, InvalidDependencyVersionException, ArtifactResolutionException,
        ArtifactNotFoundException, DependencyTreeBuilderException {
    MavenProject pomProject = mavenProjectBuilder.buildFromRepository(artifact, this.remoteRepos, this.local);
    if (pomProject.getDependencyArtifacts() == null) {
        pomProject.setDependencyArtifacts(pomProject.createArtifacts(factory, null, // Artifact.SCOPE_TEST,
                new ScopeArtifactFilter(Artifact.SCOPE_TEST)));
    }/*from   w  w w .  j  a  va 2 s  . c  o  m*/
    if (includeConflictingDepedencies) {
        pomProject.setArtifacts(getDependencyArtifacts(pomProject));
    } else {
        ArtifactResolutionResult result = resolver.resolveTransitively(pomProject.getDependencyArtifacts(),
                pomProject.getArtifact(), remoteRepos, local, artifactMetadataSource);
        pomProject.setArtifacts(result.getArtifacts());
    }
    return pomProject;
}

From source file:org.apache.tuscany.maven.plugin.eclipse.AbstractIdeSupportMojo.java

License:Apache License

/**
 * Resolve project dependencies. Manual resolution is needed in order to avoid resolution of multiproject artifacts
 * (if projects will be linked each other an installed jar is not needed) and to avoid a failure when a jar is
 * missing./*from   ww w  .  j a v  a  2 s  .co m*/
 *
 * @throws MojoExecutionException if dependencies can't be resolved
 * @return resolved IDE dependencies, with attached jars for non-reactor dependencies
 */
protected IdeDependency[] doDependencyResolution() throws MojoExecutionException {
    if (ideDeps == null) {
        if (resolveDependencies) {
            MavenProject project = getProject();
            Set<String> imported = Collections.emptySet();
            try {
                imported = BundleUtil.getImportedPackages(project.getBasedir());
            } catch (IOException e1) {
                throw new MojoExecutionException(e1.getMessage(), e1);
            }
            ArtifactRepository localRepo = getLocalRepository();

            List deps = getProject().getDependencies();

            // Collect the list of resolved IdeDependencies.
            List dependencies = new ArrayList();

            if (deps != null) {
                Map managedVersions = createManagedVersionMap(getArtifactFactory(), project.getId(),
                        project.getDependencyManagement());

                ArtifactResolutionResult artifactResolutionResult = null;

                try {

                    List listeners = new ArrayList();

                    if (logger.isDebugEnabled()) {
                        listeners.add(new DebugResolutionListener(logger));
                    }

                    listeners.add(new WarningResolutionListener(logger));

                    artifactResolutionResult = artifactCollector.collect(getProjectArtifacts(),
                            project.getArtifact(), managedVersions, localRepo,
                            project.getRemoteArtifactRepositories(), getArtifactMetadataSource(), null,
                            listeners);
                } catch (ArtifactResolutionException e) {
                    getLog().debug(e.getMessage(), e);
                    getLog().error(
                            Messages.getString("AbstractIdeSupportMojo.artifactresolution", new Object[] { //$NON-NLS-1$
                                    e.getGroupId(), e.getArtifactId(), e.getVersion(), e.getMessage() }));

                    // if we are here artifactResolutionResult is null, create a project without dependencies but
                    // don't fail
                    // (this could be a reactor projects, we don't want to fail everything)
                    // Causes MECLIPSE-185. Not sure if it should be handled this way??
                    return new IdeDependency[0];
                }

                // keep track of added reactor projects in order to avoid duplicates
                Set emittedReactorProjectId = new HashSet();

                for (Iterator i = artifactResolutionResult.getArtifactResolutionNodes().iterator(); i
                        .hasNext();) {

                    ResolutionNode node = (ResolutionNode) i.next();
                    int dependencyDepth = node.getDepth();
                    Artifact art = node.getArtifact();
                    // don't resolve jars for reactor projects
                    if (hasToResolveJar(art)) {
                        try {
                            artifactResolver.resolve(art, node.getRemoteRepositories(), localRepository);
                        } catch (ArtifactNotFoundException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactdownload", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        } catch (ArtifactResolutionException e) {
                            getLog().debug(e.getMessage(), e);
                            getLog().warn(Messages.getString("AbstractIdeSupportMojo.artifactresolution", //$NON-NLS-1$
                                    new Object[] { e.getGroupId(), e.getArtifactId(), e.getVersion(),
                                            e.getMessage() }));
                        }
                    }

                    boolean includeArtifact = true;
                    if (getExcludes() != null) {
                        String artifactFullId = art.getGroupId() + ":" + art.getArtifactId();
                        if (getExcludes().contains(artifactFullId)) {
                            getLog().info("excluded: " + artifactFullId);
                            includeArtifact = false;
                        }
                    }

                    if (includeArtifact && (!(getUseProjectReferences() && isAvailableAsAReactorProject(art))
                            || emittedReactorProjectId.add(art.getGroupId() + '-' + art.getArtifactId()))) {

                        // the following doesn't work: art.getArtifactHandler().getPackaging() always returns "jar"
                        // also
                        // if the packaging specified in pom.xml is different.

                        // osgi-bundle packaging is provided by the felix osgi plugin
                        // eclipse-plugin packaging is provided by this eclipse plugin
                        // String packaging = art.getArtifactHandler().getPackaging();
                        // boolean isOsgiBundle = "osgi-bundle".equals( packaging ) || "eclipse-plugin".equals(
                        // packaging );

                        // we need to check the manifest, if "Bundle-SymbolicName" is there the artifact can be
                        // considered
                        // an osgi bundle
                        if ("pom".equals(art.getType())) {
                            continue;
                        }
                        File artifactFile = art.getFile();
                        MavenProject reactorProject = getReactorProject(art);
                        if (reactorProject != null) {
                            artifactFile = reactorProject.getBasedir();
                        }
                        boolean isOsgiBundle = false;
                        String osgiSymbolicName = null;
                        try {
                            osgiSymbolicName = BundleUtil.getBundleSymbolicName(artifactFile);
                        } catch (IOException e) {
                            getLog().error("Unable to read jar manifest from " + artifactFile, e);
                        }
                        isOsgiBundle = osgiSymbolicName != null;

                        IdeDependency dep = new IdeDependency(art.getGroupId(), art.getArtifactId(),
                                art.getVersion(), art.getClassifier(), useProjectReference(art),
                                Artifact.SCOPE_TEST.equals(art.getScope()),
                                Artifact.SCOPE_SYSTEM.equals(art.getScope()),
                                Artifact.SCOPE_PROVIDED.equals(art.getScope()),
                                art.getArtifactHandler().isAddedToClasspath(), art.getFile(), art.getType(),
                                isOsgiBundle, osgiSymbolicName, dependencyDepth, getProjectNameForArifact(art));
                        // no duplicate entries allowed. System paths can cause this problem.
                        if (!dependencies.contains(dep)) {
                            // [rfeng] Do not add compile/provided dependencies
                            if (!(pde && (Artifact.SCOPE_COMPILE.equals(art.getScope())
                                    || Artifact.SCOPE_PROVIDED.equals(art.getScope())))) {
                                dependencies.add(dep);
                            } else {
                                // Check this compile dependency is an OSGi package supplier
                                if (!imported.isEmpty()) {
                                    Set<String> exported = Collections.emptySet();
                                    try {
                                        exported = BundleUtil.getExportedPackages(artifactFile);
                                    } catch (IOException e) {
                                        getLog().error("Unable to read jar manifest from " + art.getFile(), e);
                                    }
                                    boolean matched = false;
                                    for (String p : imported) {
                                        if (exported.contains(p)) {
                                            matched = true;
                                            break;
                                        }
                                    }
                                    if (!matched) {
                                        dependencies.add(dep);
                                    } else {
                                        getLog().debug(
                                                "Compile dependency is skipped as it is added through OSGi dependency: "
                                                        + art);
                                    }
                                } else {
                                    dependencies.add(dep);
                                }
                            }
                        }
                    }

                }

                // @todo a final report with the list of
                // missingArtifacts?

            }

            ideDeps = (IdeDependency[]) dependencies.toArray(new IdeDependency[dependencies.size()]);
        } else {
            ideDeps = new IdeDependency[0];
        }
    }

    return ideDeps;
}

From source file:org.axway.grapes.maven.report.ModuleBuilder.java

/**
 * Turn a maven project (Maven data model) into a module (Grapes data model)
 *
 * @param project MavenProject/*from  w  ww  .j  a  va  2s . c  o m*/
 * @return Module
 */
public Module getModule(final MavenProject project, final LicenseResolver licenseResolver,
        final ArtifactResolver artifactResolver) throws MojoExecutionException {

    final Module module = GrapesTranslator.getGrapesModule(project);
    final List<License> licenses = licenseResolver.resolve(project);

    /* Manage Artifacts */
    final Artifact mainArtifact = GrapesTranslator.getGrapesArtifact(project.getArtifact());
    addLicenses(mainArtifact, licenses);
    module.addArtifact(mainArtifact);

    // Get pom file if main artifact is not already a pom file
    if (!mainArtifact.getType().equals("pom")) {
        final Artifact pomArtifact = GrapesTranslator.getGrapesArtifact(project.getModel());
        addLicenses(pomArtifact, licenses);
        module.addArtifact(pomArtifact);
    }

    for (int i = 0; i < project.getAttachedArtifacts().size(); i++) {
        artifactResolver.resolveArtifact(project, project.getAttachedArtifacts().get(i));
        final Artifact attachedArtifact = GrapesTranslator
                .getGrapesArtifact(project.getAttachedArtifacts().get(i));
        // handle licenses
        addLicenses(attachedArtifact, licenses);
        module.addArtifact(attachedArtifact);
    }

    /* Manage Dependencies */
    for (int i = 0; i < project.getDependencies().size(); i++) {
        final Dependency dependency = GrapesTranslator.getGrapesDependency(
                artifactResolver.resolveArtifact(project, project.getDependencies().get(i)),
                project.getDependencies().get(i).getScope());

        // handle licenses
        for (License license : licenseResolver.resolve(project, dependency.getTarget().getGroupId(),
                dependency.getTarget().getArtifactId(), dependency.getTarget().getVersion())) {
            dependency.getTarget().addLicense(license.getName());
        }

        module.addDependency(dependency);
    }

    return module;
}