本文介绍了Maven:如何检查工件是否存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在Mojo内部检查本地存储库中是否已存在工件?
How do I check from within a Mojo if an artifact already exists in the local repository?
我正在将大型二进制文件安装到本地Maven存储库中,在尝试下载大型二进制文件之前,我需要知道它们是否已经存在.
I'm installing large binaries into the local Maven repository and I need to know if they already exist before attempting to download them.
推荐答案
在 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库执行以下操作(基于 http://dev.eclipse.org/mhonarc/lists/aether-users/msg00127.html ):
If you want to check if a remote artifact exists without downloading it, you can use the Aether library to do the following (based on 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;
这篇关于Maven:如何检查工件是否存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!