Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download artifact from Maven repository in Java program

I need to write Java code that downloads a given artifact (GAV) from a given Maven repository. In the past I used the REST interface of Nexus 2 (which is quite easy) but I would like to have something which is independent of the repository (Nexus 2, Nexus 3, Artifactory) used.

In Fetching Maven artifacts programmatically a similar question is asked, but the main answer is from 2014 and suggests a library that was not updated since 2014.

like image 270
J Fabian Meier Avatar asked Jan 31 '18 08:01

J Fabian Meier


People also ask

How do I download a dependency from Maven repository?

You can use the Maven Dependency Plugin to download dependencies. Run mvn dependency:copy-dependencies , to download all your dependencies and save them in the target/dependency folder. You can change the target location by setting the property outputDirectory .

What is Maven artifact repository?

As a Maven repository, Artifactory is both a source for artifacts needed for a build, and a target to deploy artifacts generated in the build process. Maven is configured using a settings. xml file located under your Maven home directory (typically, this will be /user.

How do I force Maven to download dependencies from remote repository?

We can use -U/--update-snapshots flag when building a maven project to force maven to download dependencies from the remote repository. Here, -U,--update-snapshots : Forces a check for missing releases and updated snapshots on remote repositories.


3 Answers

One can do the following thing with Aether (Version 1.1.0):

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.eclipse.aether.DefaultRepositorySystemSession;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.ArtifactRequest;
import org.eclipse.aether.resolution.ArtifactResolutionException;
import org.eclipse.aether.resolution.ArtifactResult;
import org.eclipse.aether.spi.connector.RepositoryConnectorFactory;
import org.eclipse.aether.spi.connector.transport.TransporterFactory;
import org.eclipse.aether.transport.file.FileTransporterFactory;
import org.eclipse.aether.transport.http.HttpTransporterFactory;


public class ArtifactDownload
{

  private static RepositorySystem newRepositorySystem()
  {
    DefaultServiceLocator locator = MavenRepositorySystemUtils
        .newServiceLocator();
    locator.addService(RepositoryConnectorFactory.class,
        BasicRepositoryConnectorFactory.class);
    locator.addService(TransporterFactory.class, FileTransporterFactory.class);
    locator.addService(TransporterFactory.class, HttpTransporterFactory.class);
    return locator.getService(RepositorySystem.class);

  }

  private static RepositorySystemSession newSession(RepositorySystem system,
      File localRepository)
  {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils
        .newSession();
    LocalRepository localRepo = new LocalRepository(localRepository.toString());
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session,
        localRepo));
    return session;
  }


  public static File getArtifactByAether(String groupId, String artifactId,
      String version, String classifier, String packaging, File localRepository)
      throws IOException
  {
    RepositorySystem repositorySystem = newRepositorySystem();
    RepositorySystemSession session = newSession(repositorySystem,
        localRepository);

    Artifact artifact = new DefaultArtifact(groupId, artifactId, classifier,
        packaging, version);
    ArtifactRequest artifactRequest = new ArtifactRequest();
    artifactRequest.setArtifact(artifact);

    List<RemoteRepository> repositories = new ArrayList<>();

    RemoteRepository remoteRepository = new RemoteRepository.Builder("public",
        "default", "http://somerepo").build();

    repositories.add(remoteRepository);

    artifactRequest.setRepositories(repositories);
    File result;

    try
    {
      ArtifactResult artifactResult = repositorySystem.resolveArtifact(session,
          artifactRequest);
      artifact = artifactResult.getArtifact();
      if (artifact != null)
      {
        result = artifact.getFile();
      }
      else
      {
        result = null;
      }
    }
    catch (ArtifactResolutionException e)
    {
      throw new IOException("Artefakt " + groupId + ":" + artifactId + ":"
          + version + " konnte nicht heruntergeladen werden.");
    }

    return result;

  }
}

using the following artifacts

    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-api</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-spi</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-impl</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-connector-basic</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-transport-file</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.eclipse.aether</groupId>
      <artifactId>aether-transport-http</artifactId>
      <version>${aetherVersion}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.maven</groupId>
      <artifactId>maven-aether-provider</artifactId>
      <version>${mavenVersion}</version>
    </dependency>

with

<aetherVersion>1.1.0</aetherVersion>
<mavenVersion>3.3.3</mavenVersion>
like image 143
J Fabian Meier Avatar answered Oct 22 '22 21:10

J Fabian Meier


I recently found myself in the situation to have the requirement to download files from a maven repository. I stumbled over (at: https://www.hascode.com/2017/09/downloading-maven-artifacts-from-a-pom-file-programmatically-with-eclipse-aether/#comment-5602) following https://github.com/shrinkwrap/resolver library which is much easier to use than the Eclipse Aether project.

String artifactoryUrl = "https://your-repo:port/repository";
String[] requiredTypes = new String[] { "zip", "xml" };

for (String requiredType : requiredTypes) {
    MavenResolvedArtifact[] result = Maven.configureResolver()
            .withMavenCentralRepo(false)
            .withRemoteRepo("default", artifactoryUrl, "default")
            .useLegacyLocalRepo(true) // You can also set to ignore origin of artifacts present in local repository via useLegacyLocalRepo(true) method.
            .resolve(
                    group + ":" +
                    id + ":" +
                    requiredType + ":" +
                    version
            )
            .withTransitivity()
            .asResolvedArtifact();

    for (MavenResolvedArtifact mavenResolvedArtifact : result) {
        System.out.println(mavenResolvedArtifact);
        System.out.println(mavenResolvedArtifact.asFile().getAbsolutePath());
    }
 }
like image 22
keocra Avatar answered Oct 22 '22 19:10

keocra


You are describing the features of maven-dependency-plugin (get goal)

So there is Java code that does exactly what you want, in the context of a maven plugin.

I would simply

  • retrieve the source code of the get plugin from github
  • remove all the maven plugin stuff (@Component dependency injection, parameters)
  • integrate the gist of it where you need it (and add dependencies on the internal maven libraries that are required)
like image 38
Arnaud Jeansen Avatar answered Oct 22 '22 20:10

Arnaud Jeansen