Java 类org.apache.maven.project.ProjectBuildingResult 实例源码

项目: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    文件: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;
}
项目:wildfly-swarm-fraction-plugin    文件:AbstractFractionsMojo.java   
private void buildProjects() throws MojoExecutionException {
    final ProjectBuildingRequest request = new DefaultProjectBuildingRequest();
    request.setProcessPlugins(false);
    request.setSystemProperties(System.getProperties());
    request.setRemoteRepositories(this.project.getRemoteArtifactRepositories());
    request.setRepositorySession(this.repositorySystemSession);
    request.setResolveDependencies(true);

    try {
        PROBABLE_FRACTIONS = this.projectBuilder
                .build(Collections.singletonList(findRoot(this.project).getFile()), true, request)
                .stream()
                .filter(this::isNotArquillianArtifact)
                .map(ProjectBuildingResult::getProject)
                .collect(Collectors.toList());
    } catch (ProjectBuildingException e) {
        throw new MojoExecutionException("Error generating list of PROBABLE_FRACTIONS", e);
    }
}
项目:furnace    文件:ProjectHelper.java   
public List<Dependency> resolveDependenciesFromPOM(File pomFile) throws Exception
{
   PlexusContainer plexus = new PlexusContainer();
   List<Dependency> result;
   try
   {
      ProjectBuildingRequest request = getBuildingRequest(plexus);
      request.setResolveDependencies(true);
      ProjectBuilder builder = plexus.lookup(ProjectBuilder.class);
      ProjectBuildingResult build = builder.build(pomFile, request);
      result = build.getDependencyResolutionResult().getDependencies();
   }
   finally
   {
      plexus.shutdown();
   }
   return result;
}
项目:oceano    文件:DefaultExceptionHandler.java   
private ExceptionSummary handle( ProjectBuildingResult result )
{
    List<ExceptionSummary> children = new ArrayList<ExceptionSummary>();

    for ( ModelProblem problem : result.getProblems() )
    {
        ExceptionSummary child = handle( problem, result.getProjectId() );
        if ( child != null )
        {
            children.add( child );
        }
    }

    if ( children.isEmpty() )
    {
        return null;
    }

    String message =
        "\nThe project " + result.getProjectId() + " (" + result.getPomFile() + ") has "
            + children.size() + " error" + ( children.size() == 1 ? "" : "s" );

    return new ExceptionSummary( null, message, null, children );
}
项目:forge-furnace    文件:ProjectHelper.java   
public List<Dependency> resolveDependenciesFromPOM(File pomFile) throws Exception
{
   PlexusContainer plexus = new PlexusContainer();
   List<Dependency> result;
   try
   {
      ProjectBuildingRequest request = getBuildingRequest(plexus);
      request.setResolveDependencies(true);
      ProjectBuilder builder = plexus.lookup(ProjectBuilder.class);
      ProjectBuildingResult build = builder.build(pomFile, request);
      result = build.getDependencyResolutionResult().getDependencies();
   }
   finally
   {
      plexus.shutdown();
   }
   return result;
}
项目: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    文件:MavenEmbedder.java   
public ProjectBuildingResult buildProject(Artifact art, ProjectBuildingRequest req) throws ProjectBuildingException {
    if (req.getLocalRepository() == null) {
       req.setLocalRepository(getLocalRepository());
    }
    MavenExecutionRequest request = createMavenExecutionRequest();
    req.setProcessPlugins(false);
    req.setRepositorySession(maven.newRepositorySession(request));
    ProjectBuildingResult res = projectBuilder.build(art, req);
    normalizePaths(res.getProject());
    return res;
}
项目:incubator-netbeans    文件:MavenEmbedder.java   
private void setResult(ProjectBuildingResult pbr, Map<File, MavenExecutionResult> results) {
    DefaultMavenExecutionResult r = new DefaultMavenExecutionResult();
    normalizePaths(pbr.getProject());
    r.setProject(pbr.getProject());
        r.setDependencyResolutionResult(pbr.getDependencyResolutionResult());
    results.put(pbr.getPomFile(), r);
}
项目: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;
}
项目:spring-cloud-function    文件:DependencyResolver.java   
public Model readModel(final Resource resource, final Properties properties) {
    initialize();
    try {
        ProjectBuildingRequest request = getProjectBuildingRequest(properties);
        request.setResolveDependencies(false);
        ProjectBuildingResult result = projectBuilder
                .build(new PropertiesModelSource(properties, resource), request);
        return result.getProject().getModel();
    }
    catch (Exception e) {
        throw new IllegalStateException("Failed to build model from effective pom",
                e);
    }
}
项目:tibco-bwmaven    文件:BWLifecycleParticipant.java   
private List<MavenProject> prepareProjects(List<MavenProject> projects, MavenSession session) throws MavenExecutionException {
    List<MavenProject> result = new ArrayList<MavenProject>();

    ProjectBuildingRequest projectBuildingRequest = session.getProjectBuildingRequest();

    for (MavenProject mavenProject : projects) {
        logger.debug("project: " + mavenProject.getGroupId()+":"+mavenProject.getArtifactId());

        List<String> oldActiveProfileIds = projectBuildingRequest.getActiveProfileIds();
        try {
            List<String> activeProfileIds = activateProfilesWithProperties(mavenProject, oldActiveProfileIds);
            if (activeProfileIds.size() != oldActiveProfileIds.size()) {
                projectBuildingRequest.setActiveProfileIds(activeProfileIds);
                if (mavenProject.getFile() != null) {
                    List<File> files = new ArrayList<File>();
                    files.add(mavenProject.getFile());
                    List<ProjectBuildingResult> results = null;
                    try {
                        results = projectBuilder.build(files, true, projectBuildingRequest);
                    } catch (ProjectBuildingException e) {
                    }

                    for (ProjectBuildingResult projectBuildingResult : results) {
                        mavenProject = projectBuildingResult.getProject();
                    }
                }
            }
        } finally {
            projectBuildingRequest.setActiveProfileIds(oldActiveProfileIds);
        }

        if (mavenProject.getPackaging().startsWith(AbstractBWMojo.BWEAR_TYPE) || "true".equals(propertiesManager.getPropertyValue("enableBWLifecycle"))) {
            addTIBCODependenciesToPlugin(mavenProject, logger);
        }
        result.add(mavenProject);
    }

    return result;
}
项目:license-audit-maven-plugin    文件:AbstractLicensingMojo.java   
protected MavenProject loadProject(org.apache.maven.artifact.Artifact mda) {
    // older code creates a new PBReq but it lacks user props; this seems to work better
    String projectId = Coords.of(mda).normal();
    MavenProject p = projectByIdCache.get(projectId);
    if (p!=null) return p;

    try {
        getLog().debug("Loading project for "+mda);
        ProjectBuildingResult res = projectBuilder.build(mda, true, mavenSession.getProjectBuildingRequest());
        p = res.getProject();
    } catch (ProjectBuildingException e) {
        if (e.getResults().size()==1) {
            getLog().warn("Error loading maven project/model for "+mda+" (but got a result so ignoring): "+e);
            p = e.getResults().get(0).getProject();
        } else {
            getLog().error("Errors loading maven project/model for "+mda+": "+e);
            addError(projectId, e);
            return null;
        }
    }
    if (p==null) {
        addError(projectId, "Failure with no data when trying to load project");
        return null;
    }

    projectByIdCache.put(projectId, p);
    return p;
}
项目:license-audit-maven-plugin    文件:BetterAbstractMojoTestCaseTest.java   
public void testSensibleSession(MavenSession s) throws Exception {
    MavenSession ms = newMavenSession();  //((LicenseAuditMojo)mojo).mavenSession;
    assertNotNull( ms );
    assertNotNull( ms.getLocalRepository().getBasedir() );
    System.out.println("Basedir: "+ms.getLocalRepository().getBasedir());
    // The following artifacts could not be resolved: org.apache.maven:maven-core:jar:2.0.7

    RepositorySystem rs = lookup(RepositorySystem.class);
    assertNotNull( rs );

    // check we can access stuff in remote repos
    // (fails if we don't have proper aether connectors + transforms,
    // or if we've not "populated" with default remote repos)
    ArtifactResult art;
    art = resolveArtifact(rs, ms, "org.apache.maven:maven-core:jar:2.0.7");
    System.out.println(art);
    assertNotNull(art.getArtifact());

    // check we avoid this:
    // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
    art = resolveArtifact(rs, ms, "org.apache.commons:commons-lang3:3.1");
    System.out.println(art);
    assertNotNull(art.getArtifact());

    ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
    ProjectBuildingResult res = projectBuilder.build(RepositoryUtils.toArtifact(art.getArtifact()), true, ms.getProjectBuildingRequest());
    System.out.println(res);
    if (!res.getProblems().isEmpty()) fail("Problems: "+res.getProblems());
}
项目:tools-idea    文件:MavenEffectivePomDumper.java   
public static String evaluateEffectivePom(final Maven3ServerEmbedderImpl embedder,
                                          @NotNull final File file,
                                          @NotNull List<String> activeProfiles)
  throws RemoteException, MavenServerProcessCanceledException {

  final MavenExecutionRequest
    request = embedder.createRequest(file, activeProfiles, Collections.<String>emptyList(), Collections.<String>emptyList());

  final StringWriter w = new StringWriter();

  embedder.executeWithMavenSession(request, new Runnable() {
    @Override
    public void run() {
      try {
        // copied from DefaultMavenProjectBuilder.buildWithDependencies
        ProjectBuilder builder = embedder.getComponent(ProjectBuilder.class);
        ProjectBuildingResult buildingResult = builder.build(new File(file.getPath()), request.getProjectBuildingRequest());

        MavenProject project = buildingResult.getProject();

        XMLWriter writer = new PrettyPrintXMLWriter(w, StringUtils.repeat(" ", XmlWriterUtil.DEFAULT_INDENTATION_SIZE));

        writeHeader(writer);

        writeEffectivePom(project, writer);
      }
      catch (Exception e) {
        throw new RuntimeException(e);
      }
    }
  });

  return w.toString();
}
项目:oceano    文件:DefaultMaven.java   
private void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request )
    throws ProjectBuildingException
{
    ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest();

    List<ProjectBuildingResult> results = projectBuilder.build( files, request.isRecursive(), projectBuildingRequest );

    boolean problems = false;

    for ( ProjectBuildingResult result : results )
    {
        projects.add( result.getProject() );

        if ( !result.getProblems().isEmpty() && logger.isWarnEnabled() )
        {
            logger.warn( "" );
            logger.warn( "Some problems were encountered while building the effective model for "
                + result.getProject().getId() );

            for ( ModelProblem problem : result.getProblems() )
            {
                String location = ModelProblemUtils.formatLocation( problem, result.getProjectId() );
                logger.warn( problem.getMessage() + ( StringUtils.isNotEmpty( location ) ? " @ " + location : "" ) );
            }

            problems = true;
        }
    }

    if ( problems )
    {
        logger.warn( "" );
        logger.warn( "It is highly recommended to fix these problems"
            + " because they threaten the stability of your build." );
        logger.warn( "" );
        logger.warn( "For this reason, future Maven versions might no"
            + " longer support building such malformed projects." );
        logger.warn( "" );
    }
}
项目:oceano    文件:DefaultExceptionHandler.java   
private ExceptionSummary handle( String message, Throwable exception )
{
    String reference = getReference( exception );

    List<ExceptionSummary> children = null;

    if ( exception instanceof ProjectBuildingException )
    {
        List<ProjectBuildingResult> results = ( (ProjectBuildingException) exception ).getResults();

        children = new ArrayList<ExceptionSummary>();

        for ( ProjectBuildingResult result : results )
        {
            ExceptionSummary child = handle( result );
            if ( child != null )
            {
                children.add( child );
            }
        }

        message = "The build could not read " + children.size() + " project" + ( children.size() == 1 ? "" : "s" );
    }
    else
    {
        message = getMessage( message, exception );
    }

    return new ExceptionSummary( exception, message, reference, children );
}
项目:xapi    文件:ProjectIterable.java   
private void addAllProjects(
    final List<MavenProject> projects,
    final MavenProject project,
    final ProjectBuilder builder,
    final ProjectBuildingRequest request
) {

  final List<String> modules = root.getModules();
  File file = project.getFile().getParentFile();
  for (String module : modules) {
    final File moduleFile = new File(
        new File(file, module),
        "pom.xml"
    );
    try {
      final ProjectBuildingResult result = builder.build(
          moduleFile,
          request
      );
      if (!result.getProblems().isEmpty()) {
        X_Log.warn(getClass(), "Problems encountered looking up module ", moduleFile, result.getProblems());
      }
      projects.add(result.getProject());
      if (!result.getProject().getModules().isEmpty()) {
        addAllProjects(projects, result.getProject(), builder, request);
      }
    } catch (ProjectBuildingException e) {
      X_Log.warn(getClass(), "Unable to build module for ", moduleFile);
    }
  }
}
项目:srcdeps-maven    文件:SrcdepsInitMojo.java   
/**
 * Find the SCM URL for the given {@code g, a, v} triple and store the association for the later retrieval via
 * {@link #createSortedScmRepositoryMap()}.
 *
 * @param g
 *            {@code groupId}
 * @param a
 *            {@code artifactId}
 * @param v
 *            {@code version}
 * @param failOnUnresolvable
 *            see {@link SrcdepsInitMojo#failOnUnresolvable}
 * @throws MojoExecutionException
 */
public void addGav(String g, String a, String v, boolean failOnUnresolvable) throws MojoExecutionException {
    final Gav gav = new Gav(g, a, v);
    if (!seenGavs.contains(gav)) {
        seenGavs.add(gav);
        final Ga ga = new Ga(g, a);
        log.debug("Adding GA: {}", ga);

        ProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
        projectBuildingRequest.setLocalRepository(session.getLocalRepository());
        projectBuildingRequest
                .setRemoteRepositories(session.getProjectBuildingRequest().getRemoteRepositories());
        projectBuildingRequest.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
        projectBuildingRequest.setProcessPlugins(false);
        projectBuildingRequest.setRepositoryMerging(ProjectBuildingRequest.RepositoryMerging.REQUEST_DOMINANT);
        projectBuildingRequest.setSystemProperties(session.getSystemProperties());
        projectBuildingRequest.setRepositorySession(repoSession);

        Artifact pomArtifact = repositorySystem.createProjectArtifact(g, a, v, "compile");
        try {
            ProjectBuildingResult result = projectBuilder.build(pomArtifact, projectBuildingRequest);
            MavenProject dependencyProject = result.getProject();
            ScmUrlAncestry ancestry = ScmUrlAncestry.of(dependencyProject);
            if (!ancestry.hasUrl()) {
                log.warn("No SCM connection for artifact [{}]", ga);
            } else {
                final String url = ancestry.getUrl();
                if (unsupportedUrls.contains(url)) {
                    /* was reported once already */
                } else if (isScmUrlSupported(url)) {
                    log.debug("Found SCM URL [{}] for GA [{}]", url, ga);
                    int len = ancestry.getLength();
                    for (int i = 0; i < len; i++) {
                        this.add(url, ancestry.getGaAt(i));
                    }
                    Set<Ga> rootGas = urlRootGasMap.get(url);
                    if (rootGas == null) {
                        rootGas = new TreeSet<>();
                        urlRootGasMap.put(url, rootGas);
                    }
                    rootGas.add(ancestry.getRootGa());
                } else {
                    log.warn("Unsupported SCM URL [{}] for GAV [{}]", url, ga);
                    unsupportedUrls.add(url);
                }
            }
        } catch (ProjectBuildingException e) {
            final String msg = String.format("Could not resolve [%s] using remote repositories [%s]",
                    pomArtifact, remoteRepos);
            if (failOnUnresolvable) {
                throw new MojoExecutionException(msg, e);
            } else {
                log.warn(msg);
            }
        }
    }
}
项目:wildfly-swarm-fraction-plugin    文件:AbstractFractionsMojo.java   
protected boolean isNotArquillianArtifact(ProjectBuildingResult result) {
    return !result.getProject().getArtifactId().contains("arquillian");
}
项目:che    文件:MavenServerImpl.java   
private MavenResult internalResolveProject(
    File pom,
    List<String> activeProfiles,
    List<String> inactiveProfiles,
    List<ResolutionListener> dependencyTreeResolutionListeners) {

  MavenExecutionRequest request =
      newMavenRequest(pom, activeProfiles, inactiveProfiles, Collections.emptyList());
  request.setUpdateSnapshots(updateSnapshots);

  AtomicReference<MavenResult> reference = new AtomicReference<>();
  runMavenRequest(
      request,
      () -> {
        try {
          ProjectBuilder builder = getMavenComponent(ProjectBuilder.class);

          List<ProjectBuildingResult> resultList =
              builder.build(
                  Collections.singletonList(pom), false, request.getProjectBuildingRequest());
          ProjectBuildingResult result = resultList.get(0);
          MavenProject mavenProject = result.getProject();
          RepositorySystemSession repositorySession =
              getMavenComponent(LegacySupport.class).getRepositorySession();
          if (repositorySession instanceof DefaultRepositorySystemSession) {
            ((DefaultRepositorySystemSession) repositorySession)
                .setTransferListener(new ArtifactTransferListener(mavenProgressNotifier));
            if (workspaceCache != null) {
              ((DefaultRepositorySystemSession) repositorySession)
                  .setWorkspaceReader(new MavenWorkspaceReader(workspaceCache));
            }
          }

          List<Exception> exceptions = new ArrayList<>();

          loadExtensions(mavenProject, exceptions);
          mavenProject.setDependencyArtifacts(
              mavenProject.createArtifacts(getMavenComponent(ArtifactFactory.class), null, null));

          ArtifactResolutionRequest resolutionRequest = new ArtifactResolutionRequest();
          resolutionRequest.setArtifact(mavenProject.getArtifact());
          resolutionRequest.setRemoteRepositories(mavenProject.getRemoteArtifactRepositories());
          resolutionRequest.setArtifactDependencies(mavenProject.getDependencyArtifacts());
          resolutionRequest.setListeners(dependencyTreeResolutionListeners);
          resolutionRequest.setLocalRepository(localRepo);
          resolutionRequest.setManagedVersionMap(mavenProject.getManagedVersionMap());
          resolutionRequest.setResolveTransitively(true);
          resolutionRequest.setResolveRoot(false);
          ArtifactResolver resolver = getMavenComponent(ArtifactResolver.class);
          ArtifactResolutionResult resolve = resolver.resolve(resolutionRequest);
          mavenProject.setArtifacts(resolve.getArtifacts());
          reference.set(new MavenResult(mavenProject, exceptions));

        } catch (Exception e) {
          reference.set(new MavenResult(null, null, Collections.singletonList(e)));
        }
      });
  return reference.get();
}
项目:evosuite    文件:EvoSuiteRunner.java   
/**
 * We run the EvoSuite that is provided with the plugin
 * 
 * @return
 */
private List<String> getCommandToRunEvoSuite(){

    logger.debug("EvoSuite Maven Plugin Artifacts: "+Arrays.toString(artifacts.toArray()));

    Artifact evosuite = null;   

    for(Artifact art : artifacts){
        //first find the main EvoSuite jar among the dependencies
        if(art.getArtifactId().equals("evosuite-master")){
            evosuite = art;
            break;
        }
    }       

    if(evosuite==null){
        logger.error("CRITICAL ERROR: plugin can detect EvoSuite executable");
        return null;
    }

    logger.debug("EvoSuite located at: "+evosuite.getFile());

    /*
     * now, build a project descriptor for evosuite, which is needed to
     * query all of its dependencies 
     */
    DefaultProjectBuildingRequest req = new DefaultProjectBuildingRequest();
    req.setRepositorySession(repoSession);
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    req.setSystemProperties(System.getProperties());
    req.setResolveDependencies(true);

    ProjectBuildingResult res;

    try {
        res = projectBuilder.build(evosuite, req);
    } catch (ProjectBuildingException e) {
        logger.error("Failed: "+e.getMessage(),e);
        return null;
    }

    //build the classpath to run EvoSuite
    String cp = evosuite.getFile().getAbsolutePath();

    for(Artifact dep  : res.getProject().getArtifacts()){
        cp += File.pathSeparator+dep.getFile().getAbsolutePath();
    }
    logger.debug("EvoSuite classpath: "+cp);

    String entryPoint = EvoSuite.class.getName();

    List<String> cmd = new ArrayList<>();
    cmd.add(JavaExecCmdUtil.getJavaBinExecutablePath()/*"java"*/);
    cmd.add("-D" + LoggingUtils.USE_DIFFERENT_LOGGING_XML_PARAMETER + "=logback-ctg-entry.xml");
    cmd.add("-Dlogback.configurationFile=logback-ctg-entry.xml");
    cmd.add("-cp");
    cmd.add(cp);
    cmd.add(entryPoint);
    return cmd;
}
项目:nifi-maven    文件:NarProvidedDependenciesMojo.java   
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    try {
        // find the nar dependency
        Artifact narArtifact = null;
        for (final Artifact artifact : project.getDependencyArtifacts()) {
            if (NAR.equals(artifact.getType())) {
                // ensure the project doesn't have two nar dependencies
                if (narArtifact != null) {
                    throw new MojoExecutionException("Project can only have one NAR dependency.");
                }

                // record the nar dependency
                narArtifact = artifact;
            }
        }

        // ensure there is a nar dependency
        if (narArtifact == null) {
            throw new MojoExecutionException("Project does not have any NAR dependencies.");
        }

        // build the project for the nar artifact
        final ProjectBuildingRequest narRequest = new DefaultProjectBuildingRequest();
        narRequest.setRepositorySession(repoSession);
        narRequest.setSystemProperties(System.getProperties());
        final ProjectBuildingResult narResult = projectBuilder.build(narArtifact, narRequest);

        // get the artifact handler for excluding dependencies
        final ArtifactHandler narHandler = excludesDependencies(narArtifact);
        narArtifact.setArtifactHandler(narHandler);

        // nar artifacts by nature includes dependencies, however this prevents the
        // transitive dependencies from printing using tools like dependency:tree.
        // here we are overriding the artifact handler for all nars so the
        // dependencies can be listed. this is important because nar dependencies
        // will be used as the parent classloader for this nar and seeing what
        // dependencies are provided is critical.
        final Map<String, ArtifactHandler> narHandlerMap = new HashMap<>();
        narHandlerMap.put(NAR, narHandler);
        artifactHandlerManager.addHandlers(narHandlerMap);

        // get the dependency tree
        final DependencyNode root = dependencyTreeBuilder.buildDependencyTree(narResult.getProject(), localRepository, null);

        // write the appropriate output
        DependencyNodeVisitor visitor = null;
        if ("tree".equals(mode)) {
            visitor = new TreeWriter();
        } else if ("pom".equals(mode)) {
            visitor = new PomWriter();
        }

        // ensure the mode was specified correctly
        if (visitor == null) {
            throw new MojoExecutionException("The specified mode is invalid. Supported options are 'tree' and 'pom'.");
        }

        // visit and print the results
        root.accept(visitor);
        getLog().info("--- Provided NAR Dependencies ---\n\n" + visitor.toString());
    } catch (DependencyTreeBuilderException | ProjectBuildingException e) {
        throw new MojoExecutionException("Cannot build project dependency tree", e);
    }
}
项目:mvn-fluid-cd    文件:JenkinsDefaultMaven.java   
private void collectProjects( List<MavenProject> projects, List<File> files, MavenExecutionRequest request )
        throws ProjectBuildingException
{
    ProjectBuildingRequest projectBuildingRequest = request.getProjectBuildingRequest();

    List<ProjectBuildingResult> results =
            projectBuilder.build( files, request.isRecursive(), projectBuildingRequest );

    boolean problems = false;

    for ( ProjectBuildingResult result : results )
    {
        projects.add( result.getProject() );

        if ( !result.getProblems().isEmpty() && logger.isWarnEnabled() )
        {
            logger.warn( "" );
            logger.warn( "Some problems were encountered while building the effective model for "
                    + result.getProject().getId() );

            for ( ModelProblem problem : result.getProblems() )
            {
                String location = ModelProblemUtils.formatLocation( problem, result.getProjectId() );
                logger.warn( problem.getMessage() + ( StringUtils.isNotEmpty( location ) ? " @ " + location : "" ) );
            }

            problems = true;
        }
    }

    if ( problems )
    {
        logger.warn( "" );
        logger.warn( "It is highly recommended to fix these problems"
                + " because they threaten the stability of your build." );
        logger.warn( "" );
        logger.warn( "For this reason, future Maven versions might no"
                + " longer support building such malformed projects." );
        logger.warn( "" );
    }
}