I want to automate part of our build system in Java. For that I need to calculate a dependency tree of the sources that are existent in a given file tree.
So, I want to crawl over a set of directories and find the pom.xml
files that are existent there. That works fine. Then I want to parse that files to instances of MavenProject
so I can call getParent()
and getDependencies()
and such on it.
So, the question is: how do I get a fully populated MavenProject
with maven3 libraries? Its is acceptable for me to include a third party library if necessary but would prefer a solution that consists of maven natives.
I have read Get MavenProject from just the POM.xml - pom parser? but the answers there don't work for me (the MavenProject
is not not populated correctly)
My code is in Java, so I want to have the contents of a method like this:
private MavenProject makeProjectFromPom(File pomXML) {
// Here is what I don't know.
}
So that I can do something like this in my program:
public List<MavenProject> getAllMavenProjectsWithParent(File rootDir, MavenProject parent) {
List<File> allPoms = findAllPoms(rootDir);
List<MavenProject> result = new ArrayList<>();
for(File nextPom : allPoms) {
MavenProject next = makeProjectFromPom(nextPom);
if(next.hasParent() && next.getParent().equals(parent))
result.add(next);
}
return result;
}
This is just an example, but one that does not work at the moment for me.
In Maven2 I could do it like this:
String basePath = "somepath";
MavenEmbedder embedder = new MavenEmbedder();
File basedir = new File(basePath);
final List<File> allDirsWithPomXML = new ArrayList<>();
// the next line crawls through the directory and collects references to pom.xml paths.
gatherPomXMLPaths(basedir, allDirsWithPomXML);
embedder.setClassLoader(this.getClass().getClassLoader());
embedder.start();
List<MavenProject> collectedProjects = new ArrayList<>();
for (File nextDir : allDirsWithPomXML) {
collectedProjects.addAll(embedder.collectProjects(nextDir, new String[]{"pom.xml"}, new String[0]));
}
The MavenProject
references in the collectedProjects
would now contain information like parent, dependencies etc.