I am inside the execute
method of my implementation for org.eclipse.core.commands.AbstractHandler
. From ExecutionEvent
I can get the project reference:
@Override
public Object execute(ExecutionEvent event) throws ExecutionException
{
TreeSelection selection = (TreeSelection)HandlerUtil.getCurrentSelection(event);
IJavaElement je = (IJavaElement)selection.getFirstElement()
IJavaProject jproj = je.getJavaProject();
IProject p = (IProject)jproj.getResource();
//...
}
Through core expressions I ensure that the project has java and maven natures. So I want to get a maven model from that project. Of course there is an approach to get it from file:
MavenXpp3Reader mReader = new MavenXpp3Reader();
Model pomModel = mReader.read(p.getFile("pom.xml").getContents());
But since I have access to the workspace I am not sure if I really need to read the POM file myself. I think it should be already evaluated by the m2eclipse plugin. Is there a way to access the maven model of a project somehow?
I found out there is a maven project registry which keeps all known maven projects of the workspace. With its aid I can get to the maven model without reading the POM manually:
public Object execute(ExecutionEvent event) throws ExecutionException
{
TreeSelection selection = (TreeSelection)HandlerUtil.getCurrentSelection(event);
IJavaElement je = (IJavaElement)selection.getFirstElement();
IJavaProject jproj = je.getJavaProject();
IProject proj = (IProject)jproj.getResource();
IMavenProjectFacade facade = MavenPlugin.getMavenProjectRegistry().getProject(proj);
Model mavenModel = facade.getMavenProject().getModel();
//...
return null;
}
Edit: Usage of IMavenProjectFacade#getMavenProject()
is not null safe. If m2eclipse hasn't loaded a referenced project to its cache yet (i.e. right after eclipse start), it will return null. That's why it's better to use IMavenProjectFacade#getMavenProject(IProgressMonitor monitor)
which does "lazy load and cache MavenProject instance" according to the javadocs.