Java 类org.apache.maven.model.building.ModelBuildingRequest 实例源码

项目:incubator-netbeans    文件:MavenEmbedder.java   
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;
}
项目:incubator-netbeans    文件:NBModelBuilder.java   
@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;
}
项目:incubator-netbeans    文件:ArtifactDependencyIndexCreator.java   
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;
}
项目:marmotta    文件:RefPackMojo.java   
private Model getArtifactModel(Artifact artifact) {
    org.apache.maven.artifact.Artifact mavenArtifact = artifactFactory.createArtifact(artifact.getGroupId(),artifact.getArtifactId(),artifact.getVersion(),"runtime",artifact.getExtension());

    DefaultProjectBuildingRequest req = new DefaultProjectBuildingRequest();
    req.setRepositorySession(session);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_STRICT);

    try {
        ProjectBuildingResult res = projectBuilder.build(mavenArtifact, req);

        return res.getProject().getModel();
    } catch (ProjectBuildingException e) {
        getLog().warn("error building artifact model for artifact "+artifact,e);
        return null;
    }

}
项目:oceano    文件:DefaultMavenProjectBuilder.java   
public MavenProject buildFromRepository( Artifact artifact, List<ArtifactRepository> remoteRepositories,
                                         ProjectBuilderConfiguration configuration, boolean allowStubModel )
    throws ProjectBuildingException
{
    ProjectBuildingRequest request = injectSession( toRequest( configuration ) );
    request.setRemoteRepositories( normalizeToArtifactRepositories( remoteRepositories, request ) );
    request.setProcessPlugins( false );
    request.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );

    try
    {
        return projectBuilder.build( artifact, allowStubModel, request ).getProject();
    }
    catch ( ProjectBuildingException e )
    {
        throw transformError( e );
    }
}
项目:oceano    文件:DefaultLifecycleBindingsInjector.java   
public void injectLifecycleBindings( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
{
    String packaging = model.getPackaging();

    Collection<Plugin> defaultPlugins = lifecycle.getPluginsBoundByDefaultToAllLifecycles( packaging );

    if ( defaultPlugins == null )
    {
        problems.add( new ModelProblemCollectorRequest( Severity.ERROR, Version.BASE)
                .setMessage( "Unknown packaging: " + packaging )
                .setLocation( model.getLocation( "packaging" )));
    }
    else if ( !defaultPlugins.isEmpty() )
    {
        Model lifecycleModel = new Model();
        lifecycleModel.setBuild( new Build() );
        lifecycleModel.getBuild().getPlugins().addAll( defaultPlugins );

        merger.merge( model, lifecycleModel );
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private void validate20EffectivePluginDependencies( ModelProblemCollector problems, Plugin plugin,
                                                  ModelBuildingRequest request )
{
    List<Dependency> dependencies = plugin.getDependencies();

    if ( !dependencies.isEmpty() )
    {
        String prefix = "build.plugins.plugin[" + plugin.getKey() + "].dependencies.dependency.";

        Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );

        for ( Dependency d : dependencies )
        {
            validateEffectiveDependency( problems, d, false, prefix, request );

            validateVersion( prefix + "version", problems, errOn30, Version.BASE, d.getVersion(), d.getManagementKey(), d );

            validateEnum( prefix + "scope", problems, errOn30, Version.BASE, d.getScope(), d.getManagementKey(), d, "compile",
                          "runtime", "system" );
        }
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private void validate20EffectiveRepository( ModelProblemCollector problems, Repository repository, String prefix,
                                 ModelBuildingRequest request )
{
    if ( repository != null )
    {
        Severity errOn31 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1 );

        validateBannedCharacters( prefix + ".id", problems, errOn31, Version.V20, repository.getId(), null, repository,
                                  ILLEGAL_REPO_ID_CHARS );

        if ( "local".equals( repository.getId() ) )
        {
            addViolation( problems, errOn31, Version.V20, prefix + ".id", null, "must not be 'local'"
                + ", this identifier is reserved for the local repository"
                + ", using it for other repositories will corrupt your repository metadata.", repository );
        }

        if ( "legacy".equals( repository.getLayout() ) )
        {
            addViolation( problems, Severity.WARNING, Version.V20, prefix + ".layout", repository.getId(),
                          "uses the unsupported value 'legacy', artifact resolution might fail.", repository );
        }
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private boolean validate20PluginVersion( String fieldName, ModelProblemCollector problems, String string,
                                       String sourceHint, InputLocationTracker tracker,
                                       ModelBuildingRequest request )
{
    if ( string == null )
    {
        // NOTE: The check for missing plugin versions is handled directly by the model builder
        return true;
    }

    Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );

    if ( !validateVersion( fieldName, problems, errOn30, Version.V20, string, sourceHint, tracker ) )
    {
        return false;
    }

    if ( string.length() <= 0 || "RELEASE".equals( string ) || "LATEST".equals( string ) )
    {
        addViolation( problems, errOn30, Version.V20, fieldName, sourceHint, "must be a valid version but is '" + string + "'.",
                      tracker );
        return false;
    }

    return true;
}
项目:oceano    文件:DefaultReportConfigurationExpander.java   
public void expandPluginConfiguration( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
{
    Reporting reporting = model.getReporting();

    if ( reporting != null )
    {
        for ( ReportPlugin reportPlugin : reporting.getPlugins() )
        {
            Xpp3Dom parentDom = (Xpp3Dom) reportPlugin.getConfiguration();

            if ( parentDom != null )
            {
                for ( ReportSet execution : reportPlugin.getReportSets() )
                {
                    Xpp3Dom childDom = (Xpp3Dom) execution.getConfiguration();
                    childDom = Xpp3Dom.mergeXpp3Dom( childDom, new Xpp3Dom( parentDom ) );
                    execution.setConfiguration( childDom );
                }
            }
        }
    }
}
项目:oceano    文件:DefaultPluginConfigurationExpander.java   
public void expandPluginConfiguration( Model model, ModelBuildingRequest request, ModelProblemCollector problems )
{
    Build build = model.getBuild();

    if ( build != null )
    {
        expand( build.getPlugins() );

        PluginManagement pluginManagement = build.getPluginManagement();

        if ( pluginManagement != null )
        {
            expand( pluginManagement.getPlugins() );
        }
    }
}
项目:oceano    文件:DefaultProfileInjector.java   
public void injectProfile( Model model, Profile profile, ModelBuildingRequest request,
                           ModelProblemCollector problems )
{
    if ( profile != null )
    {
        merger.mergeModelBase( model, profile );

        if ( profile.getBuild() != null )
        {
            if ( model.getBuild() == null )
            {
                model.setBuild( new Build() );
            }
            merger.mergeBuildBase( model.getBuild(), profile.getBuild() );
        }
    }
}
项目:oceano    文件:StringSearchModelInterpolator.java   
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();
    }
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateStringArray()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    String[] values = { "${key}", "${key2}" };

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest(p);

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( values, model, new File( "." ), config, collector );
    assertProblemFree( collector );        

    assertEquals( "value", values[0] );
    assertEquals( "value2", values[1] );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithStringArrayField()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    String[] values = { "${key}", "${key2}" };

    ObjectWithStringArrayField obj = new ObjectWithStringArrayField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );        

    assertEquals( "value", obj.values[0] );
    assertEquals( "value2", obj.values[1] );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithStringListField()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    List<String> values = new ArrayList<String>();
    values.add( "${key}" );
    values.add( "${key2}" );

    ObjectWithListField obj = new ObjectWithListField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );

    assertEquals( "value", obj.values.get( 0 ) );
    assertEquals( "value2", obj.values.get( 1 ) );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithStringListFieldAndOneLiteralValue()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    List<String> values = new ArrayList<String>();
    values.add( "key" );
    values.add( "${key2}" );

    ObjectWithListField obj = new ObjectWithListField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );        

    assertEquals( "key", obj.values.get( 0 ) );
    assertEquals( "value2", obj.values.get( 1 ) );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithUnmodifiableStringListField()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    List<String> values = Collections.unmodifiableList( Collections.singletonList( "${key}" ) );

    ObjectWithListField obj = new ObjectWithListField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );        

    assertEquals( "${key}", obj.values.get( 0 ) );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithStringToStringMapField()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    Map<String, String> values = new HashMap<String, String>();
    values.put( "key", "${key}" );
    values.put( "key2", "${key2}" );

    ObjectWithMapField obj = new ObjectWithMapField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );

    assertEquals( "value", obj.values.get( "key" ) );
    assertEquals( "value2", obj.values.get( "key2" ) );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithStringToStringMapFieldAndOneLiteralValue()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    Map<String, String> values = new HashMap<String, String>();
    values.put( "key", "val" );
    values.put( "key2", "${key2}" );

    ObjectWithMapField obj = new ObjectWithMapField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );        

    assertEquals( "val", obj.values.get( "key" ) );
    assertEquals( "value2", obj.values.get( "key2" ) );
}
项目:oceano    文件:StringSearchModelInterpolatorTest.java   
public void testInterpolateObjectWithUnmodifiableStringToStringMapField()
    throws Exception
{
    Model model = new Model();

    Properties p = new Properties();
    p.setProperty( "key", "value" );
    p.setProperty( "key2", "value2" );

    Map<String, String> values = Collections.unmodifiableMap( Collections.singletonMap( "key", "${key}" ) );

    ObjectWithMapField obj = new ObjectWithMapField( values );

    StringSearchModelInterpolator interpolator = (StringSearchModelInterpolator) createInterpolator();

    ModelBuildingRequest config = createModelBuildingRequest( p );

    final SimpleProblemCollector collector = new SimpleProblemCollector();
    interpolator.interpolateObject( obj, model, new File( "." ), config, collector );
    assertProblemFree( collector );

    assertEquals( "${key}", obj.values.get( "key" ) );
}
项目:isc-maven-plugin    文件:AbstractPackagerMojo.java   
/**f
 * Read the given POM so it can be used as the source of coordinates, etc.
 * during artifact construction. Note that if this object's
 * {@link #snapshots} property is true, and we're working with a development
 * build ({@link #buildNumber} ends with 'd'), the POM is modified to remove
 * the SNAPSHOT qualifier.
 * 
 * @param pom
 *            the POM file containing the artifact metadata
 * @return A Maven model to be used at
 *         {@link com.isomorphic.maven.packaging.Module#Module(Model)}
 *         Module construction
 * @throws ModelBuildingException
 *             if the Model cannot be built from the given POM
 * @throws IOException
 *             if the Model cannot be built from the given POM
 */
private Model getModelFromFile(File pom) throws ModelBuildingException, IOException {

    if (buildNumber.endsWith("d") && !snapshots) {
        LOGGER.info(
            "Rewriting file to remove SNAPSHOT qualifier from development POM '{}'",
            pom.getName());
        String content = FileUtils.readFileToString(pom);
        content = content.replaceAll("-SNAPSHOT", "");
        FileUtils.write(pom, content);
    }

    ModelBuildingRequest request = new DefaultModelBuildingRequest();
    request.setPomFile(pom);

    ModelBuildingResult result = modelBuilder.build(request);
    return result.getEffectiveModel();
}
项目:redhat-repository-validator    文件:AppConfig.java   
@Bean
public ModelBuildingRequest modelBuildingRequestTemplate(RepositorySystemSession repositorySystemSession, LocalRepositoryModelResolver localRepositoryModelResolver) {
    Properties userProperties = new Properties();
    userProperties.putAll(repositorySystemSession.getUserProperties());

    Properties systemProperties = new Properties();
    systemProperties.putAll(repositorySystemSession.getSystemProperties());

    DefaultModelBuildingRequest request = new DefaultModelBuildingRequest();
    request.setProcessPlugins(true);
    request.setLocationTracking(true);
    request.setModelResolver(localRepositoryModelResolver);
    request.setUserProperties(userProperties);
    request.setSystemProperties(systemProperties);

    return request;
}
项目:incubator-netbeans    文件:RepositoryMavenCPProvider.java   
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;
    }
项目:incubator-netbeans    文件:DependencyNode.java   
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;
}
项目:incubator-netbeans    文件:EffectivePomMD.java   
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;
}
项目:incubator-netbeans    文件:StatusProvider.java   
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;
}
项目:playground    文件:Main.java   
/**
 *
 * TODO: This does not currently work.
 *
 */
@SuppressWarnings("unused")
private static Model complexModelBuilding(File file) throws Exception {

    ModelBuilder builder = new DefaultModelBuilder();
    ModelBuildingRequest request = new DefaultModelBuildingRequest();
    request.setProcessPlugins(false);
    request.setPomFile(file);
    // request.setModelResolver(new ModelResolver() {});
    request.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);

    //noinspection UnnecessaryLocalVariable
    Model model = builder.build(request).getEffectiveModel();
    return model;
}
项目:intellij-ce-playground    文件:CustomMaven3ModelInterpolator2.java   
@Override
protected List<ValueSource> createValueSources(Model model,
                                               File projectDir,
                                               ModelBuildingRequest config,
                                               ModelProblemCollector problems) {
  List<ValueSource> res = super.createValueSources(model, projectDir, config, problems);

  if (localRepository != null) {
    res.add(new SingleResponseValueSource("settings.localRepository", localRepository));
  }

  return res;
}
项目:flatten-maven-plugin    文件:FlattenMojo.java   
private Model createResolvedPom( ModelBuildingRequest buildingRequest )
{
    LoggingModelProblemCollector problems = new LoggingModelProblemCollector( getLog() );
    Model originalModel = this.project.getOriginalModel().clone();
    return this.modelInterpolator.interpolateModel( originalModel, this.project.getModel().getProjectDirectory(),
                                                    buildingRequest, problems );
}
项目:flatten-maven-plugin    文件:FlattenMojo.java   
private ModelBuildingRequest createModelBuildingRequest( File pomFile )
{

    FlattenModelResolver resolver = new FlattenModelResolver( this.localRepository, this.artifactFactory,
        this.dependencyResolver, this.session.getProjectBuildingRequest(), this.session.getAllProjects() );
    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;
}
项目:flatten-maven-plugin    文件:CreateEffectivePomTest.java   
/**
 * 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 );
    Model effectivePom = FlattenMojo.createEffectivePom( buildingRequest, false );
    assertThat( effectivePom.getName() ).isEqualTo( magicValue );
}
项目:tycho-gen    文件:Maven.java   
public static Model createModel(File pom) throws ModelBuildingException, ComponentLookupException
{
    ModelBuilder builder = mavenContainer.lookup(ModelBuilder.class);
    ModelBuildingRequest req = new DefaultModelBuildingRequest();
    req.setProcessPlugins(false);
    req.setModelResolver(new RepoModelResolver());
    req.setPomFile(pom);
    return builder.build(req).getEffectiveModel();
}
项目:oceano    文件:DefaultMavenProjectBuilder.java   
/**
 * This is used for pom-less execution like running archetype:generate. I am taking out the profile handling and the
 * interpolation of the base directory until we spec this out properly.
 */
public MavenProject buildStandaloneSuperProject( ProjectBuilderConfiguration configuration )
    throws ProjectBuildingException
{
    ProjectBuildingRequest request = injectSession( toRequest( configuration ) );
    request.setProcessPlugins( false );
    request.setValidationLevel( ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL );

    ModelSource modelSource = new UrlModelSource( getClass().getResource( "standalone.xml" ) );

    MavenProject project = projectBuilder.build( modelSource, request ).getProject();
    project.setExecutionRoot( true );
    return project;
}
项目:oceano    文件:DefaultProjectBuilder.java   
InterimResult( File pomFile, ModelBuildingRequest request, ModelBuildingResult result,
               DefaultModelBuildingListener listener, boolean root )
{
    this.pomFile = pomFile;
    this.request = request;
    this.result = result;
    this.listener = listener;
    this.root = root;
}
项目:oceano    文件:PomConstructionTest.java   
private PomTestWrapper buildPom( String pomPath, boolean lenientValidation, Properties executionProperties,
                                 String... profileIds )
    throws ProjectBuildingException
{
    File pomFile = new File( testDirectory, pomPath );
    if ( pomFile.isDirectory() )
    {
        pomFile = new File( pomFile, "pom.xml" );
    }

    ProjectBuildingRequest config = new DefaultProjectBuildingRequest();

    String localRepoUrl =
        System.getProperty( "maven.repo.local", System.getProperty( "user.home" ) + "/.m2/repository" );
    localRepoUrl = "file://" + localRepoUrl;
    config.setLocalRepository( repositorySystem.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(), null, null ) );
    config.setActiveProfileIds( Arrays.asList( profileIds ) );
    config.setSystemProperties( executionProperties );
    config.setUserProperties( executionProperties );
    config.setValidationLevel( lenientValidation ? ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0
                    : ModelBuildingRequest.VALIDATION_LEVEL_STRICT );
    MavenRepositorySystemSession repoSession = new MavenRepositorySystemSession( true );
    repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager(
                                                                             new File(
                                                                                       config.getLocalRepository().getBasedir() ) ) );
    config.setRepositorySession( repoSession );

    return new PomTestWrapper( pomFile, projectBuilder.build( pomFile, config ).getProject() );
}
项目:oceano    文件:DefaultModelValidator.java   
private void validate20RawPlugins( ModelProblemCollector problems, List<Plugin> plugins, String prefix,
                                 ModelBuildingRequest request )
{
    Severity errOn31 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1 );

    Map<String, Plugin> index = new HashMap<String, Plugin>();

    for ( Plugin plugin : plugins )
    {
        String key = plugin.getKey();

        Plugin existing = index.get( key );

        if ( existing != null )
        {
            addViolation( problems, errOn31, Version.V20, prefix + ".(groupId:artifactId)", null,
                          "must be unique but found duplicate declaration of plugin " + key, plugin );
        }
        else
        {
            index.put( key, plugin );
        }

        Set<String> executionIds = new HashSet<String>();

        for ( PluginExecution exec : plugin.getExecutions() )
        {
            if ( !executionIds.add( exec.getId() ) )
            {
                addViolation( problems, Severity.ERROR, Version.V20, prefix + "[" + plugin.getKey()
                    + "].executions.execution.id", null, "must be unique but found duplicate execution with id "
                    + exec.getId(), exec );
            }
        }
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private void validateEffectiveDependencies( ModelProblemCollector problems, List<Dependency> dependencies,
                                            boolean management, ModelBuildingRequest request )
{
    Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );

    String prefix = management ? "dependencyManagement.dependencies.dependency." : "dependencies.dependency.";

    for ( Dependency d : dependencies )
    {
        validateEffectiveDependency( problems, d, management, prefix, request );

        if ( request.getValidationLevel() >= ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_2_0 )
        {
            validateBoolean( prefix + "optional", problems, errOn30, Version.V20, d.getOptional(), d.getManagementKey(), d );

            if ( !management )
            {
                validateVersion( prefix + "version", problems, errOn30, Version.V20, d.getVersion(), d.getManagementKey(), d );

                /*
                 * TODO: Extensions like Flex Mojos use custom scopes like "merged", "internal", "external", etc.
                 * In order to don't break backward-compat with those, only warn but don't error out.
                 */
                validateEnum( prefix + "scope", problems, Severity.WARNING, Version.V20, d.getScope(), d.getManagementKey(), d,
                              "provided", "compile", "runtime", "test", "system" );
            }
        }
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private void validateRawRepositories( ModelProblemCollector problems, List<Repository> repositories, String prefix,
                                   ModelBuildingRequest request )
{
    Map<String, Repository> index = new HashMap<String, Repository>();

    for ( Repository repository : repositories )
    {
        validateStringNotEmpty( prefix + ".id", problems, Severity.ERROR, Version.V20, repository.getId(), repository );

        validateStringNotEmpty( prefix + "[" + repository.getId() + "].url", problems, Severity.ERROR, Version.V20,
                                repository.getUrl(), repository );

        String key = repository.getId();

        Repository existing = index.get( key );

        if ( existing != null )
        {
            Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );

            addViolation( problems, errOn30, Version.V20, prefix + ".id", null, "must be unique: " + repository.getId() + " -> "
                + existing.getUrl() + " vs " + repository.getUrl(), repository );
        }
        else
        {
            index.put( key, repository );
        }
    }
}
项目:oceano    文件:DefaultModelValidator.java   
private void validate20RawResources( ModelProblemCollector problems, List<Resource> resources, String prefix,
                                ModelBuildingRequest request )
{
    Severity errOn30 = getSeverity( request, ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_0 );

    for ( Resource resource : resources )
    {
        validateStringNotEmpty( prefix + ".directory", problems, Severity.ERROR, Version.V20, resource.getDirectory(),
                                resource );

        validateBoolean( prefix + ".filtering", problems, errOn30, Version.V20, resource.getFiltering(),
                         resource.getDirectory(), resource );
    }
}