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:npanday.resolver.NPandayDependencyResolution.java

License:Apache License

public Set<Artifact> require(MavenProject project, ArtifactRepository localRepository, ArtifactFilter filter)
        throws ArtifactResolutionException {
    long startTime = System.currentTimeMillis();

    artifactResolver.initializeWithFilter(filter);

    if (getLogger().isDebugEnabled()) {
        getLogger().debug("NPANDAY-148-007: Resolving dependencies for " + project.getArtifact());
    }//from  w  w w .  jav a 2s. c o m

    try {
        if (project.getDependencyArtifacts() == null) {
            createArtifactsForMaven2BackCompat(project);
        }

        ArtifactResolutionResult result = artifactResolver.resolveTransitively(project.getDependencyArtifacts(),
                project.getArtifact(), project.getManagedVersionMap(), localRepository,
                project.getRemoteArtifactRepositories(), metaDataSource, filter);

        /*
        * WORKAROUND: transitive dependencies are not cached in MavenProject; in order to let
        * them "live" for following mojo executions, we'll add the custom resolved
        * dependencies to the projects DIRECT dependencies
        * */

        Set<Artifact> dependencyArtifacts = new HashSet<Artifact>(project.getDependencyArtifacts());
        addResolvedSpecialsToProjectDependencies(result, dependencyArtifacts);

        // Add custom contribute dependencies to maven project dependencies
        dependencyArtifacts.addAll(artifactResolver.getCustomDependenciesCache());
        project.setDependencyArtifacts(dependencyArtifacts);

        Set<Artifact> resultRequire = Sets.newLinkedHashSet(result.getArtifacts());
        resultRequire.addAll(artifactResolver.getCustomDependenciesCache());

        if (getLogger().isInfoEnabled()) {
            long endTime = System.currentTimeMillis();
            getLogger()
                    .info("NPANDAY-148-009: Took " + (endTime - startTime) + "ms to resolve dependencies for "
                            + project.getArtifact() + " with filter " + filter.toString());
        }

        return resultRequire;
    } catch (ArtifactResolutionException e) {
        throw new ArtifactResolutionException("NPANDAY-148-001: Could not resolve project dependencies",
                project.getArtifact(), e);
    } catch (ArtifactNotFoundException e) {
        throw new ArtifactResolutionException("NPANDAY-148-002: Could not resolve project dependencies",
                project.getArtifact(), e);
    } catch (InvalidDependencyVersionException e) {
        throw new ArtifactResolutionException("NPANDAY-148-003: Could not resolve project dependencies",
                project.getArtifact(), e);
    }
}

From source file:org.apache.axis2.maven2.repo.AbstractCreateRepositoryMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    Set<Artifact> artifacts = new HashSet<Artifact>();
    if (useDependencies) {
        artifacts.addAll(projectArtifacts);
    }//from  w  w  w  . ja  v  a  2 s.c  o m
    if (useModules) {
        for (MavenProject project : collectedProjects) {
            artifacts.add(project.getArtifact());
            artifacts.addAll(project.getAttachedArtifacts());
        }
    }
    File outputDirectory = getOutputDirectory();
    if (includeModules || includeServices) {
        FilterArtifacts filter = new FilterArtifacts();
        filter.addFilter(new ScopeFilter(getScope(), null));
        if (includeModules && includeServices) {
            filter.addFilter(new TypeFilter("aar,mar", null));
        } else if (includeModules) {
            filter.addFilter(new TypeFilter("mar", null));
        }
        try {
            artifacts = filter.filter(artifacts);
        } catch (ArtifactFilterException ex) {
            throw new MojoExecutionException(ex.getMessage(), ex);
        }
        selectArtifacts(artifacts, modules, "mar");
        selectArtifacts(artifacts, services, "aar");
        artifacts = replaceIncompleteArtifacts(artifacts);
        Map<String, ArchiveDeployer> deployers = new HashMap<String, ArchiveDeployer>();
        deployers.put("aar", new ArchiveDeployer(outputDirectory, servicesDirectory, "services.list",
                generateFileLists, stripServiceVersion));
        deployers.put("mar", new ArchiveDeployer(outputDirectory, modulesDirectory, "modules.list",
                generateFileLists, stripModuleVersion));
        for (Artifact artifact : artifacts) {
            String type = artifact.getType();
            ArchiveDeployer deployer = deployers.get(type);
            if (deployer == null) {
                throw new MojoExecutionException("No deployer found for artifact type " + type);
            }
            deployer.deploy(getLog(), artifact);
        }
        for (ArchiveDeployer deployer : deployers.values()) {
            deployer.finish(getLog());
        }
    }
    if (axis2xml != null) {
        getLog().info("Copying axis2.xml");
        File targetDirectory = configurationDirectory == null ? outputDirectory
                : new File(outputDirectory, configurationDirectory);
        try {
            FileUtils.copyFile(axis2xml, new File(targetDirectory, "axis2.xml"));
        } catch (IOException ex) {
            throw new MojoExecutionException("Error copying axis2.xml file: " + ex.getMessage(), ex);
        }
    }
}

From source file:org.apache.camel.guice.maven.RunMojo.java

License:Apache License

private Set<Artifact> resolveExecutableDependencies(Artifact executablePomArtifact)
        throws MojoExecutionException {

    Set<Artifact> executableDependencies;
    try {//from  ww w  .  j  a  va2 s.  com
        MavenProject executableProject = this.projectBuilder.buildFromRepository(executablePomArtifact,
                this.remoteRepositories, this.localRepository);

        // get all of the dependencies for the executable project
        List<Artifact> dependencies = CastUtils.cast(executableProject.getDependencies());

        // make Artifacts of all the dependencies
        Set<Artifact> dependencyArtifacts = CastUtils.cast(
                MavenMetadataSource.createArtifacts(this.artifactFactory, dependencies, null, null, null));

        // not forgetting the Artifact of the project itself
        dependencyArtifacts.add(executableProject.getArtifact());

        // resolve all dependencies transitively to obtain a comprehensive
        // list of assemblies
        ArtifactResolutionResult result = artifactResolver.resolveTransitively(dependencyArtifacts,
                executablePomArtifact, Collections.emptyMap(), this.localRepository, this.remoteRepositories,
                metadataSource, null, Collections.emptyList());
        executableDependencies = CastUtils.cast(result.getArtifacts());

    } catch (Exception ex) {
        throw new MojoExecutionException("Encountered problems resolving dependencies of the executable "
                + "in preparation for its execution.", ex);
    }

    return executableDependencies;
}

From source file:org.apache.camel.maven.packaging.PackageDataFormatMojo.java

License:Apache License

private static Artifact findCamelCoreArtifact(MavenProject project) {
    // maybe this project is camel-core itself
    Artifact artifact = project.getArtifact();
    if (artifact.getGroupId().equals("org.apache.camel") && artifact.getArtifactId().equals("camel-core")) {
        return artifact;
    }//from w ww  . j a  va2  s  .  c  o m

    // or its a component which has a dependency to camel-core
    Iterator it = project.getDependencyArtifacts().iterator();
    while (it.hasNext()) {
        artifact = (Artifact) it.next();
        if (artifact.getGroupId().equals("org.apache.camel") && artifact.getArtifactId().equals("camel-core")) {
            return artifact;
        }
    }
    return null;
}

From source file:org.apache.felix.bundleplugin.BundleAllPlugin.java

License:Apache License

/**
 * Bundle a project and its transitive dependencies up to some depth level
 * //w ww  . j a v a2s. c  o  m
 * @param project
 * @param maxDepth how deep to process the dependency tree
 * @throws MojoExecutionException
 */
protected BundleInfo bundleAll(MavenProject project, int maxDepth) throws MojoExecutionException {

    if (alreadyBundled(project.getArtifact())) {
        getLog().debug("Ignoring project already processed " + project.getArtifact());
        return null;
    }

    if (m_artifactsBeingProcessed.contains(project.getArtifact())) {
        getLog().warn("Ignoring artifact due to dependency cycle " + project.getArtifact());
        return null;
    }
    m_artifactsBeingProcessed.add(project.getArtifact());

    DependencyNode dependencyTree;

    try {
        dependencyTree = m_dependencyTreeBuilder.buildDependencyTree(project, localRepository, m_factory,
                m_artifactMetadataSource, null, m_collector);
    } catch (DependencyTreeBuilderException e) {
        throw new MojoExecutionException("Unable to build dependency tree", e);
    }

    BundleInfo bundleInfo = new BundleInfo();

    if (!dependencyTree.hasChildren()) {
        /* no need to traverse the tree */
        return bundleRoot(project, bundleInfo);
    }

    getLog().debug("Will bundle the following dependency tree" + LS + dependencyTree);

    for (Iterator it = dependencyTree.inverseIterator(); it.hasNext();) {
        DependencyNode node = (DependencyNode) it.next();
        if (!it.hasNext()) {
            /* this is the root, current project */
            break;
        }

        if (node.getState() != DependencyNode.INCLUDED) {
            continue;
        }

        if (Artifact.SCOPE_SYSTEM.equals(node.getArtifact().getScope())) {
            getLog().debug("Ignoring system scoped artifact " + node.getArtifact());
            continue;
        }

        Artifact artifact;
        try {
            artifact = resolveArtifact(node.getArtifact());
        } catch (ArtifactNotFoundException e) {
            if (ignoreMissingArtifacts) {
                continue;
            }

            throw new MojoExecutionException("Artifact was not found in the repo" + node.getArtifact(), e);
        }

        node.getArtifact().setFile(artifact.getFile());

        int nodeDepth = node.getDepth();
        if (nodeDepth > maxDepth) {
            /* node is deeper than we want */
            getLog().debug(
                    "Ignoring " + node.getArtifact() + ", depth is " + nodeDepth + ", bigger than " + maxDepth);
            continue;
        }

        MavenProject childProject;
        try {
            childProject = m_mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories,
                    localRepository, true);
            if (childProject.getDependencyArtifacts() == null) {
                childProject.setDependencyArtifacts(childProject.createArtifacts(m_factory, null, null));
            }
        } catch (ProjectBuildingException e) {
            throw new MojoExecutionException("Unable to build project object for artifact " + artifact, e);
        } catch (InvalidDependencyVersionException e) {
            throw new MojoExecutionException("Invalid dependency version for artifact " + artifact);
        }

        childProject.setArtifact(artifact);
        getLog().debug("Child project artifact location: " + childProject.getArtifact().getFile());

        if ((Artifact.SCOPE_COMPILE.equals(artifact.getScope()))
                || (Artifact.SCOPE_RUNTIME.equals(artifact.getScope()))) {
            BundleInfo subBundleInfo = bundleAll(childProject, maxDepth - 1);
            if (subBundleInfo != null) {
                bundleInfo.merge(subBundleInfo);
            }
        } else {
            getLog().debug("Not processing due to scope (" + childProject.getArtifact().getScope() + "): "
                    + childProject.getArtifact());
        }
    }

    return bundleRoot(project, bundleInfo);
}

From source file:org.apache.felix.bundleplugin.BundleAllPlugin.java

License:Apache License

/**
 * Bundle the root of a dependency tree after all its children have been bundled
 * //from w w w.  j a v a 2s  .  c  o m
 * @param project
 * @param bundleInfo
 * @return
 * @throws MojoExecutionException
 */
private BundleInfo bundleRoot(MavenProject project, BundleInfo bundleInfo) throws MojoExecutionException {
    /* do not bundle the project the mojo was called on */
    if (getProject() != project) {
        getLog().debug("Project artifact location: " + project.getArtifact().getFile());

        BundleInfo subBundleInfo = bundle(project);
        if (subBundleInfo != null) {
            bundleInfo.merge(subBundleInfo);
        }
    }
    return bundleInfo;
}

From source file:org.apache.felix.bundleplugin.BundleAllPlugin.java

License:Apache License

/**
 * Bundle one project only without building its childre
 * /*from   w w w.  j a va  2s  . c om*/
 * @param project
 * @throws MojoExecutionException
 */
protected BundleInfo bundle(MavenProject project) throws MojoExecutionException {
    Artifact artifact = project.getArtifact();
    getLog().info("Bundling " + artifact);

    try {
        Map instructions = new LinkedHashMap();
        instructions.put(Analyzer.IMPORT_PACKAGE, wrapImportPackage);

        project.getArtifact().setFile(getFile(artifact));
        File outputFile = getOutputFile(artifact);

        if (project.getArtifact().getFile().equals(outputFile)) {
            /* TODO find the cause why it's getting here */
            return null;
            //                getLog().error(
            //                                "Trying to read and write " + artifact + " to the same file, try cleaning: "
            //                                    + outputFile );
            //                throw new IllegalStateException( "Trying to read and write " + artifact
            //                    + " to the same file, try cleaning: " + outputFile );
        }

        Analyzer analyzer = getAnalyzer(project, instructions, new Properties(), getClasspath(project));

        Jar osgiJar = new Jar(project.getArtifactId(), project.getArtifact().getFile());

        outputFile.getAbsoluteFile().getParentFile().mkdirs();

        Collection exportedPackages;
        if (isOsgi(osgiJar)) {
            /* if it is already an OSGi jar copy it as is */
            getLog().info("Using existing OSGi bundle for " + project.getGroupId() + ":"
                    + project.getArtifactId() + ":" + project.getVersion());
            String exportHeader = osgiJar.getManifest().getMainAttributes().getValue(Analyzer.EXPORT_PACKAGE);
            exportedPackages = analyzer.parseHeader(exportHeader).keySet();
            FileUtils.copyFile(project.getArtifact().getFile(), outputFile);
        } else {
            /* else generate the manifest from the packages */
            exportedPackages = analyzer.getExports().keySet();
            Manifest manifest = analyzer.getJar().getManifest();
            osgiJar.setManifest(manifest);
            osgiJar.write(outputFile);
        }

        BundleInfo bundleInfo = addExportedPackages(project, exportedPackages);

        // cleanup...
        analyzer.close();
        osgiJar.close();

        return bundleInfo;
    }
    /* too bad Jar.write throws Exception */
    catch (Exception e) {
        throw new MojoExecutionException(
                "Error generating OSGi bundle for project " + getArtifactKey(project.getArtifact()), e);
    }
}

From source file:org.apache.felix.bundleplugin.BundleAllPlugin.java

License:Apache License

private BundleInfo addExportedPackages(MavenProject project, Collection packages) {
    BundleInfo bundleInfo = new BundleInfo();
    for (Iterator it = packages.iterator(); it.hasNext();) {
        String packageName = (String) it.next();
        bundleInfo.addExportedPackage(packageName, project.getArtifact());
    }/*w w w.jav  a 2 s  .  c o m*/
    return bundleInfo;
}

From source file:org.apache.felix.bundleplugin.BundlePlugin.java

License:Apache License

protected void execute(MavenProject currentProject, Map originalInstructions, Properties properties,
        Jar[] classpath) throws MojoExecutionException {
    try {/*from   www  .  ja  v a2 s.  c o  m*/
        File jarFile = new File(getBuildDirectory(), getBundleName(currentProject));

        Builder builder = buildOSGiBundle(currentProject, originalInstructions, properties, classpath);

        List errors = builder.getErrors();
        List warnings = builder.getWarnings();

        for (Iterator w = warnings.iterator(); w.hasNext();) {
            String msg = (String) w.next();
            getLog().warn("Warning building bundle " + currentProject.getArtifact() + " : " + msg);
        }
        for (Iterator e = errors.iterator(); e.hasNext();) {
            String msg = (String) e.next();
            getLog().error("Error building bundle " + currentProject.getArtifact() + " : " + msg);
        }

        if (errors.size() > 0) {
            String failok = builder.getProperty("-failok");
            if (null == failok || "false".equalsIgnoreCase(failok)) {
                jarFile.delete();

                throw new MojoFailureException("Error(s) found in bundle configuration");
            }
        }

        // attach bundle to maven project
        jarFile.getParentFile().mkdirs();
        builder.getJar().write(jarFile);

        Artifact mainArtifact = currentProject.getArtifact();

        // workaround for MNG-1682: force maven to install artifact using the "jar" handler
        mainArtifact.setArtifactHandler(m_artifactHandlerManager.getArtifactHandler("jar"));

        if (null == classifier || classifier.trim().length() == 0) {
            mainArtifact.setFile(jarFile);
        } else {
            m_projectHelper.attachArtifact(currentProject, jarFile, classifier);
        }

        if (unpackBundle) {
            unpackBundle(jarFile);
        }

        if (manifestLocation != null) {
            File outputFile = new File(manifestLocation, "MANIFEST.MF");

            try {
                Manifest manifest = builder.getJar().getManifest();
                ManifestPlugin.writeManifest(manifest, outputFile);
            } catch (IOException e) {
                getLog().error("Error trying to write Manifest to file " + outputFile, e);
            }
        }

        // cleanup...
        builder.close();
    } catch (MojoFailureException e) {
        getLog().error(e.getLocalizedMessage());
        throw new MojoExecutionException("Error(s) found in bundle configuration", e);
    } catch (Exception e) {
        getLog().error("An internal error occurred", e);
        throw new MojoExecutionException("Internal error in maven-bundle-plugin", e);
    }
}

From source file:org.apache.felix.bundleplugin.BundlePlugin.java

License:Apache License

protected Jar[] getClasspath(MavenProject currentProject) throws IOException, MojoExecutionException {
    List list = new ArrayList();

    if (getOutputDirectory() != null && getOutputDirectory().exists()) {
        list.add(new Jar(".", getOutputDirectory()));
    }//from  www . j a  v a 2 s  . c o  m

    final Collection artifacts = getSelectedDependencies(currentProject.getArtifacts());
    for (Iterator it = artifacts.iterator(); it.hasNext();) {
        Artifact artifact = (Artifact) it.next();
        if (artifact.getArtifactHandler().isAddedToClasspath()) {
            if (!Artifact.SCOPE_TEST.equals(artifact.getScope())) {
                File file = getFile(artifact);
                if (file == null) {
                    getLog().warn("File is not available for artifact " + artifact + " in project "
                            + currentProject.getArtifact());
                    continue;
                }
                Jar jar = new Jar(artifact.getArtifactId(), file);
                list.add(jar);
            }
        }
    }
    Jar[] cp = new Jar[list.size()];
    list.toArray(cp);
    return cp;
}