下面列出了org.apache.maven.plugin.BuildPluginManager#org.codehaus.plexus.util.xml.Xpp3Dom 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private ReportOptions updateFromSurefire(ReportOptions option) {
Collection<Plugin> plugins = lookupPlugin("org.apache.maven.plugins:maven-surefire-plugin");
if (!this.mojo.isParseSurefireConfig()) {
return option;
} else if (plugins.isEmpty()) {
this.log.warn("Could not find surefire configuration in pom");
return option;
}
Plugin surefire = plugins.iterator().next();
if (surefire != null) {
return this.surefireConverter.update(option,
(Xpp3Dom) surefire.getConfiguration());
} else {
return option;
}
}
private static Map<String, Object> getElement(Xpp3Dom element) {
final Map<String, Object> conf = new HashMap<>();
final Xpp3Dom[] currentElements = element.getChildren();
for (Xpp3Dom currentElement: currentElements) {
if (isSimpleType(currentElement)) {
if (isAListOfElements(conf, currentElement)) {
addAsList(conf, currentElement);
} else {
conf.put(currentElement.getName(), currentElement.getValue());
}
} else {
conf.put(currentElement.getName(), getElement(currentElement));
}
}
return conf;
}
/**
* Returns a list of {@link Plugin}
*
* @param project Maven project
* @return list of plugins
*/
public static List<Plugin> getPlugins(MavenProject project) {
List<Plugin> projectPlugins = new ArrayList<>();
for (org.apache.maven.model.Plugin plugin : project.getBuildPlugins()) {
Plugin.PluginBuilder jkubeProjectPluginBuilder = Plugin.builder();
jkubeProjectPluginBuilder.groupId(plugin.getGroupId())
.artifactId(plugin.getArtifactId())
.version(plugin.getVersion());
if (plugin.getExecutions() != null && !plugin.getExecutions().isEmpty()) {
jkubeProjectPluginBuilder.executions(getPluginExecutionsAsList(plugin));
}
jkubeProjectPluginBuilder.configuration(MavenConfigurationExtractor.extract((Xpp3Dom)plugin.getConfiguration()));
projectPlugins.add(jkubeProjectPluginBuilder.build());
}
return projectPlugins;
}
/**
* Avoid clean control-bundle file in target folde, in case of using mvn clean package, TESB-22296
*
* @return plugin
*/
private Plugin addSkipMavenCleanPlugin() {
Plugin plugin = new Plugin();
plugin.setGroupId("org.apache.maven.plugins");
plugin.setArtifactId("maven-clean-plugin");
plugin.setVersion("3.0.0");
Xpp3Dom configuration = new Xpp3Dom("configuration");
Xpp3Dom skipClean = new Xpp3Dom("skip");
skipClean.setValue("true");
configuration.addChild(skipClean);
plugin.setConfiguration(configuration);
return plugin;
}
/**
* Test of execute method, of class RequirePropertyDiverges.
*/
@Test
public void testExecuteInParentWithConfigurationInPluginManagement() throws EnforcerRuleException
{
RequirePropertyDiverges mockInstance = createMockRule();
final MavenProject project = createMavenProject( "company", "company-parent-pom" );
final Build build = new Build();
// create pluginManagement
final Plugin pluginInManagement = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0");
final Xpp3Dom configuration = createPluginConfiguration();
pluginInManagement.setConfiguration( configuration );
final PluginManagement pluginManagement = new PluginManagement();
pluginManagement.addPlugin( pluginInManagement );
build.setPluginManagement( pluginManagement );
// create plugins
final Plugin pluginInPlugins = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0");
build.addPlugin( pluginInPlugins );
// add build
project.getOriginalModel().setBuild( build );
//project.getOriginalModel().setBuild( build );
setUpHelper( project, "parentValue" );
mockInstance.execute( helper );
}
@Test
public void should_parse_list_of_elements() {
// Given
final Plugin fakePlugin = createFakePlugin("<a>"
+ "<b>"
+ "<c>c1</c><c>c2</c>"
+ "</b>"
+ "</a>");
// When
final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration());
// Then
final Map<String, Object> expectedC = new HashMap<>();
expectedC.put("c", Arrays.asList("c1", "c2"));
final Map<String, Object> expected = new HashMap<>();
expected.put("b", expectedC);
assertEquals(expected, config.get("a"));
}
@Test
public void should_parse_list_of_mixed_elements() {
// Given
final Plugin fakePlugin = createFakePlugin("<a>"
+ "<b>"
+ "<c>c1</c><d>d1</d><c>c2</c>"
+ "</b>"
+ "</a>");
// When
final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration());
// Then
final Map<String, Object> expectedC = new HashMap<>();
expectedC.put("c", Arrays.asList("c1", "c2"));
expectedC.put("d", "d1");
final Map<String, Object> expected = new HashMap<>();
expected.put("b", expectedC);
assertTrue(config.containsKey("a"));
assertEquals(expected, config.get("a"));
}
private Plugin createFakePlugin(String config) {
Plugin plugin = new Plugin();
plugin.setArtifactId("jkube-maven-plugin");
plugin.setGroupId("org.eclipse.jkube");
String content = "<configuration>"
+ config
+ "</configuration>";
Xpp3Dom dom;
try {
dom = Xpp3DomBuilder.build(new StringReader(content));
} catch (Exception e) {
throw new RuntimeException(e);
}
plugin.setConfiguration(dom);
return plugin;
}
/**
* Test of execute method, of class RequirePropertyDiverges.
*/
@Test
public void testExecuteInParentWithConfigurationInExecution() throws EnforcerRuleException
{
RequirePropertyDiverges mockInstance = createMockRule();
final MavenProject project = createMavenProject( "company", "company-parent-pom" );
final Build build = new Build();
build.setPluginManagement( new PluginManagement() );
final Plugin plugin = newPlugin( "org.apache.maven.plugins", "maven-enforcer-plugin", "1.0" );
final Xpp3Dom configuration = createPluginConfiguration();
PluginExecution pluginExecution = new PluginExecution();
pluginExecution.setConfiguration( configuration );
plugin.addExecution( pluginExecution );
build.addPlugin( plugin );
project.getOriginalModel().setBuild( build );
setUpHelper(project, "parentValue");
mockInstance.execute( helper );
}
protected void processAnnotations(MavenSession session, MavenProject project, String goal, File processor, Proc proc, Xpp3Dom... parameters) throws Exception {
MojoExecution execution = mojos.newMojoExecution(goal);
addDependency(project, "processor", new File(processor, "target/classes"));
Xpp3Dom configuration = execution.getConfiguration();
if (proc != null) {
configuration.addChild(newParameter("proc", proc.name()));
}
if (parameters != null) {
for (Xpp3Dom parameter : parameters) {
configuration.addChild(parameter);
}
}
mojos.executeMojo(session, project, execution);
}
/**
* Save the settings for the GWT nature in the application GWT preferences.
*
* @param project
* @param mavenProject
* @param mavenConfig
* @throws BackingStoreException
*/
private void persistGwtNatureSettings(IProject project, MavenProject mavenProject, Xpp3Dom mavenConfig)
throws BackingStoreException {
IPath warOutDir = getWarOutDir(project, mavenProject);
WebAppProjectProperties.setWarSrcDir(project, getWarSrcDir(mavenProject, mavenConfig)); // src/main/webapp
WebAppProjectProperties.setWarSrcDirIsOutput(project, getLaunchFromHere(mavenConfig)); // false
// TODO the extension should be used, from WarArgProcessor
WebAppProjectProperties.setLastUsedWarOutLocation(project, warOutDir);
WebAppProjectProperties.setGwtMavenModuleName(project, getGwtModuleName(mavenProject));
WebAppProjectProperties.setGwtMavenModuleShortName(project, getGwtModuleShortName(mavenProject));
String message = "MavenProjectConfiguratior Maven: Success with setting up GWT Nature\n";
message += "\tartifactId=" + mavenProject.getArtifactId() + "\n";
message += "\tversion=" + mavenProject.getVersion() + "\n";
message += "\twarOutDir=" + warOutDir;
Activator.log(message);
}
@Test
public void testLastRound_typeIndex() throws Exception {
// apparently javac can't resolve "forward" references to types generated during apt last round
Assume.assumeTrue(CompilerJdt.ID.equals(compilerId));
Xpp3Dom processors = newProcessors("processor.ProcessorLastRound_typeIndex");
File basedir = procCompile("compile-proc/multiround-type-index", Proc.proc, processors);
File target = new File(basedir, "target");
mojos.assertBuildOutputs(target, //
"generated-sources/annotations/generated/TypeIndex.java", //
"generated-sources/annotations/generated/TypeIndex2.java", //
"classes/generated/TypeIndex.class", //
"classes/generated/TypeIndex2.class", //
"classes/typeindex/Annotated.class", //
"classes/typeindex/Consumer.class" //
);
}
@Test
public void should_return_simple_single_requires() {
// given
final MavenProject project = fakeProject();
OptionsBuilder emptyOptions = OptionsBuilder.options();
AttributesBuilder emptyAttributes = AttributesBuilder.attributes();
Xpp3Dom siteConfig = Xpp3DoomBuilder.asciidocNode()
.addChild("requires")
.addChild("require", "gem")
.build();
// when
SiteConversionConfiguration configuration = new SiteConversionConfigurationParser(project)
.processAsciiDocConfig(siteConfig, emptyOptions, emptyAttributes);
// then
final Map<String, Object> optionsMap = configuration.getOptions().map();
assertThat(optionsMap).containsOnlyKeys(ATTRIBUTES);
assertThat((Map) optionsMap.get(ATTRIBUTES)).isEmpty();
assertThat(configuration.getRequires())
.containsExactly("gem");
}
/**
* @return the java version used the pom (target) and 1.7 if not present.
*/
protected String getJavaVersion() {
String javaVersion = "1.7";
Plugin p = maven_project.getPlugin("org.apache.maven.plugins:maven-compiler-plugin");
if (p != null) {
Xpp3Dom config = (Xpp3Dom) p.getConfiguration();
if (config == null) {
return javaVersion;
}
Xpp3Dom domVersion = config.getChild("target");
if (domVersion != null) {
javaVersion = domVersion.getValue();
}
}
return javaVersion;
}
/**
* Finds the ancestor project which defines the rule.
*
* @param project to inspect
* @return the defining ancestor project.
*/
final MavenProject findDefiningParent( final MavenProject project )
{
final Xpp3Dom invokingRule = createInvokingRuleDom();
MavenProject parent = project;
while ( parent != null )
{
final Model model = parent.getOriginalModel();
final Build build = model.getBuild();
if ( build != null )
{
final List<Xpp3Dom> rules = getRuleConfigurations( build );
if ( isDefiningProject( rules, invokingRule ) )
{
break;
}
}
parent = parent.getParent();
}
return parent;
}
@Test
public void testReference_testCompile_internal() throws Exception {
File basedir = resources.getBasedir("compile-jdt-classpath-visibility/reference");
MavenProject project = mojos.readMavenProject(basedir);
addDependency(project, "dependency", DEPENDENCY);
MavenSession session = mojos.newMavenSession(project);
Xpp3Dom[] params = new Xpp3Dom[] {param("compilerId", "jdt"), //
param("transitiveDependencyReference", "error"), //
param("privatePackageReference", "error")};
mojos.executeMojo(session, project, "compile", params);
// make all main classes internal
File exportsFile = new File(basedir, "target/classes/" + ExportPackageMojo.PATH_EXPORT_PACKAGE);
exportsFile.getParentFile().mkdirs();
new FileOutputStream(exportsFile).close();
mojos.executeMojo(session, project, "testCompile", params);
}
/**
* Get the GWT Maven plugin 2 <moduleName/>.
*
* @param mavenProject
* @return the moduleName from configuration
*/
private String getGwtModuleName(MavenProject mavenProject) {
if (!isGwtMavenPlugin2(mavenProject)) {
return null;
}
Plugin gwtPlugin2 = getGwtMavenPlugin2(mavenProject);
if (gwtPlugin2 == null) {
return null;
}
Xpp3Dom gwtPluginConfig = (Xpp3Dom) gwtPlugin2.getConfiguration();
if (gwtPluginConfig == null) {
return null;
}
String moduleName = null;
for (Xpp3Dom child : gwtPluginConfig.getChildren()) {
if (child != null && GWT_MAVEN_MODULENAME.equals(child.getName())) {
moduleName = child.getValue().trim();
}
}
return moduleName;
}
@Test
public void should_return_multiple_requires() {
// given
final MavenProject project = fakeProject();
OptionsBuilder emptyOptions = OptionsBuilder.options();
AttributesBuilder emptyAttributes = AttributesBuilder.attributes();
Xpp3Dom siteConfig = Xpp3DoomBuilder.asciidocNode()
.addChild("requires")
.addChild("require", "gem_1", "gem_2", "gem_3")
.build();
// when
SiteConversionConfiguration configuration = new SiteConversionConfigurationParser(project)
.processAsciiDocConfig(siteConfig, emptyOptions, emptyAttributes);
// then
final Map<String, Object> optionsMap = configuration.getOptions().map();
assertThat(optionsMap).containsOnlyKeys(ATTRIBUTES);
assertThat((Map) optionsMap.get(ATTRIBUTES)).isEmpty();
assertThat(configuration.getRequires())
.containsExactlyInAnyOrder("gem_1", "gem_2", "gem_3");
}
@Test
public void should_not_return_empty_template_dirs() {
// given
final MavenProject project = fakeProject();
OptionsBuilder emptyOptions = OptionsBuilder.options();
AttributesBuilder emptyAttributes = AttributesBuilder.attributes();
Xpp3Dom siteConfig = Xpp3DoomBuilder.asciidocNode()
.addChild("template_dirs")
.addChild("dir", "")
.parent()
.addChild("dir", null)
.build();
// when
SiteConversionConfiguration configuration = new SiteConversionConfigurationParser(project)
.processAsciiDocConfig(siteConfig, emptyOptions, emptyAttributes);
// then
final Map<String, Object> optionsMap = configuration.getOptions().map();
assertThat(optionsMap).containsOnlyKeys(ATTRIBUTES);
assertThat((Map) optionsMap.get(ATTRIBUTES)).isEmpty();
}
private boolean restartForLibertyMojoConfigChanged(Xpp3Dom config, Xpp3Dom oldConfig) {
if (!Objects.equals(config.getChild("bootstrapProperties"),
oldConfig.getChild("bootstrapProperties"))) {
return true;
} else if (!Objects.equals(config.getChild("bootstrapPropertiesFile"),
oldConfig.getChild("bootstrapPropertiesFile"))) {
return true;
} else if (!Objects.equals(config.getChild("jvmOptions"),
oldConfig.getChild("jvmOptions"))) {
return true;
} else if (!Objects.equals(config.getChild("jvmOptionsFile"),
oldConfig.getChild("jvmOptionsFile"))) {
return true;
} else if (!Objects.equals(config.getChild("serverEnv"),
oldConfig.getChild("serverEnv"))) {
return true;
} else if (!Objects.equals(config.getChild("serverEnvFile"),
oldConfig.getChild("serverEnvFile"))) {
return true;
} else if (!Objects.equals(config.getChild("configDirectory"),
oldConfig.getChild("configDirectory"))) {
return true;
}
return false;
}
@Test
@Ignore("Neither javac nor jdt support secondary types on sourcepath")
public void testSourcepathSecondatytype() throws Exception {
File processor = compileAnnotationProcessor();
File basedir = resources.getBasedir("compile-proc/proc-sourcepath-secondarytype");
File dependencyBasedir = new File(basedir, "dependency");
File projectBasedir = new File(basedir, "project");
Xpp3Dom processors = newProcessors("processor.Processor");
Xpp3Dom sourcepath = newParameter("sourcepath", "reactorDependencies");
MavenProject dependency = mojos.readMavenProject(dependencyBasedir);
MavenProject project = mojos.readMavenProject(projectBasedir);
mojos.newDependency(new File(dependencyBasedir, "target/classes")) //
.setGroupId(dependency.getGroupId()) //
.setArtifactId(dependency.getArtifactId()) //
.setVersion(dependency.getVersion()) //
.addTo(project);
MavenSession session = mojos.newMavenSession(project);
session.setProjects(Arrays.asList(project, dependency));
processAnnotations(session, project, "compile", processor, Proc.only, processors, sourcepath);
}
@Test
public void should_return_default_configuration_when_asciidoc_xml_is_null() {
// given
final MavenProject project = fakeProject();
OptionsBuilder emptyOptions = OptionsBuilder.options();
AttributesBuilder emptyAttributes = AttributesBuilder.attributes();
Xpp3Dom siteConfig = Xpp3DoomBuilder.siteNode()
.build();
// when
SiteConversionConfiguration configuration = new SiteConversionConfigurationParser(project)
.processAsciiDocConfig(siteConfig, emptyOptions, emptyAttributes);
// then
final Map<String, Object> optionsMap = configuration.getOptions().map();
assertThat(optionsMap).containsOnlyKeys(ATTRIBUTES);
assertThat((Map) optionsMap.get(ATTRIBUTES)).isEmpty();
assertThat(configuration.getRequires()).isEmpty();
}
/**
* Makes a best effort of locating the configured Java target version.
*
* @param project The relevant Maven project.
* @return The Java version string of the configured build target version or {@code null} if no explicit configuration was detected.
*/
private static String findJavaVersionString(MavenProject project) {
while (project != null) {
String target = project.getProperties().getProperty("maven.compiler.target");
if (target != null) {
return target;
}
for (org.apache.maven.model.Plugin plugin : CompoundList.of(project.getBuildPlugins(), project.getPluginManagement().getPlugins())) {
if ("maven-compiler-plugin".equals(plugin.getArtifactId())) {
if (plugin.getConfiguration() instanceof Xpp3Dom) {
Xpp3Dom node = ((Xpp3Dom) plugin.getConfiguration()).getChild("target");
if (node != null) {
return node.getValue();
}
}
}
}
project = project.getParent();
}
return null;
}
private static void addAsList(Map<String, Object> conf, Xpp3Dom currentElement) {
final Object insertedValue = conf.get(currentElement.getName());
if (insertedValue instanceof List) {
((List) insertedValue).add(currentElement.getValue());
} else {
final List<String> list = new ArrayList<>();
list.add((String) insertedValue);
list.add(currentElement.getValue());
conf.put(currentElement.getName(), list);
}
}
protected static Properties toProperties( final Xpp3Dom dom )
{
final Properties props = new Properties();
final Xpp3Dom[] children = dom.getChildren();
for ( final Xpp3Dom child : children )
props.put( child.getName(), child.getValue() );
return props;
}
public static List<RegistryServerConfiguration> getRegistryServerFromMavenSettings(Settings settings) {
List<RegistryServerConfiguration> registryServerConfigurations = new ArrayList<>();
for (Server server : settings.getServers()) {
if (server.getUsername() != null) {
registryServerConfigurations.add(RegistryServerConfiguration.builder()
.id(server.getId())
.username(server.getUsername())
.password(server.getPassword())
.configuration(MavenConfigurationExtractor.extract((Xpp3Dom) server.getConfiguration()))
.build());
}
}
return registryServerConfigurations;
}
@Test
public void should_parse_simple_types() {
// Given
final Plugin fakePlugin = createFakePlugin("<a>a</a><b>b</b>");
// When
final Map<String, Object> config = MavenConfigurationExtractor.extract((Xpp3Dom) fakePlugin.getConfiguration());
// Then
assertEquals("a", config.get("a"));
assertEquals("b", config.get("b"));
}
/** Convert a Plexus configuration to its XML equivalent.
*
* @param config the Plexus configuration.
* @return the XML configuration.
* @throws PlexusConfigurationException in case of problem.
* @since 0.8
*/
public Xpp3Dom toXpp3Dom(PlexusConfiguration config) throws PlexusConfigurationException {
final Xpp3Dom result = new Xpp3Dom(config.getName());
result.setValue(config.getValue(null));
for (final String name : config.getAttributeNames()) {
result.setAttribute(name, config.getAttribute(name));
}
for (final PlexusConfiguration child : config.getChildren()) {
result.addChild(toXpp3Dom(child));
}
return result;
}
@Test
public void when_disabled_maven_event_spy_must_not_call_reporter() throws Exception {
MavenEventReporter reporterMustNeverBeInvoked = new MavenEventReporter() {
@Override
public void print(Object message) {
throw new IllegalStateException();
}
@Override
public void print(Xpp3Dom element) {
throw new IllegalStateException();
}
@Override
public void close() {
throw new IllegalStateException();
}
};
JenkinsMavenEventSpy spy = new JenkinsMavenEventSpy(reporterMustNeverBeInvoked) {
@Override
protected boolean isEventSpyDisabled() {
return true;
}
};
spy.init(new EventSpy.Context() {
@Override
public Map<String, Object> getData() {
return new HashMap<String, Object>();
}
});
DefaultMavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setPom(new File("path/to/pom.xml"));
request.setGoals(Arrays.asList("clean", "source:jar", "deploy"));
spy.onEvent(request);
spy.close();
}
@SuppressWarnings("unchecked")
protected void startProject(MavenProject project, String executionId, XmlPlexusConfiguration process) throws InvalidPluginDescriptorException, PluginResolutionException, PluginDescriptorParsingException, PluginNotFoundException, PluginConfigurationException, MojoFailureException, MojoExecutionException, PluginManagerException {
Plugin plugin = this.project.getPlugin("org.wildfly.swarm:wildfly-swarm-plugin");
Xpp3Dom config = getConfiguration(project, executionId);
Xpp3Dom processConfig = getProcessConfiguration(process);
Xpp3Dom globalConfig = getGlobalConfig();
Xpp3Dom mergedConfig = Xpp3DomUtils.mergeXpp3Dom(processConfig, config);
mergedConfig = Xpp3DomUtils.mergeXpp3Dom(mergedConfig, globalConfig);
PluginDescriptor pluginDescriptor = this.pluginManager.loadPlugin(plugin, project.getRemotePluginRepositories(), this.repositorySystemSession);
MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo("start");
MojoExecution mojoExecution = new MojoExecution(mojoDescriptor, mergedConfig);
mavenSession.setCurrentProject(project);
this.pluginManager.executeMojo(mavenSession, mojoExecution);
List<SwarmProcess> launched = (List<SwarmProcess>) mavenSession.getPluginContext(pluginDescriptor, project).get("swarm-process");
List<SwarmProcess> procs = (List<SwarmProcess>) getPluginContext().get("swarm-process");
if (procs == null) {
procs = new ArrayList<>();
getPluginContext().put("swarm-process", procs);
}
procs.addAll(launched);
mavenSession.setCurrentProject(this.project);
}