Java Code Examples for org.apache.maven.artifact.repository.ArtifactRepository

The following examples show how to use org.apache.maven.artifact.repository.ArtifactRepository. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: appassembler   Source File: AbstractScriptGeneratorMojo.java    License: MIT License 6 votes vote down vote up
protected void installDependencies( final String outputDirectory, final String repositoryName )
    throws MojoExecutionException, MojoFailureException
{
    if ( generateRepository )
    {
        // The repo where the jar files will be installed
        ArtifactRepository artifactRepository =
            artifactRepositoryFactory.createDeploymentArtifactRepository( "appassembler", "file://"
                + outputDirectory + "/" + repositoryName, getArtifactRepositoryLayout(), false );

        for ( Artifact artifact : artifacts )
        {
            installArtifact( artifact, artifactRepository, this.useTimestampInSnapshotFileName );
        }

        // install the project's artifact in the new repository
        installArtifact( projectArtifact, artifactRepository );
    }
}
 
Example 2
Source Project: jkube   Source File: MavenUtilTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private MavenSession getMavenSession() {
    Settings settings = new Settings();
    ArtifactRepository localRepository = new MavenArtifactRepository() {
        public String getBasedir() {
            return "repository";
        }
    };

    Properties userProperties = new Properties();
    userProperties.put("user.maven.home", "/home/user/.m2");

    Properties systemProperties = new Properties();
    systemProperties.put("foo", "bar");

    return new MavenSession(null, settings, localRepository, null, null, Collections.<String>emptyList(), ".", systemProperties, userProperties, new Date(System.currentTimeMillis()));
}
 
Example 3
Source Project: java-specialagent   Source File: FingerprintMojo.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Returns a list of {@code URL} objects representing paths of
 * {@link Artifact} objects marked with {@code <optional>true</optional>} in
 * the specified iterator.
 *
 * @param localRepository The local {@link ArtifactRepository}.
 * @param iterator The {@code Iterator} of {@code Artifact} objects.
 * @param depth The depth value for stack tracking (must be called with 0).
 * @return A list of dependency paths in the specified {@code iterator}.
 */
private static URL[] getDependencyPaths(final ArtifactRepository localRepository, final String scope, final boolean optional, final Iterator<Artifact> iterator, final int depth) {
  while (iterator.hasNext()) {
    final Artifact dependency = iterator.next();
    if (optional == dependency.isOptional() && (scope == null || scope.equals(dependency.getScope()))) {
      final URL url = AssembleUtil.toURL(MavenUtil.getPathOf(localRepository.getBasedir(), dependency));
      final URL[] urls = getDependencyPaths(localRepository, scope, optional, iterator, depth + 1);
      if (urls != null && url != null)
        urls[depth] = url;

      return urls;
    }
  }

  return depth == 0 ? null : new URL[depth];
}
 
Example 4
Source Project: netbeans   Source File: ArtifactMultiViewFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static MavenProject readMavenProject(MavenEmbedder embedder, Artifact artifact, List<ArtifactRepository> remoteRepos) throws  ProjectBuildingException {
    ProjectBuilder bldr = embedder.lookupComponent(ProjectBuilder.class);
    assert bldr !=null : "ProjectBuilder component not found in maven";
    DefaultMaven maven = (DefaultMaven) embedder.lookupComponent(Maven.class);
    assert bldr !=null : "DefaultMaven component not found in maven";
    
    MavenExecutionRequest req = embedder.createMavenExecutionRequest();
    req.setLocalRepository(embedder.getLocalRepository());
    req.setRemoteRepositories(remoteRepos);

    ProjectBuildingRequest configuration = req.getProjectBuildingRequest();
    configuration.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MINIMAL);
    configuration.setResolveDependencies(true);
    configuration.setRepositorySession(maven.newRepositorySession(req));
    ProjectBuildingResult projectBuildingResult = bldr.build(artifact, configuration);
    return projectBuildingResult.getProject();    
}
 
Example 5
Source Project: furnace   Source File: RepositoryUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static ArtifactRepository convertFromMavenSettingsRepository(Repository repository)
{
   MavenArtifactRepository result = new MavenArtifactRepository();
   result.setId(repository.getId());
   result.setUrl(repository.getUrl());

   String layout = repository.getLayout();
   if ("default".equals(layout))
      result.setLayout(new DefaultRepositoryLayout());
   else if ("p2".equals(layout))
      result.setLayout(new P2ArtifactRepositoryLayout());

   RepositoryPolicy releases = repository.getReleases();
   if (releases != null)
      result.setReleaseUpdatePolicy(new ArtifactRepositoryPolicy(releases.isEnabled(), releases.getUpdatePolicy(),
               releases.getChecksumPolicy()));

   RepositoryPolicy snapshots = repository.getSnapshots();
   if (snapshots != null)
      result.setSnapshotUpdatePolicy(new ArtifactRepositoryPolicy(snapshots.isEnabled(),
               snapshots.getUpdatePolicy(),
               snapshots.getChecksumPolicy()));

   return result;
}
 
Example 6
Source Project: deadcode4j   Source File: An_UpdateChecker.java    License: Apache License 2.0 6 votes vote down vote up
private void givenAvailableVersions(final String... availableVersions) {
    try {
        doAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                RepositoryMetadata repositoryMetadata = (RepositoryMetadata) invocation.getArguments()[0];
                Versioning versioning = new Versioning();
                versioning.setVersions(Arrays.asList(availableVersions));
                repositoryMetadata.getMetadata().setVersioning(versioning);
                return null;
            }
        }).when(repositoryMetadataManager).resolve(any(RepositoryMetadata.class),
                anyListOf(ArtifactRepository.class), any(ArtifactRepository.class));
    } catch (RepositoryMetadataResolutionException e) {
        throw new RuntimeException(e);
    }
}
 
Example 7
Source Project: netbeans   Source File: DependencyTreeFactory.java    License: Apache License 2.0 6 votes vote down vote up
private static DependencyNode createDependencyTree(MavenProject project,
        DependencyTreeBuilder dependencyTreeBuilder, ArtifactRepository localRepository,
        ArtifactFactory artifactFactory, ArtifactMetadataSource artifactMetadataSource,
        ArtifactCollector artifactCollector,
        String scope) {
    ArtifactFilter artifactFilter = createResolvingArtifactFilter(scope);

    try {
        // TODO: note that filter does not get applied due to MNG-3236
        return dependencyTreeBuilder.buildDependencyTree(project,
                localRepository, artifactFactory,
                artifactMetadataSource, artifactFilter, artifactCollector);
    } catch (DependencyTreeBuilderException exception) {
    }
    return null;
}
 
Example 8
Source Project: takari-lifecycle   Source File: AetherUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static String getLayout(ArtifactRepository repo) {
  try {
    return repo.getLayout().getId();
  } catch (LinkageError e) {
    /*
     * NOTE: getId() was added in 3.x and is as such not implemented by plugins compiled against 2.x APIs.
     */
    String className = repo.getLayout().getClass().getSimpleName();
    if (className.endsWith("RepositoryLayout")) {
      String layout = className.substring(0, className.length() - "RepositoryLayout".length());
      if (layout.length() > 0) {
        layout = Character.toLowerCase(layout.charAt(0)) + layout.substring(1);
        return layout;
      }
    }
    return "";
  }
}
 
Example 9
public static Collection<Artifact> resolve(
		final ArtifactFactory artifactFactory,
		final ArtifactResolver artifactResolver,
		final ArtifactRepository localRepository,
		final ArtifactMetadataSource artifactMetadataSource,
		final Dependency[] dependencies, final MavenProject project)
		throws InvalidDependencyVersionException,
		ArtifactResolutionException, ArtifactNotFoundException {
	if (dependencies == null) {
		return Collections.emptyList();
	}

	@SuppressWarnings("unchecked")
	final Set<Artifact> artifacts = MavenMetadataSource.createArtifacts(
			artifactFactory, Arrays.asList(dependencies), "runtime", null,
			project);

	for (Artifact artifact : artifacts) {
		artifactResolver.resolve(artifact,

		project.getRemoteArtifactRepositories(), localRepository);
	}

	final Set<Artifact> resolvedArtifacts = artifacts;
	return resolvedArtifacts;
}
 
Example 10
Source Project: webstart   Source File: AbstractJnlpMojoTest.java    License: MIT License 6 votes vote down vote up
private void setUpProject( File pomFile, AbstractMojo mojo )
    throws Exception
{
    MavenProjectBuilder projectBuilder = (MavenProjectBuilder) lookup( MavenProjectBuilder.ROLE );

    ArtifactRepositoryFactory artifactRepositoryFactory =
        (ArtifactRepositoryFactory) lookup( ArtifactRepositoryFactory.ROLE );

    ArtifactRepositoryPolicy policy = new ArtifactRepositoryPolicy( true, "never", "never" );

    String localRepoUrl = "file://" + System.getProperty( "user.home" ) + "/.m2/repository";

    ArtifactRepository localRepository =
        artifactRepositoryFactory.createArtifactRepository( "local", localRepoUrl, new DefaultRepositoryLayout(),
                                                            policy, policy );

    ProfileManager profileManager = new DefaultProfileManager( getContainer() );

    MavenProject project = projectBuilder.buildWithDependencies( pomFile, localRepository, profileManager );

    //this gets the classes for these tests of this mojo (exec plugin) onto the project classpath for the test
    project.getBuild().setOutputDirectory( new File( "target/test-classes" ).getAbsolutePath() );
    setVariableValueToObject( mojo, "project", project );
}
 
Example 11
Source Project: google-cloud-eclipse   Source File: MavenHelper.java    License: Apache License 2.0 6 votes vote down vote up
private static ArtifactRepository makeRepository(String repository) throws CoreException {
  try {
    URI repoUri = new URI(repository);
    if (!repoUri.isAbsolute()) {
      throw new CoreException(
          StatusUtil.error(
              MavenHelper.class, Messages.getString("RepositoryUriNotAbsolute", repository)));
    }
    return MavenUtils.createRepository(repoUri.getHost(), repoUri.toString());
  } catch (URISyntaxException exception) {
    throw new CoreException(
        StatusUtil.error(
            MavenHelper.class,
            Messages.getString("RepositoryUriInvalid", repository),
            exception));
  }
}
 
Example 12
@Test
// SWARM-1173: swarm-plugin trying to download SNAPSHOTs from Maven Central
public void propagateRepositoryPolicies() {
    MavenArtifactResolvingHelper artifactResolverHelper = new MavenArtifactResolvingHelper(null, null, sessionMock, null);
    ArtifactRepositoryPolicy testSnapshotPolicy = new ArtifactRepositoryPolicy(false, "hourly", "warn");
    ArtifactRepositoryPolicy testReleasesPolicy = new ArtifactRepositoryPolicy(true, "never", "warn");
    ArtifactRepository testingRepo = new MavenArtifactRepository("testing-repo", "http://testing-repo.org", new DefaultRepositoryLayout(), testSnapshotPolicy, testReleasesPolicy);
    artifactResolverHelper.remoteRepository(testingRepo);

    List<RemoteRepository> remoteRepos = artifactResolverHelper.getRemoteRepositories();

    Assert.assertTrue("Remote repositories " + remoteRepos + " do not contain expected testing repo " + testingRepo,
                      remoteRepos.stream().anyMatch(
                              remoteRepo -> {
                                  RepositoryPolicy snapshotsPolicy = remoteRepo.getPolicy(true);
                                  RepositoryPolicy releasesPolicy = remoteRepo.getPolicy(false);
                                  return remoteRepo.getId().equals(testingRepo.getId()) &&
                                          !snapshotsPolicy.isEnabled() &&
                                          snapshotsPolicy.getUpdatePolicy().equals(testSnapshotPolicy.getUpdatePolicy()) &&
                                          snapshotsPolicy.getChecksumPolicy().equals(testSnapshotPolicy.getChecksumPolicy()) &&
                                          releasesPolicy.isEnabled() &&
                                          releasesPolicy.getUpdatePolicy().equals(testReleasesPolicy.getUpdatePolicy()) &&
                                          releasesPolicy.getChecksumPolicy().equals(testReleasesPolicy.getChecksumPolicy());
                              })
    );
}
 
Example 13
Source Project: furnace   Source File: RepositoryUtils.java    License: Eclipse Public License 1.0 6 votes vote down vote up
public static ArtifactRepository toArtifactRepository(String id, String url, String layout,
         boolean containsReleases,
         boolean containsSnapshots)
{
   MavenArtifactRepository result = new MavenArtifactRepository();
   result.setId(id);
   result.setUrl(url);

   if (layout == null || layout.isEmpty() || "default".equals(layout))
   {
      result.setLayout(new DefaultRepositoryLayout());
   }
   else if ("p2".equals(layout))
   {
      result.setLayout(new P2ArtifactRepositoryLayout());
   }
   result.setReleaseUpdatePolicy(new ArtifactRepositoryPolicy(containsReleases,
            ArtifactRepositoryPolicy.UPDATE_POLICY_NEVER,
            ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
   result.setSnapshotUpdatePolicy(new ArtifactRepositoryPolicy(containsSnapshots,
            ArtifactRepositoryPolicy.UPDATE_POLICY_DAILY,
            ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN));
   return result;

}
 
Example 14
Source Project: japicmp   Source File: JApiCmpMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() throws MojoFailureException, MojoExecutionException {
	JApiCmpMojo mojo = new JApiCmpMojo();
	Version oldVersion = createVersion("groupId", "artifactId", "0.1.0");
	Version newVersion = createVersion("groupId", "artifactId", "0.1.1");
	PluginParameters pluginParameters = new PluginParameters(false, newVersion, oldVersion, new Parameter(), null, Optional.of(Paths.get(System.getProperty("user.dir"), "target", "simple").toFile()), Optional.<String>absent(), true, null, null, null, null);
	ArtifactResolver artifactResolver = mock(ArtifactResolver.class);
	ArtifactResolutionResult artifactResolutionResult = mock(ArtifactResolutionResult.class);
	Set<Artifact> artifactSet = new HashSet<>();
	Artifact resolvedArtifact = mock(Artifact.class);
	artifactSet.add(resolvedArtifact);
	when(resolvedArtifact.getFile()).thenReturn(Paths.get(System.getProperty("user.dir"), "target", "guava-18.0.jar").toFile());
	when(artifactResolutionResult.getArtifacts()).thenReturn(artifactSet);
	when(artifactResolver.resolve(Matchers.<ArtifactResolutionRequest>anyObject())).thenReturn(artifactResolutionResult);
	ArtifactFactory artifactFactory = mock(ArtifactFactory.class);
	when(artifactFactory.createArtifactWithClassifier(eq("groupId"), eq("artifactId"), eq("0.1.1"), anyString(), anyString())).thenReturn(mock(Artifact.class));
	MavenProject mavenProject = mock(MavenProject.class);
	when(mavenProject.getArtifact()).thenReturn(mock(Artifact.class));
	MavenParameters mavenParameters = new MavenParameters(new ArrayList<ArtifactRepository>(), artifactFactory, mock(ArtifactRepository.class), artifactResolver, mavenProject, mock(MojoExecution.class), "0.0.1", mock(ArtifactMetadataSource.class));

	mojo.executeWithParameters(pluginParameters, mavenParameters);
	assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.diff")), is(true));
	assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.xml")), is(true));
	assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.html")), is(true));
}
 
Example 15
/**
 * 
 * @param sink
 * @param project
 * @param mavenProjectBuilder
 * @param locale
 * @param listener
 */
public DependenciesRenderer(	Sink sink, 
								MavenProject project, 
								MavenProjectBuilder mavenProjectBuilder,
								ArtifactRepository localRepository,
								ArtifactFactory factory,
								I18N i18n,
								Locale locale, 
								ReportingResolutionListener listener,
								Log log )
{
    super( sink );

    this.project = project;
    this.locale = locale;
    this.listener = listener;
    this.mavenProjectBuilder = mavenProjectBuilder;
    this.localRepository = localRepository;
    this.i18n 	= i18n;
    this.factory = factory;
    this.log = log;
}
 
Example 16
Source Project: jax-maven-plugin   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
static ArtifactResolutionResult resolve(Log log, Artifact artifact, RepositorySystem repositorySystem,
        ArtifactRepository localRepository, List<ArtifactRepository> remoteRepositories) {
    ArtifactResolutionRequest request = new ArtifactResolutionRequest() //
            .setArtifact(artifact) //
            .setLocalRepository(localRepository) //
            .setRemoteRepositories(remoteRepositories) //
            .setResolveTransitively(true) //
            .addListener(Util.createLoggingResolutionListener(log));
    return repositorySystem.resolve(request);
}
 
Example 17
Source Project: spring-init   Source File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private List<RemoteRepository> aetherRepositories(Properties properties) {
	List<RemoteRepository> list = new ArrayList<>();
	for (ArtifactRepository input : mavenRepositories(properties)) {
		list.add(remote(input));
	}
	return list;
}
 
Example 18
Source Project: spring-init   Source File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private void addRepositoryIfMissing(List<ArtifactRepository> list, String id,
		String url, boolean releases, boolean snapshots) {
	for (ArtifactRepository repo : list) {
		if (url.equals(repo.getUrl())) {
			return;
		}
		if (id.equals(repo.getId())) {
			return;
		}
	}
	list.add(repo(id, url, releases, snapshots));
}
 
Example 19
Source Project: takari-lifecycle   Source File: AetherUtils.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public static RemoteRepository toRepo(ArtifactRepository repo) {
  RemoteRepository result = null;
  if (repo != null) {
    RemoteRepository.Builder builder = new RemoteRepository.Builder(repo.getId(), getLayout(repo), repo.getUrl());
    builder.setSnapshotPolicy(toPolicy(repo.getSnapshots()));
    builder.setReleasePolicy(toPolicy(repo.getReleases()));
    builder.setAuthentication(toAuthentication(repo.getAuthentication()));
    builder.setProxy(toProxy(repo.getProxy()));
    builder.setMirroredRepositories(toRepos(repo.getMirroredRepositories()));
    result = builder.build();
  }
  return result;
}
 
Example 20
Source Project: netbeans   Source File: EffectivePomMD.java    License: Apache License 2.0 5 votes vote down vote up
static List<ModelProblem> runMavenValidationImpl(final File pom) {
    //TODO profiles based on current configuration??
    MavenEmbedder embedder = EmbedderFactory.getProjectEmbedder();
    MavenExecutionRequest meReq = embedder.createMavenExecutionRequest();
    ProjectBuildingRequest req = meReq.getProjectBuildingRequest();
    req.setValidationLevel(ModelBuildingRequest.VALIDATION_LEVEL_MAVEN_3_1); // currently enables just <reporting> warning
    req.setLocalRepository(embedder.getLocalRepository());
    List<ArtifactRepository> remoteRepos = RepositoryPreferences.getInstance().remoteRepositories(embedder);
    req.setRemoteRepositories(remoteRepos);
    req.setRepositorySession(((DefaultMaven) embedder.lookupComponent(Maven.class)).newRepositorySession(meReq));
    List<ModelProblem> problems;
    try {
        problems = embedder.lookupComponent(ProjectBuilder.class).build(pom, req).getProblems();
    } catch (ProjectBuildingException x) {
        problems = new ArrayList<ModelProblem>();
        List<ProjectBuildingResult> results = x.getResults();
        if (results != null) { //one code point throwing ProjectBuildingException contains results,
            for (ProjectBuildingResult result : results) {
                problems.addAll(result.getProblems());
            }
        } else {
            // another code point throwing ProjectBuildingException doesn't contain results..
            Throwable cause = x.getCause();
            if (cause instanceof ModelBuildingException) {
                problems.addAll(((ModelBuildingException) cause).getProblems());
            }
        }
    }
    return problems;
}
 
Example 21
Source Project: netbeans   Source File: ArtifactViewer.java    License: Apache License 2.0 5 votes vote down vote up
private static void showArtifactViewer(NBVersionInfo info, Artifact artifact, List<ArtifactRepository> repos, String panelHint) {
    ArtifactViewerFactory fact = Lookup.getDefault().lookup(ArtifactViewerFactory.class);
    if (fact == null) {
        Logger.getLogger(ArtifactViewer.class.getName()).info("No implementation of ArtifactViewerFactory available.");
        return;
    }
    Lookup l;
    if (info != null) {
        l = fact.createLookup(info);
    } else {
        l = fact.createLookup(artifact, repos);
    }
    TopComponent tc = fact.createTopComponent(l);
    tc.open();
    tc.requestActive();
    if (panelHint != null) {
        MultiViewHandler hand = MultiViews.findMultiViewHandler(tc);
        if (hand == null) {
            return;
        }
        for (MultiViewPerspective pers : hand.getPerspectives()) {
            if (panelHint.equals(pers.preferredID())) {
                hand.requestVisible(pers);
                return;
            }
        }
    }
}
 
Example 22
/**
 * Validate the generation of a java files from purchaseorder.xsd.
 * 
 * @throws MojoExecutionException
 */
public void testExecute() throws Exception {

	final File pom = new File(getBaseDir(),
	"src/test/resources/test-pom.xml");
	
       final ArtifactRepository localRepository = new DefaultArtifactRepository( "local", 
       		
       		new File(getBaseDir(), "target/test-repository").toURI().toURL().toString()        		, new DefaultRepositoryLayout());
	
	
	final MavenProject mavenProject = mavenProjectBuilder.build(pom, localRepository, null);
	

	final XJC2Mojo generator = (XJC2Mojo) lookupMojo("generate", pom);
	generator.setProject(mavenProject);
	generator.setLocalRepository(localRepository);
	generator.setSchemaDirectory(new File(getBaseDir(),"src/test/resources/"));
	generator.setSchemaIncludes(new String[] { "*.xsd" });
	generator.setBindingIncludes(new String[] { "*.xjb" });
	generator.setGenerateDirectory(new File(getBaseDir(), "target/test/generated-sources"));
	generator.setVerbose(true);
	generator.setGeneratePackage("unittest");
	generator.setRemoveOldOutput(false);
	
	generator.execute();
}
 
Example 23
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * using this method one creates an ArtifactRepository instance with injected mirrors and proxies
 * @param url
 * @param id
 * @return 
 */
public ArtifactRepository createRemoteRepository(String url, String id) {
    setUpLegacySupport();
    ArtifactRepositoryFactory fact = lookupComponent(ArtifactRepositoryFactory.class);
    assert fact!=null : "ArtifactRepositoryFactory component not found in maven";
    ArtifactRepositoryPolicy snapshotsPolicy = new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
    ArtifactRepositoryPolicy releasesPolicy = new ArtifactRepositoryPolicy(true, ArtifactRepositoryPolicy.UPDATE_POLICY_ALWAYS, ArtifactRepositoryPolicy.CHECKSUM_POLICY_WARN);
    return fact.createArtifactRepository(id, url, new DefaultRepositoryLayout(), snapshotsPolicy, releasesPolicy);
}
 
Example 24
Source Project: netbeans   Source File: MavenEmbedder.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 
 * @param sources
 * @param remoteRepositories - these instances need to be properly mirrored and proxied. Either by creating via EmbedderFactory.createRemoteRepository()
 *              or by using instances from MavenProject
 * @param localRepository
 * @throws ArtifactResolutionException
 * @throws ArtifactNotFoundException 
 */
public void resolve(Artifact sources, List<ArtifactRepository> remoteRepositories, ArtifactRepository localRepository) throws ArtifactResolutionException, ArtifactNotFoundException {
    setUpLegacySupport();
    ArtifactResolutionRequest req = new ArtifactResolutionRequest();
    req.setLocalRepository(localRepository);
    req.setRemoteRepositories(remoteRepositories);
    req.setArtifact(sources);
    req.setOffline(isOffline());
    ArtifactResolutionResult result = repositorySystem.resolve(req);
    normalizePath(sources);
    // XXX check result for exceptions and throw them now?
    for (Exception ex : result.getExceptions()) {
        LOG.log(Level.FINE, null, ex);
    }
}
 
Example 25
Source Project: netbeans   Source File: RepositoryUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tries to download an artifact.
 * @param info a version of an artifact
 * @return the file in the local repository (might not exist if download failed)
 * @throws AbstractArtifactResolutionException currently never?
 * @since 1.17
 */
public static File downloadArtifact(NBVersionInfo info) throws Exception {
    Artifact a = createArtifact(info);
    MavenEmbedder online = EmbedderFactory.getOnlineEmbedder();
    List<ArtifactRepository> remotes;
    RepositoryInfo repo = RepositoryPreferences.getInstance().getRepositoryInfoById(info.getRepoId());
    if (repo != null && repo.isRemoteDownloadable()) {
        remotes = Collections.singletonList(online.createRemoteRepository(repo.getRepositoryUrl(), repo.getId()));
    } else {
        remotes = Collections.singletonList(online.createRemoteRepository(RepositorySystem.DEFAULT_REMOTE_REPO_URL, RepositorySystem.DEFAULT_REMOTE_REPO_ID));
    }
    online.resolve(a, remotes, online.getLocalRepository());
    return a.getFile();
}
 
Example 26
/**
 * Creates a Maven ArtifactRepository for targeting deployments.
 *
 * @param id the repository identifier
 * @return the resolved repository
 *
 * @throws MojoFailureException if the repository id is not defined.
 */
ArtifactRepository getDeploymentRepository(final String id) throws MojoFailureException {
    Objects.requireNonNull(id, "A repository id must be specified.");
    Optional<ArtifactRepository> repo = project.getRemoteArtifactRepositories().stream().filter(r -> r.getId().equals(id)).findFirst();

    if (!repo.isPresent()) {
        throw new MojoFailureException("No Repository with id `" + id + "` is defined.");
    }
    return repo.get();
}
 
Example 27
@Test
public void testConstructArtifactResolverWithNull() {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(null, null, null));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(null, localRepository, emptyList()));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(repositorySystem, null, emptyList()));
    assertThrows(NullPointerException.class,
            () -> new ArtifactResolver(repositorySystem, localRepository, null));
}
 
Example 28
Source Project: mvn-golang   Source File: MavenUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Make resolve artifact project building request.
 *
 * @param session maven session, must not be null
 * @param remoteRepositories list of remote repositories, must not be null and
 * can't contain null
 * @return created request, must not be null
 */
@Nonnull
public static ProjectBuildingRequest makeResolveArtifactProjectBuildingRequest(
        @Nonnull final MavenSession session,
        @Nonnull @MustNotContainNull final List<ArtifactRepository> remoteRepositories
) {
  final ProjectBuildingRequest result = new DefaultProjectBuildingRequest(session.getProjectBuildingRequest());
  result.setRemoteRepositories(remoteRepositories);
  result.setLocalRepository(session.getLocalRepository());
  return result;
}
 
Example 29
Source Project: google-cloud-eclipse   Source File: MavenHelper.java    License: Apache License 2.0 5 votes vote down vote up
public static Artifact resolveArtifact(
    MavenCoordinates mavenCoordinates, IProgressMonitor monitor) throws CoreException {
  List<ArtifactRepository> repository = getRepository(mavenCoordinates);
  return MavenUtils.resolveArtifact(
      mavenCoordinates.getGroupId(),
      mavenCoordinates.getArtifactId(),
      mavenCoordinates.getType(),
      mavenCoordinates.getVersion(),
      mavenCoordinates.getClassifier(),
      repository,
      monitor);
}
 
Example 30
@PostConstruct
public void init() {
  // setting the artifact version to a release version temporarily since the dist repository checks for a snapshot
  // version of the artifact. Maybe this can be implemented in a different manner but then we would have to setup the
  // repository manually
  org.apache.maven.artifact.Artifact projectArtifact = this.project.getArtifact();
  String oldVersion = projectArtifact.getVersion();
  projectArtifact.setVersion("1");

  // replace properties in remote repository URL and getting the remote repo
  ArtifactRepository artifactRepository = this.project.getDistributionManagementArtifactRepository();
  if (artifactRepository != null) {
    PomPropertyResolver propertyResolver = new PomPropertyResolver(this.project, this.settings, this.profiles,
        this.releaseArgs);
    artifactRepository.setUrl(propertyResolver.expandPropertyReferences(artifactRepository.getUrl()));
    this.deploymentRepository = RepositoryUtils.toRepo(artifactRepository);
  }

  // resetting the artifact version
  projectArtifact.setVersion(oldVersion);

  for (MavenProject p : this.reactorProjects) {
    // puts the initial module artifact coordinates into the cache
    addArtifactCoordinates(ProjectToCoordinates.POM.apply(p), ReleasePhase.PRE_RELEASE);

    // caching of SCM settings of every POM in order to go back to it before setting next dev version
    this.cachedScmSettings.put(ProjectToCoordinates.EMPTY_VERSION.apply(p), p.getModel().getScm());

    Optional<Document> parsedPOM = PomUtil.parsePOM(p);
    if (parsedPOM.isPresent()) {
      this.originalPOMs.put(ProjectToCoordinates.EMPTY_VERSION.apply(p), parsedPOM.get());
    }
  }
}