使用 aether api 从指定maven仓库下载jar包

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36898043/article/details/82187326

一、简介

想要下载远程maven仓库中的jar,需要用到aether api。简单的来说我们需要远程仓库地址、用户名、密码以及maven信息等。

在aether中,针对这些信息,有着自己的类库,

下载jar主要用到:RepositorySystem、RepositorySystemSession、RemoteRepository、LocalRepository

RepositorySystem:相当于掌控全局的操作者,可以配置本地仓库对象管理器(传入本地仓库对象)

RepositorySystemSession:

RemoteRepository:相当于远程仓库

LocalRepository:相当于代表本地仓库(也可以理解为想要下载的位置)

二、具体代码:

1、pom文件:

<properties>
    <aetherVersion>1.0.0</aetherVersion>
    <mavenVersion>3.1.0</mavenVersion>
    <wagonVersion>1.0</wagonVersion>
</properties>
  <dependencies>
        <!-- aether下载jar start -->
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-api</artifactId>
            <version>${aetherVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.eclipse.aether</groupId>
            <artifactId>aether-util</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.eclipse.aether</groupId>
            <artifactId>aether-transport-wagon</artifactId>
            <version>${aetherVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-aether-provider</artifactId>
            <version>${mavenVersion}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven.wagon</groupId>
            <artifactId>wagon-ssh</artifactId>
            <version>${wagonVersion}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.5</version>
        </dependency>
        <!-- aether下载jar end -->
    </dependencies>

2、配置(参数)信息类:

package me.ele.domain;

/**
 * @author LZJ
 * @create 2018-08-18 11:41
 **/
public class Params {

    private String groupId;

    private String artifactId;

    private String version;

    //远程maven仓库的URL地址 http://" + host + ":" + port + "/nexus/content/groups/public/
    private String repository;

    //下载的jar包存放的目标地址
    private String target;

    private String username;

    private String password;

    public Params() {
        super();
    }

    public Params(String groupId, String artifactId) {
        super();
        this.groupId = groupId;
        this.artifactId = artifactId;
    }

    public Params(String groupId, String artifactId, String username,
                  String password) {
        super();
        this.groupId = groupId;
        this.artifactId = artifactId;
        this.username = username;
        this.password = password;
    }

    public Params(String groupId, String artifactId, String version,
                  String repository, /*String target,*/ String username, String password) {
        super();
        this.groupId = groupId;
        this.artifactId = artifactId;
        this.version = version;
        this.repository = repository;
        /*this.target = target;*/
        this.username = username;
        this.password = password;
    }

    public Params(String groupId, String artifactId, String version,
                  String username, String password) {
        super();
        this.groupId = groupId;
        this.artifactId = artifactId;
        this.version = version;
        this.username = username;
        this.password = password;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getArtifactId() {
        return artifactId;
    }

    public void setArtifactId(String artifactId) {
        this.artifactId = artifactId;
    }

    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public String getRepository() {
        return repository;
    }

    public void setRepository(String repository) {
        this.repository = repository;
    }

    public String getTarget() {
        return target;
    }

    public void setTarget(String target) {
        this.target = target;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

}

3、工厂类封装:生成RepositorySystem 、RepositorySystemSession、RemoteRepository、LocalRepository

package me.ele.maven;

import me.ele.domain.MavenRepositoryProperties;
import me.ele.domain.Params;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;
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.DefaultArtifact;
import org.eclipse.aether.connector.basic.BasicRepositoryConnectorFactory;
import org.eclipse.aether.graph.DependencyFilter;
import org.eclipse.aether.impl.DefaultServiceLocator;
import org.eclipse.aether.repository.Authentication;
import org.eclipse.aether.repository.LocalRepository;
import org.eclipse.aether.repository.RemoteRepository;
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;
import org.eclipse.aether.util.artifact.JavaScopes;
import org.eclipse.aether.util.filter.DependencyFilterUtils;
import org.eclipse.aether.util.graph.manager.DependencyManagerUtils;
import org.eclipse.aether.util.graph.transformer.ConflictResolver;
import org.eclipse.aether.util.repository.AuthenticationBuilder;

import java.io.File;
import java.lang.annotation.Target;

/**
 * @author LZJ
 * @create 2018-07-19 11:28
 **/
public class DependencyFactory {

    /**
     * 生成 RepositorySystem
     *
     * @return RepositorySystem
     */
    public 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);
        System.out.println("创建RepositorySystem");
        return locator.getService(RepositorySystem.class);
    }

    /**
     * 生成 RepositorySystemSession
     *
     * @param system RepositorySystem
     * @return RepositorySystemSession
     */
    public static RepositorySystemSession newSession(RepositorySystem system, String target) {
        DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
        LocalRepository localRepo = newLocalRepository(target);
        session.setConfigProperty(ConflictResolver.CONFIG_PROP_VERBOSE, true);
        session.setConfigProperty(DependencyManagerUtils.CONFIG_PROP_VERBOSE, true);
        session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
        System.out.println("创建RepositorySystemSession");
        return session;
    }

    /**
     * 生成 RemoteRepository
     *
     * @param params
     * @return
     */
    public static RemoteRepository newRemoteRepository(Params params) {
        RemoteRepository central;
        String repository = params.getRepository();
        String username = params.getUsername();
        String password = params.getPassword();
        if (StringUtils.isNotBlank(repository)) {
            System.out.println("创建自定义RemoteRepository");
            if (StringUtils.isNotBlank(username) && StringUtils.isNotBlank(password)) {
                central = new RemoteRepository.Builder("central", "default", repository).build();
            } else {
                Authentication authentication = new AuthenticationBuilder().addUsername(username).addPassword(password).build();
                central = new RemoteRepository.Builder("central", "default", repository).setAuthentication(authentication).build();
            }
        } else {
            System.out.println("创建默认RemoteRepository");
            MavenRepositoryProperties mrp = new MavenRepositoryProperties();
            repository = "http://" + mrp.getHost() + ":" + mrp.getPort() + "/nexus/content/groups/public/";
            central = new RemoteRepository.Builder("central", "default", repository).build();
        }

        return central;
    }

    /**
     * 生成 LocalRepository
     *
     * @param target
     * @return
     */
    public static LocalRepository newLocalRepository(String target) {
        System.out.println(SystemUtils.getUserHome());
        if (StringUtils.isNotBlank(target)) {
            System.out.println("创建默认LocalRepository");
            return new LocalRepository(new File("/data/parseJsonSchema/downloadTmp/repository").toString());

        } else {
            System.out.println("创建自定义LocalRepository");
            return new LocalRepository(target);
        }
    }

    public static DefaultArtifact newDefaultArtifact(String artifactId, String groupId, String version) {
        System.out.println("创建DefaultArtifact");
        String artifactStr = groupId + ":" + artifactId + ":" + version;
        return new DefaultArtifact(artifactStr);
    }

    public static void main(String[] args) {
        newLocalRepository(null);
    }
}

4、下载jar的类:

package me.ele.maven;

import me.ele.domain.Params;
import me.ele.utils.FileUtils;
import org.eclipse.aether.RepositorySystem;
import org.eclipse.aether.RepositorySystemSession;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.collection.CollectRequest;
import org.eclipse.aether.graph.Dependency;
import org.eclipse.aether.graph.DependencyNode;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.resolution.*;
import org.eclipse.aether.util.graph.visitor.PreorderNodeListGenerator;

/**
 * 下载远程仓库的jar
 *
 * @author LZJ
 * @create 2018-08-18 18:47
 **/
public class DownloadMavenJar {

    /**
     * 从指定maven地址下载指定jar包
     *
     * @param params
     * @throws ArtifactResolutionException
     */
    public static void downLoadMavenJar(Params params) throws Exception {

        FileUtils.createDir(params.getTarget());

        RepositorySystem repoSystem = DependencyFactory.newRepositorySystem();
        RepositorySystemSession session = DependencyFactory.newSession(repoSystem, params.getTarget());
        RemoteRepository central = DependencyFactory.newRemoteRepository(params);

        //下载该jar包及其所有依赖jar包
        DefaultArtifact defaultArtifact = DependencyFactory.newDefaultArtifact(params.getArtifactId(), params.getGroupId(), params.getVersion());
        Dependency dependency = new Dependency(defaultArtifact, null);

        CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(dependency);
        collectRequest.addRepository(central);
        DependencyNode node = repoSystem.collectDependencies(session, collectRequest).getRoot();

        DependencyRequest dependencyRequest = new DependencyRequest();
        dependencyRequest.setRoot(node);

        repoSystem.resolveDependencies(session, dependencyRequest);

        PreorderNodeListGenerator nlg = new PreorderNodeListGenerator();
        node.accept(nlg);

        //此时就已经下载好了 打印出jars
        System.out.println(nlg.getFiles());

    }


}

猜你喜欢

转载自blog.csdn.net/qq_36898043/article/details/82187326