如果本地存储库中已存在工件,如何从 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 库执行以下操作(基于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;
如果您希望您的工件存在于远程mavenmaven-dependency-plugin
存储库中,我建议您只需使用.
它将使用正常的 maven 解析机制来检索工件,因此不会下载本地存储库中已经存在的东西。
在插件中,当使用 maven 2(不确定 maven3)时,您可以使用mojo 执行器轻松地从您的代码中调用 mojo。
由于被接受为正确的答案不再指向有效的 URL,并且因为我知道更好的方法,所以我发布了一个新答案。
有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 );
}