Java Code Examples for org.eclipse.aether.RepositorySystemSession

The following examples show how to use org.eclipse.aether.RepositorySystemSession. 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: LicenseScout   Source File: ArtifactHelper.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Calculates the set of transitive dependencies of the passed artifacts.
 * 
 * @param repositoryParameters
 * @param artifacts
 * @param artifactScope
 * @return a list of File locations where the JARs of the dependencies are located in the local file system
 * @throws DependencyResolutionException
 */
public static List<File> getDependencies(final IRepositoryParameters repositoryParameters,
                                         final List<ArtifactItem> artifacts, final ArtifactScope artifactScope)
        throws DependencyResolutionException {
    final RepositorySystem system = repositoryParameters.getRepositorySystem();
    final RepositorySystemSession session = repositoryParameters.getRepositorySystemSession();
    final DependencyFilter classpathFlter = DependencyFilterUtils.classpathFilter(artifactScope.getScopeValue());
    final Set<File> artifactFiles = new HashSet<>();
    for (final ArtifactItem artifactItem : artifacts) {
        Artifact artifact = createDefaultArtifact(artifactItem);
        final CollectRequest collectRequest = new CollectRequest();
        collectRequest.setRoot(new Dependency(artifact, artifactScope.getScopeValue()));
        collectRequest.setRepositories(repositoryParameters.getRemoteRepositories());
        final DependencyRequest dependencyRequest = new DependencyRequest(collectRequest, classpathFlter);
        final DependencyResult dependencyResult = system.resolveDependencies(session, dependencyRequest);
        final List<ArtifactResult> artifactResults = dependencyResult.getArtifactResults();
        for (final ArtifactResult artifactResult : artifactResults) {
            artifactFiles.add(artifactResult.getArtifact().getFile());
        }
    }
    return new ArrayList<>(artifactFiles);
}
 
Example 2
public List<Version> getAllVersions(String groupId, String artifactId) {
    String repositoryUrl = "http://maven.repo/nexus/content/groups/public";
    RepositorySystem repoSystem = newRepositorySystem();

    RepositorySystemSession session = newSession(repoSystem);
    RemoteRepository central = null;
    central = new RemoteRepository.Builder("central", "default", repositoryUrl).build();

    Artifact artifact = new DefaultArtifact(groupId + ":" + artifactId + ":[0,)");
    VersionRangeRequest rangeRequest = new VersionRangeRequest();
    rangeRequest.setArtifact(artifact);
    rangeRequest.addRepository(central);
    VersionRangeResult rangeResult;
    try {
        rangeResult = repoSystem.resolveVersionRange(session, rangeRequest);
    } catch (VersionRangeResolutionException e) {
        throw new RuntimeException(e);
    }
    List<Version> versions = rangeResult.getVersions().stream()
            .filter(v -> !v.toString().toLowerCase().endsWith("-snapshot"))
            .filter(v -> !groupId.contains("org.springframework") || v.toString().equals("2.0.0.RELEASE"))
            .collect(Collectors.toList());
    logger.info("artifact: {}, Available versions: {}", artifact, versions);
    return versions;
}
 
Example 3
@BeforeEach
void before() throws Exception {
  Artifact projectArtifact = mock(Artifact.class);

  this.mavenProject = new MavenProject();
  this.mavenProject.setArtifact(projectArtifact);
  ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
  when(projectBuildingRequest.getRepositorySession()).thenReturn(mock(RepositorySystemSession.class));
  //noinspection deprecation
  this.mavenProject.setProjectBuildingRequest(projectBuildingRequest);

  this.globalFilter = mock(ArtifactFilter.class);
  ArtifactFilter transitiveIncludeExcludeFilter = mock(ArtifactFilter.class);
  ArtifactFilter targetFilter = mock(ArtifactFilter.class);
  this.graphBuilder = GraphBuilder.create(ToStringNodeIdRenderer.INSTANCE);

  this.dependenciesResolver = mock(ProjectDependenciesResolver.class);
  DependencyResolutionResult dependencyResolutionResult = mock(DependencyResolutionResult.class);
  when(dependencyResolutionResult.getDependencyGraph()).thenReturn(mock(org.eclipse.aether.graph.DependencyNode.class));
  when(this.dependenciesResolver.resolve(any(DependencyResolutionRequest.class))).thenReturn(dependencyResolutionResult);

  this.graphAdapter = new MavenGraphAdapter(this.dependenciesResolver, transitiveIncludeExcludeFilter, targetFilter, EnumSet.of(INCLUDED));
}
 
Example 4
Source Project: helidon-build-tools   Source File: StagerMojo.java    License: Apache License 2.0 6 votes vote down vote up
StagingContextImpl(File baseDir,
                   File outputDir,
                   Log log,
                   RepositorySystem repoSystem,
                   RepositorySystemSession repoSession,
                   List<RemoteRepository> remoteRepos,
                   ArchiverManager archiverManager) {

    this.baseDir = baseDir;
    this.outputDir = outputDir;
    this.log = log;
    this.repoSystem = repoSystem;
    this.repoSession = repoSession;
    this.remoteRepos = remoteRepos;
    this.archiverManager = Objects.requireNonNull(archiverManager, "archiverManager is null");
}
 
Example 5
Source Project: appengine-maven-plugin   Source File: SdkResolver.java    License: Apache License 2.0 6 votes vote down vote up
public static File getSdk(MavenProject project, RepositorySystem repoSystem, RepositorySystemSession repoSession, List<RemoteRepository>... repos)
        throws MojoExecutionException {
  Artifact artifact = (Artifact) find(project.getPluginArtifacts(), new Predicate<Artifact>() {
    @Override
    public boolean apply(Artifact artifact1) {
      return (artifact1.getArtifactId().equals("appengine-maven-plugin")
              && artifact1.getGroupId().equals("com.google.appengine"));
    }
  });

  String version = artifact.getVersion();
  
  if(version.endsWith("-SNAPSHOT")) {
    String newestVersion = determineNewestVersion(repoSystem, repoSession, repos);
    return getSdk(newestVersion, repoSystem, repoSession, repos);
  }

  return getSdk(version, repoSystem, repoSession, repos);
}
 
Example 6
@Override
public Path resolve(final RepositorySystemSession session, final List<RemoteRepository> repositories, final ArtifactName name) {
    final ArtifactResult result;
    try {
        final ArtifactRequest request = new ArtifactRequest();
        final Artifact defaultArtifact = new DefaultArtifact(name.getGroupId(), name.getArtifactId(), name.getClassifier(), name.getPackaging(), name.getVersion());
        request.setArtifact(defaultArtifact);
        request.setRepositories(repositories);
        result = repoSystem.resolveArtifact(session, request);
    } catch (ArtifactResolutionException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    if (!result.isResolved()) {
        throw new RuntimeException("Failed to resolve artifact " + name);
    }
    final Artifact artifact = result.getArtifact();
    final File artifactFile;
    if (artifact == null || (artifactFile = artifact.getFile()) == null) {
        throw new RuntimeException("Failed to resolve artifact " + name);
    }
    return artifactFile.toPath();
}
 
Example 7
Source Project: cloud-opensource-java   Source File: Bom.java    License: Apache License 2.0 6 votes vote down vote up
public static Bom readBom(Path pomFile) throws MavenRepositoryException {
  RepositorySystem system = RepositoryUtility.newRepositorySystem();
  RepositorySystemSession session = RepositoryUtility.newSession(system);

  MavenProject mavenProject = RepositoryUtility.createMavenProject(pomFile, session);
  String coordinates = mavenProject.getGroupId() + ":" + mavenProject.getArtifactId() 
      + ":" + mavenProject.getVersion();
  DependencyManagement dependencyManagement = mavenProject.getDependencyManagement();
  List<org.apache.maven.model.Dependency> dependencies = dependencyManagement.getDependencies();

  ArtifactTypeRegistry registry = session.getArtifactTypeRegistry();
  ImmutableList<Artifact> artifacts = dependencies.stream()
      .map(dependency -> RepositoryUtils.toDependency(dependency, registry))
      .map(Dependency::getArtifact)
      .filter(artifact -> !shouldSkipBomMember(artifact))
      .collect(ImmutableList.toImmutableList());
  
  Bom bom = new Bom(coordinates, artifacts);
  return bom;
}
 
Example 8
Source Project: roboconf-platform   Source File: ResolveMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
private RepositorySystem newRepositorySystem() {

		RepositorySystem repoSystem = new DefaultRepositorySystem() {
			@Override
			public ArtifactResult resolveArtifact( RepositorySystemSession session, ArtifactRequest request )
			throws ArtifactResolutionException {

				ArtifactResult res = new ArtifactResult( request );
				Artifact mavenArtifact = ResolveMojoTest.this.artifactIdToArtifact.get( request.getArtifact().getArtifactId());
				if( mavenArtifact == null )
					throw new ArtifactResolutionException( new ArrayList<ArtifactResult>( 0 ), "Error in test wrapper and settings." );

				org.eclipse.aether.artifact.DefaultArtifact art =
						new org.eclipse.aether.artifact.DefaultArtifact(
								"groupId", "artifactId", "classifier", "extension", "version",
								null, mavenArtifact.getFile());

				res.setArtifact( art );
				return res;
			}
		};

		return repoSystem;
	}
 
Example 9
Source Project: yawp   Source File: SdkResolver.java    License: MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
public static File getSdk(MavenProject project, RepositorySystem repoSystem, RepositorySystemSession repoSession,
                          List<RemoteRepository>... repos) throws MojoExecutionException {
    Artifact artifact = find(project.getPluginArtifacts(), new Predicate<Artifact>() {
        @Override
        public boolean apply(Artifact artifact1) {
            return artifact1.getArtifactId().equals("appengine-maven-plugin");
        }
    });

    String version = artifact.getVersion();

    if (version.endsWith("-SNAPSHOT")) {
        String newestVersion = determineNewestVersion(repoSystem, repoSession, repos);
        return getSdk(newestVersion, repoSystem, repoSession, repos);
    }

    return getSdk(version, repoSystem, repoSession, repos);
}
 
Example 10
private MavenProject createMavenProject(String artifactId) {
  MavenProject project = new MavenProject();
  project.setArtifactId(artifactId);
  // Make sure that we can modify the list later.
  project.setCollectedProjects(new ArrayList<>());

  DefaultArtifact artifact = new DefaultArtifact("groupId", artifactId, "version", "compile", "jar", "", null);
  project.setArtifact(artifact);

  RepositorySystemSession repositorySession = mock(RepositorySystemSession.class);
  ProjectBuildingRequest projectBuildingRequest = mock(ProjectBuildingRequest.class);
  when(projectBuildingRequest.getRepositorySession()).thenReturn(repositorySession);
  //noinspection deprecation
  project.setProjectBuildingRequest(projectBuildingRequest);

  return project;
}
 
Example 11
@Override
public void populateResult(RepositorySystemSession session,
	ArtifactDescriptorResult result,
	Model model) {
	super.populateResult(session, result, model);
	Parent parent = model.getParent();
	if (parent != null) {
		DefaultArtifact art =
			new DefaultArtifact(parent.getGroupId(),
				parent.getArtifactId(),
				"pom",
				parent.getVersion());
		Dependency dep = new Dependency(art, "compile");
		result.addDependency(dep);
	}
}
 
Example 12
Source Project: netbeans   Source File: NbRepositorySystem.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public CollectResult collectDependencies(RepositorySystemSession session, CollectRequest request) throws DependencyCollectionException {
    DefaultRepositorySystemSession cloned = new DefaultRepositorySystemSession(session);
    DependencyGraphTransformer transformer = session.getDependencyGraphTransformer();
    //need to reset the transformer to prevent the transformation to happen and to it below separately.
    cloned.setDependencyGraphTransformer(null);
    CollectResult res = super.collectDependencies(cloned, request);
    CloningDependencyVisitor vis = new CloningDependencyVisitor();
    res.getRoot().accept(vis);

    //this part copied from DefaultDependencyCollector
    try {
        DefaultDependencyGraphTransformationContext context =
                new DefaultDependencyGraphTransformationContext(session);
        res.setRoot(transformer.transformGraph(res.getRoot(), context));
    } catch (RepositoryException e) {
        res.addException(e);
    }

    if (!res.getExceptions().isEmpty()) {
        throw new DependencyCollectionException(res);
    }
    res.getRoot().setData("NB_TEST", vis.getRootNode());
    return res;
}
 
Example 13
Source Project: netbeans   Source File: NbPluginDependenciesResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Artifact resolve(Plugin plugin, List<RemoteRepository> repositories, RepositorySystemSession session) throws PluginResolutionException {
    WorkspaceReader wr = session.getWorkspaceReader();
    NbWorkspaceReader nbwr = null;
    if (wr instanceof NbWorkspaceReader) {
        nbwr = (NbWorkspaceReader)wr;
        //this only works reliably because the NbWorkspaceReader is part of the session, not a component
        nbwr.silence();
    }
    try {
        return super.resolve(plugin, repositories, session);
    } finally {
        if (nbwr != null) {
            nbwr.normal();
        }
    }
}
 
Example 14
Source Project: netbeans   Source File: NbPluginDependenciesResolver.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public DependencyNode resolve(Plugin plugin, Artifact pluginArtifact, DependencyFilter dependencyFilter, List<RemoteRepository> repositories, RepositorySystemSession session) throws PluginResolutionException {
    
    WorkspaceReader wr = session.getWorkspaceReader();
    NbWorkspaceReader nbwr = null;
    if (wr instanceof NbWorkspaceReader) {
        nbwr = (NbWorkspaceReader)wr;
        //this only works reliably because the NbWorkspaceReader is part of the session, not a component
        nbwr.silence();
    }
    try {
        return super.resolve(plugin, pluginArtifact, dependencyFilter, repositories, session);
    } finally {
        if (nbwr != null) {
            nbwr.normal();
        }
    }
}
 
Example 15
Source Project: scava   Source File: GithubImporter.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private List<String> getMavenParentDependencies(String parent)
		throws DependencyResolutionException, ArtifactDescriptorException {
	List<String> dependencies = new ArrayList<>();
	DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();
	RepositorySystem system = newRepositorySystem(locator);
	RepositorySystemSession session = newSession(system);

	RemoteRepository central = new RemoteRepository.Builder("central", "default", "http://repo1.maven.org/maven2/")
			.build();

	org.eclipse.aether.artifact.Artifact artifact = new DefaultArtifact(parent);
	ArtifactDescriptorRequest request = new ArtifactDescriptorRequest(artifact, Arrays.asList(central), null);
	try {
		ArtifactDescriptorResult result = system.readArtifactDescriptor(session, request);
		for (org.eclipse.aether.graph.Dependency dependency : result.getManagedDependencies()) {
			dependencies.add(dependency.getArtifact().getGroupId() + ":" + dependency.getArtifact().getGroupId());
		}
	} catch (Exception e) {
		logger.error(e.getMessage());
	}
	return dependencies;

}
 
Example 16
Source Project: bazel-deps   Source File: Maven.java    License: MIT License 6 votes vote down vote up
public static Set<Artifact> transitiveDependencies(Artifact artifact) {

    RepositorySystem system = newRepositorySystem();

    RepositorySystemSession session = newRepositorySystemSession(system);

    CollectRequest collectRequest = new CollectRequest();
    collectRequest.setRoot(new Dependency(artifact, ""));
    collectRequest.setRepositories(repositories());

    CollectResult collectResult = null;
    try {
      collectResult = system.collectDependencies(session, collectRequest);
    } catch (DependencyCollectionException e) {
      throw new RuntimeException(e);
    }

    PreorderNodeListGenerator visitor = new PreorderNodeListGenerator();
    collectResult.getRoot().accept(visitor);

    return ImmutableSet.copyOf(
      visitor.getNodes().stream()
        .filter(d -> !d.getDependency().isOptional())
        .map(DependencyNode::getArtifact)
        .collect(Collectors.toList()));
  }
 
Example 17
/**
 * Used by the Maven Plugin.
 * @param repositorySystem Maven repository system
 * @param remoteRepositories remote artifact repositories
 * @param session repository system session
 */
public AetherStubDownloader(RepositorySystem repositorySystem,
		List<RemoteRepository> remoteRepositories, RepositorySystemSession session,
		Settings settings) {
	this.deleteStubsAfterTest = true;
	this.remoteRepos = remoteRepositories;
	this.settings = settings;
	this.repositorySystem = repositorySystem;
	this.session = session;
	if (remoteReposMissing()) {
		log.error(
				"Remote repositories for stubs are not specified and work offline flag wasn't passed");
	}
	this.workOffline = false;
	registerShutdownHook();
}
 
Example 18
Source Project: spring-cloud-contract   Source File: RemoteStubRunner.java    License: Apache License 2.0 6 votes vote down vote up
public BatchStubRunner run(StubRunnerOptions options,
		RepositorySystemSession repositorySystemSession) {
	StubDownloader stubDownloader = this.aetherStubDownloaderFactory
			.build(repositorySystemSession).build(options);
	try {
		if (log.isDebugEnabled()) {
			log.debug("Launching StubRunner with args: " + options);
		}
		BatchStubRunner stubRunner = new BatchStubRunnerFactory(options,
				stubDownloader).buildBatchStubRunner();
		RunningStubs runningCollaborators = stubRunner.runStubs();
		log.info(runningCollaborators.toString());
		return stubRunner;
	}
	catch (Exception e) {
		log.error("An exception occurred while trying to execute the stubs: "
				+ e.getMessage());
		throw e;
	}

}
 
Example 19
private RepositorySystemSession newSession(RepositorySystem system) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

    String home = System.getenv("HOME");
    LocalRepository localRepo = new LocalRepository(new File(home, ".m2/repository"));
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));

    return session;
}
 
Example 20
Source Project: phantomjs-maven-plugin   Source File: RepositoryDetails.java    License: MIT License 5 votes vote down vote up
public RepositoryDetails(RepositorySystem repositorySystem,
                         RepositorySystemSession repositorySystemSession,
                         List<RemoteRepository> remoteRepositories) {
  this.repositorySystem = repositorySystem;
  this.repositorySystemSession = repositorySystemSession;
  this.remoteRepositories = remoteRepositories;
}
 
Example 21
Source Project: boost   Source File: RuntimeParams.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public RuntimeParams(List<AbstractBoosterConfig> boosterConfigs, Properties boostProperties, ExecutionEnvironment env, MavenProject project,
        Log log, RepositorySystem repoSystem, RepositorySystemSession repoSession,
        List<RemoteRepository> remoteRepos, Plugin mavenDepPlugin) {
    this.log = log;
    this.boosterConfigs = boosterConfigs;
    this.boostProperties = boostProperties;
    this.env = env;
    this.project = project;
    this.projectBuildDir = project.getBuild().getDirectory();
    this.repoSystem = repoSystem;
    this.repoSession = repoSession;
    this.remoteRepos = remoteRepos;
    this.mavenDepPlugin = mavenDepPlugin;
}
 
Example 22
Source Project: vertx-deploy-tools   Source File: DeployUtils.java    License: Apache License 2.0 5 votes vote down vote up
public DeployUtils(Log log, MavenProject project, List<RemoteRepository> remoteRepos, RepositorySystem repoSystem, RepositorySystemSession repoSession) {

        this.log = log;
        this.project = project;
        this.remoteRepos = remoteRepos;
        this.repoSystem = repoSystem;
        this.repoSession = repoSession;
    }
 
Example 23
/**
 * Resolve an artifact and return its location in the local repository. Aether performs the normal
 * Maven resolution process ensuring that the latest update is cached to the local repository.
 * In addition, if the {@link MavenProperties#resolvePom} flag is <code>true</code>,
 * the POM is also resolved and cached.
 * @param resource the {@link MavenResource} representing the artifact
 * @return a {@link FileSystemResource} representing the resolved artifact in the local repository
 * @throws IllegalStateException if the artifact does not exist or the resolution fails
 */
Resource resolve(MavenResource resource) {
	Assert.notNull(resource, "MavenResource must not be null");
	validateCoordinates(resource);
	RepositorySystemSession session = newRepositorySystemSession(this.repositorySystem,
			this.properties.getLocalRepository());
	ArtifactResult resolvedArtifact;
	try {
		List<ArtifactRequest> artifactRequests = new ArrayList<>(2);
		if (properties.isResolvePom()) {
			artifactRequests.add(new ArtifactRequest(toPomArtifact(resource),
					this.remoteRepositories,
					JavaScopes.RUNTIME));
		}
		artifactRequests.add(new ArtifactRequest(toJarArtifact(resource),
				this.remoteRepositories,
				JavaScopes.RUNTIME));

		List<ArtifactResult> results = this.repositorySystem.resolveArtifacts(session, artifactRequests);
		resolvedArtifact = results.get(results.size() - 1);
	}
	catch (ArtifactResolutionException e) {

		ChoiceFormat pluralizer = new ChoiceFormat(
				new double[] { 0d, 1d, ChoiceFormat.nextDouble(1d) },
				new String[] { "repositories: ", "repository: ", "repositories: " });
		MessageFormat messageFormat = new MessageFormat(
				"Failed to resolve MavenResource: {0}. Configured remote {1}: {2}");
		messageFormat.setFormat(1, pluralizer);
		String repos = properties.getRemoteRepositories().isEmpty()
				? "none"
				: StringUtils.collectionToDelimitedString(properties.getRemoteRepositories().keySet(), ",", "[", "]");
		throw new IllegalStateException(
				messageFormat.format(new Object[] { resource, properties.getRemoteRepositories().size(), repos }),
				e);
	}
	return toResource(resolvedArtifact);
}
 
Example 24
Source Project: galleon   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static RepositorySystemSession newRepositorySession(final RepositorySystem repoSystem,
        Path path, RepositoryListener listener, ProxySelector proxySelector, boolean offline) {
    final DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
    session.setRepositoryListener(listener);
    session.setOffline(offline);
    final LocalRepository localRepo = new LocalRepository(path.toString());
    session.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(session, localRepo));
    if (proxySelector != null) {
        session.setProxySelector(proxySelector);
    }
    return session;
}
 
Example 25
Source Project: galleon   Source File: CliMavenArtifactRepositoryManager.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public RepositorySystemSession getSession() throws MavenUniverseException {
    try {
        return getSettings().getSession();
    } catch (ArtifactException ex) {
        throw new MavenUniverseException(ex.getLocalizedMessage(), ex);
    }
}
 
Example 26
public static void main(String[] args) throws ArtifactDescriptorException {
  DefaultArtifact artifact =
      new DefaultArtifact("com.google.cloud:libraries-bom:pom:1.0.0");

  RepositorySystemSession session = RepositoryUtility.newSession(system);

  ArtifactDescriptorRequest request = new ArtifactDescriptorRequest();
  request.addRepository(RepositoryUtility.CENTRAL);
  request.setArtifact(artifact);

  ArtifactDescriptorResult resolved = system.readArtifactDescriptor(session, request);
  for (Dependency dependency : resolved.getManagedDependencies()) {
    System.out.println(dependency);
  }
}
 
Example 27
Source Project: cloud-opensource-java   Source File: Bom.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Parses the dependencyManagement section of an artifact and returns
 * the artifacts included there.
 *
 * @param mavenRepositoryUrls URLs of Maven repositories to search for BOM members
 */
public static Bom readBom(String coordinates, List<String> mavenRepositoryUrls)
    throws ArtifactDescriptorException {
  Artifact artifact = new DefaultArtifact(coordinates);

  RepositorySystem system = RepositoryUtility.newRepositorySystem();
  RepositorySystemSession session = RepositoryUtility.newSession(system);

  ArtifactDescriptorRequest request = new ArtifactDescriptorRequest();

  for (String repositoryUrl : mavenRepositoryUrls) {
    request.addRepository(RepositoryUtility.mavenRepositoryFromUrl(repositoryUrl));
  }

  request.setArtifact(artifact);

  ArtifactDescriptorResult resolved = system.readArtifactDescriptor(session, request);
  List<Exception> exceptions = resolved.getExceptions();
  if (!exceptions.isEmpty()) {
    throw new ArtifactDescriptorException(resolved, exceptions.get(0).getMessage());
  }
  
  List<Artifact> managedDependencies = new ArrayList<>();
  for (Dependency dependency : resolved.getManagedDependencies()) {
    Artifact managed = dependency.getArtifact();
    if (!shouldSkipBomMember(managed) && !managedDependencies.contains(managed)) {
      managedDependencies.add(managed);
    }
  }
  
  Bom bom = new Bom(coordinates, ImmutableList.copyOf(managedDependencies));
  return bom;
}
 
Example 28
Source Project: cloud-opensource-java   Source File: RepositoryUtility.java    License: Apache License 2.0 5 votes vote down vote up
static MavenProject createMavenProject(Path pomFile, RepositorySystemSession session)
    throws MavenRepositoryException {
  // MavenCli's way to instantiate PlexusContainer
  ClassWorld classWorld =
      new ClassWorld("plexus.core", Thread.currentThread().getContextClassLoader());
  ContainerConfiguration containerConfiguration =
      new DefaultContainerConfiguration()
          .setClassWorld(classWorld)
          .setRealm(classWorld.getClassRealm("plexus.core"))
          .setClassPathScanning(PlexusConstants.SCANNING_INDEX)
          .setAutoWiring(true)
          .setJSR250Lifecycle(true)
          .setName("linkage-checker");
  try {
    PlexusContainer container = new DefaultPlexusContainer(containerConfiguration);

    MavenExecutionRequest mavenExecutionRequest = new DefaultMavenExecutionRequest();
    ProjectBuildingRequest projectBuildingRequest =
        mavenExecutionRequest.getProjectBuildingRequest();

    projectBuildingRequest.setRepositorySession(session);

    // Profile activation needs properties such as JDK version
    Properties properties = new Properties(); // allowing duplicate entries
    properties.putAll(projectBuildingRequest.getSystemProperties());
    properties.putAll(OsProperties.detectOsProperties());
    properties.putAll(System.getProperties());
    projectBuildingRequest.setSystemProperties(properties);

    ProjectBuilder projectBuilder = container.lookup(ProjectBuilder.class);
    ProjectBuildingResult projectBuildingResult =
        projectBuilder.build(pomFile.toFile(), projectBuildingRequest);
    return projectBuildingResult.getProject();
  } catch (PlexusContainerException | ComponentLookupException | ProjectBuildingException ex) {
    throw new MavenRepositoryException(ex);
  }
}
 
Example 29
public MavenArtifactResolvingHelperTest() {
    sessionMock = Mockito.mock(RepositorySystemSession.class);
    MirrorSelector mirrorSelectorMock = Mockito.mock(MirrorSelector.class);
    Mockito.when(sessionMock.getMirrorSelector()).thenReturn(mirrorSelectorMock);
    ProxySelector proxySelectorMock = Mockito.mock(ProxySelector.class);
    Mockito.when(sessionMock.getProxySelector()).thenReturn(proxySelectorMock);
    localRepositoryManager = Mockito.mock(LocalRepositoryManager.class);
    Mockito.when(sessionMock.getLocalRepositoryManager()).thenReturn(localRepositoryManager);
    resolver = Mockito.mock(ArtifactResolver.class);
    system = Mockito.mock(RepositorySystem.class);

}
 
Example 30
Source Project: byte-buddy   Source File: ByteBuddyMojoTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    when(repositorySystem.collectDependencies(Mockito.<RepositorySystemSession>any(), Mockito.<CollectRequest>any())).thenReturn(new CollectResult(new CollectRequest()).setRoot(root));
    project = File.createTempFile(FOO, TEMP);
    assertThat(project.delete(), is(true));
    assertThat(project.mkdir(), is(true));
}