Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download a jar using maven programatically

Tags:

java

maven

aether

I am writing an application that requires me to download a jar given the mavens groupid/artifactid/version.

I currently start with

public Model pomToModel(String pomUrl) throws Exception {
URL url = new URL(pomUrl);
    InputStream stream = url.openStream();
    try {
        Model model = new MavenXpp3Reader().read(stream);
        return model;
    } finally {
        stream.close();
    }
}

So given the url of the POM, I now have the maven Model object representing it. This seems to work well.

What I would like to do know is two things:

  1. find the url of the jar artifact that the model represents in the maven repository that the maven plugin would use
  2. given the model, find the file representing the jar in the local repository

I already have poor quality solutions: I go to mvnrepository.com manually coding the url, and I use ~/.m2/repository as the prefix for the file. I can obviously improve this solution, but I will end up poorly duplicating the code that is well tested and well used in the maven code base.

I'd really like to know how to do this using the maven classes.

I have done a fair bit of google searching, but the amusing thing about searching for anything about maven and jars (even on stackoverflow) is that I find lots of solutions about how to use maven, rather than how to code using the maven classes.

Thanks for the help

like image 493
Phil Rice Avatar asked Jun 05 '12 11:06

Phil Rice


1 Answers

Option 1

Aether as recommended by khmarbaise.

It's the native library that ships with Maven 3.0

Option 2

If you want a simple solution for downloading Maven modules from the command line or within a shell script, Apache ivy has a standalone jar.

Example:

using IVY dependencies manager programmatically

Option 3

If you're just looking for a Maven jar and don't care about dependency management it's even simpler.

Here's how to retrieve the log4j jar direct from Maven Central:

curl -O http://search.maven.org/remotecontent?filepath=log4j/log4j/1.2.17/log4j-1.2.17.jar

If you're using a Nexus repository manager it has a useful REST API

Using the Nexus rest API to get latest artifact version for given groupid/artifactId

like image 186
Mark O'Connor Avatar answered Nov 08 '22 18:11

Mark O'Connor