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

The following examples show how to use org.apache.maven.model.building.ModelBuildingRequest. 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: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private Model getModel(ModelBuildingRequest request) {
    Model requestModel = request.getRawModel();
    if (requestModel == null) {
        if (request.getModelSource() != null) {
            try {
                requestModel = ModelUtils.readModel(request.getModelSource().getInputStream());
                request.setRawModel(requestModel);
                if (request.getPomFile() != null) {
                    requestModel.setPomFile(request.getPomFile());
                }
            } catch (IOException e) {
                // ignore
            }
        }
    }
    return requestModel;
}
 
Example 3
Source Project: quarkus   Source File: MavenModelBuilder.java    License: Apache License 2.0 6 votes vote down vote up
private void completeWorkspaceProjectBuildRequest(ModelBuildingRequest request) {
    final Set<String> addedProfiles = new HashSet<>();
    final List<Profile> profiles = request.getProfiles();
    profiles.forEach(p -> addedProfiles.add(p.getId()));

    activeSettingsProfiles.forEach(p -> {
        if (!addedProfiles.contains(p.getId())) {
            profiles.add(p);
            request.getActiveProfileIds().add(p.getId());
        }
    });

    request.getActiveProfileIds().addAll(mvnOptions.getActiveProfileIds());
    request.getInactiveProfileIds().addAll(mvnOptions.getInactiveProfileIds());
    request.setUserProperties(System.getProperties());
}
 
Example 4
Source Project: netbeans   Source File: MavenEmbedder.java    License: 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 5
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 6
Source Project: netbeans   Source File: ArtifactDependencyIndexCreator.java    License: 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 7
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 8
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 9
@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 10
Source Project: netbeans   Source File: RepositoryMavenCPProvider.java    License: 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 11
Source Project: netbeans   Source File: DependencyNode.java    License: 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 12
Source Project: netbeans   Source File: EffectivePomMD.java    License: 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 13
Source Project: netbeans   Source File: StatusProvider.java    License: 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 14
Source Project: flatten-maven-plugin   Source File: CiModelInterpolator.java    License: Apache License 2.0 5 votes vote down vote up
protected void interpolateObject(Object obj, Model model, File projectDir, ModelBuildingRequest config,
		ModelProblemCollector problems) {
	try {
		List<? extends ValueSource> valueSources = createValueSources(model, projectDir, config, problems);
		List<? extends InterpolationPostProcessor> postProcessors = createPostProcessors(model, projectDir, config);

		InterpolateObjectAction action = new InterpolateObjectAction(obj, valueSources, postProcessors, this,
				problems);

		AccessController.doPrivileged(action);
	} finally {
		getInterpolator().clearAnswers();
	}
}
 
Example 15
Source Project: flatten-maven-plugin   Source File: CiModelInterpolator.java    License: Apache License 2.0 5 votes vote down vote up
protected List<? extends InterpolationPostProcessor> createPostProcessors(final Model model, final File projectDir,
		final ModelBuildingRequest config) {
	List<InterpolationPostProcessor> processors = new ArrayList<InterpolationPostProcessor>(2);
	if (projectDir != null) {
		processors.add(new PathTranslatingPostProcessor(PROJECT_PREFIXES, TRANSLATED_PATH_EXPRESSIONS, projectDir,
				pathTranslator));
	}
	processors.add(new UrlNormalizingPostProcessor(urlNormalizer));
	return processors;
}
 
Example 16
Source Project: flatten-maven-plugin   Source File: FlattenMojo.java    License: Apache License 2.0 5 votes vote down vote up
private Model createResolvedPom( ModelBuildingRequest buildingRequest )
{
    LoggingModelProblemCollector problems = new LoggingModelProblemCollector( getLog() );
    Model originalModel = this.project.getOriginalModel().clone();
    if (this.flattenMode == FlattenMode.resolveCiFriendliesOnly) {
        return this.modelCiFriendlyInterpolator.interpolateModel( originalModel, this.project.getModel().getProjectDirectory(),
                                                        buildingRequest, problems );
    }
    return this.modelInterpolator.interpolateModel( originalModel, this.project.getModel().getProjectDirectory(),
                                                    buildingRequest, problems );
}
 
Example 17
Source Project: flatten-maven-plugin   Source File: FlattenMojo.java    License: 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 18
/**
 * 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 19
/**
 * @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 20
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 21
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 22
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);
}
 
Example 23
Source Project: flatten-maven-plugin   Source File: CiModelInterpolator.java    License: Apache License 2.0 4 votes vote down vote up
public Model interpolateModel(Model model, File projectDir, ModelBuildingRequest config,
		ModelProblemCollector problems) {
	interpolateObject(model, model, projectDir, config, problems);

	return model;
}
 
Example 24
Source Project: flatten-maven-plugin   Source File: FlattenMojo.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * This method creates the flattened POM what is the main task of this plugin.
 *
 * @param pomFile is the name of the original POM file to read and transform.
 * @return the {@link Model} of the flattened POM.
 * @throws MojoExecutionException if anything goes wrong (e.g. POM can not be processed).
 * @throws MojoFailureException   if anything goes wrong (logical error).
 */
protected Model createFlattenedPom( File pomFile ) throws MojoExecutionException, MojoFailureException
{

    ModelBuildingRequest buildingRequest = createModelBuildingRequest( pomFile );
    Model effectivePom = createEffectivePom( buildingRequest, isEmbedBuildProfileDependencies(), this.flattenMode );

    Model flattenedPom = new Model();

    // keep original encoding (we could also normalize to UTF-8 here)
    String modelEncoding = effectivePom.getModelEncoding();
    if ( StringUtils.isEmpty( modelEncoding ) )
    {
        modelEncoding = "UTF-8";
    }
    flattenedPom.setModelEncoding( modelEncoding );

    Model cleanPom = null;
    try {
        cleanPom = createCleanPom( effectivePom );
    }
    catch (Exception e) {
        throw new MojoExecutionException("failed to create a clean pom", e);
    }

    FlattenDescriptor descriptor = getFlattenDescriptor();
    Model originalPom = this.project.getOriginalModel();
    Model resolvedPom = this.project.getModel();
    Model interpolatedPom = createResolvedPom( buildingRequest );

    // copy the configured additional POM elements...

    for ( PomProperty<?> property : PomProperty.getPomProperties() )
    {
        if ( property.isElement() )
        {
            Model sourceModel = getSourceModel( descriptor, property, effectivePom, originalPom, resolvedPom,
                                                interpolatedPom, cleanPom );
            if ( sourceModel == null )
            {
                if ( property.isRequired() )
                {
                    throw new MojoFailureException( "Property " + property.getName()
                        + " is required and can not be removed!" );
                }
            }
            else
            {
                property.copy( sourceModel, flattenedPom );
            }
        }
    }

    return flattenedPom;
}
 
Example 25
Source Project: archiva   Source File: DummyLifecycleBindingsInjector.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void injectLifecycleBindings( Model model, ModelBuildingRequest modelBuildingRequest, ModelProblemCollector modelProblemCollector )
{
    // left intentionally blank
}
 
Example 26
Source Project: flatten-maven-plugin   Source File: CiInterpolator.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Interpolates expressions in the specified model. Note that implementations are free to either interpolate the
 * provided model directly or to create a clone of the model and interpolate the clone. Callers should always use
 * the returned model and must not rely on the input model being updated.
 *
 * @param model The model to interpolate, must not be {@code null}.
 * @param projectDir The project directory, may be {@code null} if the model does not belong to a local project but
 *            to some artifact's metadata.
 * @param request The model building request that holds further settings, must not be {@code null}.
 * @param problems The container used to collect problems that were encountered, must not be {@code null}.
 * @return The interpolated model, never {@code null}.
 */
Model interpolateModel( Model model, File projectDir, ModelBuildingRequest request,
                        ModelProblemCollector problems );