org.apache.maven.model.building.DefaultModelBuildingRequest Java Examples

The following examples show how to use org.apache.maven.model.building.DefaultModelBuildingRequest. 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: MavenHelper.java    From repairnator with MIT License 6 votes vote down vote up
public static Model readPomXml(File pomXml, String localMavenRepository) {
    ModelBuildingRequest req = new DefaultModelBuildingRequest();
    req.setProcessPlugins(true);
    req.setPomFile(pomXml);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setModelResolver(new RepositoryModelResolver(localMavenRepository));

    DefaultModelBuilder defaultModelBuilder = new DefaultModelBuilderFactory().newInstance();

    // we try to build the model, and if we fail, we try to get the raw model
    try {
        ModelBuildingResult modelBuildingResult = defaultModelBuilder.build(req);
        return modelBuildingResult.getEffectiveModel();
    } catch (ModelBuildingException e) {
        LOGGER.error("Error while building complete model. The raw model will be used. Error message: " + e.getMessage());
        return defaultModelBuilder.buildRawModel(pomXml, ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL, true).get();
    }

}
 
Example #2
Source File: VersionSubstitutingModelResolverTest.java    From cloud-opensource-java with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubstitution() throws ArtifactResolutionException, ModelBuildingException {

  // Google-cloud-bom 0.121.0-alpha imports google-auth-library-bom 0.19.0.
  DefaultArtifact googleCloudBom =
      new DefaultArtifact("com.google.cloud:google-cloud-bom:pom:0.121.0-alpha");
  ArtifactResult bomResult =
      repositorySystem.resolveArtifact(
          session, new ArtifactRequest(googleCloudBom, ImmutableList.of(CENTRAL), null));

  ImmutableMap<String, String> substitution =
      ImmutableMap.of(
          "com.google.auth:google-auth-library-bom",
          "0.18.0" // This is intentionally different from 0.19.0
          );
  VersionSubstitutingModelResolver resolver =
      new VersionSubstitutingModelResolver(
          session,
          null,
          repositorySystem,
          remoteRepositoryManager,
          ImmutableList.of(CENTRAL), // Needed when parent pom is not locally available
          substitution);

  ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
  modelRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
  modelRequest.setPomFile(bomResult.getArtifact().getFile());
  modelRequest.setModelResolver(resolver);
  modelRequest.setSystemProperties(System.getProperties()); // for Java version property

  ModelBuildingResult result = modelBuilder.build(modelRequest);
  DependencyManagement dependencyManagement =
      result.getEffectiveModel().getDependencyManagement();

  Truth.assertWithMessage(
          "Google-cloud-bom's google-auth-library part should be substituted for a different version.")
      .that(dependencyManagement.getDependencies())
      .comparingElementsUsing(dependencyToCoordinates)
      .contains("com.google.auth:google-auth-library-credentials:0.18.0");
}
 
Example #3
Source File: FlattenMojo.java    From flatten-maven-plugin with Apache License 2.0 5 votes vote down vote up
private ModelBuildingRequest createModelBuildingRequest( File pomFile )
{

    FlattenModelResolver resolver = new FlattenModelResolver( this.localRepository, this.artifactFactory,
        this.dependencyResolver, this.session.getProjectBuildingRequest(), getReactorModelsFromSession() );
    Properties userProperties = this.session.getUserProperties();
    List<String> activeProfiles = this.session.getRequest().getActiveProfiles();

    // @formatter:off
    ModelBuildingRequest buildingRequest =
        new DefaultModelBuildingRequest().setUserProperties( userProperties ).setSystemProperties( System.getProperties() ).setPomFile( pomFile ).setModelResolver( resolver ).setActiveProfileIds( activeProfiles );
    // @formatter:on
    return buildingRequest;
}
 
Example #4
Source File: CreateEffectivePomTest.java    From flatten-maven-plugin with 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 #5
Source File: ProjectHelper.java    From furnace with Eclipse Public License 1.0 5 votes vote down vote up
public Model loadPomFromFile(File pomFile, String... profiles)
{
   RepositorySystem system = mavenContainer.getRepositorySystem();
   Settings settings = mavenContainer.getSettings();
   DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings);
   final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest()
            .setSystemProperties(System.getProperties())
            .setPomFile(pomFile)
            .setActiveProfileIds(settings.getActiveProfiles());
   ModelBuilder builder = new DefaultModelBuilderFactory().newInstance();
   ModelBuildingResult result;
   try
   {
      request.setModelResolver(new MavenModelResolver(system, session,
               MavenRepositories.getRemoteRepositories(mavenContainer, settings)));
      result = builder.build(request);
   }
   // wrap exception message
   catch (ModelBuildingException e)
   {
      String pomPath = request.getPomFile().getAbsolutePath();
      StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size())
               .append(" problems while building POM model from ").append(pomPath).append("\n");

      int counter = 1;
      for (ModelProblem problem : e.getProblems())
      {
         sb.append(counter++).append("/ ").append(problem).append("\n");
      }

      throw new RuntimeException(sb.toString());
   }
   return result.getEffectiveModel();
}
 
Example #6
Source File: Resolver.java    From buck with Apache License 2.0 5 votes vote down vote up
private Model loadPomModel(Path pomFile) {
  DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
  request.setPomFile(pomFile.toFile());
  try {
    ModelBuildingResult result = modelBuilder.build(request);
    return result.getRawModel();
  } catch (ModelBuildingException | IllegalArgumentException e) {
    // IllegalArg can be thrown if the parent POM cannot be resolved.
    throw new RuntimeException(e);
  }
}
 
Example #7
Source File: Pom.java    From buck with Apache License 2.0 5 votes vote down vote up
private Model constructModel(File file, Model model) {
  ModelBuilder modelBuilder = MODEL_BUILDER_FACTORY.newInstance();

  try {
    ModelBuildingRequest req = new DefaultModelBuildingRequest().setPomFile(file);
    ModelBuildingResult modelBuildingResult = modelBuilder.build(req);

    Model constructed = Objects.requireNonNull(modelBuildingResult.getRawModel());

    return merge(model, constructed);
  } catch (ModelBuildingException e) {
    throw new RuntimeException(e);
  }
}
 
Example #8
Source File: LinkageMonitor.java    From cloud-opensource-java with Apache License 2.0 4 votes vote down vote up
/**
 * Returns a map from versionless coordinates to version for all pom.xml found in {@code
 * projectDirectory}.
 */
@VisibleForTesting
static ImmutableMap<String, String> findLocalArtifacts(
    RepositorySystem repositorySystem, RepositorySystemSession session, Path projectDirectory) {
  ImmutableMap.Builder<String, String> artifactToVersion = ImmutableMap.builder();
  Iterable<Path> paths = MoreFiles.fileTraverser().breadthFirst(projectDirectory);

  for (Path path : paths) {
    if (!path.getFileName().endsWith("pom.xml")) {
      continue;
    }

    // This path element check should not depend on directory name outside the project
    Path relativePath = path.isAbsolute() ? projectDirectory.relativize(path) : path;
    ImmutableSet<Path> elements = ImmutableSet.copyOf(relativePath);
    if (elements.contains(Paths.get("build")) || elements.contains(Paths.get("target"))) {
      // Exclude Gradle's build directory and Maven's target directory, which would contain irrelevant pom.xml such as
      // gax/build/tmp/expandedArchives/(... omit ...)/META-INF/maven/org.jacoco/org.jacoco.agent/pom.xml
      continue;
    }

    ModelBuildingRequest modelRequest = new DefaultModelBuildingRequest();
    modelRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    modelRequest.setProcessPlugins(false);
    modelRequest.setTwoPhaseBuilding(false);
    modelRequest.setPomFile(path.toFile());
    modelRequest.setModelResolver(
        new ProjectModelResolver(
            session,
            null,
            repositorySystem,
            new DefaultRemoteRepositoryManager(),
            ImmutableList.of(CENTRAL), // Needed when parent pom is not locally available
            null,
            null));
    // Profile activation needs JDK version through system properties
    // https://github.com/GoogleCloudPlatform/cloud-opensource-java/issues/923
    modelRequest.setSystemProperties(System.getProperties());

    try {
      ModelBuildingResult modelBuildingResult = modelBuilder.build(modelRequest);
      Model model = modelBuildingResult.getEffectiveModel();
      artifactToVersion.put(model.getGroupId() + ":" + model.getArtifactId(), model.getVersion());
    } catch (ModelBuildingException ex) {
      // Maven may fail to build pom.xml files found in irrelevant directories, such as "target"
      // and "test" directories of the project. Such failures can be ignored.
      logger.info("Ignoring bad model: " + path + ": " + ex.getMessage());
    }
  }
  return artifactToVersion.build();
}