Java Code Examples for org.apache.maven.repository.internal.MavenRepositorySystemUtils#newSession()

The following examples show how to use org.apache.maven.repository.internal.MavenRepositorySystemUtils#newSession() . 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: MavenPluginRepository.java    From BIMserver with GNU Affero General Public License v3.0 6 votes vote down vote up
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 2
Source File: DependencyResolver.java    From start.spring.io with 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 File: DependencyResolver.java    From spring-init with 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 4
Source File: JavaFXRunMojoTestCase.java    From javafx-maven-plugin with 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 5
Source File: DependencyResolver.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
static DefaultRepositorySystemSession newRepositorySystemSession(RepositorySystem system) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
    session.setCache(newRepositoryCache());
    String localRepositoryPath = resolveLocalRepository();
    if (logger.isLoggable(Level.INFO)) {
        logger.info("Local repository: " + localRepositoryPath);
    }
    LocalRepository localRepository = new LocalRepository(localRepositoryPath);

    LocalRepositoryManager localRepositoryManager = system.newLocalRepositoryManager(session, localRepository);
    session.setLocalRepositoryManager(localRepositoryManager);

    return session;
}
 
Example 6
Source File: Aether.java    From pro with GNU General Public License v3.0 5 votes vote down vote up
public static Aether create(Path mavenLocalRepository, List<URI> remoteRepositories) {
  // respository system
  var locator = MavenRepositorySystemUtils.newServiceLocator();
  locator.addService(RepositoryConnectorFactory.class, BasicRepositoryConnectorFactory.class);
  locator.addService(TransporterFactory.class, FileTransporterFactory.class);
  locator.addService(TransporterFactory.class, HttpTransporterFactory.class);

  locator.setErrorHandler(new DefaultServiceLocator.ErrorHandler() {
    @Override
    public void serviceCreationFailed(Class<?> type, Class<?> impl, Throwable exception) {
      exception.printStackTrace();
    }
  });
  RepositorySystem system = locator.getService(RepositorySystem.class);

  // session
  var session = MavenRepositorySystemUtils.newSession();
  var localRepository = new LocalRepository(mavenLocalRepository.toString());
  session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepository));

  // central repository
  var central = new RemoteRepository.Builder("central", "default",
      "https://repo1.maven.org/maven2/").build();
  
  // remote repositories
  var remotes = Stream.concat(
        remoteRepositories.stream().map(uri -> new RemoteRepository.Builder(null, "default", uri.toString()).build()),
        Stream.of(central)
      )
      .collect(Collectors.toUnmodifiableList());
  
  return new Aether(system, session, remotes);
}
 
Example 7
Source File: MavenInitializer.java    From thorntail with Apache License 2.0 5 votes vote down vote up
public static RepositorySystemSession newSession(RepositorySystem system) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();

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

    return session;
}
 
Example 8
Source File: Booter.java    From qpid-broker-j with 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;
}
 
Example 9
Source File: GithubImporter.java    From scava with Eclipse Public License 2.0 5 votes vote down vote up
private static RepositorySystemSession newSession(RepositorySystem system) {
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	LocalRepository localRepo = new LocalRepository("target/local-repo");
	session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
	// set possible proxies and mirrors
	session.setProxySelector(new DefaultProxySelector().add(new Proxy(Proxy.TYPE_HTTP, "host", 3625),
			Arrays.asList("localhost", "127.0.0.1")));
	session.setMirrorSelector(
			new DefaultMirrorSelector().add("my-mirror", "http://mirror", "default", false, "external:*", null));
	return session;
}
 
Example 10
Source File: RemotePluginRepository.java    From BIMserver with GNU Affero General Public License v3.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;
}
 
Example 11
Source File: Aether.java    From migration-tooling with 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 12
Source File: Maven.java    From bazel-deps with MIT License 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));

  return session;
}
 
Example 13
Source File: Resolver.java    From buck with 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 14
Source File: MavenDependencyResolver.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
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 15
Source File: Cadfael.java    From Poseidon with Apache License 2.0 5 votes vote down vote up
private RepositorySystemSession newSession(RepositorySystem system) {
        DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
        LocalRepository localRepo = new LocalRepository("target/local-repo");
        session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
        // set possible proxies and mirrors
//        session.setProxySelector(new DefaultProxySelector().add(new Proxy(Proxy.TYPE_HTTP, "host", 3625), Arrays.asList("localhost", "127.0.0.1")));
//        session.setMirrorSelector(new DefaultMirrorSelector().add("my-mirror", "http://mirror", "default", false, "external:*", null));
        return session;
    }
 
Example 16
Source File: MavenResolverDependencyManagementVersionResolver.java    From initializr with Apache License 2.0 5 votes vote down vote up
MavenResolverDependencyManagementVersionResolver(Path cacheLocation) {
	ServiceLocator serviceLocator = createServiceLocator();
	DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
	session.setArtifactDescriptorPolicy(new SimpleArtifactDescriptorPolicy(false, false));
	LocalRepository localRepository = new LocalRepository(cacheLocation.toFile());
	this.repositorySystem = serviceLocator.getService(RepositorySystem.class);
	session.setLocalRepositoryManager(this.repositorySystem.newLocalRepositoryManager(session, localRepository));
	session.setReadOnly();
	this.repositorySystemSession = session;
}
 
Example 17
Source File: PluginPreprocessor.java    From gyro with Apache License 2.0 4 votes vote down vote up
@Override
public List<Node> preprocess(List<Node> nodes, RootScope scope) {
    PluginSettings settings = scope.getSettings(PluginSettings.class);

    List<String> artifactCoords = new ArrayList<>();
    List<Node> repositoryNodes = new ArrayList<>();

    for (Node node : nodes) {
        if (node instanceof DirectiveNode) {
            if ("plugin".equals(((DirectiveNode) node).getName())) {
                artifactCoords.add(getArtifactCoord((DirectiveNode) node));
            } else if ("repository".equals(((DirectiveNode) node).getName())) {
                repositoryNodes.add(node);
            }
        }
    }

    if (artifactCoords.stream().allMatch(settings::pluginInitialized)) {
        return nodes;
    }

    NodeEvaluator evaluator = new NodeEvaluator();
    evaluator.evaluate(scope, repositoryNodes);

    for (String ac : artifactCoords) {
        if (settings.pluginInitialized(ac)) {
            continue;
        }

        try {
            GyroCore.ui().write("@|magenta ↓ Loading plugin:|@ %s\n", ac);

            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(ac);
            Dependency dependency = new Dependency(artifact, JavaScopes.RUNTIME);
            DependencyFilter filter = DependencyFilterUtils.classpathFilter(JavaScopes.RUNTIME);
            List<RemoteRepository> repositories = scope.getSettings(RepositorySettings.class).getRepositories();
            CollectRequest collectRequest = new CollectRequest(dependency, repositories);
            DependencyRequest request = new DependencyRequest(collectRequest, filter);
            DependencyResult result = system.resolveDependencies(session, request);

            settings.putDependencyResult(ac, result);

            for (ArtifactResult ar : result.getArtifactResults()) {
                settings.putArtifactIfNewer(ar.getArtifact());
            }
        } catch (Exception error) {
            throw new GyroException(
                String.format("Can't load the @|bold %s|@ plugin!", ac),
                error);
        }
    }

    settings.addAllUrls();

    return nodes;
}
 
Example 18
Source File: Utils.java    From gate-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
public static DefaultRepositorySystemSession getRepositorySession(RepositorySystem repoSystem, WorkspaceReader workspace) {
  
  DefaultRepositorySystemSession repoSystemSession = MavenRepositorySystemUtils.newSession();
  
  String repoLocation = System.getProperty("user.home") + File.separator
          + ".m2" + File.separator + "repository/";
  ChainedProxySelector proxySelector = new ChainedProxySelector();
  try {
    Settings effectiveSettings = loadMavenSettings();
    if(effectiveSettings.getLocalRepository() != null) {
      repoLocation = effectiveSettings.getLocalRepository();
    }

    List<Mirror> mirrors = effectiveSettings.getMirrors();
    if(!mirrors.isEmpty()) {
      DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
      for (Mirror mirror : mirrors) mirrorSelector.add(
              String.valueOf(mirror.getId()), mirror.getUrl(), mirror.getLayout(), false,
              mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
      repoSystemSession.setMirrorSelector(mirrorSelector);
    }

    List<Server> servers = effectiveSettings.getServers();
    if(!servers.isEmpty()) {
      DefaultAuthenticationSelector selector = new DefaultAuthenticationSelector();
      for (Server server : servers) {
        AuthenticationBuilder auth = new AuthenticationBuilder();
        auth.addUsername(server.getUsername()).addPassword(PASSWORD_DECRYPTER.decrypt(server.getPassword()));
        auth.addPrivateKey(server.getPrivateKey(), PASSWORD_DECRYPTER.decrypt(server.getPassphrase()));
        selector.add(server.getId(), auth.build());
      }
      repoSystemSession.setAuthenticationSelector(new ConservativeAuthenticationSelector(selector));
    }

    // extract any proxies configured in the settings - we need to pass these
    // on so that any repositories declared in a dependency POM file can be
    // accessed through the proxy too.
    List<org.apache.maven.settings.Proxy> proxies =
        effectiveSettings.getProxies().stream().filter((p) -> p.isActive())
            .collect(Collectors.toList());
    
    if(!proxies.isEmpty()) {
      DefaultProxySelector defaultSelector = new DefaultProxySelector();
      for (org.apache.maven.settings.Proxy proxy : proxies) {
        defaultSelector.add(
            new Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(),
                new AuthenticationBuilder().addUsername(proxy.getUsername())
                    .addPassword(PASSWORD_DECRYPTER.decrypt(proxy.getPassword())).build()),
            proxy.getNonProxyHosts());
      }

      proxySelector.addSelector(defaultSelector);
    }

    // pass through the "offline" setting
    repoSystemSession.setOffline(effectiveSettings.isOffline());
  } catch(SettingsBuildingException | SecDispatcherException | RuntimeException e) {
    log.warn(
            "Unable to load Maven settings, using default repository location, and no mirrors, proxy or authentication settings.",
            e);
  }

  LocalRepository localRepo = new LocalRepository(repoLocation);
  log.debug("Using local repository at: " + repoLocation);
  repoSystemSession.setLocalRepositoryManager(repoSystem
          .newLocalRepositoryManager(repoSystemSession, localRepo));
  
  //repoSystemSession.setWorkspaceReader(new SimpleMavenCache(new File("repo")));      
  if (workspace != null) repoSystemSession.setWorkspaceReader(workspace);

  // try JRE proxies after any configured in settings
  proxySelector.addSelector(new JreProxySelector());

  // set proxy selector for any repositories discovered in dependency poms
  repoSystemSession.setProxySelector(proxySelector);

  return repoSystemSession;
}
 
Example 19
Source File: LibertyFeatureVersionIT.java    From boost with Eclipse Public License 1.0 4 votes vote down vote up
private RepositorySystemSession newSession(RepositorySystem system) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
    LocalRepository localRepo = new LocalRepository("target/local-repo");
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
    return session;
}
 
Example 20
Source File: ArtifactHelperTest.java    From LicenseScout with Apache License 2.0 4 votes vote down vote up
private static RepositorySystemSession newSession(RepositorySystem system) {
    DefaultRepositorySystemSession session = MavenRepositorySystemUtils.newSession();
    LocalRepository localRepo = new LocalRepository("target/local-repo");
    session.setLocalRepositoryManager(system.newLocalRepositoryManager(session, localRepo));
    return session;
}