Maven: How to check if an artifact exists?

How can I check from Mojo if an artifact already exists in the local repository?

I install large binaries in the local Maven repository, and I need to know if they exist before trying to download them.

+3
source share
3 answers

Solved using 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());

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;
+4
source

, maven, copy mojo maven-dependency-plugin.

maven , , .

maven 2 ( maven3) mojo executor, mojo .

+1

, , URL-, , .

Here's a wagon-maven-plugin that has a purpose exist. The documentation is a little inaccurate, but you can use it.

From the code, you can take a look at the DefaultWagonDownload class < method 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 );
}
+1
source

Source: https://habr.com/ru/post/1788019/


All Articles