org.apache.maven.project.ProjectBuilder Java Examples

The following examples show how to use org.apache.maven.project.ProjectBuilder. 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: 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 #3
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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: ExecMojoTest.java    From exec-maven-plugin with Apache License 2.0 5 votes vote down vote up
private void setUpProject( File pomFile, ExecMojo 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 );

    mojo.setBasedir( File.createTempFile( "mvn-temp", "txt" ).getParentFile() );

    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() );

    mojo.setProject( project );

    mojo.setLog( new SystemStreamLog()
    {
        public boolean isDebugEnabled()
        {
            return true;
        }
    } );
}
 
Example #12
Source File: CodeGenMojoTest.java    From copybook4java with MIT License 5 votes vote down vote up
private Mojo lookupConfiguredMojo(String goal, File pom) throws Exception
{
    MavenExecutionRequest request = new DefaultMavenExecutionRequest();
    request.setBaseDirectory(pom.getParentFile());
    ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
    // Fix for bug: https://git-wip-us.apache.org/repos/asf?p=maven-plugin-testing.git;a=commit;h=3cd5f47c586499e438a3f9393304ac9d1f9a7f53
    configuration.setRepositorySession(new DefaultRepositorySystemSession());
    MavenProject project = lookup(ProjectBuilder.class).build(pom, configuration).getProject();
    return super.lookupConfiguredMojo(project, goal);
}
 
Example #13
Source File: BetterAbstractMojoTestCase.java    From repairnator 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 #14
Source File: GolangMojoCfgTest.java    From mvn-golang with Apache License 2.0 5 votes vote down vote up
private <T> T findMojo(final Class<T> klazz, final String pomName, final String goal) throws Exception {
  final File pomFile = new File(GolangMojoCfgTest.class.getResource(pomName).toURI());
  final MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
  final ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
  buildingRequest.setSystemProperties(System.getProperties());
  final ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
  final MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
  return klazz.cast(this.lookupConfiguredMojo(project, goal));
}
 
Example #15
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 #16
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 #17
Source File: MavenEmbedder.java    From netbeans with Apache License 2.0 5 votes vote down vote up
MavenEmbedder(EmbedderConfiguration configuration) throws ComponentLookupException {
    embedderConfiguration = configuration;
    plexus = configuration.getContainer();
    this.maven = (DefaultMaven) plexus.lookup(Maven.class);
    this.projectBuilder = plexus.lookup(ProjectBuilder.class);
    this.repositorySystem = plexus.lookup(RepositorySystem.class);
    this.settingsBuilder = plexus.lookup(SettingsBuilder.class);
    this.populator = plexus.lookup(MavenExecutionRequestPopulator.class);
    settingsDecrypter = plexus.lookup(SettingsDecrypter.class);
}
 
Example #18
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 #19
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 #20
Source File: JCasGenMojoTest.java    From uima-uimaj with Apache License 2.0 4 votes vote down vote up
public void test(String projectName, String... types) throws Exception {

    File projectSourceDirectory = getTestFile("src/test/resources/" + projectName);
    File projectDirectory = getTestFile("target/project-" + projectName + "-test");

    // Stage project to target folder
    FileUtils.copyDirectoryStructure(projectSourceDirectory, projectDirectory);
    
    File pomFile = new File(projectDirectory, "/pom.xml");
    assertNotNull(pomFile);
    assertTrue(pomFile.exists());

    // create the MavenProject from the pom.xml file
    MavenExecutionRequest executionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest buildingRequest = executionRequest.getProjectBuildingRequest();
    ProjectBuilder projectBuilder = this.lookup(ProjectBuilder.class);
    MavenProject project = projectBuilder.build(pomFile, buildingRequest).getProject();
    assertNotNull(project);

    // copy resources
    File source = new File(projectDirectory, "src/main/resources");
    if (source.exists()) {
      FileUtils.copyDirectoryStructure(source, new File(project.getBuild().getOutputDirectory()));
    }
    
    // load the Mojo
    JCasGenMojo generate = (JCasGenMojo) this.lookupConfiguredMojo(project, "generate");
    assertNotNull(generate);

    // set the MavenProject on the Mojo (AbstractMojoTestCase does not do this by default)
    setVariableValueToObject(generate, "project", project);

    // execute the Mojo
    generate.execute();

    // check that the Java files have been generated
    File jCasGenDirectory = new File(project.getBasedir(), "target/generated-sources/jcasgen");
    
    // Record all the files that were generated
    DirectoryScanner ds = new DirectoryScanner();
    ds.setBasedir(jCasGenDirectory);
    ds.setIncludes(new String[] { "**/*.java" });
    ds.scan();
    List<File> files = new ArrayList<>();
    for (String scannedFile : ds.getIncludedFiles()) {
      files.add(new File(ds.getBasedir(), scannedFile));
    }
    
    for (String type : types) {
      File wrapperFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + ".java");
      // no _type files in v3
//      File typeFile = new File(jCasGenDirectory + "/" + type.replace('.', '/') + "_Type.java");
      
      Assert.assertTrue(files.contains(wrapperFile));
      // no _type files in v3
//      Assert.assertTrue(files.contains(typeFile));
      
      files.remove(wrapperFile);
//      files.remove(typeFile);
    }
    
    // check that no extra files were generated
    Assert.assertTrue(files.isEmpty());

    // check that the generated sources are on the compile path
    Assert.assertTrue(project.getCompileSourceRoots().contains(jCasGenDirectory.getAbsolutePath()));
  }