gpt4 book ai didi

maven-2 - Maven : How to check if an artifact exists?

转载 作者:行者123 更新时间:2023-12-02 06:26:22 26 4
gpt4 key购买 nike

如何从 Mojo 中检查本地存储库中是否已存在工件?

我正在将大型二进制文件安装到本地 Maven 存储库中,在尝试下载它们之前我需要知道它们是否已经存在。

最佳答案

http://docs.codehaus.org/display/MAVENUSER/Mojo+Developer+Cookbook 的帮助下解决

/**
* The local maven repository.
*
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
@SuppressWarnings("UWF_UNWRITTEN_FIELD")
private ArtifactRepository localRepository;
/**
* @parameter default-value="${project.remoteArtifactRepositories}"
* @required
* @readonly
*/
private List<?> remoteRepositories;
/**
* Resolves Artifacts in the local repository.
*
* @component
*/
private ArtifactResolver artifactResolver;
/**
* @component
*/
private ArtifactFactory artifactFactory;
[...]
Artifact artifact = artifactFactory.createArtifactWithClassifier(groupId, artifactId, version, packagingType, classifier);
boolean artifactExists;
try
{
// Downloads the remote artifact, if necessary
artifactResolver.resolve(artifact, remoteRepositories, localRepository);
artifactExists = true;
}
catch (ArtifactResolutionException e)
{
throw new MojoExecutionException("", e);
}
catch (ArtifactNotFoundException e)
{
artifactExists = false;
}
if (artifactExists)
System.out.println("Artifact found at: " + artifact.getFile());

如果您想检查远程工件是否存在而不下载它,您可以使用 Aether library执行以下操作(基于 http://dev.eclipse.org/mhonarc/lists/aether-users/msg00127.html ):

MavenDefaultLayout defaultLayout = new MavenDefaultLayout();
RemoteRepository centralRepository = new RemoteRepository.Builder("central", "default", "http://repo1.maven.org/maven2/").build();
URI centralUri = URI.create(centralRepository.getUrl());
URI artifactUri = centralUri.resolve(defaultLayout.getPath(artifact));
HttpURLConnection connection = (HttpURLConnection) artifactUri.toURL().openConnection();
connection.setRequestMethod("HEAD");
connection.connect();
boolean artifactExists = connection.getResponseCode() != 404;

具有以下依赖项:org.eclipse.aether:aether-util:0.9.0.M2 和以下导入:

import java.net.HttpURLConnection;
import java.net.URI;

import org.eclipse.aether.artifact.Artifact;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.repository.RemoteRepository;
import org.eclipse.aether.util.repository.layout.MavenDefaultLayout;

关于maven-2 - Maven : How to check if an artifact exists?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4809238/

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