2011-01-26 23 views
3

如果在本地存儲庫中已經存在工件,如何從Mojo中進行檢查?Maven:如何檢查工件是否存在?

我正在將大型二進制文件安裝到本地Maven存儲庫中,我需要知道它們在嘗試下載它們之前是否已經存在。

回答

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; 
+0

我要離開這個答案起來的情況下任何人想要查找的假象,而無需實際下載。 – Gili 2011-01-27 17:35:06

+0

關於這個我不喜歡的部分是,事實上你實際上不僅僅在嘗試,而且實際上你正在下載這個工件。我懷疑這是你想要處理的大型文物。看看我的答案。 – carlspring 2013-07-05 16:21:13

1

如果您希望您的工件出現在遠程Maven存儲庫中,我建議您只使用copy mojo of the maven-dependency-plugin

它將使用正常的maven解析機制來檢索工件,因此不會下載已存在於本地存儲庫中的東西。

在插件中,當使用maven 2(不確定maven3)時,您可以使用mojo executor輕鬆地從您的代碼中調用mojo。

1

由於被接受爲正確的答案不再指向有效的URL,因爲我知道更好的方法,所以我發佈了一個新答案。

還有wagon-maven-plugin,它有一個exist的目標。文檔有點不準確,但你可以使用它。

代碼明智的,你可以看看DefaultWagonDownloadexists方法:

/** 
* 
* @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); 
}