How do I download a jar using maven programaticall

2020-07-11 09:01发布

问题:

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

回答1:

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



回答2:

To download artifacts from a Maven repository it is intended to use Aether lib.

See also http://www.sonatype.com/people/category/aether/

Furthermore there are examples how to do things and the complete source code of Aether lib. Longer time a ago i had played a little bit around with Aether.