org.apache.maven.project.ProjectBuildingResult Java Examples

The following examples show how to use org.apache.maven.project.ProjectBuildingResult. 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: ProjectHelper.java    From furnace with Eclipse Public License 1.0 6 votes vote down vote up
public List<Dependency> resolveDependenciesFromPOM(File pomFile) throws Exception
{
   PlexusContainer plexus = new PlexusContainer();
   List<Dependency> result;
   try
   {
      ProjectBuildingRequest request = getBuildingRequest(plexus);
      request.setResolveDependencies(true);
      ProjectBuilder builder = plexus.lookup(ProjectBuilder.class);
      ProjectBuildingResult build = builder.build(pomFile, request);
      result = build.getDependencyResolutionResult().getDependencies();
   }
   finally
   {
      plexus.shutdown();
   }
   return result;
}
 
Example #2
Source File: ExtensionClassLoaderFactory.java    From nifi-maven with 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 File: MavenEmbedder.java    From netbeans with Apache License 2.0 6 votes vote down vote up
public MavenExecutionResult readProjectWithDependencies(MavenExecutionRequest req, boolean useWorkspaceResolution) {
    if (useWorkspaceResolution) {
        req.setWorkspaceReader(new NbWorkspaceReader());
    }
    File pomFile = req.getPom();
    MavenExecutionResult result = new DefaultMavenExecutionResult();
    try {
        ProjectBuildingRequest configuration = req.getProjectBuildingRequest();
        configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
        configuration.setResolveDependencies(true);
        configuration.setRepositorySession(maven.newRepositorySession(req));
        ProjectBuildingResult projectBuildingResult = projectBuilder.build(pomFile, configuration);
        result.setProject(projectBuildingResult.getProject());
        result.setDependencyResolutionResult(projectBuildingResult.getDependencyResolutionResult());
    } catch (ProjectBuildingException ex) {
        //don't add the exception here. this should come out as a build marker, not fill
        //the error logs with msgs
        return result.addException(ex);
    }
    normalizePaths(result.getProject());
    return result;
}
 
Example #4
Source File: ArtifactDependencyIndexCreator.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private MavenProject load(ArtifactInfo ai) {
    try {
        Artifact projectArtifact = embedder.createArtifact(ai.getGroupId(), ai.getArtifactId(), ai.getVersion(), ai.getPackaging() != null ? ai.getPackaging() : "jar");
        ProjectBuildingRequest dpbr = embedder.createMavenExecutionRequest().getProjectBuildingRequest();
        //mkleint: remote repositories don't matter we use project embedder.
        dpbr.setRemoteRepositories(remoteRepos);
        dpbr.setProcessPlugins(false);
        dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

        ProjectBuildingResult res = embedder.buildProject(projectArtifact, dpbr);
        if (res.getProject() != null) {
            return res.getProject();
        } else {
            LOG.log(Level.FINER, "No project model from repository for {0}: {1}", new Object[] {ai, res.getProblems()});
        }
    } catch (ProjectBuildingException ex) {
        LOG.log(Level.FINER, "Failed to load project model from repository for {0}: {1}", new Object[] {ai, ex});
    } catch (Exception exception) {
        LOG.log(Level.FINER, "Failed to load project model from repository for " + ai, exception);
    }
    return null;
}
 
Example #5
Source File: SpringBootStarterMojo.java    From camel-spring-boot with Apache License 2.0 6 votes vote down vote up
private Set<String> filterIncludedArtifacts(Set<String> artifacts) {

        Set<Artifact> dependencies;
        try {
            Artifact artifact = project.getArtifactMap().get(getMainDepGroupId() + ":" + getMainDepArtifactId());
            ProjectBuildingResult result = projectBuilder.build(artifact, project.getProjectBuildingRequest());
            MavenProject prj = result.getProject();
            prj.setRemoteArtifactRepositories(project.getRemoteArtifactRepositories());
            dependencies = projectDependenciesResolver.resolve(prj, Collections.singleton(Artifact.SCOPE_COMPILE), session);
        } catch (Exception e) {
            throw new RuntimeException("Unable to build project dependency tree", e);
        }

        Set<String> included = new TreeSet<>();
        dependencies.stream()
                .filter(a -> !Artifact.SCOPE_TEST.equals(a.getScope()))
                .map(a -> a.getGroupId() + ":" + a.getArtifactId())
                .forEach(included::add);
        included.retainAll(artifacts);

        return included;
    }
 
Example #6
Source File: StatusProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static List<ModelProblem> runMavenValidationImpl(final File pom) {
    MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
    MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
    ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0); // 3.1 currently enables just <reporting> warning, see issue 223562 for details on why it's bad to show.
    req.setLocalRepository(embedder.getLocalRepository());
    List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
    req.setRemoteRepositories(remoteRepos);
    req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
    List<ModelProblem> problems;
    try {
        problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
    } catch (ProjectBuildingException x) {
        problems = new ArrayList<ModelProblem>();
        List<ProjectBuildingResult> results = x.getResults();
        if (results != null) { //one code point throwing ProjectBuildingException contains results,
            for (ProjectBuildingResult result : results) {
                problems.addAll(result.getProblems());
            }
        } else {
            // another code point throwing ProjectBuildingException doesn't contain results..
            Throwable cause = x.getCause();
            if (cause instanceof ModelBuildingException) {
                problems.addAll(((ModelBuildingException) cause).getProblems());
            }
        }
    }
    List<ModelProblem> toRet = new LinkedList<ModelProblem>();
    for (ModelProblem problem : problems) {
        if(ModelUtils.checkByCLIMavenValidationLevel(problem)) {
            toRet.add(problem);
        }
    }
    return toRet;
}
 
Example #7
Source File: AbstractGitFlowMojo.java    From gitflow-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Reloads project info from file
 * 
 * @param project
 * @return
 * @throws MojoFailureException
 */
private MavenProject reloadProject(MavenProject project) throws MojoFailureException {
    try {
    	ProjectBuildingResult result = projectBuilder.build(project.getFile(), mavenSession.getProjectBuildingRequest());
    	return result.getProject();
    } catch (Exception e) {
        throw new MojoFailureException("Error re-loading project info", e);
    }
}
 
Example #8
Source File: ExtensionClassLoaderFactory.java    From nifi-maven with 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 #9
Source File: RootLocationMojo.java    From build-helper-maven-plugin with MIT License 5 votes vote down vote up
/**
 * Finds the local root of the specified project.
 *
 * @param project The project to find the local root for.
 * @return The local root project (this may be the current project)
 */
private MavenProject getLocalRoot( final MavenProject project ) throws IOException
{
    MavenProject currentProject = project;
    MavenProject localRootProject = project;

    List<File> parentDirs = new ArrayList<>();
    getAllParentDirectories( project.getBasedir(), parentDirs );

    for (File parentDir : parentDirs) {
        getLog().debug( "Checking to see if " + parentDir + " is an aggregator parent" );
        File parent = new File( parentDir, "pom.xml" );
        if ( parent.isFile() )
        {
            try
            {
                final ProjectBuildingResult result = projectBuilder.build( parent, session.getProjectBuildingRequest() );
                final MavenProject parentProject = result.getProject();
                final String currentProjectCanonicalPath = currentProject.getBasedir().getCanonicalPath();
                if ( getAllChildModules( parentProject ).contains( currentProjectCanonicalPath ) )
                {
                    getLog().debug( parentDir + " is an aggregator parent of current project " );
                    localRootProject = parentProject;
                    currentProject = parentProject;
                }
                else
                {
                    getLog().debug( parentDir + " is not an aggregator parent of current project ("+getAllChildModules( parentProject )+"/"+currentProjectCanonicalPath+") " );
                }
            }
            catch ( ProjectBuildingException e )
            {
                getLog().warn( e );
            }
        }
    }

    getLog().debug( "Local aggregation root is " + localRootProject.getBasedir() );
    return localRootProject;
}
 
Example #10
Source File: DependencyResolver.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
public Model readModel(final Resource resource, final Properties properties) {
	initialize();
	try {
		ProjectBuildingRequest request = getProjectBuildingRequest(properties);
		request.setResolveDependencies(false);
		ProjectBuildingResult result = this.projectBuilder
				.build(new PropertiesModelSource(properties, resource), request);
		return result.getProject().getModel();
	}
	catch (Exception e) {
		throw new IllegalStateException("Failed to build model from effective pom",
				e);
	}
}
 
Example #11
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void setResult(ProjectBuildingResult pbr, Map<File, MavenExecutionResult> results) {
    DefaultMavenExecutionResult r = new DefaultMavenExecutionResult();
    normalizePaths(pbr.getProject());
    r.setProject(pbr.getProject());
        r.setDependencyResolutionResult(pbr.getDependencyResolutionResult());
    results.put(pbr.getPomFile(), r);
}
 
Example #12
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
public ProjectBuildingResult buildProject(Artifact art, ProjectBuildingRequest req) throws ProjectBuildingException {
    if (req.getLocalRepository() == null) {
       req.setLocalRepository(getLocalRepository());
    }
    MavenExecutionRequest request = createMavenExecutionRequest();
    req.setProcessPlugins(false);
    req.setRepositorySession(maven.newRepositorySession(request));
    ProjectBuildingResult res = projectBuilder.build(art, req);
    normalizePaths(res.getProject());
    return res;
}
 
Example #13
Source File: EffectivePomMD.java    From netbeans with Apache License 2.0 5 votes vote down vote up
static List<ModelProblem> runMavenValidationImpl(final File pom) {
    //TODO profiles based on current configuration??
    MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
    MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
    ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1); // currently enables just <reporting> warning
    req.setLocalRepository(embedder.getLocalRepository());
    List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
    req.setRemoteRepositories(remoteRepos);
    req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
    List<ModelProblem> problems;
    try {
        problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
    } catch (ProjectBuildingException x) {
        problems = new ArrayList<ModelProblem>();
        List<ProjectBuildingResult> results = x.getResults();
        if (results != null) { //one code point throwing ProjectBuildingException contains results,
            for (ProjectBuildingResult result : results) {
                problems.addAll(result.getProblems());
            }
        } else {
            // another code point throwing ProjectBuildingException doesn't contain results..
            Throwable cause = x.getCause();
            if (cause instanceof ModelBuildingException) {
                problems.addAll(((ModelBuildingException) cause).getProblems());
            }
        }
    }
    return problems;
}
 
Example #14
Source File: DependencyNode.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private Relocation getRelocation(org.netbeans.modules.maven.model.pom.Dependency d) {
    ProjectBuildingRequest dpbr = EmbedderFactory.getProjectEmbedder().createMavenExecutionRequest().getProjectBuildingRequest();
    dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    dpbr.setProcessPlugins(false);
    dpbr.setResolveDependencies(false);
    ArrayList<ArtifactRepository> remoteRepos = new ArrayList<>();
    dpbr.setRemoteRepositories(remoteRepos);
    String groupId = d.getGroupId();
    String artifactId = d.getArtifactId();
    String version = d.getVersion();
    if(groupId != null && !"".equals(groupId.trim()) &&
       artifactId != null && !"".equals(artifactId.trim()) &&
       version != null && !"".equals(version.trim())) 
    {           
        MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
        Artifact a = embedder.createProjectArtifact(groupId, artifactId, version);
        try {
            ProjectBuildingResult r = embedder.buildProject(a, dpbr);
            DistributionManagement dm = r.getProject().getDistributionManagement();
            return dm != null ? dm.getRelocation() : null;
        } catch (ProjectBuildingException ex) {
            // just log and hope for the best ...
            Logger.getLogger(DependencyNode.class.getName()).log(Level.INFO, version, ex);                
        }
    }
    return null;
}
 
Example #15
Source File: RepositoryMavenCPProvider.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private MavenProject loadMavenProject(File pom, String groupId, String artifactId, String version) {
        MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
        Artifact projectArtifact = embedder.createArtifact(groupId, artifactId, version,  "jar");
        try {
            ProjectBuildingRequest dpbr = embedder.createMavenExecutionRequest().getProjectBuildingRequest();
            dpbr.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
            
            dpbr.setProcessPlugins(false);
            dpbr.setResolveDependencies(true);
            ArrayList<ArtifactRepository> remoteRepos = new ArrayList<ArtifactRepository>();
//for project embedder doens't matter            
//            remoteRepos = RepositoryPreferences.getInstance().remoteRepositories();
            dpbr.setRemoteRepositories(remoteRepos);
            
            ProjectBuildingResult res = embedder.buildProject(projectArtifact, dpbr);
            if (res.getProject() != null) {
                return res.getProject();
            } else {
                LOG.log(Level.INFO, "No project model from repository for {0}: {1}", new Object[] {projectArtifact, res.getProblems()});
            }
        } catch (ProjectBuildingException ex) {
            LOG.log(Level.FINER, "Failed to load project model from repository for {0}: {1}", new Object[] {projectArtifact, ex});
        } catch (Exception exception) {
            LOG.log(Level.FINER, "Failed to load project model from repository for " + projectArtifact, exception);
        }
        return null;
    }
 
Example #16
Source File: DependencyResolver.java    From spring-init with Apache License 2.0 5 votes vote down vote up
public Model readModel(final Resource resource, final Properties properties) {
	initialize();
	try {
		ProjectBuildingRequest request = getProjectBuildingRequest(properties);
		request.setResolveDependencies(false);
		ProjectBuildingResult result = projectBuilder
				.build(new PropertiesModelSource(properties, resource), request);
		return result.getProject().getModel();
	}
	catch (Exception e) {
		throw new IllegalStateException("Failed to build model from effective pom",
				e);
	}
}
 
Example #17
Source File: RepositoryUtility.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
static MavenProject createMavenProject(Path pomFile, RepositorySystemSession session)
    throws MavenRepositoryException {
  // MavenCli's way to instantiate PlexusContainer
  ClassWorld classWorld =
      new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
  ContainerConfiguration containerConfiguration =
      new DefaultContainerConfiguration()
          .setClassWorld(classWorld)
          .setRealm(classWorld.getClassRealm("plexus.core"))
          .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
          .setAutoWiring(true)
          .setJSR250Lifecycle(true)
          .setName("linkage-checker");
  try {
    PlexusContainer container = new DefaultPlexusContainer(containerConfiguration);

    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest projectBuildingRequest =
        mavenExecutionRequest.getProjectBuildingRequest();

    projectBuildingRequest.setRepositorySession(session);

    // Profile activation needs properties such as JDK version
    Properties properties = new Properties(); // allowing duplicate entries
    properties.putAll(projectBuildingRequest.getSystemProperties());
    properties.putAll(OsProperties.detectOsProperties());
    properties.putAll(System.getProperties());
    projectBuildingRequest.setSystemProperties(properties);

    ProjectBuilder projectBuilder = container.lookup(ProjectBuilder.class);
    ProjectBuildingResult projectBuildingResult =
        projectBuilder.build(pomFile.toFile(), projectBuildingRequest);
    return projectBuildingResult.getProject();
  } catch (PlexusContainerException | ComponentLookupException | ProjectBuildingException ex) {
    throw new MavenRepositoryException(ex);
  }
}
 
Example #18
Source File: NarProvidedDependenciesMojo.java    From nifi-maven with 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);
    }
}