如何在Mojo中检查本地存储库中是否已存在工件?
我正在将大型二进制文件安装到本地Maven存储库中,在尝试下载之前我需要知道它们是否已经存在。
答案 0 :(得分:4)
在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;
答案 1 :(得分:1)
如果您希望您的工件存在于远程maven存储库中,我建议您只使用copy mojo of the maven-dependency-plugin
。
它将使用普通的maven解析机制来检索工件,因此不会下载已存在于本地存储库中的内容。
在插件中,当使用maven 2(不确定maven3)时,您可以使用mojo executor轻松地从代码中调用mojo。
答案 2 :(得分:1)
由于接受的答案是正确的,不再指向有效的URL-s,因为我知道更好的方法,我发布了一个新答案。
wagon-maven-plugin有一个exist
目标。文档有点不准确,但您可以使用它。
代码方面,您可以查看DefaultWagonDownload类“exists
方法:
/**
*
* @param wagon - a Wagon instance
* @param resource - Remote resource to check
* @throws WagonException
*/
public boolean exists( Wagon wagon, String resource )
throws WagonException
{
return wagon.resourceExists( resource );
}