15

Is it possible to get an instance of org.apache.maven.project.MavenProject or some other object form of the POM from just the pom.xml file?

Thanks in advance.

javamonkey79
  • 17,443
  • 36
  • 114
  • 172

2 Answers2

29

yes you can . This is the code. You need maven-model-3.0.4.jar and plexus-utils-2.0.6.jar and maven-core-3.0.4.jar

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();
try {
    reader = new FileReader(pomfile);
    model = mavenreader.read(reader);
    model.setPomFile(pomfile);
}catch(Exception ex){}
MavenProject project = new MavenProject(model);
Manfred Moser
  • 29,539
  • 13
  • 92
  • 123
rxx
  • 744
  • 6
  • 16
  • 1
    Tried you solution but it doesn't populate some fields of the MavenProject object that I was expecting, like getCompileSourceRoots() returns empty list. – javydreamercsw Nov 21 '12 at 20:43
  • 1
    Reading a pom file does not involve interpolation of data such as variables, inherited settings from parents (and their proto-parents) and so on. – carlspring Jul 11 '13 at 14:26
2

If you want to get the MavenProject based on groupid, artifactId and version you have to run inside of a maven plugin. And this code will do the job:

ProjectBuildingRequest configuration = new DefaultProjectBuildingRequest();
configuration.setProcessPlugins( false );
configuration.setRepositorySession( session );
org.apache.maven.artifact.Artifact artifact = new org.apache.maven.artifact.DefaultArtifact(groupId, artifactId, version, "compile", "", "", new DefaultArtifactHandler());
MavenProject project = projectBuilder.build(artifact, configuration).getProject();

The missing properties can be injected into the maven plugin.

Robert Reiz
  • 4,243
  • 2
  • 30
  • 43