Java Code Examples for org.eclipse.aether.DefaultRepositorySystemSession

The following examples show how to use org.eclipse.aether.DefaultRepositorySystemSession. 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: javafx-maven-plugin   Source File: JavaFXRunMojoTestCase.java    License: Apache License 2.0 6 votes vote down vote up
private void setUpProject(File pomFile, AbstractMojo mojo) throws Exception {
    super.setUp();

    MockitoAnnotations.initMocks(this);

    ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
    buildingRequest.setResolveDependencies(true);
    when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
    DefaultRepositorySystemSession repositorySession = MavenRepositorySystemUtils.newSession();
    repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
            .newInstance(repositorySession, new LocalRepository(RepositorySystem.defaultUserLocalRepository)));
    when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);

    ProjectBuilder builder = lookup(ProjectBuilder.class);
    ProjectBuildingResult build = builder.build(pomFile, buildingRequest);
    MavenProject project = build.getProject();

    project.getBuild().setOutputDirectory(new File( "target/test-classes").getAbsolutePath());
    setVariableValueToObject(mojo, "project", project);
}
 
Example 2
Source Project: start.spring.io   Source File: DependencyResolver.java    License: Apache License 2.0 6 votes vote down vote up
DependencyResolver() {
	try {
		ServiceLocator serviceLocator = createServiceLocator();
		DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
		session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(false, false));
		this.localRepositoryLocation = Files.createTempDirectory("metadata-validation-m2");
		LocalRepository localRepository = new LocalRepository(this.localRepositoryLocation.toFile());
		this.repositorySystem = serviceLocator.getService(RepositorySystem.class);
		session.setLocalRepositoryManager(
				this.repositorySystem.newLocalRepositoryManager(session, localRepository));
		session.setReadOnly();
		this.repositorySystemSession = session;
	}
	catch (Exception ex) {
		throw new RuntimeException(ex);
	}
}
 
Example 3
Source Project: vertx-maven-plugin   Source File: InitializeMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
private InitializeMojo createMojoInstance() throws PlexusContainerException {
    InitializeMojo mojo = new InitializeMojo();
    mojo.project = new MavenProject();
    mojo.repositorySystem = new DefaultRepositorySystem();
    mojo.repositorySystemSession = new DefaultRepositorySystemSession();
    mojo.buildPluginManager = new DefaultBuildPluginManager();
    mojo.container = new DefaultPlexusContainer(new DefaultContainerConfiguration());
    mojo.mavenSession = new MavenSession(mojo.container, mojo.repositorySystemSession, new DefaultMavenExecutionRequest(),
        new DefaultMavenExecutionResult());

    mojo.lifecycleExecutor = new DefaultLifecycleExecutor();
    mojo.scmManager = new DefaultScmManager();
    mojo.remoteRepositories = Collections.emptyList();
    mojo.projectBuildDir = OUT.getAbsolutePath();

    Build build = new Build();
    build.setOutputDirectory(OUT.getAbsolutePath());
    mojo.project.setBuild(build);

    return mojo;
}
 
Example 4
private DependencyGraph buildDependencyGraph(
    List<DependencyNode> dependencyNodes, DefaultRepositorySystemSession session) {
   
  try {
    DependencyNode node = resolveCompileTimeDependencies(dependencyNodes, session);
    return DependencyGraph.from(node);
  } catch (DependencyResolutionException ex) {
    DependencyResult result = ex.getResult();
    DependencyGraph graph = DependencyGraph.from(result.getRoot());

    for (ArtifactResult artifactResult : result.getArtifactResults()) {
      Artifact resolvedArtifact = artifactResult.getArtifact();

      if (resolvedArtifact == null) {
        Artifact requestedArtifact = artifactResult.getRequest().getArtifact();
        graph.addUnresolvableArtifactProblem(requestedArtifact);
      }
    }
    
    return graph;
  }
}
 
Example 5
Source Project: cloud-opensource-java   Source File: RepositoryUtility.java    License: Apache License 2.0 6 votes vote down vote up
private static DefaultRepositorySystemSession newSession(
    RepositorySystem system, DependencySelector dependencySelector) {
  DefaultRepositorySystemSession session = createDefaultRepositorySystemSession(system);
  session.setDependencySelector(dependencySelector);

  // By default, Maven's MavenRepositorySystemUtils.newSession() returns a session with
  // ChainedDependencyGraphTransformer(ConflictResolver(...), JavaDependencyContextRefiner()).
  // Because the full dependency graph does not resolve conflicts of versions, this session does
  // not use ConflictResolver.
  session.setDependencyGraphTransformer(
      new ChainedDependencyGraphTransformer(
          new CycleBreakerGraphTransformer(), // Avoids StackOverflowError
          new JavaDependencyContextRefiner()));

  // No dependency management in the full dependency graph
  session.setDependencyManager(null);

  return session;
}
 
Example 6
Source Project: spring-init   Source File: MavenSettingsReader.java    License: Apache License 2.0 6 votes vote down vote up
public static void applySettings(MavenSettings settings,
		DefaultRepositorySystemSession session) {
	if (settings.getLocalRepository() != null) {
		try {
			session.setLocalRepositoryManager(
					new SimpleLocalRepositoryManagerFactory().newInstance(session,
							new LocalRepository(settings.getLocalRepository())));
		}
		catch (NoLocalRepositoryManagerException e) {
			throw new IllegalStateException(
					"Cannot set local repository to " + settings.getLocalRepository(),
					e);
		}
	}
	session.setOffline(settings.getOffline());
	session.setMirrorSelector(settings.getMirrorSelector());
	session.setAuthenticationSelector(settings.getAuthenticationSelector());
	session.setProxySelector(settings.getProxySelector());
}
 
Example 7
Source Project: spring-init   Source File: DependencyResolver.java    License: Apache License 2.0 6 votes vote down vote up
private DefaultRepositorySystemSession createSession(Properties properties)
		throws NoLocalRepositoryManagerException {
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	LocalRepository repository = localRepository(properties);
	session.setLocalRepositoryManager(
			localRepositoryManagerFactory.newInstance(session, repository));
	applySettings(session);
	ProxySelector existing = session.getProxySelector();
	if (existing == null || !(existing instanceof CompositeProxySelector)) {
		JreProxySelector fallback = new JreProxySelector();
		ProxySelector selector = existing == null ? fallback
				: new CompositeProxySelector(Arrays.asList(existing, fallback));
		session.setProxySelector(selector);
	}
	return session;
}
 
Example 8
Source Project: quarkus   Source File: MavenArtifactResolver.java    License: Apache License 2.0 6 votes vote down vote up
private MavenArtifactResolver(Builder builder) throws BootstrapMavenException {
    final BootstrapMavenContext mvnSettings = new BootstrapMavenContext(builder);
    this.repoSystem = mvnSettings.getRepositorySystem();

    final RepositorySystemSession session = mvnSettings.getRepositorySystemSession();
    if (builder.localRepo != null && builder.reTryFailedResolutionsAgainstDefaultLocalRepo) {
        localRepoManager = new MavenLocalRepositoryManager(
                repoSystem.newLocalRepositoryManager(session, new LocalRepository(builder.localRepo)),
                Paths.get(BootstrapMavenContext.resolveLocalRepo(mvnSettings.getEffectiveSettings())));
        this.repoSession = new DefaultRepositorySystemSession(session).setLocalRepositoryManager(localRepoManager);
    } else {
        this.repoSession = session;
        localRepoManager = null;
    }

    this.remoteRepos = mvnSettings.getRemoteRepositories();
    this.remoteRepoManager = mvnSettings.getRemoteRepositoryManager();
}
 
Example 9
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 10
Source Project: spring-cloud-contract   Source File: AetherFactories.java    License: Apache License 2.0 6 votes vote down vote up
public static RepositorySystemSession newSession(RepositorySystem system,
		boolean workOffline) {
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	session.setOffline(workOffline);
	if (!workOffline) {
		session.setUpdatePolicy(RepositoryPolicy.UPDATE_POLICY_ALWAYS);
	}
	session.setChecksumPolicy(RepositoryPolicy.CHECKSUM_POLICY_WARN);
	String localRepositoryDirectory = localRepositoryDirectory(workOffline);
	if (log.isDebugEnabled()) {
		log.debug("Local Repository Directory set to [" + localRepositoryDirectory
				+ "]. Work offline: [" + workOffline + "]");
	}
	LocalRepository localRepo = new LocalRepository(localRepositoryDirectory);
	session.setLocalRepositoryManager(
			system.newLocalRepositoryManager(session, localRepo));
	return session;
}
 
Example 11
Source Project: spring-cloud-function   Source File: MavenSettingsReader.java    License: Apache License 2.0 6 votes vote down vote up
public static void applySettings(MavenSettings settings,
		DefaultRepositorySystemSession session) {
	if (settings.getLocalRepository() != null) {
		try {
			session.setLocalRepositoryManager(
					new SimpleLocalRepositoryManagerFactory().newInstance(session,
							new LocalRepository(settings.getLocalRepository())));
		}
		catch (NoLocalRepositoryManagerException e) {
			throw new IllegalStateException(
					"Cannot set local repository to " + settings.getLocalRepository(),
					e);
		}
	}
	session.setOffline(settings.getOffline());
	session.setMirrorSelector(settings.getMirrorSelector());
	session.setAuthenticationSelector(settings.getAuthenticationSelector());
	session.setProxySelector(settings.getProxySelector());
}
 
Example 12
Source Project: archiva   Source File: MavenSystemManager.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new aether repository system session for the given directory and assigns the
 * repository to this session.
 *
 * @param localRepoDir The repository directory
 * @return The newly created session object.
 */
public static RepositorySystemSession newRepositorySystemSession(String localRepoDir) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

    LocalRepository repo = new LocalRepository(localRepoDir);

    DependencySelector depFilter = new AndDependencySelector(new ExclusionDependencySelector());
    session.setDependencySelector(depFilter);
    SimpleLocalRepositoryManagerFactory repFactory = new SimpleLocalRepositoryManagerFactory();
    try {
        LocalRepositoryManager manager = repFactory.newInstance(session, repo);
        session.setLocalRepositoryManager(manager);
    } catch (NoLocalRepositoryManagerException e) {
        log.error("Could not assign the repository manager to the session: {}", e.getMessage(), e);
    }

    return session;
}
 
Example 13
private DefaultRepositorySystemSession newRepositorySystemSession(RepositorySystem system, File localRepoFile, Settings settings) {
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	if (!settings.getMirrors().isEmpty()) {
		DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
		for (Mirror mirror : settings.getMirrors()) {
			mirrorSelector.add(mirror.getId(), mirror.getUrl(), "default", true, mirror.getMirrorOf(), "*");
		}
		session.setMirrorSelector(mirrorSelector);
	}
	session.setProxySelector(proxySelector);

	LocalRepository localRepo = new LocalRepository(localRepoFile);
	session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));

	return session;
}
 
Example 14
Source Project: buck   Source File: Publisher.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * @param toPublish each {@link Artifact} must contain a file, that will be published under maven
 *     coordinates in the corresponding {@link Artifact}.
 * @see Artifact#setFile
 */
public DeployResult publish(List<Artifact> toPublish) throws DeploymentException {
  RepositorySystem repoSys = Objects.requireNonNull(locator.getService(RepositorySystem.class));

  DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
  session.setLocalRepositoryManager(repoSys.newLocalRepositoryManager(session, localRepo));
  session.setReadOnly();

  DeployRequest deployRequest = createDeployRequest(toPublish);

  if (dryRun) {
    return new DeployResult(deployRequest)
        .setArtifacts(toPublish)
        .setMetadata(deployRequest.getMetadata());
  } else {
    return repoSys.deploy(session, deployRequest);
  }
}
 
Example 15
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 16
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 17
protected void setUp() throws Exception
{
    // required for mojo lookups to work
    super.setUp();

    File testPom = new File( getBasedir(),
            "target/test-classes/DependencyGraphBuilderTest/DependencyGraphBuilderTest.xml" );
    mojo = (DependencyGraphBuilder) lookupMojo( "getBuildingRequest", testPom );

    assertNotNull( mojo );
    assertNotNull( mojo.getProject() );
    MavenProject project = mojo.getProject();

    MavenSession session = newMavenSession( project );
    setVariableValueToObject( mojo, "session", session );

    DefaultRepositorySystemSession repoSession = (DefaultRepositorySystemSession) session.getRepositorySession();
    //repoSession.setLocalRepositoryManager( new SimpleLocalRepositoryManager( stubFactory.getWorkingDir() ) );

    Artifact artifact = new DefaultArtifact( "org.com.google","artifactId", "1.0.0", "compile", "jar", "C1",
            null);
    Set<Artifact> set = new HashSet<Artifact>();
    set.add( artifact );

    project.setArtifacts( set );
    project.setArtifactId( "id" );

    ArtifactHandlerManager manager = lookup( ArtifactHandlerManager.class );
    setVariableValueToObject( mojo, "artifactHandlerManager", manager );
}
 
Example 18
private DependencyNode resolveCompileTimeDependencies(
    List<DependencyNode> dependencyNodes, DefaultRepositorySystemSession session)
    throws DependencyResolutionException {

  ImmutableList.Builder<Dependency> dependenciesBuilder = ImmutableList.builder();
  for (DependencyNode dependencyNode : dependencyNodes) {
    Dependency dependency = dependencyNode.getDependency();
    if (dependency == null) {
      // Root DependencyNode has null dependency field.
      dependenciesBuilder.add(new Dependency(dependencyNode.getArtifact(), "compile"));
    } else {
      // The dependency field carries exclusions
      dependenciesBuilder.add(dependency.setScope("compile"));
    }
  }
  ImmutableList<Dependency> dependencyList = dependenciesBuilder.build();
          
  if (localRepository != null) {
    LocalRepository local = new LocalRepository(localRepository.toAbsolutePath().toString());
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, local));
  }

  CollectRequest collectRequest = new CollectRequest();
  if (dependencyList.size() == 1) {
    // With setRoot, the result includes dependencies with `optional:true` or `provided`
    collectRequest.setRoot(dependencyList.get(0));
  } else {
    collectRequest.setDependencies(dependencyList);
  }
  for (RemoteRepository repository : repositories) {
    collectRequest.addRepository(repository);
  }
  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setCollectRequest(collectRequest);

  // resolveDependencies equals to calling both collectDependencies (build dependency tree) and
  // resolveArtifacts (download JAR files).
  DependencyResult dependencyResult = system.resolveDependencies(session, dependencyRequest);
  return dependencyResult.getRoot();
}
 
Example 19
Source Project: cloud-opensource-java   Source File: RepositoryUtility.java    License: Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
static DefaultRepositorySystemSession createDefaultRepositorySystemSession(
    RepositorySystem system) {
  DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
  LocalRepository localRepository = new LocalRepository(findLocalRepository());
  session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepository));
  return session;
}
 
Example 20
Source Project: cloud-opensource-java   Source File: RepositoryUtility.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Open a new Maven repository session for full dependency graph resolution.
 *
 * @see {@link DependencyGraphBuilder}
 */
static DefaultRepositorySystemSession newSessionForFullDependency(RepositorySystem system) {
  // This combination of DependencySelector comes from the default specified in
  // `MavenRepositorySystemUtils.newSession`.
  // LinkageChecker needs to include 'provided'-scope and optional dependencies.
  DependencySelector dependencySelector =
      new AndDependencySelector(
          // ScopeDependencySelector takes exclusions. 'Provided' scope is not here to avoid
          // false positive in LinkageChecker.
          new ScopeDependencySelector("test"),
          new ExclusionDependencySelector(),
          new FilteringZipDependencySelector());
  
  return newSession(system, dependencySelector);
}
 
Example 21
Source Project: cloud-opensource-java   Source File: RepositoryUtility.java    License: Apache License 2.0 5 votes vote down vote up
static DefaultRepositorySystemSession newSessionForVerboseDependency(RepositorySystem system) {
  DependencySelector dependencySelector =
      new AndDependencySelector(
          // ScopeDependencySelector takes exclusions. 'Provided' scope is not here to avoid
          // false positive in LinkageChecker.
          new ScopeDependencySelector("test"),
          new OptionalDependencySelector(),
          new ExclusionDependencySelector(),
          new FilteringZipDependencySelector());
  
  return newSession(system, dependencySelector);
}
 
Example 22
Source Project: gyro   Source File: PluginAddCommand.java    License: Apache License 2.0 5 votes vote down vote up
private boolean validate(String plugin) {
    try {
        DefaultServiceLocator locator = MavenRepositorySystemUtils.newServiceLocator();

        locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
        locator.addService(TransporterFactory.class, FileTransporterFactory.class);
        locator.addService(TransporterFactory.class, HttpTransporterFactory.class);

        RepositorySystem system = locator.getService(RepositorySystem.class);
        DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
        String localDir = Paths.get(System.getProperty("user.home"), ".m2", "repository").toString();
        LocalRepository local = new LocalRepository(localDir);
        LocalRepositoryManager manager = system.newLocalRepositoryManager(session, local);

        session.setLocalRepositoryManager(manager);

        Artifact artifact = new DefaultArtifact(plugin);
        Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);
        DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
        CollectRequest collectRequest = new CollectRequest(dependency, repositories);
        DependencyRequest request = new DependencyRequest(collectRequest, filter);
        system.resolveDependencies(session, request);

        return true;
    } catch (DependencyResolutionException e) {
        GyroCore.ui().write("@|bold %s|@ was not installed for the following reason(s):\n", plugin);

        for (Exception ex : e.getResult().getCollectExceptions()) {
            GyroCore.ui().write("   @|red %s|@\n", ex.getMessage());
        }

        GyroCore.ui().write("\n");

        return false;
    }
}
 
Example 23
Source Project: spring-init   Source File: DependencyResolver.java    License: Apache License 2.0 5 votes vote down vote up
private ProjectBuildingRequest getProjectBuildingRequest(Properties properties)
		throws NoLocalRepositoryManagerException {
	DefaultProjectBuildingRequest projectBuildingRequest = new DefaultProjectBuildingRequest();
	DefaultRepositorySystemSession session = createSession(properties);
	projectBuildingRequest.setRepositoryMerging(RepositoryMerging.REQUEST_DOMINANT);
	projectBuildingRequest.setRemoteRepositories(mavenRepositories(properties));
	projectBuildingRequest.getRemoteRepositories()
			.addAll(mavenRepositories(settings));
	projectBuildingRequest.setRepositorySession(session);
	projectBuildingRequest.setProcessPlugins(false);
	projectBuildingRequest.setBuildStartTime(new Date());
	projectBuildingRequest.setUserProperties(properties);
	projectBuildingRequest.setSystemProperties(System.getProperties());
	return projectBuildingRequest;
}
 
Example 24
Source Project: migration-tooling   Source File: Aether.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Aether and its components are designed to be stateless. All configurations and state
 * are provided through the RepositorySystemSession.
 *
 * TODO(petros): Separate this out into its own class.
 * This is the most intricate element of Aether.
 * There are various settings that are useful to us.
 * Specifically, these are the (1) LocalRepositoryManager, (2) DependencyManager,
 * (3) DependencyGraphTransformer, (4) TransferListener, (5) ProxySelector
 */
static RepositorySystemSession newRepositorySession(RepositorySystem system) {
  DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

  // TODO(petros): Decide on where to cache things.
  LocalRepository localRepository = new LocalRepository("target/local-repo");
  session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepository));

  session.setDependencyManager(new ClassicDependencyManager());
  return session;
}
 
Example 25
Source Project: syndesis   Source File: RepackageExtensionMojo.java    License: Apache License 2.0 5 votes vote down vote up
private List<Dependency> obtainBomDependencies(final String urlLocation) {
    final Artifact artifact = downloadAndInstallArtifact(urlLocation).getArtifact();

    final Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);

    final List<RemoteRepository> remoteRepositories = project.getRepositories().stream()
        .map(r -> new RemoteRepository.Builder(r.getId(), r.getLayout(), r.getUrl()).build())
        .collect(Collectors.toList());

    CollectResult result;
    try {
        final ArtifactDescriptorRequest descriptorRequest = new ArtifactDescriptorRequest(artifact, remoteRepositories, null);
        final ArtifactDescriptorResult descriptor = repository.readArtifactDescriptor(session, descriptorRequest);

        final List<Dependency> dependencies = Stream.concat(
            descriptor.getDependencies().stream(),
            descriptor.getManagedDependencies().stream())
            .collect(Collectors.toList());

        final DefaultRepositorySystemSession sessionToUse = new DefaultRepositorySystemSession(session);
        sessionToUse.setDependencyGraphTransformer(new NoopDependencyGraphTransformer());

        final CollectRequest request = new CollectRequest(dependency, dependencies, remoteRepositories);
        result = repository.collectDependencies(sessionToUse, request);
    } catch (final DependencyCollectionException | ArtifactDescriptorException e) {
        throw new IllegalStateException("Unabele to obtain BOM dependencies for: " + urlLocation, e);
    }

    final DependencyNode root = result.getRoot();

    final PostorderNodeListGenerator visitor = new PostorderNodeListGenerator();
    root.accept(visitor);

    return visitor.getDependencies(true);
}
 
Example 26
public void cacheArtifact(Artifact artifact)
    throws IOException, SettingsBuildingException,
    DependencyCollectionException, DependencyResolutionException,
    ArtifactResolutionException, ModelBuildingException {

  // setup a maven resolution hierarchy that uses the main local repo as
  // a remote repo and then cache into a new local repo
  List<RemoteRepository> repos = Utils.getRepositoryList();
  RepositorySystem repoSystem = Utils.getRepositorySystem();
  DefaultRepositorySystemSession repoSession =
      Utils.getRepositorySession(repoSystem, null);

  // treat the usual local repository as if it were a remote, ignoring checksum
  // failures as the local repo doesn't have checksums as a rule
  RemoteRepository localAsRemote =
      new RemoteRepository.Builder("localAsRemote", "default",
          repoSession.getLocalRepository().getBasedir().toURI().toString())
              .setPolicy(new RepositoryPolicy(true,
                      RepositoryPolicy.UPDATE_POLICY_NEVER,
                      RepositoryPolicy.CHECKSUM_POLICY_IGNORE))
              .build();

  repos.add(0, localAsRemote);

  repoSession.setLocalRepositoryManager(repoSystem.newLocalRepositoryManager(
      repoSession, new LocalRepository(head.getAbsolutePath())));

  Dependency dependency = new Dependency(artifact, "runtime");

  CollectRequest collectRequest = new CollectRequest(dependency, repos);

  DependencyNode node =
      repoSystem.collectDependencies(repoSession, collectRequest).getRoot();

  DependencyRequest dependencyRequest = new DependencyRequest();
  dependencyRequest.setRoot(node);

  repoSystem.resolveDependencies(repoSession, dependencyRequest);

}
 
Example 27
protected MavenSession newMavenSession() {
    try {
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
        populator.populateDefaults(request);

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties(System.getProperties());

        // and this is needed so that the repo session in the maven session
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
        DefaultRepositorySystemSession repoSession =
                (DefaultRepositorySystemSession) maven.newRepositorySession(request);
        repoSession.setLocalRepositoryManager(
                new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                        new LocalRepository(request.getLocalRepository().getBasedir())));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession(getContainer(),
                repoSession,
                request, result);
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 28
Source Project: swaggerhub-maven-plugin   Source File: BetterMojoRule.java    License: Apache License 2.0 5 votes vote down vote up
protected MavenSession newMavenSession() {
    try {
        MavenExecutionRequest request = new DefaultMavenExecutionRequest();
        MavenExecutionResult result = new DefaultMavenExecutionResult();

        // populate sensible defaults, including repository basedir and remote repos
        MavenExecutionRequestPopulator populator;
        populator = getContainer().lookup(MavenExecutionRequestPopulator.class);
        populator.populateDefaults(request);

        // this is needed to allow java profiles to get resolved; i.e. avoid during project builds:
        // [ERROR] Failed to determine Java version for profile java-1.5-detected @ org.apache.commons:commons-parent:22, /Users/alex/.m2/repository/org/apache/commons/commons-parent/22/commons-parent-22.pom, line 909, column 14
        request.setSystemProperties(System.getProperties());

        // and this is needed so that the repo session in the maven session
        // has a repo manager, and it points at the local repo
        // (cf MavenRepositorySystemUtils.newSession() which is what is otherwise done)
        DefaultMaven maven = (DefaultMaven) getContainer().lookup(Maven.class);
        DefaultRepositorySystemSession repoSession =
                (DefaultRepositorySystemSession) maven.newRepositorySession(request);
        repoSession.setLocalRepositoryManager(
                new SimpleLocalRepositoryManagerFactory().newInstance(repoSession,
                        new LocalRepository(request.getLocalRepository().getBasedir())));

        @SuppressWarnings("deprecation")
        MavenSession session = new MavenSession(getContainer(),
                repoSession,
                request, result);
        return session;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 29
Source Project: buck   Source File: Resolver.java    License: Apache License 2.0 5 votes vote down vote up
private static RepositorySystemSession newSession(
    RepositorySystem repoSys, LocalRepository localRepo) {
  DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

  session.setLocalRepositoryManager(repoSys.newLocalRepositoryManager(session, localRepo));
  session.setReadOnly();

  return session;
}
 
Example 30
Source Project: qpid-broker-j   Source File: Booter.java    License: Apache License 2.0 5 votes vote down vote up
public static DefaultRepositorySystemSession newRepositorySystemSession(RepositorySystem system)
{
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

    LocalRepository localRepo = new LocalRepository("target/local-repo");
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));

    session.setTransferListener(new ConsoleTransferListener());
    session.setRepositoryListener(new ConsoleRepositoryListener());

    // uncomment to generate dirty trees
    // session.setDependencyGraphTransformer( null );

    return session;
}