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.sourcepit.osgifier.maven.p2.P2UpdateSiteGenerator.java

License:Apache License

public OsgifierContext generateUpdateSite(File siteDir, MavenProject project,
        List<ArtifactRepository> remoteArtifactRepositories, ArtifactRepository localRepository,
        String repositoryName, PropertiesSource options) {
    return generateUpdateSite(siteDir, project.getArtifact(), remoteArtifactRepositories, localRepository,
            repositoryName, options);//from   ww  w  .jav a 2s .c om
}

From source file:org.springframework.ide.vscode.commons.maven.java.MavenProjectClasspath.java

License:Open Source License

private ClasspathData createClasspathData() throws Exception {
    MavenProject project = createMavenProject();

    ImmutableList<CPE> entries = resolveClasspathEntries(project);
    String name = project.getArtifact().getArtifactId();

    return new ClasspathData(name, new LinkedHashSet<>(entries));
}

From source file:org.springframework.ide.vscode.commons.maven.MavenBridge.java

License:Open Source License

MavenProject resolveParentProject(RepositorySystemSession repositorySession, MavenProject child,
        ProjectBuildingRequest configuration) throws MavenException {
    configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    configuration.setRepositorySession(repositorySession);

    try {/*from   w  w  w .  j  a  va 2s . c o  m*/
        configuration.setRemoteRepositories(child.getRemoteArtifactRepositories());

        File parentFile = child.getParentFile();
        if (parentFile != null) {
            return lookup(ProjectBuilder.class).build(parentFile, configuration).getProject();
        }

        Artifact parentArtifact = child.getParentArtifact();
        if (parentArtifact != null) {
            MavenProject parent = lookup(ProjectBuilder.class).build(parentArtifact, configuration)
                    .getProject();
            parentFile = parentArtifact.getFile(); // file is resolved as
            // side-effect of the
            // prior call
            // compensate for apparent bug in maven 3.0.4 which does not set
            // parent.file and parent.artifact.file
            if (parent.getFile() == null) {
                parent.setFile(parentFile);
            }
            if (parent.getArtifact().getFile() == null) {
                parent.getArtifact().setFile(parentFile);
            }
            return parent;
        }
    } catch (ProjectBuildingException ex) {
        log.error("Could not read parent project", ex);
    }

    return null;
}

From source file:org.springframework.ide.vscode.commons.maven.MavenCore.java

License:Open Source License

/**
 * Calculates dependency graph for a Maven project provided the scope.
 *
 * @param project Maven Project descriptor
 * @param scope Dependency scope//from   ww w . j  a va2 s  .com
 * @return Set of all dependencies including transient ones
 * @throws MavenException
 */
public Set<Artifact> resolveDependencies(MavenProject project, String scope) throws MavenException {
    MavenExecutionRequest request = maven.createExecutionRequest();
    DefaultRepositorySystemSession session = maven.createRepositorySession(request);

    DependencyNode graph = readDependencyTree(maven.lookupComponent(org.eclipse.aether.RepositorySystem.class),
            session, project, scope);
    if (graph != null) {

        ArrayList<DependencyNode> dependencyNodes = new ArrayList<>();
        graph.accept(new DependencyVisitor() {
            @Override
            public boolean visitEnter(DependencyNode node) {
                if (node.getDependency() != null) {
                    dependencyNodes.add(node);
                }
                return true;
            }

            @Override
            public boolean visitLeave(DependencyNode dependencynode) {
                return true;
            }
        });

        LinkedHashSet<Artifact> artifacts = new LinkedHashSet<>();
        RepositoryUtils.toArtifacts(artifacts, dependencyNodes,
                Collections.singletonList(project.getArtifact().getId()), null);

        return artifacts.parallelStream().map(artifact -> {
            if (!artifact.isResolved()) {
                try {
                    artifact = maven.resolve(artifact, project.getRemoteArtifactRepositories(), request);
                } catch (MavenException e) {
                    log.error("", e);
                    // Maven 2.x quirk: an artifact always points at the local repo,
                    // regardless whether resolved or not
                    LocalRepositoryManager lrm = session.getLocalRepositoryManager();
                    String path = lrm.getPathForLocalArtifact(RepositoryUtils.toArtifact(artifact));
                    artifact.setFile(new File(lrm.getRepository().getBasedir(), path));
                }
            }
            return artifact;
        }).collect(Collectors.toSet());
    }

    return Collections.emptySet();
}

From source file:org.universAAL.maven.treebuilder.DependencyTreeBuilder.java

License:Apache License

/**
 * Method builds dependency tree for a list of maven projects. All artifacts
 * in the tree are crosschecked against duplications and conflicts. In each
 * case of duplication, conflict, the case is resolved by omitting artifact
 * which is lower in the tree and keeping artifact which is higher in the
 * tree. If artifacts are on the same level then the one occuring first in
 * the tree is kept.//from   w  ww . j  a v  a  2s . c  om
 * 
 * @param repository
 *            Maven repository.
 * @param factory
 *            Factory used for creating artifacts.
 * @param metadataSource
 *            ArtifactMetadataSource provided by maven.
 * @param projectDescs
 *            list of maven project descriptors. Each descriptor contains
 *            MavenProject, a list of project's remote repositories and a
 *            boolean indicator if the project needs to be resolved
 *            transitively or not.
 * @return a dependency tree as a list of rootnodes (instances of
 *         DependencyNode class) which contain their own subtrees. Each
 *         rootnode corresponds to one maven project provided as argument.
 *         The order of rootnodes list is the same as order of provided
 *         maven projects list.
 * @throws DependencyTreeBuilderException
 *             Notifies about a problem during building the dependency tree.
 * @throws ArtifactMetadataRetrievalException
 *             Signals problem with metadata retieval.
 * @throws InvalidVersionSpecificationException
 *             Informs about invalid version specifications.
 * @throws NoSuchFieldException
 *             Exception related to reflection.
 * @throws SecurityException
 *             Exception thrown by security manager.
 * @throws IllegalAccessException
 *             Illegal access during usage of java reflection.
 * @throws IllegalArgumentException
 *             Illegal argument was passed.
 */
public List<RootNode> buildDependencyTree(final ArtifactRepository repository, final ArtifactFactory factory,
        final ArtifactMetadataSource metadataSource, final MavenProjectDescriptor... projectDescs)
        throws DependencyTreeBuilderException, ArtifactMetadataRetrievalException,
        InvalidVersionSpecificationException, SecurityException, NoSuchFieldException, IllegalArgumentException,
        IllegalAccessException {
    ArtifactFilter filter = new ScopeArtifactFilter();
    DependencyTreeResolutionListener listener = new DependencyTreeResolutionListener(filter);
    Map resolvedArtifacts = new LinkedHashMap();
    for (MavenProjectDescriptor projectDesc : projectDescs) {
        MavenProject project = projectDesc.project;
        try {
            List<String> separatedGroupId = extractSeparatedGroupIds(project);

            // Here you can simply add to create a new list
            List remoteRepositories = projectDesc.remoteRepositories;

            // If artifact is marked in pom as a bundle then it is changed
            // to jar. Retaining bundle can impose problems when the
            // artifact is duplicated or conflicted with other artifact
            // specified as a dependency, because in the
            // dependency there is only jar type specified.
            Artifact originatingArtifact = project.getArtifact();
            this.stringifiedRoot = FilteringVisitorSupport.stringify(originatingArtifact);
            if ("bundle".equals(originatingArtifact.getType())) {
                Artifact changeArtifact = artifactFactory.createArtifact(originatingArtifact.getGroupId(),
                        originatingArtifact.getArtifactId(), originatingArtifact.getVersion(),
                        originatingArtifact.getScope(), "jar");
                originatingArtifact = changeArtifact;
            }
            ResolutionNode root = new ResolutionNode(originatingArtifact, remoteRepositories);

            // If the project is not supposed to be transitively resolved
            // then its dependencies are not added to the root. Moreover the
            // parameter is passed to the recurse method. Thanks to than
            // when transitive is false, resolving of runtime dependencies
            // is not performed.
            if (projectDesc.transitive) {
                Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();

                if (dependencyArtifacts == null) {
                    dependencyArtifacts = new LinkedHashSet();
                    List dependencies = project.getDependencies();
                    for (Object depObj : dependencies) {
                        Dependency dep = (Dependency) depObj;
                        if (dep.isOptional()) {
                            // filtering optional dependencies
                            continue;
                        }
                        Artifact dependencyArtifact;
                        VersionRange versionRange = VersionRange.createFromVersionSpec(dep.getVersion());
                        dependencyArtifact = factory.createDependencyArtifact(dep.getGroupId(),
                                dep.getArtifactId(), versionRange, dep.getType(), dep.getClassifier(),
                                dep.getScope());
                        if (dep.getExclusions() != null) {
                            if (!dep.getExclusions().isEmpty()) {
                                List<String> patterns = new ArrayList<String>();
                                for (Exclusion exclusion : dep.getExclusions()) {
                                    patterns.add(exclusion.getGroupId() + ":" + exclusion.getArtifactId());
                                }
                                dependencyArtifact.setDependencyFilter(new ExcludesArtifactFilter(patterns));
                            }
                        }
                        dependencyArtifacts.add(dependencyArtifact);
                    }
                } else {
                    // filtering optional dependencies
                    Set<Artifact> filteredArtifacts = new LinkedHashSet();
                    for (Artifact a : dependencyArtifacts) {
                        if (!a.isOptional()) {
                            filteredArtifacts.add(a);
                        }
                    }
                    dependencyArtifacts = filteredArtifacts;
                }

                for (Artifact depArtifact : dependencyArtifacts) {
                    if (depArtifact.getVersion() != null) {
                        if (!depArtifact.getVersion().equals(depArtifact.getBaseVersion())) {
                            if (depArtifact.isSnapshot()) {
                                depArtifact.setVersion(depArtifact.getBaseVersion());
                            }
                        }
                    }
                }

                root.addDependencies(dependencyArtifacts, remoteRepositories, filter);
            }

            // Information about managed versions is extracted from the
            // artifact's pom (but also from parent poms and settings.xml
            // file).
            ManagedVersionMap versionMap = getManagedVersionsMap(originatingArtifact,
                    project.getManagedVersionMap());

            recurse(originatingArtifact, root, resolvedArtifacts, versionMap, localRepository,
                    remoteRepositories, metadataSource, filter, listener, projectDesc.transitive,
                    new HashSet<String>(separatedGroupId));
        } catch (ArtifactResolutionException exception) {
            throw new DependencyTreeBuilderException("Cannot build project dependency tree", exception);
        }
    }
    return listener.getRootNodes();
}

From source file:org.universAAL.maven.treebuilder.ExecutionListCreator.java

License:Apache License

/**
 * Creates execution list for given MavenProject.
 * /*  w  w  w  . ja va 2  s.  c o  m*/
 * @param mavenProject
 * @return
 * @throws MojoExecutionException
 * @throws MojoFailureException
 */
public List createArtifactExecutionList(final MavenProject mavenProject,
        final Set<String> separatedArtifactDepsOfRootMvnUrls, final boolean includeTestRuntimes)
        throws Exception {
    DependencyTreeBuilder treeBuilder = new DependencyTreeBuilder(artifactFactory, mavenProjectBuilder,
            localRepository, includeTestRuntimes);
    List<ArtifactRepository> finalRemoteRpositories = addMissingRepositories(
            mavenProject.getRemoteArtifactRepositories());
    List<RootNode> rootNodes = treeBuilder.buildDependencyTree(localRepository, artifactFactory,
            artifactMetadataSource, new MavenProjectDescriptor(mavenProject, finalRemoteRpositories, true));
    List<ResolutionNode> separatedArtifactDepsOfRoot = treeBuilder.getSeparatedArtifactDepsOfRoot();
    for (ResolutionNode separatedRootDep : separatedArtifactDepsOfRoot) {
        Artifact artifact = separatedRootDep.getArtifact();
        separatedArtifactDepsOfRootMvnUrls.add(String.format("mvn:%s/%s/%s", artifact.getGroupId(),
                artifact.getArtifactId(), artifact.getVersion()));
    }
    if (rootNodes.size() != 1) {
        throw new IllegalStateException("rootNodes.size() != 1");
    }
    List<RootNode> realRootNodes = new ArrayList<RootNode>();
    RootNode theRootNode = rootNodes.get(0);
    theRootNode.remoteRepositories = finalRemoteRpositories;
    realRootNodes.add(theRootNode);
    return processTreeIntoFlatList(realRootNodes, mavenProject.getArtifact());
}

From source file:org.vafer.jdeb.maven.DebMojo.java

License:Apache License

/**
 * @return whether or not the main artifact was created
 *//*from w  w w  . jav a 2 s  . com*/
private boolean hasMainArtifact() {
    final MavenProject project = getProject();
    final Artifact artifact = project.getArtifact();
    return artifact.getFile() != null && artifact.getFile().isFile();
}

From source file:org.vafer.jdeb.maven.DebMojo.java

License:Apache License

/**
 * Main entry point//from w w  w . j a  v  a2s.c  o m
 *
 * @throws MojoExecutionException on error
 */
@Override
public void execute() throws MojoExecutionException {

    final MavenProject project = getProject();

    if (skip) {
        getLog().info("skipping as configured (skip)");
        return;
    }

    if (skipPOMs && isPOM()) {
        getLog().info("skipping because artifact is a pom (skipPOMs)");
        return;
    }

    if (skipSubmodules && isSubmodule()) {
        getLog().info("skipping submodule (skipSubmodules)");
        return;
    }

    setData(dataSet);

    console = new MojoConsole(getLog(), verbose);

    initializeSignProperties();

    final VariableResolver resolver = initializeVariableResolver(new HashMap<String, String>());

    final File debFile = new File(Utils.replaceVariables(resolver, deb, openReplaceToken, closeReplaceToken));
    final File controlDirFile = new File(
            Utils.replaceVariables(resolver, controlDir, openReplaceToken, closeReplaceToken));
    final File installDirFile = new File(
            Utils.replaceVariables(resolver, installDir, openReplaceToken, closeReplaceToken));
    final File changesInFile = new File(
            Utils.replaceVariables(resolver, changesIn, openReplaceToken, closeReplaceToken));
    final File changesOutFile = new File(
            Utils.replaceVariables(resolver, changesOut, openReplaceToken, closeReplaceToken));
    final File changesSaveFile = new File(
            Utils.replaceVariables(resolver, changesSave, openReplaceToken, closeReplaceToken));
    final File keyringFile = keyring == null ? null
            : new File(Utils.replaceVariables(resolver, keyring, openReplaceToken, closeReplaceToken));

    // if there are no producers defined we try to use the artifacts
    if (dataProducers.isEmpty()) {

        if (hasMainArtifact()) {
            Set<Artifact> artifacts = new HashSet<Artifact>();

            artifacts.add(project.getArtifact());

            @SuppressWarnings("unchecked")
            final Set<Artifact> projectArtifacts = project.getArtifacts();

            for (Artifact artifact : projectArtifacts) {
                artifacts.add(artifact);
            }

            @SuppressWarnings("unchecked")
            final List<Artifact> attachedArtifacts = project.getAttachedArtifacts();

            for (Artifact artifact : attachedArtifacts) {
                artifacts.add(artifact);
            }

            for (Artifact artifact : artifacts) {
                final File file = artifact.getFile();
                if (file != null) {
                    dataProducers.add(new DataProducer() {
                        @Override
                        public void produce(final DataConsumer receiver) {
                            try {
                                final File path = new File(installDirFile.getPath(), file.getName());
                                final String entryName = path.getPath();

                                final boolean symbolicLink = SymlinkUtils.isSymbolicLink(path);
                                final TarArchiveEntry e;
                                if (symbolicLink) {
                                    e = new TarArchiveEntry(entryName, TarConstants.LF_SYMLINK);
                                    e.setLinkName(SymlinkUtils.readSymbolicLink(path));
                                } else {
                                    e = new TarArchiveEntry(entryName, true);
                                }

                                e.setUserId(0);
                                e.setGroupId(0);
                                e.setUserName("root");
                                e.setGroupName("root");
                                e.setMode(TarEntry.DEFAULT_FILE_MODE);
                                e.setSize(file.length());

                                receiver.onEachFile(new FileInputStream(file), e);
                            } catch (Exception e) {
                                getLog().error(e);
                            }
                        }
                    });
                } else {
                    getLog().error("No file for artifact " + artifact);
                }
            }
        }
    }

    try {
        DebMaker debMaker = new DebMaker(console, dataProducers, conffileProducers);
        debMaker.setDeb(debFile);
        debMaker.setControl(controlDirFile);
        debMaker.setPackage(getProject().getArtifactId());
        debMaker.setDescription(getProject().getDescription());
        debMaker.setHomepage(getProject().getUrl());
        debMaker.setChangesIn(changesInFile);
        debMaker.setChangesOut(changesOutFile);
        debMaker.setChangesSave(changesSaveFile);
        debMaker.setCompression(compression);
        debMaker.setKeyring(keyringFile);
        debMaker.setKey(key);
        debMaker.setPassphrase(passphrase);
        debMaker.setSignPackage(signPackage);
        debMaker.setSignMethod(signMethod);
        debMaker.setSignRole(signRole);
        debMaker.setResolver(resolver);
        debMaker.setOpenReplaceToken(openReplaceToken);
        debMaker.setCloseReplaceToken(closeReplaceToken);
        debMaker.validate();
        debMaker.makeDeb();

        // Always attach unless explicitly set to false
        if ("true".equalsIgnoreCase(attach)) {
            console.info("Attaching created debian package " + debFile);
            if (!isType()) {
                projectHelper.attachArtifact(project, type, classifier, debFile);
            } else {
                project.getArtifact().setFile(debFile);
            }
        }

    } catch (PackagingException e) {
        getLog().error("Failed to create debian package " + debFile, e);
        throw new MojoExecutionException("Failed to create debian package " + debFile, e);
    }

    if (!isBlank(propertyPrefix)) {
        project.getProperties().put(propertyPrefix + "version", getProjectVersion());
        project.getProperties().put(propertyPrefix + "deb", debFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "deb.name", debFile.getName());
        project.getProperties().put(propertyPrefix + "changes", changesOutFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "changes.name", changesOutFile.getName());
        project.getProperties().put(propertyPrefix + "changes.txt", changesSaveFile.getAbsolutePath());
        project.getProperties().put(propertyPrefix + "changes.txt.name", changesSaveFile.getName());
    }

}

From source file:org.wildfly.maven.plugins.licenses.DependenciesResolver.java

private MavenProject getDependencyMavenProject(ArtifactRepository localRepository,
        List<ArtifactRepository> remoteRepositories, SortedMap<String, MavenProject> cache, boolean verbose,
        Artifact artifact, Logger log, String id) {
    MavenProject depMavenProject = null;

    if (cache != null) {
        // try to get project from cache
        depMavenProject = cache.get(id);
        if (depMavenProject != null) {
            if (verbose) {
                log.info("add dependency [" + id + "] (from cache)");
            }//from w w w .j  a  v a 2 s . com
            return depMavenProject;
        }
    }

    try {
        depMavenProject = mavenProjectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository,
                true);
        depMavenProject.getArtifact().setScope(artifact.getScope());
    } catch (ProjectBuildingException e) {
        log.warn("Unable to obtain POM for artifact : " + artifact, e);
        return null;
    }

    if (verbose) {
        log.info("add dependency [" + id + "]");
    }

    if (cache != null) {
        cache.put(id, depMavenProject);
    }
    return depMavenProject;
}

From source file:org.wisdom.maven.utils.MavenUtils.java

License:Apache License

/**
 * Gets the default set of properties for the given project.
 *
 * @param currentProject the project//from  ww w .j  a  v a  2  s. c o m
 * @return the set of properties, containing default bundle packaging instructions.
 */
public static Properties getDefaultProperties(MavenProject currentProject) {
    Properties properties = new Properties();
    String bsn = DefaultMaven2OsgiConverter.getBundleSymbolicName(currentProject.getArtifact());

    // Setup defaults
    properties.put(MAVEN_SYMBOLICNAME, bsn);
    properties.put("bundle.file.name",
            DefaultMaven2OsgiConverter.getBundleFileName(currentProject.getArtifact()));
    properties.put(Analyzer.BUNDLE_SYMBOLICNAME, bsn);
    properties.put(Analyzer.IMPORT_PACKAGE, "*");
    properties.put(Analyzer.BUNDLE_VERSION, DefaultMaven2OsgiConverter.getVersion(currentProject.getVersion()));

    header(properties, Analyzer.BUNDLE_DESCRIPTION, currentProject.getDescription());
    StringBuilder licenseText = printLicenses(currentProject.getLicenses());
    if (licenseText != null) {
        header(properties, Analyzer.BUNDLE_LICENSE, licenseText);
    }
    header(properties, Analyzer.BUNDLE_NAME, currentProject.getName());

    if (currentProject.getOrganization() != null) {
        if (currentProject.getOrganization().getName() != null) {
            String organizationName = currentProject.getOrganization().getName();
            header(properties, Analyzer.BUNDLE_VENDOR, organizationName);
            properties.put("project.organization.name", organizationName);
            properties.put("pom.organization.name", organizationName);
        }
        if (currentProject.getOrganization().getUrl() != null) {
            String organizationUrl = currentProject.getOrganization().getUrl();
            header(properties, Analyzer.BUNDLE_DOCURL, organizationUrl);
            properties.put("project.organization.url", organizationUrl);
            properties.put("pom.organization.url", organizationUrl);
        }
    }

    properties.putAll(currentProject.getModel().getProperties());

    for (String s : currentProject.getFilters()) {
        File filterFile = new File(s);
        if (filterFile.isFile()) {
            properties.putAll(PropertyUtils.loadProperties(filterFile));
        }
    }

    properties.putAll(getProperties(currentProject.getModel(), "project.build."));
    properties.putAll(getProperties(currentProject.getModel(), "pom."));
    properties.putAll(getProperties(currentProject.getModel(), "project."));

    properties.put("project.baseDir", currentProject.getBasedir().getAbsolutePath());
    properties.put("project.build.directory", currentProject.getBuild().getDirectory());
    properties.put("project.build.outputdirectory", currentProject.getBuild().getOutputDirectory());

    properties.put("project.source.roots", getArray(currentProject.getCompileSourceRoots()));
    properties.put("project.testSource.roots", getArray(currentProject.getTestCompileSourceRoots()));

    properties.put("project.resources", toString(currentProject.getResources()));
    properties.put("project.testResources", toString(currentProject.getTestResources()));

    return properties;
}