maven-2mojo

Maven: How to check if an artifact exists?


How do I check from within a Mojo if an artifact already exists in the local repository?

I'm installing large binaries into the local Maven repository and I need to know if they already exist before attempting to download them.


Solution

  • Solved with the help of 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;
    

    With following dependency: org.eclipse.aether:aether-util:0.9.0.M2 and following imports:

    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;