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.codehaus.mojo.nbm.CreateClusterMojo.java

License:Apache License

public void execute() throws MojoExecutionException, MojoFailureException {
    Project antProject = registerNbmAntTasks();

    if (!nbmBuildDir.exists()) {
        nbmBuildDir.mkdirs();/* www  .  ja  v  a2 s.co m*/
    }

    if (reactorProjects != null && reactorProjects.size() > 0) {
        for (MavenProject proj : reactorProjects) {
            //TODO how to figure where the the buildDir/nbm directory is
            File nbmDir = new File(proj.getBasedir(),
                    "target" + File.separator + "nbm" + File.separator + "netbeans");
            if (nbmDir.exists()) {
                Copy copyTask = (Copy) antProject.createTask("copy");
                copyTask.setTodir(nbmBuildDir);
                copyTask.setOverwrite(true);
                FileSet set = new FileSet();
                set.setDir(nbmDir);
                set.createInclude().setName("**");
                copyTask.addFileset(set);

                try {
                    copyTask.execute();
                } catch (BuildException ex) {
                    getLog().error("Cannot merge modules into cluster");
                    throw new MojoExecutionException("Cannot merge modules into cluster", ex);
                }
            } else {
                if ("nbm".equals(proj.getPackaging())) {
                    String error = "The NetBeans binary directory structure for " + proj.getId()
                            + " is not created yet."
                            + "\n Please execute 'mvn install nbm:cluster' to build all relevant projects in the reactor.";
                    throw new MojoFailureException(error);
                }
                if ("bundle".equals(proj.getPackaging())) {
                    Artifact art = proj.getArtifact();
                    final ExamineManifest mnf = new ExamineManifest(getLog());

                    File jar = new File(proj.getBuild().getDirectory(),
                            proj.getBuild().getFinalName() + ".jar");
                    if (!jar.exists()) {
                        getLog().error("Skipping " + proj.getId()
                                + ". Cannot find the main artifact in output directory.");
                        continue;
                    }
                    mnf.setJarFile(jar);
                    mnf.checkFile();

                    File cluster = new File(nbmBuildDir, defaultCluster);
                    getLog().debug("Copying " + art.getId() + " to cluster " + defaultCluster);
                    File modules = new File(cluster, "modules");
                    modules.mkdirs();
                    File config = new File(cluster, "config");
                    File confModules = new File(config, "Modules");
                    confModules.mkdirs();
                    File updateTracting = new File(cluster, "update_tracking");
                    updateTracting.mkdirs();

                    final String cnb = mnf.getModule();
                    final String cnbDashed = cnb.replace(".", "-");
                    final File moduleArt = new File(modules, cnbDashed + ".jar"); //do we need the file in some canotical name pattern?
                    final String specVer = mnf.getSpecVersion();
                    try {
                        FileUtils.copyFile(jar, moduleArt);
                        final File moduleConf = new File(confModules, cnbDashed + ".xml");
                        FileUtils.copyStreamToFile(new InputStreamFacade() {
                            public InputStream getInputStream() throws IOException {
                                return new StringInputStream(CreateClusterAppMojo.createBundleConfigFile(cnb,
                                        mnf.isBundleAutoload()), "UTF-8");
                            }
                        }, moduleConf);
                        FileUtils.copyStreamToFile(new InputStreamFacade() {
                            public InputStream getInputStream() throws IOException {
                                return new StringInputStream(CreateClusterAppMojo.createBundleUpdateTracking(
                                        cnb, moduleArt, moduleConf, specVer), "UTF-8");
                            }
                        }, new File(updateTracting, cnbDashed + ".xml"));
                    } catch (IOException exc) {
                        getLog().error(exc);
                    }

                }
            }
        }
        //in 6.1 the rebuilt modules will be cached if the timestamp is not touched.
        File[] files = nbmBuildDir.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isDirectory()) {
                File stamp = new File(files[i], ".lastModified");
                if (!stamp.exists()) {
                    try {
                        stamp.createNewFile();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                }
                stamp.setLastModified(new Date().getTime());
            }
        }
        getLog().info("Created NetBeans module cluster(s) at " + nbmBuildDir);
    } else {
        throw new MojoExecutionException("This goal only makes sense on reactor projects.");
    }
}

From source file:org.codehaus.mojo.pluginsupport.dependency.DependencyHelper.java

License:Apache License

public DependencyTree getDependencies(final MavenProject project)
        throws ProjectBuildingException, InvalidDependencyVersionException, ArtifactResolutionException {
    assert project != null;

    Map managedVersions = getManagedVersionMap(project, artifactFactory);
    DependencyResolutionListener listener = new DependencyResolutionListener();

    if (project.getDependencyArtifacts() == null) {
        project.setDependencyArtifacts(project.createArtifacts(artifactFactory, null, null));
    }/*from  w ww  . j a va 2 s  .  co  m*/

    artifactCollector.collect(project.getDependencyArtifacts(), project.getArtifact(), managedVersions,
            getArtifactRepository(), project.getRemoteArtifactRepositories(), artifactMetadataSource, null,
            Collections.singletonList(listener));

    return listener.getDependencyTree();
}

From source file:org.codehaus.mojo.pomtools.helpers.MetadataHelper.java

License:Apache License

/** Resolves all transitive dependencies for the current project and returns a list
 * of {@link TransitiveDependencyInfo} objects.  Each object represents a distinct 
 * groupId:artifactId:type dependency.  The {@link TransitiveDependencyInfo#getResolutionNodes()}
 * represent all of the possible ResolutionNodes which resolve to this groupId:artifactId.
 * //from  www  . j  a  v  a 2  s .c  om
 * @return
 * @throws PomToolsException
 */
public List getTransitiveDependencies() throws PomToolsException, ProjectBuildingException {
    // Certain things like groupId or versions for dependencies may be declared in a parent
    // pom so we need to have maven fully resolve the model before walking the tree.
    MavenProject project = PomToolsPluginContext.getInstance().getActiveProject().getTemporaryResolvedProject();

    try {
        project.setDependencyArtifacts(project.createArtifacts(artifactFactory, null, null));
    } catch (InvalidDependencyVersionException e) {
        throw new PomToolsVersionException(
                "Unable to build project due to an invalid dependency version: " + e.getMessage(), e);
    }

    Artifact projectArtifact = project.getArtifact();

    Set artifacts = project.getDependencyArtifacts();

    try {
        List dependencies = new ArrayList();

        ArtifactResolutionResult result;
        result = artifactResolver.resolveTransitively(artifacts, projectArtifact, Collections.EMPTY_MAP,
                localRepository, remoteRepositories, metadataSource, projectArtifact.getDependencyFilter());

        Map dependencyMap = new HashMap();
        Set seen = new HashSet();

        // First build our map of distinct groupId:artifactIds
        for (Iterator iter = result.getArtifactResolutionNodes().iterator(); iter.hasNext();) {
            ResolutionNode node = (ResolutionNode) iter.next();

            TransitiveDependencyInfo info = new TransitiveDependencyInfo(node);

            dependencyMap.put(info.getKey(), info);

            dependencies.add(info);
        }

        // Now populate the map with all children
        recurseNode(dependencyMap, seen, result.getArtifactResolutionNodes().iterator(), 0);

        return dependencies;
    } catch (ArtifactNotFoundException e) {
        throw new PomToolsException(e);
    } catch (ArtifactResolutionException e) {
        throw new PomToolsException(e);
    }

}

From source file:org.codehaus.mojo.taglist.TagListReport.java

License:Apache License

/**
 * Construct the list of source directories to analyze.
 * /*from  w  ww.ja  v  a  2  s  .  com*/
 * @return the list of dirs.
 */
public List constructSourceDirs() {
    List dirs = new ArrayList(project.getCompileSourceRoots());
    if (!skipTestSources) {
        dirs.addAll(project.getTestCompileSourceRoots());
    }

    if (aggregate) {
        for (Iterator i = reactorProjects.iterator(); i.hasNext();) {
            MavenProject reactorProject = (MavenProject) i.next();

            if ("java".equals(reactorProject.getArtifact().getArtifactHandler().getLanguage())) {
                dirs.addAll(reactorProject.getCompileSourceRoots());
                if (!skipTestSources) {
                    dirs.addAll(reactorProject.getTestCompileSourceRoots());
                }
            }
        }
    }

    dirs = pruneSourceDirs(dirs);
    return dirs;
}

From source file:org.codehaus.mojo.unix.maven.plugin.MavenProjectWrapper.java

License:Open Source License

public static MavenProjectWrapper mavenProjectWrapper(final MavenProject project, MavenSession session) {
    SortedMap<String, String> properties = new TreeMap<String, String>();

    // This is perhaps not ideal. Maven uses reflection to dynamically extract properties from the project
    // when interpolating each file. This uses a static list that doesn't contain the project.* properties, except
    // the new we hard-code support for.
    //// www . j  ava  2s  . c  o  m
    // The user can work around this like this:
    // <properties>
    //   <project.build.directory>${project.build.directory}</project.build.directory>
    // </properties>
    //
    // If this has to change, the properties has to be a F<String, String> and interpolation tokens ("${" and "}")
    // has to be defined. Doable but too painful for now.
    properties.putAll(toMap(session.getSystemProperties()));
    properties.putAll(toMap(session.getUserProperties()));
    properties.putAll(toMap(project.getProperties()));
    properties.put("project.groupId", project.getGroupId());
    properties.put("project.artifactId", project.getArtifactId());
    properties.put("project.version", project.getVersion());

    return new MavenProjectWrapper(project.getGroupId(), project.getArtifactId(), project.getVersion(),
            project.getArtifact(), project.getName(), project.getDescription(), project.getBasedir(),
            new File(project.getBuild().getDirectory()), new LocalDateTime(), project.getArtifacts(),
            project.getLicenses(), new ArtifactMap(project.getArtifacts()), unmodifiableSortedMap(properties));
}

From source file:org.codehaus.mojo.versions.api.DefaultVersionsHelper.java

License:Apache License

/**
 * {@inheritDoc}/* w  w w  .  j a  v a  2s .co m*/
 */
public Set<Artifact> extractArtifacts(Collection<MavenProject> mavenProjects) {
    Set<Artifact> result = new HashSet<Artifact>();
    for (MavenProject project : mavenProjects) {
        result.add(project.getArtifact());
    }

    return result;
}

From source file:org.codehaus.mojo.webstart.JnlpDownloadServletMojo.java

License:Apache License

/**
 * Resolve artifact of incoming jar resources (user configured ones), check their main class.
 * <p/>/*from   w ww.j  a  v  a 2s .co m*/
 * If must include transitive dependencies, collect them and wrap them as new jar resources.
 * <p/>
 * For each collected jar resource, copy his artifact file to lib directory (if it has changed),
 * fill also his hrefValue if required (jar resource with outputJarVersion filled).
 *
 * @param configuredJarResources list of configured jar resources
 * @param commonJarResources     list of resolved common jar resources (null when resolving common jar resources)
 * @return the set of resolved jar resources
 * @throws MojoExecutionException if something bas occurs while retrieving resources
 */
private Set<ResolvedJarResource> resolveJarResources(Collection<JarResource> configuredJarResources,
        Set<ResolvedJarResource> commonJarResources) throws MojoExecutionException {

    Set<ResolvedJarResource> collectedJarResources = new LinkedHashSet<ResolvedJarResource>();

    if (commonJarResources != null) {
        collectedJarResources.addAll(commonJarResources);
    }

    ArtifactUtil artifactUtil = getArtifactUtil();

    // artifacts resolved from repositories
    Set<Artifact> artifacts = new LinkedHashSet<Artifact>();

    // sibling projects hit from a jar resources (need a special transitive resolution)
    Set<MavenProject> siblingProjects = new LinkedHashSet<MavenProject>();

    // for each configured JarResource, create and resolve the corresponding artifact and
    // check it for the mainClass if specified
    for (JarResource jarResource : configuredJarResources) {
        Artifact artifact = artifactUtil.createArtifact(jarResource);

        // first try to resolv from reactor
        MavenProject siblingProject = artifactUtil.resolveFromReactor(artifact, getProject(), reactorProjects);
        if (siblingProject == null) {
            // try to resolve from repositories
            artifactUtil.resolveFromRepositories(artifact, getRemoteRepositories(), getLocalRepository());
            artifacts.add(artifact);
        } else {
            artifact = siblingProject.getArtifact();
            siblingProjects.add(siblingProject);
            artifacts.add(artifact);
            artifact.setResolved(true);
        }

        if (StringUtils.isNotBlank(jarResource.getMainClass())) {
            // check main class

            if (artifact == null) {
                throw new IllegalStateException(
                        "Implementation Error: The given jarResource cannot be checked for "
                                + "a main class until the underlying artifact has been resolved: ["
                                + jarResource + "]");
            }

            boolean containsMainClass = artifactUtil.artifactContainsClass(artifact,
                    jarResource.getMainClass());
            if (!containsMainClass) {
                throw new MojoExecutionException(
                        "The jar specified by the following jarResource does not contain the declared main class:"
                                + jarResource);
            }
        }
        ResolvedJarResource resolvedJarResource = new ResolvedJarResource(jarResource, artifact);
        getLog().debug("Add jarResource (configured): " + jarResource);
        collectedJarResources.add(resolvedJarResource);
    }

    if (!isExcludeTransitive()) {

        // prepare artifact filter

        AndArtifactFilter artifactFilter = new AndArtifactFilter();
        // restricts to runtime and compile scope
        artifactFilter.add(new ScopeArtifactFilter(Artifact.SCOPE_RUNTIME));
        // restricts to not pom dependencies
        artifactFilter.add(new InversionArtifactFilter(new TypeArtifactFilter("pom")));

        // get all transitive dependencies

        Set<Artifact> transitiveArtifacts = getArtifactUtil().resolveTransitively(artifacts, siblingProjects,
                getProject().getArtifact(), getLocalRepository(), getRemoteRepositories(), artifactFilter,
                getProject().getManagedVersionMap());

        // for each transitive dependency, wrap it in a JarResource and add it to the collection of
        // existing jar resources (if not already in)
        for (Artifact resolvedArtifact : transitiveArtifacts) {

            ResolvedJarResource newJarResource = new ResolvedJarResource(resolvedArtifact);

            if (!collectedJarResources.contains(newJarResource)) {
                getLog().debug("Add jarResource (transitive): " + newJarResource);
                collectedJarResources.add(newJarResource);
            }
        }
    }

    // for each JarResource, copy its artifact to the lib directory if necessary
    for (ResolvedJarResource jarResource : collectedJarResources) {
        Artifact artifact = jarResource.getArtifact();

        String filenameWithVersion = getDependencyFilenameStrategy().getDependencyFilename(artifact, false,
                isUseUniqueVersions());

        boolean copied = copyJarAsUnprocessedToDirectoryIfNecessary(artifact.getFile(), getLibDirectory(),
                filenameWithVersion);

        if (copied) {
            String name = artifact.getFile().getName();

            verboseLog("Adding " + name + " to modifiedJnlpArtifacts list.");
            getModifiedJnlpArtifacts().add(name.substring(0, name.lastIndexOf('.')));
        }

        String filename = getDependencyFilenameStrategy().getDependencyFilename(artifact,
                jarResource.isOutputJarVersion() ? null : false, isUseUniqueVersions());
        jarResource.setHrefValue(filename);
    }
    return collectedJarResources;
}

From source file:org.commonjava.poc.ral.AppLauncher.java

License:Open Source License

public AppLauncher(final Options options) throws AppLauncherException {
    setupLogging(Level.INFO);//from  w ww .j av a2  s .  c  o m

    this.options = options;

    try {
        load();
    } catch (MAEException e) {
        throw new AppLauncherException("Failed to initialize MAE subsystem: %s", e, e.getMessage());
    }

    SimpleProjectToolsSession session = new SimpleProjectToolsSession();
    session.setPomValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    session.setDependencySelector(
            new FlexibleScopeDependencySelector(org.apache.maven.artifact.Artifact.SCOPE_TEST,
                    org.apache.maven.artifact.Artifact.SCOPE_PROVIDED).setTransitive(true));

    MavenProject project = loadProject(options.coordinate, session);

    DependencyGraph depGraph = resolveDependencies(project, session);

    List<URL> urls = new ArrayList<URL>();
    try {
        ArtifactResult result = repositorySystem.resolveArtifact(session.getRepositorySystemSession(),
                new ArtifactRequest(RepositoryUtils.toArtifact(project.getArtifact()),
                        session.getRemoteRepositoriesForResolution(), null));

        mainJar = result.getArtifact().getFile().toURI().normalize().toURL();
        urls.add(mainJar);
    } catch (ArtifactResolutionException e) {
        throw new AppLauncherException("Failed to resolve main project artifact: %s. Reason: %s", e,
                project.getId(), e.getMessage());
    } catch (MalformedURLException e) {
        throw new AppLauncherException("Cannot format classpath URL from: %s. Reason: %s", e, project.getId(),
                e.getMessage());
    }

    for (DepGraphNode node : depGraph) {
        try {
            ArtifactResult result = node.getLatestResult();
            if (result == null) {
                if (node.getKey()
                        .equals(key(project.getGroupId(), project.getArtifactId(), project.getVersion()))) {
                    continue;
                } else {
                    throw new AppLauncherException("Failed to resolve: %s", node.getKey());
                }
            }

            Artifact artifact = result.getArtifact();
            File file = artifact.getFile();
            URL url = file.toURI().normalize().toURL();
            urls.add(url);
        } catch (MalformedURLException e) {
            throw new AppLauncherException("Cannot format classpath URL from: %s. Reason: %s", e, node.getKey(),
                    e.getMessage());
        }
    }

    classLoader = new URLClassLoader(urls.toArray(new URL[] {}), ClassLoader.getSystemClassLoader());
}

From source file:org.commonjava.sjbi.maven3.builder.M3BuildResult.java

License:Open Source License

M3BuildResult(final MavenExecutionResult mavenResult) {
    if (mavenResult.hasExceptions()) {
        setErrors(mavenResult.getExceptions());
    }/*from   w  w  w .  j a va2  s .  c  o  m*/

    final List<ArtifactSetRef> ars = new ArrayList<ArtifactSetRef>();
    for (final MavenProject project : mavenResult.getTopologicallySortedProjects()) {
        final ProjectRef pr = new ProjectRef(project.getGroupId(), project.getArtifactId(),
                project.getVersion());
        pr.setPomFile(project.getFile());

        final ArtifactSetRef ar = new ArtifactSetRef(pr);

        final Artifact mainArtifact = project.getArtifact();
        ar.addArtifactRef(mainArtifact.getType(), mainArtifact.getClassifier(), mainArtifact.getFile());

        for (final Artifact a : project.getAttachedArtifacts()) {
            ar.addArtifactRef(a.getType(), a.getClassifier(), a.getFile());
        }

        ars.add(ar);
    }

    setArtifactSets(ars);
}

From source file:org.debian.dependency.ProjectArtifactSpy.java

License:Apache License

@Override
public void onEvent(final Object event) {
    if (!(event instanceof ExecutionEvent)) {
        return;/*from   w w  w .  ja  va2s.com*/
    }
    ExecutionEvent execEvent = (ExecutionEvent) event;
    if (!Type.ProjectSucceeded.equals(execEvent.getType())
            && !Type.ForkedProjectSucceeded.equals(execEvent.getType())) {
        return;
    }

    MavenProject project = execEvent.getProject();
    Artifact pomArtifact = repoSystem.createProjectArtifact(project.getGroupId(), project.getArtifactId(),
            project.getVersion());
    pomArtifact.setFile(project.getFile());

    // the first project should always be the top-level project
    if (outputFile == null) {
        outputFile = new File(project.getBuild().getDirectory(), ServicePackage.PROJECT_ARTIFACT_REPORT_NAME);
    }

    recordArtifact(pomArtifact);
    recordArtifact(project.getArtifact());
    for (Artifact artifact : project.getAttachedArtifacts()) {
        recordArtifact(artifact);
    }
}