下面列出了怎么用org.apache.maven.plugin.Mojo的API类实例代码及写法,或者点击链接到github查看源代码。
@Test
public void testExecuteCommands() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-commands-pom.xml");
executeCommandsMojo.execute();
// Read the attribute
ModelNode address = ServerOperations.createAddress("system-property", "org.wildfly.maven.plugin-exec-cmd");
ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
ModelNode result = executeOperation(op);
assertEquals("true", ServerOperations.readResultAsString(result));
// Clean up the property
executeOperation(ServerOperations.createRemoveOperation(address));
// Read the attribute
address = ServerOperations.createAddress("system-property", "property2");
op = ServerOperations.createReadAttributeOperation(address, "value");
result = executeOperation(op);
assertEquals("property 2", ServerOperations.readResultAsString(result));
// Clean up the property
executeOperation(ServerOperations.createRemoveOperation(address));
}
@Test
public void testExecuteBatchCommands() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-batch-commands-pom.xml");
executeCommandsMojo.execute();
// Read the attribute
final ModelNode address = ServerOperations.createAddress("system-property", "org.wildfly.maven.plugin-batch");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
assertEquals("true", ServerOperations.readResultAsString(result));
// Clean up the property
executeOperation(ServerOperations.createRemoveOperation(address));
}
@Test
public void testExecuteCommandsFailOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-commands-failOnError-pom.xml");
try {
executeCommandsMojo.execute();
fail("MojoExecutionException expected.");
} catch (MojoExecutionException e) {
assertEquals(CommandLineException.class, e.getCause().getClass());
}
final ModelNode address = ServerOperations.createAddress("system-property", "propertyFailOnError");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
try {
assertEquals("initial value", ServerOperations.readResultAsString(result));
} finally {
// Remove the system property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
@Test
public void testExecuteCommandsForkOpFailOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-commands-fork-op-failOnError-pom.xml");
// Set the JBoss home field so commands will be executed in a new process
setValue(executeCommandsMojo, "jbossHome", TestEnvironment.WILDFLY_HOME.toString());
try {
executeCommandsMojo.execute();
fail("MojoExecutionException expected.");
} catch (MojoExecutionException ignore) {
}
final ModelNode address = ServerOperations.createAddress("system-property", "propertyFailOnError");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
try {
assertEquals("initial value", ServerOperations.readResultAsString(result));
} finally {
// Remove the system property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
@Test
public void testExecuteCommandsForkCmdFailOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-commands-fork-cmd-failOnError-pom.xml");
// Set the JBoss home field so commands will be executed in a new process
setValue(executeCommandsMojo, "jbossHome", TestEnvironment.WILDFLY_HOME.toString());
try {
executeCommandsMojo.execute();
fail("MojoExecutionException expected.");
} catch (MojoExecutionException ignore) {
}
// Read the attribute
final ModelNode address = ServerOperations.createAddress("system-property", "propertyFailOnError.in.try");
final ModelNode result = executeOperation(ServerOperations.createReadAttributeOperation(address, "value"));
try {
assertEquals("inside catch", ServerOperations.readResultAsString(result));
} finally {
// Remove the system property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
@Test
public void testExecuteCommandsContinueOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-commands-continueOnError-pom.xml");
executeCommandsMojo.execute();
// Read the attribute
final ModelNode address = ServerOperations.createAddress("system-property", "propertyContinueOnError");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
try {
assertEquals("continue on error", ServerOperations.readResultAsString(result));
} finally {
// Clean up the property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
@Test
public void testExecuteCommandScriptFailOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-script-failOnError-pom.xml");
try {
executeCommandsMojo.execute();
fail("MojoExecutionException expected.");
} catch (MojoExecutionException e) {
assertEquals(CommandLineException.class, e.getCause().getClass());
}
final ModelNode address = ServerOperations.createAddress("system-property", "scriptFailOnError");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
try {
assertEquals("initial value", ServerOperations.readResultAsString(result));
} finally {
// Remove the system property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
@Test
public void testExecuteCommandScriptContinueOnError() throws Exception {
final Mojo executeCommandsMojo = lookupMojoAndVerify("execute-commands", "execute-script-continueOnError-pom.xml");
executeCommandsMojo.execute();
// Read the attribute
final ModelNode address = ServerOperations.createAddress("system-property", "scriptContinueOnError");
final ModelNode op = ServerOperations.createReadAttributeOperation(address, "value");
final ModelNode result = executeOperation(op);
try {
assertEquals("continue on error", ServerOperations.readResultAsString(result));
} finally {
// Clean up the property
executeOperation(ServerOperations.createRemoveOperation(address));
}
}
public <T> T getMojo (String pom, File dir, String execName, Class<T> clazz) throws Exception {
MavenProject project = newMavenProject(pom, dir);
MavenSession session = newMavenSession(project);
MojoExecution execution = newMojoExecution(execName);
Mojo mojo = lookupConfiguredMojo(session, execution);
assertNotNull(mojo);
return clazz.cast(mojo);
}
public <T> T getMojo (String pom, File dir, String execName, Class<T> clazz) throws Exception {
MavenProject project = newMavenProject(pom, dir);
MavenSession session = newMavenSession(project);
MojoExecution execution = newMojoExecution(execName);
Mojo mojo = lookupConfiguredMojo(session, execution);
assertNotNull(mojo);
return clazz.cast(mojo);
}
/**
* As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom file
* and creating the {@link MavenProject}.
*/
public Mojo lookupConfiguredMojo(File pom, String goal) throws Exception {
assertNotNull(pom);
assertTrue(pom.exists());
ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest();
ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();
return lookupConfiguredMojo(project, goal);
}
/**
* Tests the generated Swagger specifications based on the given method parameters.
*
* @param folder The base folder of the expected output.
* @param basename The basename for the generated Swagger specifications.
* @param pom The name of the POM file to be used for the test.
* @param prettyPrinted If true, the generated JSON Swagger specification should be pretty-printed.
* @param outputFormats The output formats that should be generated and checked.
*
* @throws Exception If a JSON parsing or file-read exception happens.
*/
private void testGenerate(String folder, String basename, String pom, boolean prettyPrinted, OutputFormat... outputFormats)
throws Exception {
Path output = Paths.get(folder);
if (Files.exists(output)) {
Files.walkFileTree(output, new DeleteVisitor());
}
Mojo mojo = rule.lookupMojo("generate", new File("src/test/resources/" + pom));
mojo.execute();
List<OutputFormat> formats = Arrays.asList(outputFormats);
if (formats.contains(OutputFormat.JSON)) {
Path expectedJson = Paths.get("src/test/resources/expectedOutput", folder, basename + ".json");
Path generatedJson = Paths.get("target", folder, basename + ".json");
assertJsonEquals(expectedJson, generatedJson);
// We test the indentation by simply checking that the generated JSON contains 2 spaces
String json = new String(Files.readAllBytes(generatedJson), StandardCharsets.UTF_8);
Assert.assertEquals(prettyPrinted, json.contains(" "));
}
if (formats.contains(OutputFormat.YAML)) {
Path expectedYaml = Paths.get("src/test/resources/expectedOutput", folder, basename + ".yaml");
Path generatedYaml = Paths.get("target", folder, basename + ".yaml");
assertYamlEquals(expectedYaml, generatedYaml);
}
}
public void testNPEFixRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "npefix-safe");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof NPEFixSafeMojo);
NPEFixSafeMojo repair = (NPEFixSafeMojo) mojo;
repair.execute();
assertTrue(repair.getResult().size() > 0);
}
public void testNopolRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "nopol");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof NopolMojo);
NopolMojo repair = (NopolMojo) mojo;
repair.execute();
assertEquals(NopolStatus.PATCH, repair.getResult().getNopolStatus());
}
public void testNPEFixRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "npefix");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof NPEFixMojo);
NPEFixMojo repair = (NPEFixMojo) mojo;
repair.execute();
assertTrue(repair.getResult().size() > 0);
}
public void testGenProgRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "jGenProg");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof GenProgMojo);
GenProgMojo repair = (GenProgMojo) mojo;
repair.execute();
}
public void testKaliRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "jKali");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof KaliMojo);
KaliMojo repair = (KaliMojo) mojo;
repair.execute();
}
public void testCardumenRepair() throws Exception {
File f = getTestFile(projectPath + "pom.xml");
Mojo mojo = lookupConfiguredMojo(f, "cardumen");
assertNotNull( mojo );
assertTrue("Wrong class: "+mojo, mojo instanceof CardumenMojo);
CardumenMojo repair = (CardumenMojo) mojo;
repair.execute();
}
/** As {@link #lookupConfiguredMojo(MavenProject, String)} but taking the pom file
* and creating the {@link MavenProject}. */
protected Mojo lookupConfiguredMojo(File pom, String goal) throws Exception {
assertNotNull( pom );
assertTrue( pom.exists() );
ProjectBuildingRequest buildingRequest = newMavenSession().getProjectBuildingRequest();
ProjectBuilder projectBuilder = lookup(ProjectBuilder.class);
MavenProject project = projectBuilder.build(pom, buildingRequest).getProject();
return lookupConfiguredMojo(project, goal);
}
private Mojo lookupConfiguredMojo(String goal, File pom) throws Exception
{
MavenExecutionRequest request = new DefaultMavenExecutionRequest();
request.setBaseDirectory(pom.getParentFile());
ProjectBuildingRequest configuration = request.getProjectBuildingRequest();
// Fix for bug: https://git-wip-us.apache.org/repos/asf?p=maven-plugin-testing.git;a=commit;h=3cd5f47c586499e438a3f9393304ac9d1f9a7f53
configuration.setRepositorySession(new DefaultRepositorySystemSession());
MavenProject project = lookup(ProjectBuilder.class).build(pom, configuration).getProject();
return super.lookupConfiguredMojo(project, goal);
}
private Mojo configureMojo(final String parameter, final String value) throws Exception {
final MavenSession mavenSession = mojoRule.newMavenSession(getMavenProject(DEFAULT_CONFIG));
final MojoExecution mojoExecution = mojoRule.newMojoExecution(GOAL_NAME);
final Xpp3Dom configuration = new Xpp3Dom("configuration");
final Xpp3Dom generationConfig = new Xpp3Dom("generationConfig");
final Xpp3Dom useBigDecimal = new Xpp3Dom(parameter);
useBigDecimal.setValue(value);
generationConfig.addChild(useBigDecimal);
configuration.addChild(generationConfig);
mojoExecution.setConfiguration(configuration);
return mojoRule.lookupConfiguredMojo(mavenSession, mojoExecution);
}
protected void setUp() throws Exception {
super.setUp();
mavenProjectBuilder = (MavenProjectBuilder) getContainer().lookup(
MavenProjectBuilder.ROLE);
ArtifactFactory artifactFactory = (ArtifactFactory) getContainer()
.lookup(ArtifactFactory.ROLE);
final Map<String, Mojo> mojos = (Map<String, Mojo>) getContainer()
.lookupMap(Mojo.ROLE);
for (Mojo mojo : mojos.values()) {
if (mojo instanceof Hyperjaxb3Mojo) {
this.mojo = (Hyperjaxb3Mojo) mojo;
}
}
MavenSettingsBuilder settingsBuilder = (MavenSettingsBuilder) getContainer()
.lookup(MavenSettingsBuilder.ROLE);
ArtifactRepositoryLayout repositoryLayout = (ArtifactRepositoryLayout) getContainer()
.lookup(ArtifactRepositoryLayout.ROLE, "default");
Settings settings = settingsBuilder.buildSettings();
String url = settings.getLocalRepository();
if (!url.startsWith("file:")) {
url = "file://" + url;
}
localRepository = new DefaultArtifactRepository("local", url,
new DefaultRepositoryLayout());
}
protected Mojo lookupAndPrepareMojo( String artifactId, File testPom )
throws Exception
{
Mojo mojo = lookupMojo( artifactId, testPom );
MavenProject mavenProject = new MavenProjectStub();
setVariableValueToObject( mojo, "project", mavenProject );
return mojo;
}
@SuppressWarnings("unchecked")
public <T extends Mojo> T loadPlugin(final String goal, final URL config) throws Exception {
final File pomFile = temporaryFolder.newFile();
try (final InputStream in = config.openStream()) {
FileUtils.copyInputStreamToFile(in, pomFile);
}
return (T) mojo.lookupMojo(goal, pomFile);
}
@Override
public void testExecute() throws Exception {
final Mojo mojo = initMojo();
mojo.execute();
generatedCodeFixture.assertInterfaces();
}
private void execute(String goal, String target) throws Exception {
InputStream in = ByteBuddyMojoTest.class.getResourceAsStream("/net/bytebuddy/test/" + target + ".pom.xml");
if (in == null) {
throw new AssertionError("Cannot find resource for: " + target);
}
try {
File pom = File.createTempFile("maven", ".pom");
OutputStream out = new FileOutputStream(pom);
try {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
} finally {
out.close();
}
Mojo mojo = mojoRule.lookupMojo(goal, pom);
if (goal.equals("transform")) {
mojoRule.setVariableValueToObject(mojo, "outputDirectory", project.getAbsolutePath());
mojoRule.setVariableValueToObject(mojo, "compileClasspathElements", Collections.emptyList());
} else if (goal.equals("transform-test")) {
mojoRule.setVariableValueToObject(mojo, "testOutputDirectory", project.getAbsolutePath());
mojoRule.setVariableValueToObject(mojo, "testClasspathElements", Collections.emptyList());
} else {
throw new AssertionError("Unknown goal: " + goal);
}
mojoRule.setVariableValueToObject(mojo, "repositorySystem", repositorySystem);
mojoRule.setVariableValueToObject(mojo, "groupId", FOO);
mojoRule.setVariableValueToObject(mojo, "artifactId", BAR);
mojoRule.setVariableValueToObject(mojo, "version", QUX);
mojoRule.setVariableValueToObject(mojo, "packaging", JAR);
mojo.setLog(new SilentLog());
mojo.execute();
} finally {
in.close();
}
}
/**
* Creates a new pipeline. Notice that the set of watchers cannot change.
* @param mojo the 'run' mojo
* @param baseDir the base directory of the watched project
* @param list the set of watchers plugged on the pipeline, the order of the list will be the notification order.
* @param pomFileMonitoring flag enabling or disabling the pom file monitoring
*/
public Pipeline(Mojo mojo, File baseDir, List<? extends Watcher> list, boolean pomFileMonitoring) {
this.mojo = mojo;
this.baseDir = baseDir;
this.pomFileMonitoring = pomFileMonitoring;
mojo.getLog().debug("Initializing watch mode with " + list);
watchers = new ArrayList<>();
for (Object o : list) {
watchers.add(new WatcherDelegate(o));
}
}
@Test
public void testNoWatchers() throws Exception {
MavenSession session = mock(MavenSession.class);
when(session.getExecutionProperties()).thenReturn(new Properties());
File baseDir = new File("target/junk");
Mojo mojo = mock(Mojo.class);
Log log = mock(Log.class);
when(mojo.getLog()).thenReturn(log);
Pipelines.watchers(session, baseDir, mojo, true);
}
@Before
public void setUp() throws IOException {
FileUtils.forceMkdir(SOURCES);
textWatcher = new SpyWatcher(SOURCES, "txt");
mdWatcher = new SpyWatcher(SOURCES, "md");
mojo = mock(Mojo.class);
Log log = mock(Log.class);
when(mojo.getLog()).thenReturn(log);
pipeline = new Pipeline(mojo, FAKE, Arrays.asList(textWatcher, mdWatcher), false);
pipeline.watch();
}
@Before
public void setUp() {
log = new CollectorLog();
Mojo mojo = mock(Mojo.class);
when(mojo.getLog()).thenReturn(log);
factory = new DefensiveThreadFactory("test", mojo);
}