org.apache.maven.project.ProjectBuildingRequest Java Examples

The following examples show how to use org.apache.maven.project.ProjectBuildingRequest. 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: 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 #2
Source File: ExecJavaMojo.java    From exec-maven-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the executable dependencies for the specified project
 * 
 * @param executablePomArtifact the project's POM
 * @return a set of Artifacts
 * @throws MojoExecutionException if a failure happens
 */
private Set<Artifact> resolveExecutableDependencies( Artifact executablePomArtifact )
    throws MojoExecutionException
{

    Set<Artifact> executableDependencies = new LinkedHashSet<>();
    try
    {
        ProjectBuildingRequest buildingRequest = getSession().getProjectBuildingRequest();
        
        MavenProject executableProject =
            this.projectBuilder.build( executablePomArtifact, buildingRequest ).getProject();

        for ( ArtifactResult artifactResult : dependencyResolver.resolveDependencies( buildingRequest, executableProject.getModel(), null ) )
        {
            executableDependencies.add( artifactResult.getArtifact() );
        }
    }
    catch ( Exception ex )
    {
        throw new MojoExecutionException( "Encountered problems resolving dependencies of the executable "
            + "in preparation for its execution.", ex );
    }

    return executableDependencies;
}
 
Example #3
Source File: ExecJavaMojoTest.java    From exec-maven-plugin with Apache License 2.0 6 votes vote down vote up
private void setUpProject( File pomFile, AbstractMojo mojo )
    throws Exception
{
    super.setUp();
    
    MockitoAnnotations.initMocks( this );
    
    ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class );
    when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest );
    MavenRepositorySystemSession repositorySession = new MavenRepositorySystemSession();
    repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( LOCAL_REPO ) );
    when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession );
    
    ProjectBuilder builder = lookup( ProjectBuilder.class );

    MavenProject project = builder.build( pomFile, buildingRequest ).getProject();
    // this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
    project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
    setVariableValueToObject( mojo, "project", project );
}
 
Example #4
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 #5
Source File: BaseCycloneDxMojo.java    From cyclonedx-maven-plugin with 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 #6
Source File: ForArtifactMojo.java    From depgraph-maven-plugin with 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 #7
Source File: AggregatingGraphFactoryTest.java    From depgraph-maven-plugin with Apache License 2.0 6 votes vote down vote up
private MavenProject createMavenProject(String artifactId) {
  MavenProject project = new MavenProject();
  project.setArtifactId(artifactId);
  // Make sure that we can modify the list later.
  project.setCollectedProjects(new ArrayList<>());

  DefaultArtifact artifact = new DefaultArtifact("groupId", artifactId, "version", "compile", "jar", "", null);
  project.setArtifact(artifact);

  RepositorySystemSession repositorySession = mock(RepositorySystemSession.class);
  ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
  when(projectBuildingRequest.getRepositorySession()).thenReturn(repositorySession);
  //noinspection deprecation
  project.setProjectBuildingRequest(projectBuildingRequest);

  return project;
}
 
Example #8
Source File: MavenGraphAdapterTest.java    From depgraph-maven-plugin with Apache License 2.0 6 votes vote down vote up
@BeforeEach
void before() throws Exception {
  Artifact projectArtifact = mock(Artifact.class);

  this.mavenProject = new MavenProject();
  this.mavenProject.setArtifact(projectArtifact);
  ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
  when(projectBuildingRequest.getRepositorySession()).thenReturn(mock(RepositorySystemSession.class));
  //noinspection deprecation
  this.mavenProject.setProjectBuildingRequest(projectBuildingRequest);

  this.globalFilter = mock(ArtifactFilter.class);
  ArtifactFilter transitiveIncludeExcludeFilter = mock(ArtifactFilter.class);
  ArtifactFilter targetFilter = mock(ArtifactFilter.class);
  this.graphBuilder = GraphBuilder.create(ToStringNodeIdRenderer.INSTANCE);

  this.dependenciesResolver = mock(ProjectDependenciesResolver.class);
  DependencyResolutionResult dependencyResolutionResult = mock(DependencyResolutionResult.class);
  when(dependencyResolutionResult.getDependencyGraph()).thenReturn(mock(org.eclipse.aether.graph.DependencyNode.class));
  when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenReturn(dependencyResolutionResult);

  this.graphAdapter = new MavenGraphAdapter(this.dependenciesResolver, transitiveIncludeExcludeFilter, targetFilter, EnumSet.of(INCLUDED));
}
 
Example #9
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testResolveProjectArtifactsEmpty() throws MojoExecutionException {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final MavenSession session = mock(MavenSession.class);
    final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
    when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
    final List<ArtifactRepository> remoteRepositories = emptyList();
    when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);

    final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
    final MavenProject project = mock(MavenProject.class);

    final Configuration config = new Configuration(new CompositeSkipper(emptyList()),
            new CompositeSkipper(emptyList()), false, false, false, false);
    final Set<Artifact> resolved = resolver.resolveProjectArtifacts(project, config);
    assertEquals(emptySet(), resolved);
}
 
Example #10
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 #11
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 #12
Source File: BotsingMojo.java    From botsing with Apache License 2.0 6 votes vote down vote up
public List<Artifact> getDependencyTree(DependencyInputType dependencyType) throws MojoExecutionException {
	try {
		ProjectBuildingRequest buildingRequest = getProjectbuildingRequest(dependencyType);

		// TODO check if it is necessary to specify an artifact filter
		DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, null,
				reactorProjects);

		List<Artifact> artifactList = new ArrayList<Artifact>();
		addChildDependencies(rootNode, artifactList);

		return artifactList;

	} catch (DependencyGraphBuilderException e) {
		throw new MojoExecutionException("Couldn't download artifact: " + e.getMessage(), e);
	}
}
 
Example #13
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveSignaturesEmpty() throws MojoExecutionException {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final MavenSession session = mock(MavenSession.class);
    final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
    when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
    final List<ArtifactRepository> remoteRepositories = emptyList();
    when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);
    final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
    final Map<Artifact, Artifact> resolvedSignatures = resolver.resolveSignatures(
            emptyList(), SignatureRequirement.NONE);
    assertEquals(resolvedSignatures.size(), 0);
}
 
Example #14
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 #15
Source File: AbstractInstallDriversMojoTest.java    From webdriverextensions-maven-plugin with Apache License 2.0 5 votes vote down vote up
private MavenProject getMavenProject(String pomPath) throws Exception {
    File pom = new File(pomPath);
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(pom);
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    return lookup(ProjectBuilder.class).build(pom, configuration).getProject();
}
 
Example #16
Source File: YeomanMojoTest.java    From yeoman-maven-plugin with Apache License 2.0 5 votes vote down vote up
private MavenProject getMavenProject(String pomPath) throws Exception {
    File pom = new File(pomPath);
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setPom(pom);
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    return lookup( ProjectBuilder.class ).build( pom, configuration ).getProject();
}
 
Example #17
Source File: InstallDeployTest.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
private MavenProject readMavenProject(File basedir, Properties properties) throws Exception {
  File pom = new File(basedir, "pom.xml");
  MavenExecutionRequest request = new DefaultMavenExecutionRequest();
  request.setUserProperties(properties);
  request.setBaseDirectory(basedir);
  ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
  configuration.setRepositorySession(new DefaultRepositorySystemSession());
  MavenProject project = mojos.lookup(ProjectBuilder.class).build(pom, configuration).getProject();
  Assert.assertNotNull(project);
  return project;
}
 
Example #18
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 #19
Source File: AbstractWildFlyMojoTest.java    From wildfly-maven-plugin with GNU Lesser General Public License v2.1 5 votes vote down vote up
public MavenProject readMavenProject(Path pom)
        throws Exception {
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(pom.getParent().toFile());
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    configuration.setRepositorySession(new DefaultRepositorySystemSession());
    MavenProject project = rule.lookup(ProjectBuilder.class).build(pom.toFile(), configuration).getProject();
    Assert.assertNotNull(project);
    return project;
}
 
Example #20
Source File: JBBPGenerateMojoTest.java    From java-binary-block-parser with Apache License 2.0 5 votes vote down vote up
private JBBPGenerateMojo findMojo(final String pomName, final String goal) throws Exception {
  final File pomFile = new File(this.getClass().getResource(pomName).toURI());
  final MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
  final ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
  final ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
  final MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
  return (JBBPGenerateMojo) this.lookupConfiguredMojo(project, goal);
}
 
Example #21
Source File: FlattenModelResolver.java    From flatten-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * The constructor.
 * @param localRepository is the local repository.
 * @param artifactFactory is the factory used to create project artifact instances.
 * @param dependencyResolver is the resolver to use for resolving version ranges.
 * @param projectBuildingRequest is the request for resolving version ranges against {@code dependencyResolver}.
 * @param reactorModels is the list of modules of the project being built.
 */
public FlattenModelResolver( ArtifactRepository localRepository, ArtifactFactory artifactFactory,
                            DependencyResolver dependencyResolver,
                            ProjectBuildingRequest projectBuildingRequest, List<MavenProject> reactorModels )
{
    this.localRepository = localRepository;
    this.artifactFactory = artifactFactory;
    this.depencencyResolver = dependencyResolver;
    this.projectBuildingRequest = projectBuildingRequest;
    this.reactorModelPool = new ReactorModelPool();
    reactorModelPool.addProjects( reactorModels );
}
 
Example #22
Source File: AbstractXmlMojoTestCase.java    From xml-maven-plugin with Apache License 2.0 5 votes vote down vote up
protected AbstractXmlMojo newMojo( String pDir )
        throws Exception
    {
        File testPom = new File( new File( getBasedir(), pDir ), "pom.xml" );
        
        MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
        ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
        ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
        MavenProject project = projectBuilder.build(testPom, buildingRequest).getProject();
//        final Build build = new Build();
//        build.setDirectory( "target" );
//        project.setBuild(build);
        project.getBuild().setDirectory("target");
        AbstractXmlMojo vm = (AbstractXmlMojo) lookupConfiguredMojo(project, getGoal());
        setVariableValueToObject( vm, "basedir", new File( getBasedir(), pDir ) );
        final Log log = new SilentLog();
        DefaultResourceManager rm = new DefaultResourceManager();
        setVariableValueToObject( rm, "logger", log );
        setVariableValueToObject( vm, "locator", rm );
        final Map<String, ResourceLoader> resourceLoaders = new HashMap<String, ResourceLoader>();
        resourceLoaders.put( "file", new FileResourceLoader() );
        resourceLoaders.put( "jar", new JarResourceLoader() );
        resourceLoaders.put( "classloader", new ThreadContextClasspathResourceLoader() );
        URLResourceLoader url = new URLResourceLoader();
        setVariableValueToObject( url, "logger", log );
        resourceLoaders.put( "url", url );
        setVariableValueToObject( rm, "resourceLoaders", resourceLoaders );

//        MavenProjectStub project = new MavenProjectStub()
//        {
//            public Build getBuild()
//            {
//                return build;
//            }
//        };
//        setVariableValueToObject( vm, "project", project );
        return vm;
    }
 
Example #23
Source File: BetterAbstractMojoTestCase.java    From markdown-page-generator-plugin with MIT License 5 votes vote down vote up
/**
 * As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom file
 * and creating the {@link MavenProject}.
 */
protected Mojo lookupConfiguredMojo(File pom, String goal) throws Exception {
    assertNotNull(pom);
    assertTrue(pom.exists());

    ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest();
    ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();

    return lookupConfiguredMojo(project, goal);
}
 
Example #24
Source File: BetterMojoRule.java    From swaggerhub-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom file
 * and creating the {@link MavenProject}.
 */
public Mojo lookupConfiguredMojo(File pom, String goal) throws Exception {
    assertNotNull(pom);
    assertTrue(pom.exists());

    ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest();
    ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();

    return lookupConfiguredMojo(project, goal);
}
 
Example #25
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 #26
Source File: NbMavenProjectImpl.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * replacement for MavenProject.getParent() which has bad long term memory behaviour. We offset it by recalculating/reparsing everything
 * therefore should not be used lightly!
 * pass a MavenProject instance and current configuration and other settings will be applied when loading the parent.
 * @param project
 * @return null or the parent mavenproject
 */

public MavenProject loadParentOf(MavenEmbedder embedder, MavenProject project) throws ProjectBuildingException {

    MavenProject parent = null;
    ProjectBuilder builder = embedder.lookupComponent(ProjectBuilder.class);
    MavenExecutionRequest req = embedder.createMavenExecutionRequest();
    M2Configuration active = configProvider.getActiveConfiguration();
    req.addActiveProfiles(active.getActivatedProfiles());
    req.setNoSnapshotUpdates(true);
    req.setUpdateSnapshots(false);
    req.setInteractiveMode(false);
    req.setRecursive(false);
    req.setOffline(true);
    //#238800 important to merge, not replace
    Properties uprops = req.getUserProperties();
    uprops.putAll(MavenProjectCache.createUserPropsForProjectLoading(active.getProperties()));
    req.setUserProperties(uprops);
    
    ProjectBuildingRequest request = req.getProjectBuildingRequest();
    request.setRemoteRepositories(project.getRemoteArtifactRepositories());
    DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class);
    
    request.setRepositorySession(maven.newRepositorySession(req));

    if (project.getParentFile() != null) {
        parent = builder.build(project.getParentFile(), request).getProject();
    } else if (project.getModel().getParent() != null) {
        parent = builder.build(project.getParentArtifact(), request).getProject();
    }
    //clear the project building request, it references multiple Maven Models via the RepositorySession cache
    //is not used in maven itself, most likely used by m2e only..
    if (parent != null) {
        parent.setProjectBuildingRequest(null);
    }
    MavenEmbedder.normalizePaths(parent);
    return parent;
}
 
Example #27
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 #28
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 #29
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 #30
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;
}