Java Code Examples for org.apache.maven.settings.Settings

The following examples show how to use org.apache.maven.settings.Settings. 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
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 Project: jkube   Source File: MavenUtilTest.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private MavenSession getMavenSession() {
    Settings settings = new Settings();
    ArtifactRepository localRepository = new MavenArtifactRepository() {
        public String getBasedir() {
            return "repository";
        }
    };

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

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

    return new MavenSession(null, settings, localRepository, null, null, Collections.<String>emptyList(), ".", systemProperties, userProperties, new Date(System.currentTimeMillis()));
}
 
Example 3
Source Project: pom-manipulation-ext   Source File: SettingsIOTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void verifyWriteSettngs() throws IOException, ManipulationException
{
    URL resource = SettingsIOTest.class.getResource( "settings.xml" );
    assertNotNull( resource );
    File originalSettingsFile = new File( resource.getFile() );
    assertTrue( originalSettingsFile.exists() );

    Settings settings = new DefaultSettingsReader().read( originalSettingsFile, Collections.emptyMap() );
    assertNull( settings.getModelEncoding() );

    File targetFile = folder.newFile( "settings.xml" );

    new SettingsIO( null ).write( settings, targetFile );
    assertFalse( FileUtils.contentEquals( targetFile, originalSettingsFile ) );
}
 
Example 4
Source Project: spring-init   Source File: MavenSettings.java    License: Apache License 2.0 6 votes vote down vote up
private List<Profile> determineActiveProfiles(Settings settings) {
	SpringBootCliModelProblemCollector problemCollector = new SpringBootCliModelProblemCollector();
	List<org.apache.maven.model.Profile> activeModelProfiles = createProfileSelector()
			.getActiveProfiles(createModelProfiles(settings.getProfiles()),
					new SpringBootCliProfileActivationContext(
							settings.getActiveProfiles()),
					problemCollector);
	if (!problemCollector.getProblems().isEmpty()) {
		throw new IllegalStateException(createFailureMessage(problemCollector));
	}
	List<Profile> activeProfiles = new ArrayList<Profile>();
	Map<String, Profile> profiles = settings.getProfilesAsMap();
	for (org.apache.maven.model.Profile modelProfile : activeModelProfiles) {
		activeProfiles.add(profiles.get(modelProfile.getId()));
	}
	return activeProfiles;
}
 
Example 5
Source Project: spring-init   Source File: MavenSettingsReader.java    License: Apache License 2.0 6 votes vote down vote up
private Settings loadSettings() {
	File settingsFile = new File(this.homeDir, ".m2/settings.xml");
	if (settingsFile.exists()) {
		log.debug("Reading settings from: " + settingsFile);
	}
	else {
		log.debug("No settings found at: " + settingsFile);
	}
	SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
	request.setUserSettingsFile(settingsFile);
	request.setSystemProperties(System.getProperties());
	try {
		return new DefaultSettingsBuilderFactory().newInstance().build(request)
				.getEffectiveSettings();
	}
	catch (SettingsBuildingException ex) {
		throw new IllegalStateException(
				"Failed to build settings from " + settingsFile, ex);
	}
}
 
Example 6
public MavenPluginRepository() {
	Settings settings = loadDefaultUserSettings();

	system = newRepositorySystem();
	String userHome = System.getProperty("user.home");
	File localRepository = new File(settings.getLocalRepository() == null ? userHome + "/.m2/repository" : settings.getLocalRepository());
	session = newRepositorySystemSession(system, localRepository, settings);

	localRepositories = new ArrayList<>();

	RemoteRepository.Builder localRepoBuilder = new RemoteRepository.Builder("local", "default", "file://" + localRepository.toString());
	localRepoBuilder.setPolicy(new RepositoryPolicy(true, RepositoryPolicy.UPDATE_POLICY_INTERVAL + ":60", RepositoryPolicy.CHECKSUM_POLICY_FAIL));
	local = localRepoBuilder.build();
	repositories.add(local);
	localRepositories.add(local);

	addRepository("central", "default", "https://repo1.maven.org/maven2/");
}
 
Example 7
Source Project: spring-cloud-function   Source File: MavenSettings.java    License: Apache License 2.0 6 votes vote down vote up
private List<Profile> determineActiveProfiles(Settings settings) {
	SpringBootCliModelProblemCollector problemCollector = new SpringBootCliModelProblemCollector();
	List<org.apache.maven.model.Profile> activeModelProfiles = createProfileSelector()
			.getActiveProfiles(createModelProfiles(settings.getProfiles()),
					new SpringBootCliProfileActivationContext(
							settings.getActiveProfiles()),
					problemCollector);
	if (!problemCollector.getProblems().isEmpty()) {
		throw new IllegalStateException(createFailureMessage(problemCollector));
	}
	List<Profile> activeProfiles = new ArrayList<Profile>();
	Map<String, Profile> profiles = settings.getProfilesAsMap();
	for (org.apache.maven.model.Profile modelProfile : activeModelProfiles) {
		activeProfiles.add(profiles.get(modelProfile.getId()));
	}
	return activeProfiles;
}
 
Example 8
Source Project: spring-cloud-function   Source File: MavenSettingsReader.java    License: Apache License 2.0 6 votes vote down vote up
private Settings loadSettings() {
	File settingsFile = new File(this.homeDir, ".m2/settings.xml");
	if (settingsFile.exists()) {
		log.info("Reading settings from: " + settingsFile);
	}
	else {
		log.info("No settings found at: " + settingsFile);
	}
	SettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
	request.setUserSettingsFile(settingsFile);
	request.setSystemProperties(System.getProperties());
	try {
		return new DefaultSettingsBuilderFactory().newInstance().build(request)
				.getEffectiveSettings();
	}
	catch (SettingsBuildingException ex) {
		throw new IllegalStateException(
				"Failed to build settings from " + settingsFile, ex);
	}
}
 
Example 9
Source Project: sql-maven-plugin   Source File: SqlExecMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test002DefaultUsernamePassword()
    throws MojoExecutionException
{

    Settings settings = new Settings();
    Server server = new Server();
    settings.addServer( server );

    mojo.setSettings( settings );

    // force a lookup of username
    mojo.setUsername( null );
    mojo.setPassword( null );

    mojo.execute();

    assertEquals( "", mojo.getUsername() );
    assertEquals( "", mojo.getPassword() );

}
 
Example 10
Source Project: sql-maven-plugin   Source File: SqlExecMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
public void test003UsernamePasswordLookup()
    throws MojoExecutionException
{

    Settings settings = new Settings();
    Server server = new Server();
    server.setId( "somekey" );
    server.setUsername( "username" );
    server.setPassword( "password" );
    settings.addServer( server );

    mojo.setSettings( settings );

    // force a lookup of username
    mojo.setSettingsKey( "somekey" );
    mojo.setUsername( null );
    mojo.setPassword( null );

    mojo.execute();

    assertEquals( "username", mojo.getUsername() );
    assertEquals( "password", mojo.getPassword() );

}
 
Example 11
/**
 * Gets a settings.xml file from the input File and prepares it to be
 * attached to a pom.xml
 *
 * @param fileName file object pointing to the candidate settings file
 *
 * @return the settings object
 *
 * @throws java.io.IOException - if the settings file can't be read
 */
private Settings getSettingsFile(final String fileName) throws IOException {
    Map<String, ?> options = Collections.singletonMap(SettingsReader.IS_STRICT, Boolean.TRUE);
    SettingsReader reader = new DefaultSettingsReader();
    final File settingsFile = new File(BASE_CONFIG_DIR, fileName);
    assertTrue("Could not find settings file: " + settingsFile.getAbsolutePath(), settingsFile.exists());

    Settings settings = null;
    try {
        settings = reader.read(settingsFile, options);
    } catch (SettingsParseException e) {

    }

    return settings;
}
 
Example 12
private Settings loadDefaultUserSettings() {
	String userHome = System.getProperty("user.home");
    File userMavenConfigurationHome = new File(userHome, ".m2");
    String envM2Home = System.getenv("M2_HOME");
    File DEFAULT_USER_SETTINGS_FILE = new File(userMavenConfigurationHome, "settings.xml");
    File DEFAULT_GLOBAL_SETTINGS_FILE = new File(System.getProperty("maven.home", envM2Home != null ? envM2Home : ""), "conf/settings.xml");
    SettingsBuildingRequest settingsBuildingRequest = new DefaultSettingsBuildingRequest();
    settingsBuildingRequest.setSystemProperties(System.getProperties());
    settingsBuildingRequest.setUserSettingsFile(DEFAULT_USER_SETTINGS_FILE);
    settingsBuildingRequest.setGlobalSettingsFile(DEFAULT_GLOBAL_SETTINGS_FILE);

    DefaultSettingsBuilderFactory mvnSettingBuilderFactory = new DefaultSettingsBuilderFactory();
    DefaultSettingsBuilder settingsBuilder = mvnSettingBuilderFactory.newInstance();
    try {
		SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(settingsBuildingRequest);
		Settings settings = settingsBuildingResult.getEffectiveSettings();
		return settings;
	} catch (SettingsBuildingException e) {
		e.printStackTrace();
	}
    return null;
}
 
Example 13
private DefaultVersionsHelper createHelper( String rulesUri, ArtifactMetadataSource metadataSource )
    throws MojoExecutionException
{
    final DefaultWagonManager wagonManager = new DefaultWagonManager()
    {
        public Wagon getWagon( Repository repository )
            throws UnsupportedProtocolException, WagonConfigurationException
        {
            return new FileWagon();
        }
    };

    DefaultVersionsHelper helper =
        new DefaultVersionsHelper( new DefaultArtifactFactory(), new DefaultArtifactResolver(), metadataSource, new ArrayList(),
                                   new ArrayList(),
                                   new DefaultArtifactRepository( "", "", new DefaultRepositoryLayout() ),
                                   wagonManager, new Settings(), "", rulesUri, mock( Log.class ), mock( MavenSession.class ),
                                   new DefaultPathTranslator());
    return helper;
}
 
Example 14
Source Project: pgpverify-maven-plugin   Source File: PGPVerifyMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * test that if we set a proxy, we want to ensure that it is the right one from our config
 * @throws Exception unexcpected reflection issues etc.
 */
@Test
public void testIfProxyDeterminationWorksUsingIDs() throws Exception {

    List<Proxy> proxies = Arrays.asList(
        makeMavenProxy(null, null, "p1", true),
        makeMavenProxy(null, null, "p2", false));

    PGPVerifyMojo mojo = new PGPVerifyMojo();
    Field settings = PGPVerifyMojo.class.getDeclaredField("settings");
    settings.setAccessible(true);
    Settings mavenSettings = mock(Settings.class);
    settings.set(mojo, mavenSettings);
    Field proxyName = PGPVerifyMojo.class.getDeclaredField("proxyName");
    proxyName.setAccessible(true);

    when(mavenSettings.getProxies()).thenReturn(proxies);

    proxyName.set(mojo, "p2");
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p2");
    proxyName.set(mojo, "p1");
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p1");
    proxyName.set(mojo, "p3");
    Assert.assertNull(mojo.getMavenProxy());
}
 
Example 15
Source Project: pgpverify-maven-plugin   Source File: PGPVerifyMojoTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * If the proxy is not set, it should take the first active one
 * @throws Exception unexpected reflection issue
 */
@Test
public void testIfProxyDeterminationWorksUsinFirstActive() throws Exception {
    List<Proxy> proxies = Arrays.asList(
        makeMavenProxy(null, null, "p1", false),
        makeMavenProxy(null, null, "p2", true));
    PGPVerifyMojo mojo = new PGPVerifyMojo();
    Field settings = PGPVerifyMojo.class.getDeclaredField("settings");
    settings.setAccessible(true);
    Settings mavenSettings = mock(Settings.class);
    settings.set(mojo, mavenSettings);
    Field proxyName = PGPVerifyMojo.class.getDeclaredField("proxyName");
    proxyName.setAccessible(true);

    when(mavenSettings.getProxies()).thenReturn(proxies);

    proxyName.set(mojo, null);
    Assert.assertEquals(mojo.getMavenProxy().getId(), "p2");
}
 
Example 16
/**
 * Method updateSettings.
 *  @param settings
 * @param counter
 * @param element
 */
protected void updateSettings( final Settings settings, final IndentationCounter counter, final Element element )
{
    final IndentationCounter innerCount = new IndentationCounter( counter.getDepth() + 1 );
    findAndReplaceSimpleElement( innerCount, element, "localRepository", settings.getLocalRepository(), null );
    findAndReplaceSimpleElement( innerCount, element, "interactiveMode", String.valueOf( settings.isInteractiveMode() ), "true" );
    findAndReplaceSimpleElement( innerCount, element, "usePluginRegistry", String.valueOf( settings.isUsePluginRegistry() ), "false" );
    findAndReplaceSimpleElement( innerCount, element, "offline", !settings.isOffline() ? null : String.valueOf( settings.isOffline() ),
                                 "false" );
    iterateProxy( innerCount, element, settings.getProxies() );
    iterateServer( innerCount, element, settings.getServers() );
    iterateMirror( innerCount, element, settings.getMirrors() );
    iterateProfile( innerCount, element, settings.getProfiles() );
    findAndReplaceSimpleLists( innerCount, element, settings.getActiveProfiles(), "activeProfiles", "activeProfile" );
    findAndReplaceSimpleLists( innerCount, element, settings.getPluginGroups(), "pluginGroups", "pluginGroup" );
}
 
Example 17
Source Project: jkube   Source File: MojoParameters.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public MojoParameters(MavenSession session, MavenProject project, MavenArchiveConfiguration archive, MavenFileFilter mavenFileFilter,
                      MavenReaderFilter mavenFilterReader, Settings settings, String sourceDirectory, String outputDirectory, List<MavenProject> reactorProjects) {
    this.archive = archive;
    this.session = session;
    this.mavenFileFilter = mavenFileFilter;
    this.mavenFilterReader = mavenFilterReader;
    this.project = project;
    this.settings = settings;

    this.sourceDirectory = sourceDirectory;
    this.outputDirectory = outputDirectory;

    this.reactorProjects = reactorProjects;
}
 
Example 18
Source Project: LicenseScout   Source File: ConfigurationHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Converts Maven database configuration to execution database configuration.
 * 
 * <p>This resolves the server definition given by ID from the settings and takes the DB connection
 * credentials from there.</p>
 * 
 * @param databaseConfiguration
 * @param settings the settings.xml object
 * @param log the logger
 * @return a database configuration for the execution engine
 * @throws MojoExecutionException if the server ID is not found in settings, or username or password are not specified in the server definition
 */
public static ExecutionDatabaseConfiguration getExecutionDatabaseConfiguration(final DatabaseConfiguration databaseConfiguration,
                                                                               final Settings settings,
                                                                               final ILSLog log)
        throws MojoExecutionException {
    if (databaseConfiguration == null) {
        return null;
    }
    final ExecutionDatabaseConfiguration executionDatabaseConfiguration = new ExecutionDatabaseConfiguration();
    executionDatabaseConfiguration.setJdbcUrl(databaseConfiguration.getJdbcUrl());
    final String serverId = databaseConfiguration.getServerId();
    log.info("Resolving database server ID: " + serverId);
    final Server server = settings.getServer(serverId);
    if (server == null) {
        throw new MojoExecutionException(
                String.format("No definition found for server ID %s in settings.xml", serverId));
    }
    final String username = server.getUsername();
    final String password = server.getPassword();
    if (username == null) {
        throw new MojoExecutionException(
                String.format("No username defined in server specification with ID %s in settings.xml", serverId));
    }
    if (password == null) {
        throw new MojoExecutionException(
                String.format("No password defined in server specification with ID %s in settings.xml", serverId));
    }
    executionDatabaseConfiguration.setUsername(username);
    executionDatabaseConfiguration.setPassword(password);
    return executionDatabaseConfiguration;
}
 
Example 19
Source Project: LicenseScout   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test case for the method {@link ConfigurationHelper#getExecutionDatabaseConfiguration(DatabaseConfiguration, Settings, ILSLog)}.
 * @throws Exception 
 */
@Test
public void testGetExecutionDatabaseConfigurationSuccess() throws Exception {
    final Settings settings = createSettings();
    final DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration("jdbcUrl", "serverId");
    final ExecutionDatabaseConfiguration executionDatabaseConfiguration = ConfigurationHelper
            .getExecutionDatabaseConfiguration(databaseConfiguration, settings, TestUtil.createTestLog());
    Assert.assertEquals("jdbcUrl", "jdbcUrl", executionDatabaseConfiguration.getJdbcUrl());
    Assert.assertEquals("username", "serverIdusername", executionDatabaseConfiguration.getUsername());
    Assert.assertEquals("password", "serverIdpassword", executionDatabaseConfiguration.getPassword());
}
 
Example 20
public MavenLocationExpander( final List<Location> customLocations,
                              final List<ArtifactRepository> artifactRepositories,
                              final ArtifactRepository localRepository, final MirrorSelector mirrorSelector,
                              final Settings settings, final List<String> activeProfiles )
    throws MalformedURLException
{
    final Set<Location> locs = new LinkedHashSet<>();

    if ( localRepository != null )
    {
        locs.add( new SimpleLocation( localRepository.getId(), new File( localRepository.getBasedir() ).toURI()
                                                                                                       .toString() ) );
    }

    if ( customLocations != null )
    {
        locs.addAll( customLocations );
    }

    addSettingsProfileRepositoriesTo( locs, settings, activeProfiles, mirrorSelector );
    addRequestRepositoriesTo( locs, artifactRepositories, settings, mirrorSelector );

    if ( logger.isDebugEnabled() && !locs.isEmpty() )
    {
        logger.debug( "Configured to use Maven locations:{}  {}", System.lineSeparator(),
                new JoinString( System.lineSeparator() + "  ", locs ) );
    }
    this.locations = new ArrayList<>( locs );
}
 
Example 21
Source Project: LicenseScout   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Test case for the method {@link ConfigurationHelper#getExecutionDatabaseConfiguration(DatabaseConfiguration, Settings, ILSLog)}.
 * @throws Exception 
 */
@Test(expected = MojoExecutionException.class)
public void testGetExecutionDatabaseConfigurationServerIdNotFound() throws Exception {
    final Settings settings = createSettings();
    final DatabaseConfiguration databaseConfiguration = new DatabaseConfiguration("jdbcUrl", "serverId_noexisting");
    ConfigurationHelper.getExecutionDatabaseConfiguration(databaseConfiguration, settings,
            TestUtil.createTestLog());
}
 
Example 22
Source Project: LicenseScout   Source File: ConfigurationHelperTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a settings instance for testing.
 * @return a settings instance
 * @throws SettingsBuildingException
 */
private Settings createSettings() throws SettingsBuildingException {
    DefaultSettingsBuilderFactory settingsBuilderFactory = new DefaultSettingsBuilderFactory();
    SettingsBuilder settingsBuilder = settingsBuilderFactory.newInstance();
    DefaultSettingsBuildingRequest request = new DefaultSettingsBuildingRequest();
    final File userSettingsFile = new File("src/test/resources/ConfigurationHelperTest/settings.xml");
    request.setUserSettingsFile(userSettingsFile);
    SettingsBuildingResult settingsBuildingResult = settingsBuilder.build(request);
    return settingsBuildingResult.getEffectiveSettings();
}
 
Example 23
Source Project: galleon   Source File: MavenMvnSettings.java    License: Apache License 2.0 5 votes vote down vote up
MavenMvnSettings(MavenConfig config, RepositorySystem repoSystem, RepositoryListener listener) throws ArtifactException {
    this.config = config;
    Settings settings = buildMavenSettings(config.getSettings());
    Proxy proxy = settings.getActiveProxy();
    if (proxy != null) {
        MavenProxySelector.Builder builder = new MavenProxySelector.Builder(proxy.getHost(), proxy.getPort(), proxy.getProtocol());
        builder.setPassword(proxy.getPassword());
        builder.setUserName(proxy.getUsername());
        if (proxy.getNonProxyHosts() != null) {
            String[] hosts = proxy.getNonProxyHosts().split("\\|");
            builder.addNonProxyHosts(Arrays.asList(hosts));
        }
        proxySelector = builder.build();
        Authentication auth = null;
        if (proxy.getPassword() != null && proxy.getUsername() != null) {
            auth = new AuthenticationBuilder().addUsername(proxy.getUsername()).addPassword(proxy.getPassword()).build();
        }
        this.proxy = new org.eclipse.aether.repository.Proxy(proxy.getProtocol(), proxy.getHost(), proxy.getPort(), auth);
    } else {
        this.proxy = null;
        proxySelector = null;
    }
    try {
        repositories = Collections.unmodifiableList(buildRemoteRepositories(settings));
    } catch (MalformedURLException ex) {
        throw new ArtifactException(ex.getMessage(), ex);
    }
    session = Util.newRepositorySession(repoSystem,
            settings.getLocalRepository() == null ? config.getLocalRepository() : Paths.get(settings.getLocalRepository()),
            listener, proxySelector, settings.isOffline());
}
 
Example 24
@Override
public Response<File[]> resolveResources(final AddonId addonId)
{
   RepositorySystem system = container.getRepositorySystem();
   Settings settings = getSettings();
   DefaultRepositorySystemSession session = container.setupRepoSession(system, settings);
   final String mavenCoords = toMavenCoords(addonId);
   Artifact queryArtifact = new DefaultArtifact(mavenCoords);
   session.setDependencyTraverser(new AddonDependencyTraverser(classifier));
   session.setDependencySelector(new AddonDependencySelector(classifier));
   Dependency dependency = new Dependency(queryArtifact, null);

   List<RemoteRepository> repositories = MavenRepositories.getRemoteRepositories(container, settings);

   CollectRequest collectRequest = new CollectRequest(dependency, repositories);
   DependencyResult result;
   try
   {
      result = system.resolveDependencies(session, new DependencyRequest(collectRequest, null));
   }
   catch (DependencyResolutionException e)
   {
      throw new RuntimeException(e);
   }
   List<Exception> collectExceptions = result.getCollectExceptions();
   Set<File> files = new HashSet<File>();
   List<ArtifactResult> artifactResults = result.getArtifactResults();
   for (ArtifactResult artifactResult : artifactResults)
   {
      Artifact artifact = artifactResult.getArtifact();
      if (isFurnaceAPI(artifact) ||
               (this.classifier.equals(artifact.getClassifier())
                        && !addonId.getName().equals(artifact.getGroupId() + ":" + artifact.getArtifactId())))
      {
         continue;
      }
      files.add(artifact.getFile());
   }
   return new MavenResponseBuilder<File[]>(files.toArray(new File[files.size()])).setExceptions(collectExceptions);
}
 
Example 25
Source Project: furnace   Source File: ProjectHelper.java    License: Eclipse Public License 1.0 5 votes vote down vote up
public Model loadPomFromFile(File pomFile, String... profiles)
{
   RepositorySystem system = mavenContainer.getRepositorySystem();
   Settings settings = mavenContainer.getSettings();
   DefaultRepositorySystemSession session = mavenContainer.setupRepoSession(system, settings);
   final DefaultModelBuildingRequest request = new DefaultModelBuildingRequest()
            .setSystemProperties(System.getProperties())
            .setPomFile(pomFile)
            .setActiveProfileIds(settings.getActiveProfiles());
   ModelBuilder builder = new DefaultModelBuilderFactory().newInstance();
   ModelBuildingResult result;
   try
   {
      request.setModelResolver(new MavenModelResolver(system, session,
               MavenRepositories.getRemoteRepositories(mavenContainer, settings)));
      result = builder.build(request);
   }
   // wrap exception message
   catch (ModelBuildingException e)
   {
      String pomPath = request.getPomFile().getAbsolutePath();
      StringBuilder sb = new StringBuilder("Found ").append(e.getProblems().size())
               .append(" problems while building POM model from ").append(pomPath).append("\n");

      int counter = 1;
      for (ModelProblem problem : e.getProblems())
      {
         sb.append(counter++).append("/ ").append(problem).append("\n");
      }

      throw new RuntimeException(sb.toString());
   }
   return result.getEffectiveModel();
}
 
Example 26
Source Project: furnace   Source File: MavenContainer.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private DefaultMirrorSelector createMirrorSelector(Settings settings)
{
   final DefaultMirrorSelector mirrorSelector = new DefaultMirrorSelector();
   final List<Mirror> mirrors = settings.getMirrors();
   if (mirrors != null)
   {
      for (Mirror mirror : mirrors)
      {
         mirrorSelector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false, mirror.getMirrorOf(),
                  mirror.getMirrorOfLayouts());
      }
   }
   return mirrorSelector;
}
 
Example 27
@Override
public Response<String> resolveAPIVersion(AddonId addonId)
{
   RepositorySystem system = container.getRepositorySystem();
   Settings settings = getSettings();
   DefaultRepositorySystemSession session = container.setupRepoSession(system, settings);
   return resolveAPIVersion(addonId, system, settings, session);
}
 
Example 28
Source Project: spring-init   Source File: MavenSettings.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create a new {@link MavenSettings} instance.
 * @param settings the source settings
 * @param decryptedSettings the decrypted settings
 */
public MavenSettings(Settings settings, SettingsDecryptionResult decryptedSettings) {
	this.offline = settings.isOffline();
	this.mirrorSelector = createMirrorSelector(settings);
	this.authenticationSelector = createAuthenticationSelector(decryptedSettings);
	this.proxySelector = createProxySelector(decryptedSettings);
	this.localRepository = settings.getLocalRepository();
	this.activeProfiles = determineActiveProfiles(settings);
}
 
Example 29
Source Project: spring-init   Source File: MavenSettings.java    License: Apache License 2.0 5 votes vote down vote up
private MirrorSelector createMirrorSelector(Settings settings) {
	DefaultMirrorSelector selector = new DefaultMirrorSelector();
	for (Mirror mirror : settings.getMirrors()) {
		selector.add(mirror.getId(), mirror.getUrl(), mirror.getLayout(), false,
				mirror.getMirrorOf(), mirror.getMirrorOfLayouts());
	}
	return selector;
}
 
Example 30
Source Project: spring-init   Source File: MavenSettingsReader.java    License: Apache License 2.0 5 votes vote down vote up
public MavenSettings readSettings() {
	Settings settings = loadSettings();
	SettingsDecryptionResult decrypted = decryptSettings(settings);
	if (!decrypted.getProblems().isEmpty()) {
		log.error(
				"Maven settings decryption failed. Some Maven repositories may be inaccessible");
		// Continue - the encrypted credentials may not be used
	}
	return new MavenSettings(settings, decrypted);
}