org.apache.maven.project.DefaultProjectBuildingRequest Java Examples

The following examples show how to use org.apache.maven.project.DefaultProjectBuildingRequest. 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 Project: cyclonedx-maven-plugin   Author: CycloneDX   File: BaseCycloneDxMojo.java    License: Apache License 2.0 6 votes vote down vote up
protected Set<Dependency> buildDependencyGraph(final Set<String> componentRefs) throws MojoExecutionException {
    final Set<Dependency> dependencies = new LinkedHashSet<>();
    final Collection<String> scope = new HashSet<>();
    if (includeCompileScope) scope.add("compile");
    if (includeProvidedScope) scope.add("provided");
    if (includeRuntimeScope) scope.add("runtime");
    if (includeSystemScope) scope.add("system");
    if (includeTestScope) scope.add("test");
    final ArtifactFilter artifactFilter = new CumulativeScopeArtifactFilter(scope);
    final ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
    buildingRequest.setProject(this.project);
    try {
        final DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter);
        buildDependencyGraphNode(componentRefs, dependencies, rootNode, null);
        final CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
        rootNode.accept(visitor);
        for (final DependencyNode dependencyNode : visitor.getNodes()) {
            buildDependencyGraphNode(componentRefs, dependencies, dependencyNode, null);
        }
    } catch (DependencyGraphBuilderException e) {
        throw new MojoExecutionException("An error occurred building dependency graph", e);
    }
    return dependencies;
}
 
Example #2
Source Project: nifi-maven   Author: apache   File: ExtensionClassLoaderFactory.java    License: Apache License 2.0 6 votes vote down vote up
private Set<Artifact> getNarDependencies(final Artifact narArtifact) throws MojoExecutionException, ProjectBuildingException {
    final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
    narRequest.setRepositorySession(repoSession);
    narRequest.setSystemProperties(System.getProperties());
    narRequest.setLocalRepository(localRepo);

    final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);

    final Set<Artifact> narDependencies = new TreeSet<>();
    gatherArtifacts(narResult.getProject(), narDependencies);
    narDependencies.remove(narArtifact);
    narDependencies.remove(project.getArtifact());

    getLog().debug("Found NAR dependency of " + narArtifact + ", which resolved to the following artifacts: " + narDependencies);
    return narDependencies;
}
 
Example #3
Source Project: depgraph-maven-plugin   Author: ferstl   File: ForArtifactMojo.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public MavenProject getProject() {
  ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(this.session.getProjectBuildingRequest());
  buildingRequest.setRepositorySession(this.session.getRepositorySession());
  buildingRequest.setProject(null);
  buildingRequest.setResolveDependencies(true);
  buildingRequest.setActiveProfileIds(this.profiles);

  DefaultArtifact artifact = new DefaultArtifact(this.groupId, this.artifactId, this.version, SCOPE_COMPILE, this.type, this.classifier, new DefaultArtifactHandler());
  try {
    return this.projectBuilder.build(artifact, buildingRequest).getProject();
  } catch (ProjectBuildingException e) {
    throw new IllegalStateException("Error while creating Maven project from Artifact '" + artifact + "'.", e);
  }

}
 
Example #4
Source Project: spring-init   Author: spring-projects-experimental   File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private ProjectBuildingRequest getProjectBuildingRequest(Properties properties)
		throws NoLocalRepositoryManagerException {
	DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
	DefaultRepositorySystemSession session = createSession(properties);
	projectBuildingRequest.setRepositoryMerging(RepositoryMerging.REQUEST_DOMINANT);
	projectBuildingRequest.setRemoteRepositories(mavenRepositories(properties));
	projectBuildingRequest.getRemoteRepositories()
			.addAll(mavenRepositories(settings));
	projectBuildingRequest.setRepositorySession(session);
	projectBuildingRequest.setProcessPlugins(false);
	projectBuildingRequest.setBuildStartTime(new Date());
	projectBuildingRequest.setUserProperties(properties);
	projectBuildingRequest.setSystemProperties(System.getProperties());
	return projectBuildingRequest;
}
 
Example #5
Source Project: quarkus   Author: quarkusio   File: CreateProjectMojo.java    License: Apache License 2.0 5 votes vote down vote up
private void createMavenWrapper(File createdPomFile, Properties props) {
    try {
        // we need to modify the maven environment used by the wrapper plugin since the project could have been
        // created in a directory other than the current
        MavenProject newProject = projectBuilder.build(
                createdPomFile, new DefaultProjectBuildingRequest(session.getProjectBuildingRequest())).getProject();

        MavenExecutionRequest newExecutionRequest = DefaultMavenExecutionRequest.copy(session.getRequest());
        newExecutionRequest.setBaseDirectory(createdPomFile.getParentFile());

        MavenSession newSession = new MavenSession(session.getContainer(), session.getRepositorySession(),
                newExecutionRequest, session.getResult());
        newSession.setCurrentProject(newProject);

        setProxySystemPropertiesFromSession();

        executeMojo(
                plugin(
                        groupId("io.takari"),
                        artifactId("maven"),
                        version(ToolsUtils.getMavenWrapperVersion(props))),
                goal("wrapper"),
                configuration(
                        element(name("maven"), ToolsUtils.getProposedMavenVersion(props))),
                executionEnvironment(
                        newProject,
                        newSession,
                        pluginManager));
    } catch (Exception e) {
        // no reason to fail if the wrapper could not be created
        getLog().error("Unable to install the Maven wrapper (./mvnw) in the project", e);
    }
}
 
Example #6
Source Project: component-runtime   Author: Talend   File: ArtifactTransformer.java    License: Apache License 2.0 5 votes vote down vote up
private ArtifactResult doResolve(final ArtifactResolver resolver, final Artifact art, final MavenSession session)
        throws ArtifactResolverException {
    final ProjectBuildingRequest request = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
    session
            .getTopLevelProject()
            .getPluginRepositories()
            .stream()
            .map(this::toArtifactRepo)
            .filter(it -> request
                    .getPluginArtifactRepositories()
                    .stream()
                    .noneMatch(a -> String.valueOf(a.getId()).equalsIgnoreCase(it.getId())))
            .forEach(it -> request.getRemoteRepositories().add(it));
    return resolver.resolveArtifact(request, art);
}
 
Example #7
Source Project: mvn-golang   Author: raydac   File: MavenUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Make resolve artifact project building request.
 *
 * @param session maven session, must not be null
 * @param remoteRepositories list of remote repositories, must not be null and
 * can't contain null
 * @return created request, must not be null
 */
@Nonnull
public static ProjectBuildingRequest makeResolveArtifactProjectBuildingRequest(
        @Nonnull final MavenSession session,
        @Nonnull @MustNotContainNull final List<ArtifactRepository> remoteRepositories
) {
  final ProjectBuildingRequest result = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
  result.setRemoteRepositories(remoteRepositories);
  result.setLocalRepository(session.getLocalRepository());
  return result;
}
 
Example #8
Source Project: spring-cloud-function   Author: spring-cloud   File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private ProjectBuildingRequest getProjectBuildingRequest(Properties properties)
		throws NoLocalRepositoryManagerException {
	DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
	DefaultRepositorySystemSession session = createSession(properties);
	projectBuildingRequest.setRepositoryMerging(RepositoryMerging.REQUEST_DOMINANT);
	projectBuildingRequest.setRemoteRepositories(mavenRepositories(properties));
	projectBuildingRequest.getRemoteRepositories()
			.addAll(mavenRepositories(this.settings));
	projectBuildingRequest.setRepositorySession(session);
	projectBuildingRequest.setProcessPlugins(false);
	projectBuildingRequest.setBuildStartTime(new Date());
	projectBuildingRequest.setUserProperties(properties);
	projectBuildingRequest.setSystemProperties(System.getProperties());
	return projectBuildingRequest;
}
 
Example #9
Source Project: flatten-maven-plugin   Author: mojohaus   File: CreateEffectivePomTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests method to create effective POM.
 *
 * @throws Exception if something goes wrong.
 */
@Test
public void testCreateEffectivePom()
    throws Exception
{

    String magicValue = "magic-value";
    Properties userProperties = new Properties();
    userProperties.setProperty( "cmd.test.property", magicValue );

    File pomFile = new File( "src/test/resources/cmdpropertysubstituion/pom.xml" );
    ArtifactRepository localRepository = new MavenArtifactRepository();
    localRepository.setLayout( new DefaultRepositoryLayout() );
    ArtifactFactory artifactFactory = new DefaultArtifactFactory();
    ArtifactHandlerManager artifactHandlerManager = new DefaultArtifactHandlerManager();
    setDeclaredField( artifactFactory, "artifactHandlerManager", artifactHandlerManager );
    Map<String, ArtifactHandler> artifactHandlers = new HashMap<String, ArtifactHandler>();
    setDeclaredField( artifactHandlerManager, "artifactHandlers", artifactHandlers );
    DefaultDependencyResolver depencencyResolver = new DefaultDependencyResolver();
    DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
    FlattenModelResolver resolver = new FlattenModelResolver( localRepository, artifactFactory,
            depencencyResolver, projectBuildingRequest, Collections.<MavenProject>emptyList() );
    ModelBuildingRequest buildingRequest =
        new DefaultModelBuildingRequest().setPomFile( pomFile ).setModelResolver( resolver ).setUserProperties( userProperties );
    setDeclaredField( tested, "modelBuilderThreadSafetyWorkaround", buildModelBuilderThreadSafetyWorkaroundForTest() );
    Model effectivePom = tested.createEffectivePom( buildingRequest, false, FlattenMode.defaults );
    assertThat( effectivePom.getName() ).isEqualTo( magicValue );
}
 
Example #10
Source Project: nifi-maven   Author: apache   File: ExtensionClassLoaderFactory.java    License: Apache License 2.0 5 votes vote down vote up
private String findProvidedDependencyVersion(final Set<Artifact> artifacts, final String groupId, final String artifactId) {
    final ProjectBuildingRequest projectRequest = new DefaultProjectBuildingRequest();
    projectRequest.setRepositorySession(repoSession);
    projectRequest.setSystemProperties(System.getProperties());
    projectRequest.setLocalRepository(localRepo);

    for (final Artifact artifact : artifacts) {
        final Set<Artifact> artifactDependencies = new HashSet<>();
        try {
            final ProjectBuildingResult projectResult = projectBuilder.build(artifact, projectRequest);
            gatherArtifacts(projectResult.getProject(), artifactDependencies);
            getLog().debug("For Artifact " + artifact + ", found the following dependencies:");
            artifactDependencies.forEach(dep -> getLog().debug(dep.toString()));

            for (final Artifact dependency : artifactDependencies) {
                if (dependency.getGroupId().equals(groupId) && dependency.getArtifactId().equals(artifactId)) {
                    getLog().debug("Found version of " + groupId + ":" + artifactId + " to be " + artifact.getVersion());
                    return artifact.getVersion();
                }
            }
        } catch (final Exception e) {
            getLog().warn("Unable to construct Maven Project for " + artifact + " when attempting to determine the expected version of NiFi API");
            getLog().debug("Unable to construct Maven Project for " + artifact + " when attempting to determine the expected version of NiFi API", e);
        }
    }

    return null;
}
 
Example #11
Source Project: syndesis   Author: syndesisio   File: ExtractConnectorDescriptorsMojo.java    License: Apache License 2.0 4 votes vote down vote up
@Override
@SuppressWarnings({"PMD.EmptyCatchBlock", "PMD.CyclomaticComplexity"})
public void execute() throws MojoExecutionException, MojoFailureException {

    ArrayNode root = new ArrayNode(JsonNodeFactory.instance);

    URLClassLoader classLoader = null;
    try {
        PluginDescriptor desc = (PluginDescriptor) getPluginContext().get("pluginDescriptor");
        List<Artifact> artifacts = desc.getArtifacts();
        ProjectBuildingRequest buildingRequest =
            new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
        buildingRequest.setRemoteRepositories(remoteRepositories);
        for (Artifact artifact : artifacts) {
            ArtifactResult result = artifactResolver.resolveArtifact(buildingRequest, artifact);
            File jar = result.getArtifact().getFile();
            classLoader = createClassLoader(jar);
            if (classLoader == null) {
                throw new IOException("Can not create classloader for " + jar);
            }
            ObjectNode entry = new ObjectNode(JsonNodeFactory.instance);
            addConnectorMeta(entry, classLoader);
            addComponentMeta(entry, classLoader);
            if (entry.size() > 0) {
                addGav(entry, artifact);
                root.add(entry);
            }
        }
        if (root.size() > 0) {
            saveCamelMetaData(root);
        }
    } catch (ArtifactResolverException | IOException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    } finally {
        if (classLoader != null) {
            try {
                classLoader.close();
            } catch (IOException ignored) {

            }
        }
    }
}
 
Example #12
Source Project: nifi-maven   Author: apache   File: NarProvidedDependenciesMojo.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        // find the nar dependency
        Artifact narArtifact = null;
        for (final Artifact artifact : project.getDependencyArtifacts()) {
            if (NAR.equals(artifact.getType())) {
                // ensure the project doesn't have two nar dependencies
                if (narArtifact != null) {
                    throw new MojoExecutionException("Project can only have one NAR dependency.");
                }

                // record the nar dependency
                narArtifact = artifact;
            }
        }

        // ensure there is a nar dependency
        if (narArtifact == null) {
            throw new MojoExecutionException("Project does not have any NAR dependencies.");
        }

        // build the project for the nar artifact
        final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
        narRequest.setRepositorySession(repoSession);
        narRequest.setSystemProperties(System.getProperties());

        final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);
        narRequest.setProject(narResult.getProject());

        // get the artifact handler for excluding dependencies
        final ArtifactHandler narHandler = excludesDependencies(narArtifact);
        narArtifact.setArtifactHandler(narHandler);

        // nar artifacts by nature includes dependencies, however this prevents the
        // transitive dependencies from printing using tools like dependency:tree.
        // here we are overriding the artifact handler for all nars so the
        // dependencies can be listed. this is important because nar dependencies
        // will be used as the parent classloader for this nar and seeing what
        // dependencies are provided is critical.
        final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>();
        narHandlerMap.put(NAR, narHandler);
        artifactHandlerManager.addHandlers(narHandlerMap);

        // get the dependency tree
        final DependencyNode root = dependencyGraphBuilder.buildDependencyGraph(narRequest, null);

        // write the appropriate output
        DependencyNodeVisitor visitor = null;
        if ("tree".equals(mode)) {
            visitor = new TreeWriter();
        } else if ("pom".equals(mode)) {
            visitor = new PomWriter();
        }

        // ensure the mode was specified correctly
        if (visitor == null) {
            throw new MojoExecutionException("The specified mode is invalid. Supported options are 'tree' and 'pom'.");
        }

        // visit and print the results
        root.accept(visitor);
        getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString());
    } catch (ProjectBuildingException | DependencyGraphBuilderException e) {
        throw new MojoExecutionException("Cannot build project dependency tree", e);
    }
}