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

The following examples show how to use org.apache.maven.artifact.repository.ArtifactRepository. 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 File: AbstractJnlpMojoTest.java    From webstart with 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 #2
Source File: FingerprintMojo.java    From java-specialagent with 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 #3
Source File: MavenUtilTest.java    From jkube with 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 #4
Source File: AbstractScriptGeneratorMojo.java    From appassembler with 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 #5
Source File: DependenciesRenderer.java    From maven-confluence-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 
 * @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 #6
Source File: ArtifactMultiViewFactory.java    From netbeans with 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 #7
Source File: RepositoryUtils.java    From furnace with 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 #8
Source File: An_UpdateChecker.java    From deadcode4j with 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 #9
Source File: JApiCmpMojoTest.java    From japicmp with 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 #10
Source File: RepositoryUtils.java    From furnace with 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 #11
Source File: MavenArtifactResolvingHelperTest.java    From thorntail with Apache License 2.0 6 votes vote down vote up
@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 #12
Source File: DependencyTreeFactory.java    From netbeans with 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 #13
Source File: AetherUtils.java    From takari-lifecycle with 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 #14
Source File: ArtifactUtils.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 6 votes vote down vote up
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 #15
Source File: MavenHelper.java    From google-cloud-eclipse with 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 #16
Source File: DependencyResolver.java    From spring-cloud-function with Apache License 2.0 5 votes vote down vote up
private List<ArtifactRepository> mavenRepositories(Properties properties) {
	List<ArtifactRepository> list = new ArrayList<>();
	addRepositoryIfMissing(list, "spring-snapshots",
			"https://repo.spring.io/libs-snapshot", true, true);
	addRepositoryIfMissing(list, "central", "https://repo1.maven.org/maven2", true,
			false);
	return list;
}
 
Example #17
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testResolveSignaturesEmpty() throws MojoExecutionException {
    final RepositorySystem repositorySystem = mock(RepositorySystem.class);
    final MavenSession session = mock(MavenSession.class);
    final ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
    when(session.getProjectBuildingRequest()).thenReturn(projectBuildingRequest);
    final ArtifactRepository localRepository = mock(ArtifactRepository.class);
    when(projectBuildingRequest.getLocalRepository()).thenReturn(localRepository);
    final List<ArtifactRepository> remoteRepositories = emptyList();
    when(projectBuildingRequest.getRemoteRepositories()).thenReturn(remoteRepositories);
    final ArtifactResolver resolver = new ArtifactResolver(repositorySystem, localRepository, remoteRepositories);
    final Map<Artifact, Artifact> resolvedSignatures = resolver.resolveSignatures(
            emptyList(), SignatureRequirement.NONE);
    assertEquals(resolvedSignatures.size(), 0);
}
 
Example #18
Source File: JAXBGenerateTest.java    From maven-jaxb2-plugin with BSD 2-Clause "Simplified" License 5 votes vote down vote up
/**
 * 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 #19
Source File: CreateEffectivePomTest.java    From flatten-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Tests method to create effective POM.
 *
 * @throws Exception if something goes wrong.
 */
@Test
public void testCreateEffectivePom()
    throws Exception
{

    String magicValue = "magic-value";
    Properties userProperties = new Properties();
    userProperties.setProperty( "cmd.test.property", magicValue );

    File pomFile = new File( "src/test/resources/cmdpropertysubstituion/pom.xml" );
    ArtifactRepository localRepository = new MavenArtifactRepository();
    localRepository.setLayout( new DefaultRepositoryLayout() );
    ArtifactFactory artifactFactory = new DefaultArtifactFactory();
    ArtifactHandlerManager artifactHandlerManager = new DefaultArtifactHandlerManager();
    setDeclaredField( artifactFactory, "artifactHandlerManager", artifactHandlerManager );
    Map<String, ArtifactHandler> artifactHandlers = new HashMap<String, ArtifactHandler>();
    setDeclaredField( artifactHandlerManager, "artifactHandlers", artifactHandlers );
    DefaultDependencyResolver depencencyResolver = new DefaultDependencyResolver();
    DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
    FlattenModelResolver resolver = new FlattenModelResolver( localRepository, artifactFactory,
            depencencyResolver, projectBuildingRequest, Collections.<MavenProject>emptyList() );
    ModelBuildingRequest buildingRequest =
        new DefaultModelBuildingRequest().setPomFile( pomFile ).setModelResolver( resolver ).setUserProperties( userProperties );
    setDeclaredField( tested, "modelBuilderThreadSafetyWorkaround", buildModelBuilderThreadSafetyWorkaroundForTest() );
    Model effectivePom = tested.createEffectivePom( buildingRequest, false, FlattenMode.defaults );
    assertThat( effectivePom.getName() ).isEqualTo( magicValue );
}
 
Example #20
Source File: MavenArtifactResolvingHelper.java    From ARCHIVE-wildfly-swarm with Apache License 2.0 5 votes vote down vote up
public void remoteRepository(ArtifactRepository repo) {
    RemoteRepository.Builder builder = new RemoteRepository.Builder(repo.getId(), "default", repo.getUrl());
    final Authentication mavenAuth = repo.getAuthentication();
    if (mavenAuth != null && mavenAuth.getUsername() != null && mavenAuth.getPassword() != null) {
        builder.setAuthentication(new AuthenticationBuilder()
                .addUsername(mavenAuth.getUsername())
                .addPassword(mavenAuth.getPassword()).build());
    }
    this.remoteRepositories.add(builder.build());
}
 
Example #21
Source File: MavenEmbedder.java    From netbeans with 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 #22
Source File: DaemonGenerationRequest.java    From appassembler with MIT License 5 votes vote down vote up
/**
 * Request with the given parameters.
 *
 * @param daemon The Daemon to use.
 * @param project The Maven Project
 * @param localRepository The local repository.
 * @param outputDir The output directory.
 * @param binFolder The binary folder.
 */
public DaemonGenerationRequest( Daemon daemon, MavenProject project, ArtifactRepository localRepository,
                                File outputDir, String binFolder )
{
    this.daemon = daemon;

    this.mavenProject = project;

    this.localRepository = localRepository;

    this.outputDirectory = outputDir;

    this.binFolder = binFolder;
}
 
Example #23
Source File: Util.java    From jax-maven-plugin with 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 #24
Source File: RepositoryUtil.java    From netbeans with 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 #25
Source File: ReleaseMetadata.java    From unleash-maven-plugin with Eclipse Public License 1.0 5 votes vote down vote up
@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());
    }
  }
}
 
Example #26
Source File: AbstractGitflowBasedRepositoryMojo.java    From gitflow-helper-maven-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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
Source File: ArtifactResolverTest.java    From pgpverify-maven-plugin with Apache License 2.0 5 votes vote down vote up
@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 File: MavenUtils.java    From mvn-golang with 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 File: MavenHelper.java    From google-cloud-eclipse with 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
Source File: MavenEmbedder.java    From netbeans with 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);
}