Getting the versioning through maven API - maven

I'm trying to get the versions of a maven artifact by using:
#Mojo(name = "myGoal", defaultPhase = LifecyclePhase.VERIFY)
public class MyMojo extends AbstractMojo{
#Parameter(defaultValue = "${project}", readonly = true)
private MavenProject project;
public void execute() throws MojoExecutionException, MojoFailureException {
Artifact myartifact = project.getArtifact();
ArtifactRepositoryMetadata artifactRepoMetadata = new ArtifactRepositoryMetadata(myartifact);
Versioning versioning = artifactRepoMetadata.getMetadata().getVersioning();
List<Version> versions = versioning.getVersions();
But for some reason "versioning" is null. What do I need to do to get it to work and return the versioning so that I can get a list of versions for my artifact?

Related

How to get the location of a Maven dependency in a custom plugin?

In a custom Maven plugin, during of execution I need to know the location of all dependencies of the Maven project, something like
/home/kider/.m2/repository/org/jdom/jdom/1.1/jdom-1.1.jar
I tried to get the dependencies one by one from MavenProject but I have access only to the GAV informations, but not to the file itself.
#Mojo(name = "testplugin", defaultPhase = LifecyclePhase.TEST)
public class MyMojo extends AbstractMojo {
#Parameter( defaultValue = "${localRepository}", readonly = true, required = true )
private ArtifactRepository localRepo;
#Parameter(defaultValue = "${project}")
public MavenProject project;
...
for (Dependency dep : this.project.getDependencyManagement().getDependencies()) {
this.localRepo.getBasedir()
+ File.separator
+ dep.getGroupId().replace(".", File.separator)
+ File.separator
+ dep.getArtifactId().replace(".", File.separator)
+ File.separator
+ dep.getVersion()
}
Is there any other solution to this?

Using HttpConnector in a SonarQube plugin

I'm trying to develop a SonarQube (Compute Engine) plugin and I need to use the credentials (sonar.user // sonar.password) in order to invoke web services from within the plugin itself.
I try declaring the use of them in the Plugin class, e.g.:
#Override
public void define(Plugin.Context context) {
...
context.addExtensions(asList(
PropertyDefinition.builder(SONAR_USER)
.name("Sonar user")
.description("SonarQube user")
.onQualifiers(Qualifiers.PROJECT)
.type(PropertyType.STRING)
.defaultValue("admin")
.build()
...
Then in the hook:
public class Hook implements PostProjectAnalysisTask {
private final Server server;
private final Settings settings;
public Hook(Server server, Settings settings) {
this.server = server;
this.settings = settings;
}
#Override
public void finished(ProjectAnalysis projectAnalysis) {
final HttpConnector httpConnector =
HttpConnector.newBuilder()
.url(server.getURL())
.credentials(
settings.getString(CePlugin.SONAR_USER), // null
settings.getString(CePlugin.SONAR_PASSWORD) // null
).build();
final WsClient wsClient = WsClientFactories.getDefault().newClient(httpConnector);
}
}
But when I inject Settings inside the hook the property is not available.
How do I retrieve sonar.user and sonar.password so that I can invoke the Web Service API?

Find dependencies of a Maven Dependency object

I'm writing a Maven 3 plugin that needs to know the transitive dependencies of a given org.apache.maven.model.Dependency. How can I do that?
In Maven 3, you access all dependencies in a tree-based form by relying on the maven-dependency-tree shared component:
A tree-based API for resolution of Maven project dependencies.
This component introduces the DependencyGraphBuilder that can build the dependency tree for a given Maven project. You can also filter artifacts with a ArtifactFilter, that has a couple of built-in implementations to filter by groupId, artifactId (IncludesArtifactFilter and ExcludesArtifactFilter), scope (ScopeArtifactFilter), etc. If the fiter is null, all dependencies are kept.
In your case, since you target a specific artifact, you could add a IncludesArtifactFilter with the pattern groupId:artifactId of your artifact. A sample code would be:
#Mojo(name = "foo")
public class MyMojo extends AbstractMojo {
#Parameter(defaultValue = "${project}", readonly = true, required = true)
private MavenProject project;
#Parameter(defaultValue = "${session}", readonly = true, required = true)
private MavenSession session;
#Component(hint = "default")
private DependencyGraphBuilder dependencyGraphBuilder;
public void execute() throws MojoExecutionException, MojoFailureException {
ArtifactFilter artifactFilter = new IncludesArtifactFilter(Arrays.asList("groupId:artifactId"));
ProjectBuildingRequest buildingRequest = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
buildingRequest.setProject(project);
try {
DependencyNode rootNode = dependencyGraphBuilder.buildDependencyGraph(buildingRequest, artifactFilter);
CollectingDependencyNodeVisitor visitor = new CollectingDependencyNodeVisitor();
rootNode.accept(visitor);
for (DependencyNode node : visitor.getNodes()) {
System.out.println(node.toNodeString());
}
} catch (DependencyGraphBuilderException e) {
throw new MojoExecutionException("Couldn't build dependency graph", e);
}
}
}
This gives access to the root node of the dependency tree, which is the current project. From that node, you can access all chidren by calling the getChildren() method. So if you want to list all dependencies, you can traverse that graph recursively. This component does provide a facility for doing that with the CollectingDependencyNodeVisitor. It will collect all dependencies into a List to easily loop through it.
For the Maven plugin, the following dependency is therefore necessary:
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-dependency-tree</artifactId>
<version>3.0</version>
</dependency>
So the following code should give you an impression how to do it.
#Mojo( name = "test", requiresDependencyResolution = ResolutionScope.COMPILE, defaultPhase = LifecyclePhase.PACKAGE ...)
public class TestMojo
extends AbstractMojo
{
#Parameter( defaultValue = "${project}", readonly = true )
private MavenProject project;
public void execute()
throws MojoExecutionException, MojoFailureException
{
List<Dependency> dependencies = project.getDependencies();
for ( Dependency dependency : dependencies )
{
getLog().info( "Dependency: " + getId(dependency) );
}
Set<Artifact> artifacts = project.getArtifacts();
for ( Artifact artifact : artifacts )
{
getLog().info( "Artifact: " + artifact.getId() );
}
}
private String getId(Dependency dep) {
StringBuilder sb = new StringBuilder();
sb.append( dep.getGroupId() );
sb.append( ':' );
sb.append( dep.getArtifactId() );
sb.append( ':' );
sb.append( dep.getVersion() );
return sb.toString();
}
}
The above code will give you the resolved artifacts as well as dependencies. You need to make a difference between the dependencies (in this case the project dependencies without transitive and the artifacts which are the solved artifacts incl. transitive.).
Most important is requiresDependencyResolution = ResolutionScope.COMPILE otherwise you will get null for getArtifacts().
The suggestion by Tunaki will work for any kind of artifact which is not part of your project...The question is what you really need?

How to get programmatically the highest version for a Maven artifact from my local repository?

in many posts I saw that the Aether project helps in working with artifact repositories. What I would like is to retrieve the highest version for a specified groupId and artifactId only.
In Aether wiki they present a case for the org.apache.maven:maven-profile:2.2.1 artifact where they specify also the version:
Dependency dependency =
new Dependency(
new DefaultArtifact("org.apache.maven:maven-profile:2.2.1"),
"compile"
);
But I need to get back the version, the highest version for an artifact. How could I do this?
If you can read the pom.xml file, you can do it with bare xml parsing.
public static String getVersionOf(File pomFile) throws ParserConfigurationException, IOException, SAXException {
String version = "";
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(pomFile);
NodeList nodeList = doc.getElementsByTagName("project");
for(int i = 0; i < nodeList.getLength(); i++) {
Element node = (Element) nodeList.item(i);
version = node.getElementsByTagName("version").item(0).getTextContent();
}
return version;
}

For a Maven 3 plugin what is the latest way to resolve a artifact

What is the latest way of resolving an Artifact within a Maven 3.2.5 plugin. ArtifactResolver and ArtifactFactory(depreciated) are in the compat library which implies that there is a newer/better way of resolution, but I can not find any examples, docs or searches that do not use the above.
Thanks
Michael
There's a blog from sonatype on exactly this:
http://blog.sonatype.com/2011/01/how-to-use-aether-in-maven-plugins
This is the code from the blog entry (full details are obviously described there):
public MyMojo extends AbstractMojo {
/**
* The entry point to Aether, i.e. the component doing all the work.
*/
#Component
private RepositorySystem repoSystem;
/**
* The current repository/network configuration of Maven.
*/
#Parameter(defaultValue = "${repositorySystemSession}", readonly = true)
private RepositorySystemSession repoSession;
/**
* The project's remote repositories to use for the resolution of plugins and their dependencies.
*/
#Parameter(defaultValue = "${project.remotePluginRepositories}", readonly = true)
private List<RemoteRepository> remoteRepos;
public void execute() throws MojoExecutionException, MojoFailureException {
ArtifactRequest request = new ArtifactRequest();
request.setArtifact(new DefaultArtifact( "org.apache.maven:maven-model:3.0" ) );
request.setRepositories( remoteRepos );
ArtifactResult result = repoSystem.resolveArtifact( repoSession, request );
}
}
You can then use result.getArtifact() to get the artifact and result.getArtifact().getFile() to get the file of the artifact if you need it.

Resources