Java Code Examples for org.apache.maven.project.MavenProject#getArtifacts()

The following examples show how to use org.apache.maven.project.MavenProject#getArtifacts() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: AbstractKieMojo.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
protected boolean hasClassOnClasspath(MavenProject project, String className) {
    try {
        Set<Artifact> elements = project.getArtifacts();
        URL[] urls = new URL[elements.size()];

        int i = 0;
        Iterator<Artifact> it = elements.iterator();
        while (it.hasNext()) {
            Artifact artifact = it.next();

            urls[i] = artifact.getFile().toURI().toURL();
            i++;
        }
        try (URLClassLoader cl = new URLClassLoader(urls)) {
            cl.loadClass(className);
        }
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 2
Source File: MojoUtil.java    From kogito-runtimes with Apache License 2.0 6 votes vote down vote up
public static Set<URL> getProjectFiles(final MavenProject mavenProject, final List<InternalKieModule> kmoduleDeps)
        throws DependencyResolutionRequiredException, IOException {
    final Set<URL> urls = new HashSet<>();
    for (final String element : mavenProject.getCompileClasspathElements()) {
        urls.add(new File(element).toURI().toURL());
    }

    mavenProject.setArtifactFilter(new CumulativeScopeArtifactFilter(Arrays.asList("compile", "runtime")));
    for (final Artifact artifact : mavenProject.getArtifacts()) {
        final File file = artifact.getFile();
        if (file != null && file.isFile()) {
            urls.add(file.toURI().toURL());
            final KieModuleModel depModel = getDependencyKieModel(file);
            if (kmoduleDeps != null && depModel != null) {
                final ReleaseId releaseId = new ReleaseIdImpl(artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion());
                kmoduleDeps.add(new ZipKieModule(releaseId, depModel, file));
            }
        }
    }
    return urls;
}
 
Example 3
Source File: DependenciesNode.java    From netbeans with Apache License 2.0 6 votes vote down vote up
Collection<DependencyWrapper> list(boolean longLiving) {  
    HashSet<DependencyWrapper> lst;
    MavenProject mp = project.getOriginalMavenProject();
    Set<Artifact> arts = mp.getArtifacts();
    switch (type) {
        case COMPILE:
        case TEST:
        case RUNTIME:
            lst = create(arts, longLiving, type.artifactScopes());
            break;
        default:
            lst = create(arts, longLiving, (a) -> !a.getArtifactHandler().isAddedToClasspath());
    }
    //#200927 do not use comparator in treeset, comparator not equivalent to equals/hashcode
    ArrayList<DependencyWrapper> l = new ArrayList<>(lst);
    Collections.sort(l, new DependenciesComparator());
    return l;
}
 
Example 4
Source File: MavenUtil.java    From jkube with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Returns the version associated to the dependency with the given groupId and artifactId (if present)
 *
 * @param project MavenProject object for project
 * @param groupId group id
 * @param artifactId artifact id
 * @return version associated to dependency
 */
public static String getDependencyVersion(MavenProject project, String groupId, String artifactId) {
    Set<Artifact> artifacts = project.getArtifacts();
    if (artifacts != null) {
        for (Artifact artifact : artifacts) {
            String scope = artifact.getScope();
            if (Objects.equal("test", scope)) {
                continue;
            }
            if (artifactId != null && !Objects.equal(artifactId, artifact.getArtifactId())) {
                continue;
            }
            if (Objects.equal(groupId, artifact.getGroupId())) {
                return artifact.getVersion();
            }
        }
    }
    return null;
}
 
Example 5
Source File: AbstractDocumentationMojo.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Replies the current classpath.
 *
 * @return the current classpath.
 * @throws IOException on failure.
 */
protected List<File> getClassPath() throws IOException {
	final Set<String> classPath = new LinkedHashSet<>();
	final MavenProject curProj = this.session.getCurrentProject();
	classPath.add(curProj.getBuild().getSourceDirectory());
	try {
		classPath.addAll(curProj.getCompileClasspathElements());
	} catch (DependencyResolutionRequiredException e) {
		throw new IOException(e.getLocalizedMessage(), e);
	}
	for (final Artifact dep : curProj.getArtifacts()) {
		classPath.add(dep.getFile().getAbsolutePath());
	}
	classPath.remove(curProj.getBuild().getOutputDirectory());
	final List<File> files = new ArrayList<>();
	for (final String filename : classPath) {
		final File file = new File(filename);
		if (file.exists()) {
			files.add(file);
		}
	}
	return files;
}
 
Example 6
Source File: AbstractCodeGeneratorMojo.java    From cxf with Apache License 2.0 5 votes vote down vote up
private Artifact resolveRemoteWadlArtifact(Artifact artifact)
    throws MojoExecutionException {

    /**
     * First try to find the artifact in the reactor projects of the maven session.
     * So an artifact that is not yet built can be resolved
     */
    List<MavenProject> rProjects = mavenSession.getProjects();
    for (MavenProject rProject : rProjects) {
        if (artifact.getGroupId().equals(rProject.getGroupId())
            && artifact.getArtifactId().equals(rProject.getArtifactId())
            && artifact.getVersion().equals(rProject.getVersion())) {
            Set<Artifact> artifacts = rProject.getArtifacts();
            for (Artifact pArtifact : artifacts) {
                if ("wadl".equals(pArtifact.getType())) {
                    return pArtifact;
                }
            }
        }
    }

    ArtifactResolutionRequest request = new ArtifactResolutionRequest();
    request.setArtifact(artifact);
    request.setResolveRoot(true).setResolveTransitively(false);
    request.setServers(mavenSession.getRequest().getServers());
    request.setMirrors(mavenSession.getRequest().getMirrors());
    request.setProxies(mavenSession.getRequest().getProxies());
    request.setLocalRepository(mavenSession.getLocalRepository());
    request.setRemoteRepositories(mavenSession.getRequest().getRemoteRepositories());
    ArtifactResolutionResult result = repositorySystem.resolve(request);
    Artifact resolvedArtifact = result.getOriginatingArtifact();
    if (resolvedArtifact == null && !CollectionUtils.isEmpty(result.getArtifacts())) {
        resolvedArtifact = result.getArtifacts().iterator().next();
    }
    return resolvedArtifact;
}
 
Example 7
Source File: Util.java    From yangtools with Eclipse Public License 1.0 5 votes vote down vote up
static List<File> getClassPath(final MavenProject project) {
    final List<File> dependencies = new ArrayList<>();
    for (Artifact element : project.getArtifacts()) {
        File asFile = element.getFile();
        if (isJar(asFile) || asFile.isDirectory()) {
            dependencies.add(asFile);
        }
    }
    return dependencies;
}
 
Example 8
Source File: DeployMojoSupport.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
private void addSkinnyWarLib(Element parent, MavenProject proj, LooseEarApplication looseEar) throws Exception {
    Set<Artifact> artifacts = proj.getArtifacts();
    log.debug("Number of compile dependencies for " + proj.getArtifactId() + " : " + artifacts.size());

    for (Artifact artifact : artifacts) {
        // skip the embedded library if it is included in the lib directory of the ear
        // package
        if (("compile".equals(artifact.getScope()) || "runtime".equals(artifact.getScope()))
                && "jar".equals(artifact.getType()) && !looseEar.isEarDependency(artifact)) {
            addLibrary(parent, looseEar, "/WEB-INF/lib/", artifact);
        }
    }
}
 
Example 9
Source File: JUnitOutputListenerProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String getJUnitVersion(MavenProject prj) {
    String juVersion = "";
    for (Artifact a : prj.getArtifacts()) {
        if ("junit".equals(a.getGroupId()) && ("junit".equals(a.getArtifactId()) || "junit-dep".equals(a.getArtifactId()))) { //junit-dep  see #214238
            String version = a.getVersion();
            if (version != null && new ComparableVersion(version).compareTo(new ComparableVersion("4.8")) >= 0) {
                return "JUNIT4"; //NOI18N
            }
            if (version != null && new ComparableVersion(version).compareTo(new ComparableVersion("3.8")) >= 0) {
                return "JUNIT3"; //NOI18N
            }
        }
    }
    return juVersion;
}
 
Example 10
Source File: JUnitOutputListenerProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private boolean usingJUnit4(MavenProject prj) { // SUREFIRE-724
    for (Artifact a : prj.getArtifacts()) {
        if ("junit".equals(a.getGroupId()) && ("junit".equals(a.getArtifactId()) || "junit-dep".equals(a.getArtifactId()))) { //junit-dep  see #214238
            String version = a.getVersion();
            if (version != null && new ComparableVersion(version).compareTo(new ComparableVersion("4.8")) >= 0) {
                return true;
            }
        }
    }
    return false;
}
 
Example 11
Source File: DeployMojoSupport.java    From ci.maven with Apache License 2.0 5 votes vote down vote up
private void addEmbeddedLib(Element parent, MavenProject proj, LooseApplication looseApp, String dir)
        throws Exception {
    Set<Artifact> artifacts = proj.getArtifacts();
    log.debug("Number of compile dependencies for " + proj.getArtifactId() + " : " + artifacts.size());

    for (Artifact artifact : artifacts) {
        if (("compile".equals(artifact.getScope()) || "runtime".equals(artifact.getScope()))
                && "jar".equals(artifact.getType())) {
            addLibrary(parent, looseApp, dir, artifact);
        }
    }
}
 
Example 12
Source File: AbstractSarlBatchCompilerMojo.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Replies the classpath for the standard code.
 *
 * @return the current classpath.
 * @throws MojoExecutionException on failure.
 * @see #getTestClassPath()
 */
protected List<File> getClassPath() throws MojoExecutionException {
	if (this.bufferedClasspath == null) {
		final Set<String> classPath = new LinkedHashSet<>();
		final MavenProject project = getProject();
		classPath.add(project.getBuild().getSourceDirectory());
		try {
			classPath.addAll(project.getCompileClasspathElements());
		} catch (DependencyResolutionRequiredException e) {
			throw new MojoExecutionException(e.getLocalizedMessage(), e);
		}
		for (final Artifact dep : project.getArtifacts()) {
			classPath.add(dep.getFile().getAbsolutePath());
		}
		classPath.remove(project.getBuild().getOutputDirectory());
		final List<File> files = new ArrayList<>();
		for (final String filename : classPath) {
			final File file = new File(filename);
			if (file.exists()) {
				files.add(file);
			} else {
				getLog().warn(MessageFormat.format(Messages.AbstractSarlBatchCompilerMojo_10, filename));
			}
		}
		this.bufferedClasspath = files;
	}
	return this.bufferedClasspath;
}
 
Example 13
Source File: CycloneDxAggregateMojo.java    From cyclonedx-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void execute() throws MojoExecutionException {
    final boolean shouldSkip = Boolean.parseBoolean(System.getProperty("cyclonedx.skip", Boolean.toString(getSkip())));
    if (shouldSkip) {
        getLog().info("Skipping CycloneDX");
        return;
    }

    final Set<Component> components = new LinkedHashSet<>();
    final Set<String> componentRefs = new LinkedHashSet<>();
    Set<Dependency> dependencies = new LinkedHashSet<>();
    for (final MavenProject mavenProject : getReactorProjects()) {
        for (final Artifact artifact : mavenProject.getArtifacts()) {
            if (shouldInclude(artifact)) {
                final Component component = convert(artifact);
                // ensure that only one component with the same bom-ref exists in the BOM
                boolean found = false;
                for (String s : componentRefs) {
                    if (s != null && s.equals(component.getBomRef())) {
                        found = true;
                    }
                }
                if (!found) {
                    componentRefs.add(component.getBomRef());
                    components.add(component);
                }
            }
        }
    }
    if (getIncludeDependencyGraph() && !getSchemaVersion().equals("1.0")) {
        dependencies = buildDependencyGraph(componentRefs);
    }
    super.execute(components, dependencies);
}
 
Example 14
Source File: ProGuardMojo.java    From code-hidding-plugin with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static Artifact getDependancy(Inclusion inc, MavenProject mavenProject)
                                                                               throws MojoExecutionException {
    Set dependancy = mavenProject.getArtifacts();
    for (Iterator i = dependancy.iterator(); i.hasNext();) {
        Artifact artifact = (Artifact) i.next();
        if (inc.match(artifact)) {
            return artifact;
        }
    }
    throw new MojoExecutionException("artifactId Not found " + inc.artifactId);
}
 
Example 15
Source File: Artifacts.java    From vespa with Apache License 2.0 5 votes vote down vote up
static ArtifactSet getArtifacts(MavenProject project, boolean includeTestArtifacts, String testProvidedConfig) {
    TestProvidedArtifacts testProvidedArtifacts = TestProvidedArtifacts.from(project.getArtifactMap(), testProvidedConfig);
    List<Artifact> jarArtifactsToInclude = new ArrayList<>();
    List<Artifact> jarArtifactsProvided = new ArrayList<>();
    List<Artifact> nonJarArtifactsToInclude = new ArrayList<>();
    List<Artifact> nonJarArtifactsProvided = new ArrayList<>();
    for (Artifact artifact : project.getArtifacts()) {
        if ("jar".equals(artifact.getType())) {
            if (includeTestArtifacts && testProvidedArtifacts.isTestProvided(artifact)) {
                jarArtifactsProvided.add(artifact);
            } else if (Artifact.SCOPE_COMPILE.equals(artifact.getScope())) {
                jarArtifactsToInclude.add(artifact);
            } else if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) {
                jarArtifactsProvided.add(artifact);
            } else if (includeTestArtifacts && Artifact.SCOPE_TEST.equals(artifact.getScope())) {
                jarArtifactsToInclude.add(artifact);
            }
        } else {
            if (Artifact.SCOPE_COMPILE.equals(artifact.getScope())) {
                nonJarArtifactsToInclude.add(artifact);
            } else if (Artifact.SCOPE_PROVIDED.equals(artifact.getScope())) {
                nonJarArtifactsProvided.add(artifact);
            }
        }
    }
    nonJarArtifactsToInclude.addAll(nonJarArtifactsProvided);
    return new ArtifactSet(jarArtifactsToInclude, jarArtifactsProvided, nonJarArtifactsToInclude);
}
 
Example 16
Source File: EarImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
public List<Project> getProjects() {
    MavenProject mp = mavenproject().getMavenProject();
    @SuppressWarnings("unchecked")
    Set<Artifact> artifactSet = mp.getArtifacts();
    @SuppressWarnings("unchecked")
    List<Dependency> deps = mp.getRuntimeDependencies();
    List<Project> toRet = new ArrayList<Project>();
    EarImpl.MavenModule[] mm = readPomModules();
    //#162173 order by dependency list, artifacts is unsorted set.
    for (Dependency d : deps) {
        if ("war".equals(d.getType()) || "ejb".equals(d.getType()) || "app-client".equals(d.getType())) {//NOI18N
            for (Artifact a : artifactSet) {
                if (a.getGroupId().equals(d.getGroupId()) &&
                        a.getArtifactId().equals(d.getArtifactId()) &&
                        StringUtils.equals(a.getClassifier(), d.getClassifier())) {
                    URI uri = Utilities.toURI(FileUtil.normalizeFile(a.getFile()));
                    //#174744 - it's of essence we use the URI based method. items in local repo might not be available yet.
                    Project owner = FileOwnerQuery.getOwner(uri);
                    if (owner != null) {
                        EarImpl.MavenModule m = findMavenModule(a, mm);
                        //#162173 respect order in pom configuration.. shall we?
                        if (m.pomIndex > -1 && toRet.size() > m.pomIndex) {
                            toRet.add(m.pomIndex, owner);
                        } else {
                            toRet.add(owner);
                        }
                        
                    }
                }
            }
        }
    }
    // This might happened if someone calls getProjects() before the EAR childs were actually opened
    // Typically if childs are needed during the project creation
    if (toRet.isEmpty()) {
        FileObject parentFO = project.getProjectDirectory().getParent();
        for (FileObject childFO : parentFO.getChildren()) {
            if (childFO.isData()) {
                continue;
            }
            
            try {
                Project childProject = ProjectManager.getDefault().findProject(childFO);
                if (childProject != null && !childProject.equals(project)) {
                    toRet.add(childProject);
                }
            } catch (IOException | IllegalArgumentException ex) {
                Exceptions.printStackTrace(ex);
            }
        }
    }
    return toRet;
}
 
Example 17
Source File: MavenProjectUtil.java    From microprofile-sandbox with Apache License 2.0 4 votes vote down vote up
public static Map<String, String> getAllDependencies(MavenProject project, RepositorySystem repoSystem,
        RepositorySystemSession repoSession, List<RemoteRepository> remoteRepos, BoostLogger logger)
        throws ArtifactDescriptorException {
    logger.debug("Processing project for dependencies.");
    Map<String, String> dependencies = new HashMap<String, String>();

    for (Artifact artifact : project.getArtifacts()) {
        logger.debug("Found dependency while processing project: " + artifact.getGroupId() + ":"
                + artifact.getArtifactId() + ":" + artifact.getVersion() + ":" + artifact.getType() + ":"
                + artifact.getScope());

        if (artifact.getType().equals("war")) {
            logger.debug("Resolving transitive booster dependencies for war");
            org.eclipse.aether.artifact.Artifact pomArtifact = new DefaultArtifact(artifact.getGroupId(),
                    artifact.getArtifactId(), "pom", artifact.getVersion());

            List<org.eclipse.aether.artifact.Artifact> warArtifacts = getWarArtifacts(pomArtifact, repoSystem,
                    repoSession, remoteRepos);

            for (org.eclipse.aether.artifact.Artifact warArtifact : warArtifacts) {
                // Only add booster dependencies for this war. Anything else
                // like datasource
                // dependencies must be explicitly defined by this project.
                // This is to allow the
                // current project to have full control over those optional
                // dependencies.
                if (warArtifact.getGroupId().equals(AbstractBoosterConfig.BOOSTERS_GROUP_ID)) {
                    logger.debug("Found booster dependency: " + warArtifact.getGroupId() + ":"
                            + warArtifact.getArtifactId() + ":" + warArtifact.getVersion());

                    dependencies.put(warArtifact.getGroupId() + ":" + warArtifact.getArtifactId(),
                            warArtifact.getVersion());
                }
            }

        } else {
            dependencies.put(artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getVersion());
        }
    }

    return dependencies;
}
 
Example 18
Source File: MavenProjectUtil.java    From boost with Eclipse Public License 1.0 4 votes vote down vote up
public static Map<String, String> getAllDependencies(MavenProject project, RepositorySystem repoSystem,
        RepositorySystemSession repoSession, List<RemoteRepository> remoteRepos, BoostLogger logger)
        throws ArtifactDescriptorException {
    logger.debug("Processing project for dependencies.");
    Map<String, String> dependencies = new HashMap<String, String>();

    for (Artifact artifact : project.getArtifacts()) {
        logger.debug("Found dependency while processing project: " + artifact.getGroupId() + ":"
                + artifact.getArtifactId() + ":" + artifact.getVersion() + ":" + artifact.getType() + ":"
                + artifact.getScope());

        if (artifact.getType().equals("war")) {
            logger.debug("Resolving transitive booster dependencies for war");
            org.eclipse.aether.artifact.Artifact pomArtifact = new DefaultArtifact(artifact.getGroupId(),
                    artifact.getArtifactId(), "pom", artifact.getVersion());

            List<org.eclipse.aether.artifact.Artifact> warArtifacts = getWarArtifacts(pomArtifact, repoSystem,
                    repoSession, remoteRepos);

            for (org.eclipse.aether.artifact.Artifact warArtifact : warArtifacts) {
                // Only add booster dependencies for this war. Anything else
                // like datasource
                // dependencies must be explicitly defined by this project.
                // This is to allow the
                // current project to have full control over those optional
                // dependencies.
                if (warArtifact.getGroupId().equals(AbstractBoosterConfig.BOOSTERS_GROUP_ID)) {
                    logger.debug("Found booster dependency: " + warArtifact.getGroupId() + ":"
                            + warArtifact.getArtifactId() + ":" + warArtifact.getVersion());

                    dependencies.put(warArtifact.getGroupId() + ":" + warArtifact.getArtifactId(),
                            warArtifact.getVersion());
                }
            }

        } else {
            dependencies.put(artifact.getGroupId() + ":" + artifact.getArtifactId(), artifact.getVersion());
        }
    }

    return dependencies;
}
 
Example 19
Source File: DeployMojoSupport.java    From ci.maven with Apache License 2.0 4 votes vote down vote up
protected void installLooseConfigEar(MavenProject proj, LooseConfigData config) throws Exception {
    LooseEarApplication looseEar = new LooseEarApplication(proj, config);
    looseEar.addSourceDir();
    looseEar.addApplicationXmlFile();

    Set<Artifact> artifacts = proj.getArtifacts();
    log.debug("Number of compile dependencies for " + proj.getArtifactId() + " : " + artifacts.size());

    for (Artifact artifact : artifacts) {
        if ("compile".equals(artifact.getScope()) || "runtime".equals(artifact.getScope())) {
            if (!isReactorMavenProject(artifact)) {
                if (looseEar.isEarSkinnyWars() && "war".equals(artifact.getType())) {
                    throw new MojoExecutionException(
                            "Unable to create loose configuration for the EAR application with skinnyWars package from "
                                    + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
                                    + artifact.getVersion()
                                    + ". Please set the looseApplication configuration parameter to false and try again.");
                }
                looseEar.addModuleFromM2(resolveArtifact(artifact));
            } else {
                MavenProject dependencyProject = getReactorMavenProject(artifact);
                switch (artifact.getType()) {
                case "jar":
                    looseEar.addJarModule(dependencyProject);
                    break;
                case "ejb":
                    looseEar.addEjbModule(dependencyProject);
                    break;
                case "war":
                    Element warArchive = looseEar.addWarModule(dependencyProject,
                            getWarSourceDirectory(dependencyProject));
                    if (looseEar.isEarSkinnyWars()) {
                        // add embedded lib only if they are not a compile dependency in the ear
                        // project.
                        addSkinnyWarLib(warArchive, dependencyProject, looseEar);
                    } else {
                        addEmbeddedLib(warArchive, dependencyProject, looseEar, "/WEB-INF/lib/");
                    }
                    break;
                case "rar":
                    Element rarArchive = looseEar.addRarModule(dependencyProject);
                    addEmbeddedLib(rarArchive, dependencyProject, looseEar, "/");
                    break;
                default:
                    // use the artifact from local .m2 repo
                    looseEar.addModuleFromM2(resolveArtifact(artifact));
                    break;
                }
            }
        }
    }

    // add Manifest file
    File manifestFile = MavenProjectUtil.getManifestFile(proj, "maven-ear-plugin");
    looseEar.addManifestFile(manifestFile);
}
 
Example 20
Source File: ProjectDependencies.java    From wisdom with Apache License 2.0 2 votes vote down vote up
/**
 * Creates the project dependencies instance from a Maven Project.
 *
 * @param project the maven project
 */
public ProjectDependencies(MavenProject project) {
    this(project.getDependencyArtifacts(), project.getArtifacts());
}