private static MavenProject readMavenProject(MavenEmbedder embedder, Artifact artifact, List<ArtifactRepository> remoteRepos) throws ProjectBuildingException { ProjectBuilder bldr = embedder.lookupComponent(ProjectBuilder.class); assert bldr !=null : "ProjectBuilder component not found in maven"; DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class); assert bldr !=null : "DefaultMaven component not found in maven"; MavenExecutionRequest req = embedder.createMavenExecutionRequest(); req.setLocalRepository(embedder.getLocalRepository()); req.setRemoteRepositories(remoteRepos); ProjectBuildingRequest configuration = req.getProjectBuildingRequest(); configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL); configuration.setResolveDependencies(true); configuration.setRepositorySession(maven.newRepositorySession(req)); ProjectBuildingResult projectBuildingResult = bldr.build(artifact, configuration); return projectBuildingResult.getProject(); }
protected List<File> getParents() { LinkedList<File> ret = new LinkedList<>(); MavenProject project = getOriginalMavenProject(); while(true) { try { MavenProject parent = loadParentOf(getEmbedder(), project); File parentFile = parent != null ? parent.getFile() : null; if(parentFile != null) { ret.add(parentFile); project = parent; } else { break; } } catch (ProjectBuildingException ex) { break; } } return ret; }
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; }
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; }
private void warProjects(FileNode pomXml, Properties userProperties, List<String> profiles, List<MavenProject> result) throws IOException { MavenProject root; FileNode modulePom; try { root = maven().loadPom(pomXml, false, userProperties, profiles, null); } catch (ProjectBuildingException | RepositoryException e) { throw new IOException("cannot parse " + pomXml + ": " + e.getMessage(), e); } session.console.verbose.println("loading " + pomXml); if ("war".equals(root.getPackaging())) { result.add(root); } else { for (String module : root.getModules()) { modulePom = session.world.file(root.getBasedir()).join(module); if (modulePom.isDirectory()) { modulePom = modulePom.join("pom.xml"); } warProjects(modulePom, userProperties, profiles, result); } } }
/** * Get the <code>Maven project</code> from the repository depending * the <code>Artifact</code> given. * * @param artifact an artifact * @return the Maven project for the given artifact * @throws org.apache.maven.project.ProjectBuildingException * if any */ private MavenProject getMavenProjectFromRepository( Artifact artifact, ArtifactRepository localRepository ) throws ProjectBuildingException { Artifact projectArtifact = artifact; boolean allowStubModel = false; if ( !"pom".equals( artifact.getType() ) ) { projectArtifact = factory.createProjectArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope() ); allowStubModel = true; } // TODO: we should use the MavenMetadataSource instead return mavenProjectBuilder.buildFromRepository( projectArtifact, project.getRemoteArtifactRepositories(), localRepository, allowStubModel ); }
/** * * @param projectId * @param dependencyManagement * @return * @throws ProjectBuildingException */ private Map createManagedVersionMap(String projectId, DependencyManagement dependencyManagement) throws ProjectBuildingException { Map map; if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { map = new HashMap(); for (Dependency d : dependencyManagement.getDependencies()) { try { VersionRange versionRange = VersionRange.createFromVersionSpec(d.getVersion()); Artifact artifact = factory.createDependencyArtifact(d.getGroupId(), d.getArtifactId(), versionRange, d.getType(), d.getClassifier(), d.getScope()); map.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new ProjectBuildingException(projectId, "Unable to parse version '" + d.getVersion() + "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e); } } } else { map = Collections.EMPTY_MAP; } return map; }
protected List getTransitiveDependencies( final Set previousArtifacts ) throws ProjectBuildingException, InvalidDependencyVersionException, ArtifactResolutionException, ArtifactNotFoundException { final List dependencies = new ArrayList(); for ( Iterator iter = previousArtifacts.iterator(); iter.hasNext(); ) { final Artifact a = (Artifact) iter.next(); final Artifact pomArtifact = factory.createArtifact( a.getGroupId(), a.getArtifactId(), a.getVersion(), a.getScope(), "pom" ); final MavenProject pomProject = mavenProjectBuilder.buildFromRepository( pomArtifact, project.getRemoteArtifactRepositories(), localRepository ); final Set pomProjectArtifacts = pomProject.createArtifacts( factory, null, null ); final ArtifactResolutionResult result = resolver.resolveTransitively( pomProjectArtifacts, pomArtifact, localRepository, project.getRemoteArtifactRepositories(), metadataSource, null ); dependencies.addAll( result.getArtifacts() ); } return dependencies; }
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); } }
/** * Construct a PomModel from a pom.xml file * @param pomStream InputStream to the pom.xml file * @return a populated PomModel or throws exception if the file could not be parsed or deployed */ public static PomModel resolveFromPom(InputStream pomStream) throws Exception { try { return PomModel.Parser.parse("pom.xml", pomStream); } catch (final Exception e) { if (e.getCause() != null) { if (e.getCause() instanceof ProjectBuildingException) { throw (ProjectBuildingException) e.getCause(); } if (e.getCause() instanceof MavenEmbedderException) { throw (MavenEmbedderException) e.getCause(); } } log.info("Failed to process pom.xml for GAV information.", e); throw e; } }
private List<MavenProject> getProjectsForMavenReactor( MavenSession session ) throws ProjectBuildingException { MavenExecutionRequest request = session.getRequest(); request.getProjectBuildingRequest().setRepositorySession( session.getRepositorySession() ); List<MavenProject> projects = new ArrayList<MavenProject>(); // We have no POM file. // if ( request.getPom() == null ) { ModelSource modelSource = new UrlModelSource( DefaultMaven.class.getResource( "project/standalone.xml" ) ); MavenProject project = projectBuilder.build( modelSource, request.getProjectBuildingRequest() ).getProject(); project.setExecutionRoot( true ); projects.add( project ); request.setProjectPresent( false ); return projects; } List<File> files = Arrays.asList( request.getPom().getAbsoluteFile() ); collectProjects( projects, files, request ); return projects; }
/** * Manually constructs an list of effective reactor projects by recursively * searching parent and submodule projects. This allows the intention of the * reactor to be preserved, as long as it is fully available on disk, even * when building a submodule directly. * * @param defaultReactor Return value to use if a comprehensive list can not * be discovered. * @param baseProject {@link MavenProject} where invocation started. * @return A list of MavenProjects that can be treated as though within the * current reactor. * @throws ProjectBuildingException */ public static List<MavenProject> findEffectiveReactor( final List<MavenProject> defaultReactor, final MavenSession session, final MavenProject baseProject, final MavenProjectBuilder projectBuilder, final ArtifactRepository localRepository) throws ProjectBuildingException { final Set<MavenProject> reactor = new HashSet<MavenProject>(); final Set<MavenProject> visited = new HashSet<MavenProject>(); final ProfileManager profileManager = getProfileManager(session); findEffectiveReactor(reactor, visited, baseProject, baseProject, projectBuilder, localRepository, profileManager); if (reactor.size() <= 1 || !reactor.contains(baseProject)) return defaultReactor; return new ArrayList<MavenProject>(reactor); }
@Override public void execute() throws MojoExecutionException, MojoFailureException { // Find the plugin in the project dependencies final List<DependencyNode> projectChildren = resolveDependencies(getProject(), new FlumePluginDependencyArtifactFilter(dependency)); if (projectChildren.isEmpty()) { throw new MojoFailureException(String.format("No dependency found matching %s in dependency list.", dependency.getFormattedIdentifier())); } else if (projectChildren.size() > 1) { throw new MojoFailureException(String.format("More than one dependency matching %s found in project dependencies: %s", dependency.getFormattedIdentifier(), projectChildren)); } // Resolve the dependencies of the project we've located final Artifact projectChildArtifact = projectChildren.get(0).getArtifact(); final File projectChildFile = getArtifactRepository().find(projectChildArtifact).getFile(); try { buildFlumePluginArchive(projectChildFile, projectBuilder.buildFromRepository(projectChildArtifact, getRemoteArtifactRepositories(), getArtifactRepository())); } catch (ProjectBuildingException e) { throw new MojoExecutionException(String.format("Failed to resolve project for artifact %s", formatIdentifier(projectChildArtifact)), e); } }
private ModelProblem hasMissingParentPom( ProjectBuildingException e ) { if ( e.getCause() instanceof ModelBuildingException ) { ModelBuildingException mbe = (ModelBuildingException) e.getCause(); for ( ModelProblem problem : mbe.getProblems() ) { if ( problem.getException() instanceof UnresolvableModelException ) { return problem; } } } return null; }
private List<MavenProject> getProjectsForMavenReactor( MavenExecutionRequest request ) throws ProjectBuildingException { List<MavenProject> projects = new ArrayList<MavenProject>(); // We have no POM file. // if ( request.getPom() == null ) { ModelSource modelSource = new UrlModelSource( DefaultMaven.class.getResource( "project/standalone.xml" ) ); MavenProject project = projectBuilder.build( modelSource, request.getProjectBuildingRequest() ).getProject(); project.setExecutionRoot( true ); projects.add( project ); request.setProjectPresent( false ); return projects; } List<File> files = Arrays.asList( request.getPom().getAbsoluteFile() ); collectProjects( projects, files, request ); return projects; }
/** * Gathers the project's artifacts and the artifacts of all its (transitive) * dependencies filtered by the given filter instance. * * @param filter * @return * @throws ArtifactResolutionException * @throws ArtifactNotFoundException * @throws ProjectBuildingException * @throws InvalidDependencyVersionException */ @SuppressWarnings("unchecked") public static Set<Artifact> findArtifacts(ArtifactFilter filter, ArtifactFactory factory, ArtifactResolver resolver, MavenProject project, Artifact artifact, ArtifactRepository local, List<ArtifactRepository> remoteRepos, ArtifactMetadataSource metadataSource) throws ArtifactResolutionException, ArtifactNotFoundException, ProjectBuildingException, InvalidDependencyVersionException { ArtifactResolutionResult result = resolver.resolveTransitively( project.getDependencyArtifacts(), artifact, local, remoteRepos, metadataSource, filter); return (Set<Artifact>) result.getArtifacts(); }
/** * replacement for MavenProject.getParent() which has bad long term memory behaviour. We offset it by recalculating/reparsing everything * therefore should not be used lightly! * pass a MavenProject instance and current configuration and other settings will be applied when loading the parent. * @param project * @return null or the parent mavenproject */ public MavenProject loadParentOf(MavenEmbedder embedder, MavenProject project) throws ProjectBuildingException { MavenProject parent = null; ProjectBuilder builder = embedder.lookupComponent(ProjectBuilder.class); MavenExecutionRequest req = embedder.createMavenExecutionRequest(); M2Configuration active = configProvider.getActiveConfiguration(); req.addActiveProfiles(active.getActivatedProfiles()); req.setNoSnapshotUpdates(true); req.setUpdateSnapshots(false); req.setInteractiveMode(false); req.setRecursive(false); req.setOffline(true); //#238800 important to merge, not replace Properties uprops = req.getUserProperties(); uprops.putAll(MavenProjectCache.createUserPropsForProjectLoading(active.getProperties())); req.setUserProperties(uprops); ProjectBuildingRequest request = req.getProjectBuildingRequest(); request.setRemoteRepositories(project.getRemoteArtifactRepositories()); DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class); request.setRepositorySession(maven.newRepositorySession(req)); if (project.getParentFile() != null) { parent = builder.build(project.getParentFile(), request).getProject(); } else if (project.getModel().getParent() != null) { parent = builder.build(project.getParentArtifact(), request).getProject(); } //clear the project building request, it references multiple Maven Models via the RepositorySession cache //is not used in maven itself, most likely used by m2e only.. if (parent != null) { parent.setProjectBuildingRequest(null); } MavenEmbedder.normalizePaths(parent); return parent; }
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; }
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; }
private static List<Dependency> getDependenciesFromDM(MavenProject project, Project nbprj) { NbMavenProjectImpl p = nbprj.getLookup().lookup(NbMavenProjectImpl.class); MavenProject localProj = project; DependencyManagement curDM; List<Dependency> result = new ArrayList<Dependency>(); //mkleint: without the managementKey checks I got some entries multiple times. // do we actually need to traverse the parent poms, are they completely resolved anyway? //XXX Set<String> knownKeys = new HashSet<String>(); while (localProj != null) { curDM = localProj.getDependencyManagement(); if (curDM != null) { @SuppressWarnings("unchecked") List<Dependency> ds = curDM.getDependencies(); for (Dependency d : ds) { if (knownKeys.contains(d.getManagementKey())) { continue; } result.add(d); knownKeys.add(d.getManagementKey()); } } try { localProj = p.loadParentOf(EmbedderFactory.getProjectEmbedder(), localProj); } catch (ProjectBuildingException x) { break; } } Collections.sort(result, new Comparator<Dependency>() { @Override public int compare(Dependency o1, Dependency o2) { return o1.getManagementKey().compareTo(o2.getManagementKey()); } }); return result; }
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; }
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; }
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; }
public String svnurl() throws IOException { try { return maven.loadPom(artifact).getScm().getUrl(); } catch (ProjectBuildingException | RepositoryException e) { throw new IOException(e.getMessage(), e); } }
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; }
/** {@inheritDoc} */ public final File resolve(String value) throws ProjectBuildingException { File projectFile = new File(value); MavenProject mavenProject = embedder.readProject(projectFile); mavenGAV = new ProjectFileResolver.MavenGAV(mavenProject.getGroupId(),mavenProject.getArtifactId(),mavenProject.getVersion()); mavenGAV.setPackaging(mavenProject.getPackaging()); return projectFile; }
@Test public void canResolve() throws ProjectBuildingException { MavenEmbedder mavenEmbedder = createMock(MavenEmbedder.class); MavenProject mavenProject = new MavenProject(); expect(mavenEmbedder.readProject(anyObject(File.class))).andReturn(mavenProject); resolver = new FileResolver(mavenEmbedder, null); replay(mavenEmbedder); assertTrue( resolver.canResolve( "src/test/resources/pom.xml" ) ); File expected = new File( "src/test/resources/pom.xml" ); assertEquals( expected, resolver.resolve( "src/test/resources/pom.xml" ) ); verify(mavenEmbedder); }
private void validate(File pom, List<Exception> exceptions, List<MavenProjectProblem> problems) throws RemoteException { for (Throwable exception : exceptions) { if (exception instanceof IllegalStateException && exception.getCause() != null) { exception = exception.getCause(); } if (exception instanceof InvalidProjectModelException) { ModelValidationResult validationResult = ((InvalidProjectModelException) exception).getValidationResult(); if (validationResult != null) { problems.addAll( validationResult .getMessages() .stream() .map(s -> MavenProjectProblem.newStructureProblem(pom.getPath(), s)) .collect(Collectors.toList())); } else { problems.add( MavenProjectProblem.newStructureProblem( pom.getPath(), exception.getCause().getMessage())); } } if (exception instanceof ProjectBuildingException) { String message = exception.getCause() == null ? exception.getMessage() : exception.getCause().getMessage(); problems.add(MavenProjectProblem.newStructureProblem(pom.getPath(), message)); } else { MavenServerContext.getLogger().info(exception); problems.add( MavenProjectProblem.newStructureProblem(pom.getPath(), exception.getMessage())); } } }
/** * Finds the local root of the specified project. * * @param project The project to find the local root for. * @param localRepository the local repo. * @param globalProfileManager the global profile manager. * @param logger The logger to log to. * @return The local root (note this may be the project passed as an argument). */ public static MavenProject getLocalRoot( MavenProjectBuilder builder, MavenProject project, ArtifactRepository localRepository, ProfileManager globalProfileManager, Log logger ) { logger.info( "Searching for local aggregator root..." ); while ( true ) { final File parentDir = project.getBasedir().getParentFile(); if ( parentDir != null && parentDir.isDirectory() ) { logger.debug( "Checking to see if " + parentDir + " is an aggregator parent" ); File parent = new File( parentDir, "pom.xml" ); if ( parent.isFile() ) { try { final MavenProject parentProject = builder.build( parent, localRepository, globalProfileManager ); if ( getAllChildModules( parentProject, logger ).contains( project.getBasedir().getName() ) ) { logger.debug( parentDir + " is an aggregator parent" ); project = parentProject; continue; } else { logger.debug( parentDir + " is not an aggregator parent" ); } } catch ( ProjectBuildingException e ) { logger.warn( e ); } } } logger.debug( "Local aggregation root is " + project.getBasedir() ); return project; } }
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; }
/** * Finds the local root of the specified project. * * @param project The project to find the local root for. * @param localRepository the local repo. * @param globalProfileManager the global profile manager. * @param logger The logger to log to. * @return The local root (note this may be the project passed as an argument). */ public static MavenProject getLocalRoot( MavenProjectBuilder builder, MavenProject project, ArtifactRepository localRepository, ProfileManager globalProfileManager, Log logger ) { logger.info( "Searching for local aggregator root..." ); while ( true ) { final File parentDir = project.getBasedir().getParentFile(); if ( parentDir.isDirectory() ) { logger.debug( "Checking to see if " + parentDir + " is an aggregator parent" ); File parent = new File( parentDir, "pom.xml" ); if ( parent.isFile() ) { try { final MavenProject parentProject = builder.build( parent, localRepository, globalProfileManager ); if ( getAllChildModules( parentProject, logger ).contains( project.getBasedir().getName() ) ) { logger.debug( parentDir + " is an aggregator parent" ); project = parentProject; continue; } else { logger.debug( parentDir + " is not an aggregator parent" ); } } catch ( ProjectBuildingException e ) { logger.warn( e ); } } } logger.debug( "Local aggregation root is " + project.getBasedir() ); return project; } }
public MavenProject buildFromRepository(Artifact artifact) throws PluginException { try { return projectBuilder.buildFromRepository(artifact, remoteRepositories, localRepository, true); } catch (ProjectBuildingException e) { throw new PluginException( "Unable to build project: " + artifact.getDependencyConflictId(), e); } }
private Collection resolveArtifact(Artifact artifact, Stack dependencies) throws ArtifactResolutionException, ArtifactNotFoundException { MavenProject project = null; try { project = projectBuilder.buildFromRepository(artifact, remoteRepos, localRepo, false); } catch (ProjectBuildingException e) { getLog().warn( "Unable to determine packaging for dependency : " + artifact.getArtifactId() + " assuming jar"); } if (project != null) { if (getDeployablePackagingTypes().contains(project.getPackaging())) { getLog().debug( "Checking for dependency from project " + project.getArtifactId()); JbiDeployableArtifact deployableArtifact = resolveDeploymentPackage( project, artifact); if (!dependencies.contains(deployableArtifact)) { getLog().debug( "Adding dependency from project " + project.getArtifactId()); dependencies.push(deployableArtifact); } List artifactList = new ArrayList(); artifactList.addAll(project.getArtifacts()); Collections.sort(artifactList, new ArtifactDepthComparator()); for (Iterator iter = artifactList.iterator(); iter.hasNext();) { resolveArtifact((Artifact) iter.next(), dependencies); } } else { getLog().debug( "Ignoring non-jbi dependency: " + project.getArtifactId() + " of type " + project.getPackaging()); } } return dependencies; }
protected Map createManagedVersionMap(String projectId, DependencyManagement dependencyManagement) throws ProjectBuildingException { Map map; if (dependencyManagement != null && dependencyManagement.getDependencies() != null) { map = new HashMap(); for (Iterator i = dependencyManagement.getDependencies().iterator(); i .hasNext();) { Dependency d = (Dependency) i.next(); try { VersionRange versionRange = VersionRange .createFromVersionSpec(d.getVersion()); Artifact artifact = factory.createDependencyArtifact(d .getGroupId(), d.getArtifactId(), versionRange, d .getType(), d.getClassifier(), d.getScope()); map.put(d.getManagementKey(), artifact); } catch (InvalidVersionSpecificationException e) { throw new ProjectBuildingException(projectId, "Unable to parse version '" + d.getVersion() + "' for dependency '" + d.getManagementKey() + "': " + e.getMessage(), e); } } } else { map = Collections.EMPTY_MAP; } return map; }
public MavenProject loadPom(FileNode file) throws ProjectBuildingException { try { return loadPom(file, false); } catch (RepositoryException e) { throw new IllegalStateException(e); } }
@Test public void loadPom() throws ArtifactResolutionException, ProjectBuildingException { MavenProject pom; pom = maven.loadPom(maven.getWorld().guessProjectHome(getClass()).join("pom.xml")); assertEquals("embedded", pom.getArtifactId()); }
/** * Entry point for mojo execution */ @Override public void execute() throws MojoExecutionException, MojoFailureException { try { reactorModules = DependencyUtils.findEffectiveReactor(reactorModules, mavenSession, mavenProject, projectBuilder, localRepository); } catch (final ProjectBuildingException exc) { getLog().warn("Error during project construction:\n" + exc.getMessage(), exc); } // Enter recursive project checking final SnapshotFinder fs = new SnapshotFinder(projectBuilder, localRepository, mavenProject .getRemoteArtifactRepositories()); fs.setLog(getLog()); fs.setFailFast(failFast); fs.setGroupIds(getGroupIds()); fs.setReactorModules(reactorModules); try { DependencyUtils.checkDependencies(mavenProject, localRepository, dependencyTreeBuilder, fs); } catch (final SciJavaDependencyException e) { throw new MojoFailureException(e.getMessage() + "\nTo disable Maven Enforcer rules for local development, re-run" + " Maven\n with the -Denforcer.skip property set.\n"); } }
@Override public boolean visit(final DependencyNode node) { final Artifact a = node.getArtifact(); MavenProject pom = null; Result r = null; try { pom = getProject(a); // for the root node, we want to check its parents but we don't care if // it is a SNAPSHOT itself. if (isRoot(node)) { r = new Result(); checkParent(pom, r); } else { r = containsSnapshots(pom); } } catch (final ProjectBuildingException e) { r = new Result(); r.setFailTag(" Failed to build pom."); } // save the results results.put(node, r); // set failure and propagate to parent nodes if (r.failed() && matches(a.getGroupId())) { setFailed(); markParent(node); } return !stopVisit(); }