chenhui0212
9/19/2018 - 1:45 AM

Maven手动加载需要的Jar包环境

Maven手动加载需要的Jar包环境

@Mojo(name = "generate", defaultPhase = LifecyclePhase.INITIALIZE)
public class ProtoFileGenerator extends AbstractMojo {

    @Component
    private MavenProject project;
    @Component
    private PluginDescriptor descriptor;
    @Component
    private RepositorySystem repoSystem;
    @Parameter(defaultValue = "${repositorySystemSession}", readonly = true, required = true)
    private RepositorySystemSession repoSession;

    public void execute() throws MojoExecutionException {
        // 加载环境
        loadClassRealm();

        doSomething();
    }

    /**
     * 加载依赖的环境,并查询要生成Proto文件的Jar包路径
     */
    private void loadClassRealm() throws MojoExecutionException {
        try {
            ClassRealm realm = descriptor.getClassRealm();

            // 将所有依赖的Jar包,添加到Maven环境中
            for (org.apache.maven.model.Dependency dependency : project.getDependencies()) {
                List<ArtifactResult> artifactResults = getAllRelatedArtifacts(dependency);
                for (ArtifactResult ar : artifactResults) {
                    realm.addURL(ar.getArtifact().getFile().toURI().toURL());
                }
            }
        } catch (MalformedURLException e) {
            throw new MojoExecutionException("Could not load project dependencies.", e);
        }
    }

    private List<ArtifactResult> getAllRelatedArtifacts(org.apache.maven.model.Dependency dependency)
            throws MojoExecutionException {
        Artifact artifact = new DefaultArtifact(
                dependency.getGroupId(),
                dependency.getArtifactId(),
                dependency.getClassifier(),
                dependency.getType(),
                dependency.getVersion());

        ArtifactRequest artifactReq = new ArtifactRequest()
                .setRepositories(project.getRemotePluginRepositories())
                .setArtifact(artifact);

        CollectRequest collectRequest = new CollectRequest(new Dependency(artifact, JavaScopes.COMPILE),
                project.getRemotePluginRepositories());
//        DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.COMPILE);
        DependencyRequest dependencyReq = new DependencyRequest(collectRequest, null);

        List<ArtifactResult> artifactResults = new ArrayList<>();
        try {
            ArtifactResult ar = repoSystem.resolveArtifact(repoSession, artifactReq);
            artifactResults.add(ar);

            List<ArtifactResult> dar = repoSystem.resolveDependencies(repoSession, dependencyReq).getArtifactResults();
            artifactResults.addAll(dar);
        } catch (ArtifactResolutionException | DependencyResolutionException e) {
            throw new MojoExecutionException("Artifact " + dependency.getArtifactId() + " could not be resolved.", e);
        }
        return artifactResults;
    }
}