gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 08:18:01 25 4
gpt4 key购买 nike

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

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

最佳答案

我想通了:

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

关于java - 加载 Maven 的 settings.xml 供 Jcabi-Aether 使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27818659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com