下面列出了怎么用org.apache.maven.plugin.MojoExecution的API类实例代码及写法,或者点击链接到github查看源代码。
private Callable<Void> toTask(MojoExecution execution) {
MojoExecutor executor = new MojoExecutor(execution, project, mavenSession, buildPluginManager);
return () -> {
try {
//--- vertx-maven-plugin:1.0-SNAPSHOT:run (default-cli) @ vertx-demo
getLog().info(">>> "
+ execution.getArtifactId() + ":" + execution.getVersion() + ":" + execution.getGoal()
+ " (" + execution.getExecutionId() + ") @" + project.getArtifactId());
executor.execute();
} catch (Exception e) {
getLog().error("Error while doing incremental build", e);
}
return null;
};
}
/**
* Taken from MojoExecutor of Don Brown. Make it working with Maven 3.1.
*
* @param plugin
* @param goal
* @param configuration
* @param env
* @throws MojoExecutionException
* @throws PluginResolutionException
* @throws PluginDescriptorParsingException
* @throws InvalidPluginDescriptorException
* @throws PluginManagerException
* @throws PluginConfigurationException
* @throws MojoFailureException
*/
private void executeMojo( Plugin plugin, String goal, Xpp3Dom configuration )
throws MojoExecutionException, PluginResolutionException, PluginDescriptorParsingException,
InvalidPluginDescriptorException, MojoFailureException, PluginConfigurationException, PluginManagerException
{
if ( configuration == null )
{
throw new NullPointerException( "configuration may not be null" );
}
PluginDescriptor pluginDescriptor = getPluginDescriptor( plugin );
MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo( goal );
if ( mojoDescriptor == null )
{
throw new MojoExecutionException( "Could not find goal '" + goal + "' in plugin " + plugin.getGroupId()
+ ":" + plugin.getArtifactId() + ":" + plugin.getVersion() );
}
MojoExecution exec = mojoExecution( mojoDescriptor, configuration );
pluginManager.executeMojo( getMavenSession(), exec );
}
static void resolveDependencies(final MavenSession session, final MojoExecution execution, final MojoExecutor executor, final ProjectDependenciesResolver projectDependenciesResolver) throws DependencyResolutionException, LifecycleExecutionException {
// flushProjectArtifactsCache(executor);
final MavenProject project = session.getCurrentProject();
final Set<Artifact> dependencyArtifacts = project.getDependencyArtifacts();
final Map<String,List<MojoExecution>> executions = new LinkedHashMap<>(execution.getForkedExecutions());
final ExecutionListener executionListener = session.getRequest().getExecutionListener();
try {
project.setDependencyArtifacts(null);
execution.getForkedExecutions().clear();
session.getRequest().setExecutionListener(null);
executor.execute(session, Collections.singletonList(execution), new ProjectIndex(session.getProjects()));
}
finally {
execution.getForkedExecutions().putAll(executions);
session.getRequest().setExecutionListener(executionListener);
project.setDependencyArtifacts(dependencyArtifacts);
}
projectDependenciesResolver.resolve(newDefaultDependencyResolutionRequest(session));
}
@Test
public void testSimple() throws MojoFailureException, MojoExecutionException {
JApiCmpMojo mojo = new JApiCmpMojo();
Version oldVersion = createVersion("groupId", "artifactId", "0.1.0");
Version newVersion = createVersion("groupId", "artifactId", "0.1.1");
PluginParameters pluginParameters = new PluginParameters(false, newVersion, oldVersion, new Parameter(), null, Optional.of(Paths.get(System.getProperty("user.dir"), "target", "simple").toFile()), Optional.<String>absent(), true, null, null, null, null);
ArtifactResolver artifactResolver = mock(ArtifactResolver.class);
ArtifactResolutionResult artifactResolutionResult = mock(ArtifactResolutionResult.class);
Set<Artifact> artifactSet = new HashSet<>();
Artifact resolvedArtifact = mock(Artifact.class);
artifactSet.add(resolvedArtifact);
when(resolvedArtifact.getFile()).thenReturn(Paths.get(System.getProperty("user.dir"), "target", "guava-18.0.jar").toFile());
when(artifactResolutionResult.getArtifacts()).thenReturn(artifactSet);
when(artifactResolver.resolve(Matchers.<ArtifactResolutionRequest>anyObject())).thenReturn(artifactResolutionResult);
ArtifactFactory artifactFactory = mock(ArtifactFactory.class);
when(artifactFactory.createArtifactWithClassifier(eq("groupId"), eq("artifactId"), eq("0.1.1"), anyString(), anyString())).thenReturn(mock(Artifact.class));
MavenProject mavenProject = mock(MavenProject.class);
when(mavenProject.getArtifact()).thenReturn(mock(Artifact.class));
MavenParameters mavenParameters = new MavenParameters(new ArrayList<ArtifactRepository>(), artifactFactory, mock(ArtifactRepository.class), artifactResolver, mavenProject, mock(MojoExecution.class), "0.0.1", mock(ArtifactMetadataSource.class));
mojo.executeWithParameters(pluginParameters, mavenParameters);
assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.diff")), is(true));
assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.xml")), is(true));
assertThat(Files.exists(Paths.get(System.getProperty("user.dir"), "target", "simple", "japicmp", "japicmp.html")), is(true));
}
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
throws LifecycleExecutionException
{
if (SkipCheck.skip(session.getCurrentProject().getBasedir())
&& mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
.anyMatch(s ->
s.contains("group.idealworld.dew:dew-maven-plugin:release")
|| s.contains("dew:release")
|| s.contains("deploy"))) {
return;
}
DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );
PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );
for ( MojoExecution mojoExecution : mojoExecutions )
{
execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
}
}
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
throws LifecycleExecutionException
{
if (SkipCheck.skip(session.getCurrentProject().getBasedir())
&& mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
.anyMatch(s ->
s.contains("group.idealworld.dew:dew-maven-plugin:release")
|| s.contains("dew:release")
|| s.contains("deploy"))) {
return;
}
DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );
PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );
for ( MojoExecution mojoExecution : mojoExecutions )
{
execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
}
}
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
throws LifecycleExecutionException
{
if (SkipCheck.skip(session.getCurrentProject().getBasedir())
&& mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
.anyMatch(s ->
s.contains("group.idealworld.dew:dew-maven-plugin:release")
|| s.contains("dew:release")
|| s.contains("deploy"))) {
return;
}
DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );
PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );
for ( MojoExecution mojoExecution : mojoExecutions )
{
execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
}
}
public void execute( MavenSession session, List<MojoExecution> mojoExecutions, ProjectIndex projectIndex )
throws LifecycleExecutionException
{
if (SkipCheck.skip(session.getCurrentProject().getBasedir())
&& mojoExecutions.stream().map(MojoExecution::getGoal).map(String::toLowerCase)
.anyMatch(s ->
s.contains("group.idealworld.dew:dew-maven-plugin:release")
|| s.contains("dew:release")
|| s.contains("deploy"))) {
return;
}
DependencyContext dependencyContext = newDependencyContext( session, mojoExecutions );
PhaseRecorder phaseRecorder = new PhaseRecorder( session.getCurrentProject() );
for ( MojoExecution mojoExecution : mojoExecutions )
{
execute( session, mojoExecution, projectIndex, dependencyContext, phaseRecorder );
}
}
private Callable<Void> toTask(MojoExecution execution) {
MojoExecutor executor = new MojoExecutor(execution, project, mavenSession, buildPluginManager);
return () -> {
try {
//--- vertx-maven-plugin:1.0-SNAPSHOT:run (default-cli) @ vertx-demo
getLog().info(">>> "
+ execution.getArtifactId() + ":" + execution.getVersion() + ":" + execution.getGoal()
+ " (" + execution.getExecutionId() + ") @" + project.getArtifactId());
executor.execute();
} catch (Exception e) {
getLog().error("Error while doing incremental build", e);
}
return null;
};
}
static boolean inputFilesChangeDetected(File contractsDirectory,
MojoExecution mojoExecution, MavenSession session)
throws MojoExecutionException {
IncrementalBuildHelper incrementalBuildHelper = new IncrementalBuildHelper(
mojoExecution, session);
DirectoryScanner scanner = incrementalBuildHelper.getDirectoryScanner();
scanner.setBasedir(contractsDirectory);
scanner.scan();
boolean changeDetected = incrementalBuildHelper.inputFileTreeChanged(scanner);
if (scanner.getIncludedFiles().length == 0) {
// at least one input file must exist to consider changed/unchanged
// return true to skip incremental build and make visible no input file at all
return true;
}
return changeDetected;
}
@Nonnull
@Override
protected List<String> getConfigurationParametersToReport(ExecutionEvent executionEvent) {
MojoExecution mojoExecution = executionEvent.getMojoExecution();
if (mojoExecution == null) {
return Collections.emptyList();
}
Xpp3Dom configuration = mojoExecution.getConfiguration();
List<String> parameters = new ArrayList<String>();
for (Xpp3Dom configurationParameter : configuration.getChildren()) {
parameters.add(configurationParameter.getName());
}
return parameters;
}
@Override
public void configure(ProjectConfigurationRequest request,
IProgressMonitor monitor) throws CoreException {
addNature(request.getProject(), XtextProjectHelper.NATURE_ID, monitor);
OutputConfiguration config = new XtendOutputConfigurationProvider()
.getOutputConfigurations().iterator().next();
List<MojoExecution> executions = getMojoExecutions(request, monitor);
SubMonitor progress = SubMonitor.convert(monitor, executions.size());
for (MojoExecution execution : executions) {
String goal = execution.getGoal();
if (goal.equals("compile")) {
readCompileConfig(config, request, execution, progress.split(1));
} else if (goal.equals("testCompile")) {
readTestCompileConfig(config, request, execution, progress.split(1));
} else if (goal.equals("xtend-install-debug-info")) {
readDebugInfoConfig(config, request, execution, progress.split(1));
} else if (goal.equals("xtend-test-install-debug-info")) {
readTestDebugInfoConfig(config, request, execution, progress.split(1));
}
}
writePreferences(config, request.getProject());
}
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);
}
public void callPluginGoal(String fullGoal) {
String[] parts = splitGoalSpec(fullGoal);
Plugin plugin = project.getPlugin(parts[0]);
String goal = parts[1];
if (plugin == null) {
throw new IllegalStateException("No goal " + fullGoal + " found in pom.xml");
}
try {
String executionId = null;
if (goal != null && goal.length() > 0 && goal.indexOf('#') > -1) {
int pos = goal.indexOf('#');
executionId = goal.substring(pos + 1);
goal = goal.substring(0, pos);
}
PluginDescriptor pluginDescriptor = getPluginDescriptor(project, plugin);
MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal);
if (mojoDescriptor == null) {
throw new MojoExecutionException("Could not find goal '" + goal + "' in plugin "
+ plugin.getGroupId() + ":"
+ plugin.getArtifactId() + ":"
+ plugin.getVersion());
}
MojoExecution exec = getMojoExecution(executionId, mojoDescriptor);
pluginManager.executeMojo(session, exec);
} catch (Exception e) {
throw new IllegalStateException("Unable to execute mojo", e);
}
}
private MojoExecution getMojoExecution(String executionId, MojoDescriptor mojoDescriptor) {
if (executionId != null) {
return new MojoExecution(mojoDescriptor, executionId);
} else {
return new MojoExecution(mojoDescriptor, toXpp3Dom(mojoDescriptor.getMojoConfiguration()));
}
}
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 void mojoSucceeded(ExecutionEvent event) {
final MojoExecution execution = event.getMojoExecution();
next.mojoSucceeded(event);
if (execution.getGoal().equals(COMPILE_GOAL)) {
collectConfig(event.getProject(), event.getSession());
}
}
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);
}
@Override
public void mojoSucceeded(ExecutionEvent executionEvent) {
// Unlike mojoStarted, this callback has the lifecycle phase set.
MojoExecution execution = executionEvent.getMojoExecution();
addExecutionIfNotContainedAlready(execution);
if (delegate != null) {
delegate.mojoSucceeded(executionEvent);
}
}
/**
* Returns the {@link PluginExecution} in the {@code mojoExecution}, if a
* plugin is currently being executed.
*
* @param execution The {@link MojoExecution}.
* @return The {@link PluginExecution} in the {@code mojoExecution}, if a
* plugin is currently being executed.
* @throws NullPointerException If {@code execution} is null.
*/
public static PluginExecution getPluginExecution(final MojoExecution execution) {
final Plugin plugin = execution.getPlugin();
plugin.flushExecutionMap();
for (final PluginExecution pluginExecution : plugin.getExecutions())
if (pluginExecution.getId().equals(execution.getExecutionId()))
return pluginExecution;
return null;
}
private void setupMock()
throws ExpressionEvaluationException, ComponentLookupException,
DependencyResolutionException {
mockProject = mock(MavenProject.class);
mockMavenSession = mock(MavenSession.class);
when(mockMavenSession.getRepositorySession()).thenReturn(repositorySystemSession);
mockRuleHelper = mock(EnforcerRuleHelper.class);
mockProjectDependenciesResolver = mock(ProjectDependenciesResolver.class);
mockDependencyResolutionResult = mock(DependencyResolutionResult.class);
mockLog = mock(Log.class);
when(mockRuleHelper.getLog()).thenReturn(mockLog);
when(mockRuleHelper.getComponent(ProjectDependenciesResolver.class))
.thenReturn(mockProjectDependenciesResolver);
when(mockProjectDependenciesResolver.resolve(any(DependencyResolutionRequest.class)))
.thenReturn(mockDependencyResolutionResult);
when(mockRuleHelper.evaluate("${session}")).thenReturn(mockMavenSession);
when(mockRuleHelper.evaluate("${project}")).thenReturn(mockProject);
mockMojoExecution = mock(MojoExecution.class);
when(mockMojoExecution.getLifecyclePhase()).thenReturn("verify");
when(mockRuleHelper.evaluate("${mojoExecution}")).thenReturn(mockMojoExecution);
org.apache.maven.artifact.DefaultArtifact rootArtifact =
new org.apache.maven.artifact.DefaultArtifact(
"com.google.cloud",
"linkage-checker-rule-test",
"0.0.1",
"compile",
"jar",
null,
new DefaultArtifactHandler());
rootArtifact.setFile(new File("dummy.jar"));
when(mockProject.getArtifact()).thenReturn(rootArtifact);
}
public DependencyContext newDependencyContext( MavenSession session, List<MojoExecution> mojoExecutions )
{
Set<String> scopesToCollect = new TreeSet<String>();
Set<String> scopesToResolve = new TreeSet<String>();
collectDependencyRequirements( scopesToResolve, scopesToCollect, mojoExecutions );
return new DependencyContext( session.getCurrentProject(), scopesToCollect, scopesToResolve );
}
private void collectDependencyRequirements( Set<String> scopesToResolve, Set<String> scopesToCollect,
Collection<MojoExecution> mojoExecutions )
{
for ( MojoExecution mojoExecution : mojoExecutions )
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
scopesToResolve.addAll( toScopes( mojoDescriptor.getDependencyResolutionRequired() ) );
scopesToCollect.addAll( toScopes( mojoDescriptor.getDependencyCollectionRequired() ) );
}
}
public void execute( MavenSession session, MojoExecution mojoExecution, ProjectIndex projectIndex,
DependencyContext dependencyContext, PhaseRecorder phaseRecorder )
throws LifecycleExecutionException
{
execute( session, mojoExecution, projectIndex, dependencyContext );
phaseRecorder.observeExecution( mojoExecution );
}
public DependencyContext newDependencyContext( MavenSession session, List<MojoExecution> mojoExecutions )
{
Set<String> scopesToCollect = new TreeSet<>();
Set<String> scopesToResolve = new TreeSet<>();
collectDependencyRequirements( scopesToResolve, scopesToCollect, mojoExecutions );
return new DependencyContext( session.getCurrentProject(), scopesToCollect, scopesToResolve );
}
private void collectDependencyRequirements( Set<String> scopesToResolve, Set<String> scopesToCollect,
Collection<MojoExecution> mojoExecutions )
{
for ( MojoExecution mojoExecution : mojoExecutions )
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
scopesToResolve.addAll( toScopes( mojoDescriptor.getDependencyResolutionRequired() ) );
scopesToCollect.addAll( toScopes( mojoDescriptor.getDependencyCollectionRequired() ) );
}
}
public void execute( MavenSession session, MojoExecution mojoExecution, ProjectIndex projectIndex,
DependencyContext dependencyContext, PhaseRecorder phaseRecorder )
throws LifecycleExecutionException
{
execute( session, mojoExecution, projectIndex, dependencyContext );
phaseRecorder.observeExecution( mojoExecution );
}
public void compile(MavenSession session, MavenProject project, Xpp3Dom... parameters) throws Exception {
MojoExecution execution = newMojoExecution();
if (parameters != null) {
Xpp3Dom configuration = execution.getConfiguration();
for (Xpp3Dom parameter : parameters) {
configuration.addChild(parameter);
}
}
executeMojo(session, project, execution);
}
private void collectDependencyRequirements( Set<String> scopesToResolve, Set<String> scopesToCollect,
Collection<MojoExecution> mojoExecutions )
{
for ( MojoExecution mojoExecution : mojoExecutions )
{
MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor();
scopesToResolve.addAll( toScopes( mojoDescriptor.getDependencyResolutionRequired() ) );
scopesToCollect.addAll( toScopes( mojoDescriptor.getDependencyCollectionRequired() ) );
}
}
private void whenCheckingForUpdate() {
PluginDescriptor pluginDescriptor = new PluginDescriptor();
pluginDescriptor.setPluginArtifact(new DefaultArtifact("de.is24", "junit", "23", null, "maven-plugin", "", null));
MojoDescriptor mojoDescriptor = new MojoDescriptor();
mojoDescriptor.setPluginDescriptor(pluginDescriptor);
result = objectUnderTest.checkForUpdate(new MojoExecution(mojoDescriptor));
}