下面列出了怎么用org.apache.maven.plugin.BuildPluginManager的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 初始化当前Maven项目.
*
* @param session the session
* @param pluginManager this plugin manager
*/
private static void initMavenProject(MavenSession session, BuildPluginManager pluginManager) {
String projectId = session.getCurrentProject().getId();
if (!DevOps.Config.getFinalConfig().getProjects().containsKey(projectId)) {
// 尚未初始化
return;
}
if (!mavenProps.containsKey(projectId)) {
mavenProps.put(projectId, new HashMap<>());
}
// 更新 session project plugin
FinalProjectConfig projectConfig = DevOps.Config.getFinalConfig().getProjects().get(projectId);
projectConfig.setMavenSession(session);
projectConfig.setPluginManager(pluginManager);
projectConfig.setMavenProject(session.getCurrentProject());
// 更新maven prop
projectConfig.getMavenProject().getProperties().putAll(mavenProps.get(projectId));
// 设置为当前项目
DevOps.Config.setCurrentProjectId(projectId);
}
public static void copyDependenciesToBuildDirectory(MavenProject mavenProject,
MavenSession mavenSession,
BuildPluginManager pluginManager) throws MojoExecutionException {
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("2.4")
),
goal("copy-dependencies"),
configuration(
element(name("outputDirectory"), "${project.build.directory}/dependency")
),
executionEnvironment(
mavenProject,
mavenSession,
pluginManager
)
);
}
public static Path createDependencyListFile(MavenProject mavenProject,
MavenSession mavenSession,
BuildPluginManager pluginManager) throws MojoExecutionException, IOException {
Path path = Files.createTempFile("heroku-maven-plugin", "mvn-dependency-list.log");
executeMojo(
plugin(
groupId("org.apache.maven.plugins"),
artifactId("maven-dependency-plugin"),
version("2.4")
),
goal("list"),
configuration(
element(name("outputFile"), path.toString())
),
executionEnvironment(
mavenProject,
mavenSession,
pluginManager
)
);
return path;
}
/**
* Constructor.
*
* @param project The maven project.
* @param session The maven session.
* @param plugins The maven plugin manager.
*/
public MavenProjectSupplier(MavenProject project,
MavenSession session,
BuildPluginManager plugins) {
MavenProjectConfigCollector.assertSupportedProject(session);
this.project = project;
this.session = requireNonNull(session);
this.plugins = requireNonNull(plugins);
this.firstBuild = new AtomicBoolean(true);
}
public MojoExecutor(MojoExecution execution, MavenProject project, MavenSession session, BuildPluginManager buildPluginManager) {
this.build = buildPluginManager;
this.project = project;
this.session = session;
this.plugin = execution.getPlugin();
configuration = execution.getConfiguration();
goal = execution.getGoal();
}
/**
* Executes the Maven Resource Plugin to copy resources to `target/classes`
*
* @param project the project
* @param mavenSession the maven session
* @param buildPluginManager the build plugin manager
* @throws MojoExecutionException if the copy cannot be completed successfully
*/
public static void copyResources(MavenProject project, MavenSession mavenSession,
BuildPluginManager buildPluginManager) throws MojoExecutionException {
Optional<Plugin> resourcesPlugin = hasPlugin(project, RESOURCES_PLUGIN_KEY);
Xpp3Dom pluginConfig = configuration(element("outputDirectory", "${project.build.outputDirectory}"));
if (resourcesPlugin.isPresent()) {
Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_RESOURCES_PLUGIN, GOAL_RESOURCES);
if (optConfiguration.isPresent()) {
pluginConfig = optConfiguration.get();
}
executeMojo(
resourcesPlugin.get(),
goal(GOAL_RESOURCES),
pluginConfig,
executionEnvironment(project, mavenSession, buildPluginManager)
);
} else {
executeMojo(
plugin(G_MAVEN_RESOURCES_PLUGIN, A_MAVEN_RESOURCES_PLUGIN,
properties.getProperty(V_MAVEN_RESOURCES_PLUGIN)),
goal(GOAL_RESOURCES),
pluginConfig,
executionEnvironment(project, mavenSession, buildPluginManager)
);
}
}
/**
* Execute the Maven Compiler Plugin to compile java sources.
*
* @param project the project
* @param mavenSession the session
* @param buildPluginManager the build plugin manager
* @throws Exception if the compilation fails for any reason
*/
public static void compile(MavenProject project, MavenSession mavenSession,
BuildPluginManager buildPluginManager) throws Exception {
Optional<Plugin> mvnCompilerPlugin = project.getBuildPlugins().stream()
.filter(plugin -> A_MAVEN_COMPILER_PLUGIN.equals(plugin.getArtifactId()))
.findFirst();
String pluginVersion = properties.getProperty(V_MAVEN_COMPILER_PLUGIN);
if (mvnCompilerPlugin.isPresent()) {
pluginVersion = mvnCompilerPlugin.get().getVersion();
}
Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_COMPILER_PLUGIN, GOAL_COMPILE);
if (optConfiguration.isPresent()) {
Xpp3Dom configuration = optConfiguration.get();
executeMojo(
plugin(G_MAVEN_COMPILER_PLUGIN, A_MAVEN_COMPILER_PLUGIN, pluginVersion),
goal(GOAL_COMPILE),
configuration,
executionEnvironment(project, mavenSession, buildPluginManager)
);
}
}
/**
* 调用指定的Maven mojo.
*
* @param groupId the group id
* @param artifactId the artifact id
* @param version the version
* @param goal the goal
* @param configuration the configuration
* @param mavenProject the maven project
* @param mavenSession the maven session
* @param mavenPluginManager the maven plugin manager
*/
@SneakyThrows
public static void invoke(String groupId, String artifactId, String version,
String goal, Map<String, Object> configuration,
MavenProject mavenProject, MavenSession mavenSession, BuildPluginManager mavenPluginManager
) {
log.debug("invoke groupId = " + groupId + " ,artifactId = " + artifactId + " ,version = " + version);
List<Element> config = configuration.entrySet().stream()
.map(item -> {
if (item.getValue() instanceof Map<?, ?>) {
var eles = ((Map<?, ?>) item.getValue()).entrySet().stream()
.map(subItem -> element(subItem.getKey().toString(), subItem.getValue().toString()))
.collect(Collectors.toList());
return element(item.getKey(), eles.toArray(new MojoExecutor.Element[eles.size()]));
} else {
return element(item.getKey(), item.getValue().toString());
}
})
.collect(Collectors.toList());
org.apache.maven.model.Plugin plugin;
if (version == null) {
plugin = plugin(groupId, artifactId);
} else {
plugin = plugin(groupId, artifactId, version);
}
executeMojo(
plugin,
goal(goal),
configuration(config.toArray(new Element[]{})),
executionEnvironment(
mavenProject,
mavenSession,
mavenPluginManager
)
);
}
public static void process(MavenProject mavenProject, MavenSession mavenSession, BuildPluginManager pluginManager, File output) {
log.info("Deploy SDK from : {}", output.getPath());
MavenHelper.invoke("org.apache.maven.plugins", "maven-invoker-plugin", null,
"run", new HashMap<>() {
{
put("projectsDirectory", output.getParent());
put("goals", new HashMap<>() {
{
put("goal", "-P release");
}
});
put("mavenOpts", "");
}
}, mavenProject, mavenSession, pluginManager);
}
public MojoExecutor(MojoExecution execution, MavenProject project, MavenSession session, BuildPluginManager buildPluginManager) {
this.build = buildPluginManager;
this.project = project;
this.session = session;
this.plugin = execution.getPlugin();
configuration = execution.getConfiguration();
goal = execution.getGoal();
}
/**
* Executes the Maven Resource Plugin to copy resources to `target/classes`
*
* @param project the project
* @param mavenSession the maven session
* @param buildPluginManager the build plugin manager
* @throws MojoExecutionException if the copy cannot be completed successfully
*/
public static void copyResources(MavenProject project, MavenSession mavenSession,
BuildPluginManager buildPluginManager) throws MojoExecutionException {
Optional<Plugin> resourcesPlugin = hasPlugin(project, RESOURCES_PLUGIN_KEY);
Xpp3Dom pluginConfig = configuration(element("outputDirectory", "${project.build.outputDirectory}"));
if (resourcesPlugin.isPresent()) {
Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_RESOURCES_PLUGIN, GOAL_RESOURCES);
if (optConfiguration.isPresent()) {
pluginConfig = optConfiguration.get();
}
executeMojo(
resourcesPlugin.get(),
goal(GOAL_RESOURCES),
pluginConfig,
executionEnvironment(project, mavenSession, buildPluginManager)
);
} else {
executeMojo(
plugin(G_MAVEN_RESOURCES_PLUGIN, A_MAVEN_RESOURCES_PLUGIN,
properties.getProperty(V_MAVEN_RESOURCES_PLUGIN)),
goal(GOAL_RESOURCES),
pluginConfig,
executionEnvironment(project, mavenSession, buildPluginManager)
);
}
}
/**
* Execute the Maven Compiler Plugin to compile java sources.
*
* @param project the project
* @param mavenSession the session
* @param buildPluginManager the build plugin manager
* @throws Exception if the compilation fails for any reason
*/
public static void compile(MavenProject project, MavenSession mavenSession,
BuildPluginManager buildPluginManager) throws Exception {
Optional<Plugin> mvnCompilerPlugin = project.getBuildPlugins().stream()
.filter(plugin -> A_MAVEN_COMPILER_PLUGIN.equals(plugin.getArtifactId()))
.findFirst();
String pluginVersion = properties.getProperty(V_MAVEN_COMPILER_PLUGIN);
if (mvnCompilerPlugin.isPresent()) {
pluginVersion = mvnCompilerPlugin.get().getVersion();
}
Optional<Xpp3Dom> optConfiguration = buildConfiguration(project, A_MAVEN_COMPILER_PLUGIN, GOAL_COMPILE);
if (optConfiguration.isPresent()) {
Xpp3Dom configuration = optConfiguration.get();
executeMojo(
plugin(G_MAVEN_COMPILER_PLUGIN, A_MAVEN_COMPILER_PLUGIN, pluginVersion),
goal(GOAL_COMPILE),
configuration,
executionEnvironment(project, mavenSession, buildPluginManager)
);
}
}
ServiceHub(DockerAccess dockerAccess, ContainerTracker containerTracker, BuildPluginManager pluginManager,
DockerAssemblyManager dockerAssemblyManager, MavenProject project, MavenSession session,
Logger logger, LogOutputSpecFactory logSpecFactory) {
this.dockerAccess = dockerAccess;
mojoExecutionService = new MojoExecutionService(project, session, pluginManager);
archiveService = new ArchiveService(dockerAssemblyManager, logger);
if (dockerAccess != null) {
queryService = new QueryService(dockerAccess);
registryService = new RegistryService(dockerAccess, logger);
runService = new RunService(dockerAccess, queryService, containerTracker, logSpecFactory, logger);
buildService = new BuildService(dockerAccess, queryService, registryService, archiveService, logger);
volumeService = new VolumeService(dockerAccess);
watchService = new WatchService(archiveService, buildService, dockerAccess, mojoExecutionService, queryService, runService, logger);
waitService = new WaitService(dockerAccess, queryService, logger);
} else {
queryService = null;
registryService = null;
runService = null;
buildService = null;
volumeService = null;
watchService = null;
waitService = null;
}
}
public MojoExecutionService(MavenProject project, MavenSession session, BuildPluginManager pluginManager) {
this.project = project;
this.session = session;
this.pluginManager = pluginManager;
}
/**
* Init.
*
* @param session the session
* @param pluginManager the plugin manager
* @param inputProfile the input profile
* @param quiet the quiet
* @param inputDockerHost the input docker host
* @param inputDockerRegistryUrl the input docker registry url
* @param inputDockerRegistryUserName the input docker registry user name
* @param inputDockerRegistryPassword the input docker registry password
* @param inputKubeBase64Config the input kube base 64 config
* @param inputAssignationProjects the assignation projects
* @param rollbackVersion the rollback version
* @param dockerHostAppendOpt the docker host append opt
* @param dockerRegistryUrlAppendOpt the docker registry url append opt
* @param dockerRegistryUserNameAppendOpt the docker registry user name append opt
* @param dockerRegistryPasswordAppendOpt the docker registry password append opt
* @param mockClasspath the mock classpath
*/
public static synchronized void init(MavenSession session, BuildPluginManager pluginManager,
String inputProfile, boolean quiet,
String inputDockerHost, String inputDockerRegistryUrl,
String inputDockerRegistryUserName, String inputDockerRegistryPassword,
String inputKubeBase64Config, String inputAssignationProjects, String rollbackVersion,
Optional<String> dockerHostAppendOpt, Optional<String> dockerRegistryUrlAppendOpt,
Optional<String> dockerRegistryUserNameAppendOpt, Optional<String> dockerRegistryPasswordAppendOpt,
String mockClasspath) {
try {
Config.initMavenProject(session, pluginManager);
if (ExecuteOnceProcessor.executedCheck(MavenDevOps.class)) {
return;
}
logger.info("Start init ...");
logger.info("Dependencies resolver ...");
DependenciesResolver.init(session);
inputProfile = inputProfile.toLowerCase();
logger.info("Active profile : " + inputProfile);
// 全局只初始化一次
GitHelper.init(logger);
YamlHelper.init(logger);
initFinalConfig(session, inputProfile,
inputDockerHost, inputDockerRegistryUrl, inputDockerRegistryUserName, inputDockerRegistryPassword,
inputKubeBase64Config, inputAssignationProjects,
dockerHostAppendOpt, dockerRegistryUrlAppendOpt, dockerRegistryUserNameAppendOpt, dockerRegistryPasswordAppendOpt);
DevOps.Init.init(mockClasspath);
Config.initMavenProject(session, pluginManager);
initAssignDeploymentProjects(inputAssignationProjects);
// 特殊Mojo处理
if (session.getGoals().stream().map(String::toLowerCase)
.anyMatch(s ->
s.contains("group.idealworld.dew:dew-maven-plugin:release")
|| s.contains("dew:release")
|| s.contains("deploy"))) {
NeedProcessChecker.checkNeedProcessProjects(quiet);
MavenSkipProcessor.process(session);
}
if (session.getGoals().stream().map(String::toLowerCase)
.anyMatch(s -> s.contains("dew:rollback"))) {
NeedProcessChecker.checkNeedRollbackProcessProjects(rollbackVersion, quiet);
}
} catch (Exception e) {
throw new ConfigException(e.getMessage(), e);
}
}
/**
* Process.
*
* @param mojo the mojo
* @param mavenProject the maven project
* @param mavenSession the maven session
* @param pluginManager the plugin manager
* @param language the language
* @param inputSpec the input spec
* @return the file
*/
public static File process(SDKGenMojo mojo, MavenProject mavenProject, MavenSession mavenSession, BuildPluginManager pluginManager,
String language, String inputSpec) {
log.info("Generate SDK by {}", language);
/*MavenHelper.invoke("io.swagger.core.v3", "swagger-maven-plugin", "2.1.1",
"resolve", new HashMap<>() {
{
put("outputFileName", output.getParent());
put("goals", new HashMap<>() {
{
put("goal", "-P release");
}
});
put("mavenOpts", "");
}
}, mavenProject, mavenSession, pluginManager);*/
String groupId = mavenProject.getGroupId();
String artifactId = mavenProject.getArtifactId() + ".sdk";
String basePackage = NameHelper.formatPackage(groupId + "." + mavenProject.getArtifactId() + ".sdk");
setAndGetIfNotExist(mojo, "apiPackage", basePackage + ".api");
setAndGetIfNotExist(mojo, "modelPackage", basePackage + ".model");
setAndGetIfNotExist(mojo, "invokerPackage", basePackage + ".invoker");
setAndGetIfNotExist(mojo, "groupId", groupId);
setAndGetIfNotExist(mojo, "artifactId", artifactId);
setAndGetIfNotExist(mojo, "artifactVersion", mavenProject.getVersion());
setValueToParentField(mojo, "language", language);
setValueToParentField(mojo, "inputSpec", inputSpec);
String lang;
switch (language) {
case "group.idealworld.dew.sdkgen.lang.java.DewJavaClientCodegen":
lang = "java";
break;
default:
lang = language;
}
String finalLang = lang;
setAndGetIfNotExist(mojo, "configOptions", new HashMap<String, Object>() {
{
put("sourceFolder", "src/main/" + finalLang);
}
});
return (File) $.bean.getValue(mojo, "output");
}
/**
* Gets plugin manager.
*
* @return the plugin manager
*/
public BuildPluginManager getPluginManager() {
return pluginManager;
}
/**
* Sets plugin manager.
*
* @param pluginManager the plugin manager
*/
public void setPluginManager(BuildPluginManager pluginManager) {
this.pluginManager = pluginManager;
}
/** Replies the manager of the build plugins.
*
* @return the manager of the build plugins.
*/
public BuildPluginManager getBuildPluginManager() {
return this.buildPluginManager;
}