加载Maven的settings.xml以供Jcabi-Aether使用

时间:2015-01-07 11:39:00

标签: java maven aether jcabi

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

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并获取存储库信息?

1 个答案:

答案 0 :(得分:3)

我已经弄明白了:

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);
        }
    }