gpt4 book ai didi

java - 以编程方式解决插件外部的 Maven 依赖关系 - 获取 RepositorySystemSession 和 RepositorySystem

转载 作者:搜寻专家 更新时间:2023-10-30 21:05:24 24 4
gpt4 key购买 nike

也许这将是一项比我原先想象的更大的任务,但无论如何,我正在尝试从文件加载 MavenProject,然后解析其依赖项。我有两个位的代码,但缺少一些我需要的对象引用;具体来说,我需要获取 RepositorySystemSessionRepositorySystem 的实例。有什么建议吗?

注意:我用 标记了这个问题,但这不是 Maven 插件。我很高兴授权 Maven 3(我想我已经拥有了......)

这是我目前的代码:

构建MavenProject:

public static MavenProject loadProject(File pomFile) throws Exception
{
MavenProject ret = null;
MavenXpp3Reader mavenReader = new MavenXpp3Reader();

if (pomFile != null && pomFile.exists())
{
FileReader reader = null;

try
{
reader = new FileReader(pomFile);
Model model = mavenReader.read(reader);
model.setPomFile(pomFile);

ret = new MavenProject(model);
}
finally
{
// Close reader
}
}

return ret;
}

解决依赖关系:

public static List<Dependency> getArtifactsDependencies(MavenProject project, String dependencyType, String scope) throws Exception
{
DefaultArtifact pomArtifact = new DefaultArtifact(project.getId());

RepositorySystemSession repoSession = null; // TODO
RepositorySystem repoSystem = null; // TODO

List<RemoteRepository> remoteRepos = project.getRemoteProjectRepositories();
List<Dependency> ret = new ArrayList<Dependency>();

Dependency dependency = new Dependency(pomArtifact, scope);

CollectRequest collectRequest = new CollectRequest();
collectRequest.setRoot(dependency);
collectRequest.setRepositories(remoteRepos);

DependencyNode node = repoSystem.collectDependencies(repoSession, collectRequest).getRoot();
DependencyRequest projectDependencyRequest = new DependencyRequest(node, null);

repoSystem.resolveDependencies(repoSession, projectDependencyRequest);

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

ret.addAll(nlg.getDependencies(true));

return ret;
}

我意识到这可能是一个不寻常的请求,也许我应该放弃我正在尝试做的事情并将其包装为一个插件......但我有点想完成我现在开始的事情!提前致谢。

最佳答案

尝试 jcabi-aether ,它是 Apache Aether 的包装器来自 Sonatype:

final File repo = this.session.getLocalRepository().getBasedir();
final Collection<Artifact> deps = new Aether(this.getProject(), repo).resolve(
new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
JavaScopes.RUNTIME
);

如果您在 Maven 插件之外:

final File repo = new File(System.getProperty("java.io.tmpdir"), "my-repo");
final MavenProject project = new MavenProject();
project.setRemoteArtifactRepositories(
Arrays.asList(
new RemoteRepository(
"maven-central",
"default",
"http://repo1.maven.org/maven2/"
)
)
);
final Collection<Artifact> deps = new Aether(project, repo).resolve(
new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
JavaScopes.RUNTIME
);

关于java - 以编程方式解决插件外部的 Maven 依赖关系 - 获取 RepositorySystemSession 和 RepositorySystem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11799923/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com