3

我正在尝试使用 Maven 和 Jcabi-Aether 获取/解决一些工件。我想我已经准备好了大部分代码,但是我很难弄清楚如何加载用户的代码settings.xml,以便我可以将 Maven 存储库加载到remotesAether 使用的变量中:

import com.jcabi.aether.Aether;
import java.io.File;
import java.util.Arrays;
import org.apache.maven.project.MavenProject;
import org.sonatype.aether.artifact.Artifact;
import org.sonatype.aether.repository.RemoteRepository;
import org.sonatype.aether.util.artifact.DefaultArtifact;

public class Main {
  public static void main(String[] args) {
    File local = new File("/tmp/local-repository");
    Collection<RemoteRepository> remotes = Arrays.asList(
      new RemoteRepository(
        "maven-central",
        "default",
        "http://repo1.maven.org/maven2/"
      )
    );
    Collection<Artifact> deps = new Aether(remotes, local).resolve(
      new DefaultArtifact("junit", "junit-dep", "", "jar", "4.10"),
      "runtime"
    );
  }
}

是否可以加载settings.xml和获取存储库信息?

4

1 回答 1

5

我已经想通了:

public static final String userHome = System.getProperty( "user.home" );
public static final File userMavenConfigurationHome = new File( userHome, ".m2" );
public static final String envM2Home = System.getenv("M2_HOME");
public static final File DEFAULT_USER_SETTINGS_FILE = new File( userMavenConfigurationHome, "settings.xml" );
public static final 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);

    SettingsBuildingResult settingsBuildingResult;
    DefaultSettingsBuilderFactory mvnSettingBuilderFactory = new DefaultSettingsBuilderFactory();
    DefaultSettingsBuilder settingsBuilder =  mvnSettingBuilderFactory.newInstance();
    settingsBuildingResult = settingsBuilder.build(settingsBuildingRequest);

    Settings effectiveSettings = settingsBuildingResult.getEffectiveSettings();
    Map<String, Profile> profilesMap = effectiveSettings.getProfilesAsMap();
    Collection<RemoteRepository> remotes = new ArrayList<>(20);
    for (String profileName : effectiveSettings.getActiveProfiles())
    {
        Profile profile = profilesMap.get(profileName);
        List<Repository> repositories = profile.getRepositories();
        for (Repository repo : repositories)
        {
            RemoteRepository remoteRepo
                = new RemoteRepository(repo.getId(), "default", repo.getUrl());
            remotes.add(remoteRepo);
        }
    }
于 2015-01-09T09:44:17.570 回答