Java Code Examples for org.apache.maven.model.building.ModelBuildingResult

The following examples show how to use org.apache.maven.model.building.ModelBuildingResult. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
    if (workspaceResolver != null) {
        request.setWorkspaceModelResolver(workspaceResolver);
        final Model requestModel = getModel(request);
        try {
            if (requestModel != null && workspaceResolver.resolveRawModel(ModelUtils.getGroupId(requestModel),
                    requestModel.getArtifactId(), ModelUtils.getVersion(requestModel)) != null) {
                completeWorkspaceProjectBuildRequest(request);
            }
        } catch (UnresolvableModelException e) {
            // ignore
        }
    }
    return builder.build(request);
}
 
Example 2
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 6 votes vote down vote up
/**
     * Creates a list of POM models in an inheritance lineage.
     * Each resulting model is "raw", so contains no interpolation or inheritance.
     * In particular beware that groupId and/or version may be null if inherited from a parent; use {@link Model#getParent} to resolve.
     * Internally calls <code>executeModelBuilder</code> so if you need to call both just use the execute method.
     * @param pom a POM to inspect
     * @param embedder an embedder to use
     * @return a list of models, starting with the specified POM, going through any parents, finishing with the Maven superpom (with a null artifactId)
     * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported
     */
    public List<Model> createModelLineage(File pom) throws ModelBuildingException {
        ModelBuildingResult res = executeModelBuilder(pom);
        List<Model> toRet = new ArrayList<Model>();

        for (String id : res.getModelIds()) {
            Model m = res.getRawModel(id);
            normalizePath(m);
            toRet.add(m);
        }
//        for (ModelProblem p : res.getProblems()) {
//            System.out.println("problem=" + p);
//            if (p.getException() != null) {
//                p.getException().printStackTrace();
//            }
//        }
        return toRet;
    }
 
Example 3
Source Project: netbeans   Source File: NBModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request) throws ModelBuildingException {
    ModelBuildingResult toRet = super.build(request);
    Model eff = toRet.getEffectiveModel();
    InputSource source = new InputSource();
    source.setLocation("");
    InputLocation location = new InputLocation(-1, -1, source);
    eff.setLocation(NETBEANS_PROFILES, location);
    for (String id : toRet.getModelIds()) {
        Model mdl = toRet.getRawModel(id);
        for (Profile p : mdl.getProfiles()) {
            source.setLocation(source.getLocation() + "|" + p.getId());
        }
    }
    return toRet;
}
 
Example 4
Source Project: repairnator   Source File: MavenHelper.java    License: 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 5
public ModelBuildingResult build( ModelBuildingRequest buildingRequest, ProfileInjector customInjector, ProfileSelector customSelector )
    throws ModelBuildingException
{
    // note: there is neither DefaultModelBuilder.get*(), nor DefaultModelBuilder.clone()
    return new DefaultModelBuilderFactory().newInstance()
        .setProfileInjector( customInjector )
        .setProfileSelector( customSelector )
        // apply currently active ModelProcessor etc. to support extensions like jgitver
        .setDependencyManagementImporter( dependencyManagementImporter )
        .setDependencyManagementInjector( dependencyManagementInjector )
        .setInheritanceAssembler( inheritanceAssembler )
        .setLifecycleBindingsInjector( lifecycleBindingsInjector )
        .setModelInterpolator( modelInterpolator )
        .setModelNormalizer( modelNormalizer )
        .setModelPathTranslator( modelPathTranslator )
        .setModelProcessor( modelProcessor )
        .setModelUrlNormalizer( modelUrlNormalizer )
        .setModelValidator( modelValidator )
        .setPluginConfigurationExpander( pluginConfigurationExpander )
        .setPluginManagementInjector( pluginManagementInjector )
        .setReportConfigurationExpander( reportConfigurationExpander )
        .setReportingConverter( reportingConverter )
        .setSuperPomProvider( superPomProvider )
        .build( buildingRequest );
}
 
Example 6
@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 7
Source Project: netbeans   Source File: NbMavenProjectImpl.java    License: Apache License 2.0 5 votes vote down vote up
public Model getRawModel() throws ModelBuildingException {
    synchronized(MODEL_LOCK) {
        if(model == null) {
            MavenEmbedder projectEmbedder = EmbedderFactory.getProjectEmbedder();
            ModelBuildingResult br = projectEmbedder.executeModelBuilder(getPOMFile());
            model = br.getRawModel();
        }
        return model;
    }
}
 
Example 8
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param pom
 * @return result object with access to effective pom model and raw models for each parent.
 * @throws ModelBuildingException if the POM or parents could not even be parsed; warnings are not reported
 */
public ModelBuildingResult executeModelBuilder(File pom) throws ModelBuildingException {
    ModelBuilder mb = lookupComponent(ModelBuilder.class);
    assert mb!=null : "ModelBuilder component not found in maven";
    ModelBuildingRequest req = new DefaultModelBuildingRequest();
    req.setPomFile(pom);
    req.setProcessPlugins(false);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setLocationTracking(true);
    req.setModelResolver(new NBRepositoryModelResolver(this));
    req.setSystemProperties(getSystemProperties());
    req.setUserProperties(embedderConfiguration.getUserProperties());
    return mb.build(req);
    
}
 
Example 9
/**
 * @return ModelBuilderThreadSafetyWorkaround with a reduced scope for this simple test
 */
private ModelBuilderThreadSafetyWorkaround buildModelBuilderThreadSafetyWorkaroundForTest()
{
    return new ModelBuilderThreadSafetyWorkaround() {
        @Override
        public ModelBuildingResult build(ModelBuildingRequest buildingRequest, ProfileInjector customInjector, ProfileSelector customSelector)
                throws ModelBuildingException {

            return new DefaultModelBuilderFactory().newInstance()
                .setProfileInjector( customInjector )
                .setProfileSelector( customSelector )
                .build( buildingRequest );
        }
    };
}
 
Example 10
Source Project: furnace   Source File: ProjectHelper.java    License: 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 11
Source Project: buck   Source File: Resolver.java    License: 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 12
Source Project: buck   Source File: Pom.java    License: 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 13
Source Project: cloud-opensource-java   Source File: LinkageMonitor.java    License: 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();
}
 
Example 14
Source Project: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public ModelBuildingResult build(ModelBuildingRequest request, ModelBuildingResult result) throws ModelBuildingException {
    return builder.build(request, result);
}