MNG-5530 Introduced mojo execution guice component scope

Mojo execution scoped components are annotated with @MojoExecutionScoped
They are created just before configured mojo instance is created
and disposed immediately after mojo execution finishes.

Execution scoped components can request @Inject MavenSession,
MavenProject and MojoExecution instances in addition to any
standard Maven core components and components defined in
maven plugin contributing execution scoped components.

Execution scoped components can be injected into Mojos using
standard /* @component */ javadoc (and likely new mojo
annotations).

If execution scoped component implements MojoExecutionListener
callback interface, its #afterMojoExecutionSuccess method will be
invoked after successful mojo execution and #afterMojoExecutionAlways
method will be executed after both successful and failed mojo
executions.

Signed-off-by: Igor Fedorenko <igor@ifedorenko.com>
This commit is contained in:
Igor Fedorenko 2012-11-25 01:34:53 -05:00
parent 70218af1c1
commit 8700b05857
11 changed files with 429 additions and 5 deletions

View File

@ -161,6 +161,19 @@
<groupId>org.codehaus.plexus</groupId> <groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-component-metadata</artifactId> <artifactId>plexus-component-metadata</artifactId>
</plugin> </plugin>
<plugin>
<groupId>org.sonatype.plugins</groupId>
<artifactId>sisu-maven-plugin</artifactId>
<version>1.1</version>
<executions>
<execution>
<goals>
<goal>main-index</goal>
<goal>test-index</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin> <plugin>
<groupId>org.codehaus.modello</groupId> <groupId>org.codehaus.modello</groupId>
<artifactId>modello-maven-plugin</artifactId> <artifactId>modello-maven-plugin</artifactId>

View File

@ -139,6 +139,7 @@ public class DefaultClassRealmManager
imports.put( "org.apache.maven.configuration", coreRealm ); imports.put( "org.apache.maven.configuration", coreRealm );
imports.put( "org.apache.maven.exception", coreRealm ); imports.put( "org.apache.maven.exception", coreRealm );
imports.put( "org.apache.maven.execution", coreRealm ); imports.put( "org.apache.maven.execution", coreRealm );
imports.put( "org.apache.maven.execution.scope", coreRealm );
imports.put( "org.apache.maven.lifecycle", coreRealm ); imports.put( "org.apache.maven.lifecycle", coreRealm );
imports.put( "org.apache.maven.model", coreRealm ); imports.put( "org.apache.maven.model", coreRealm );
imports.put( "org.apache.maven.monitor", coreRealm ); imports.put( "org.apache.maven.monitor", coreRealm );

View File

@ -0,0 +1,48 @@
package org.apache.maven.execution.scope;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.plugin.MojoExecutionException;
/**
* Helper interface that allows mojo execution scoped components to be notified before execution start and after
* execution completion. The main purpose of this interface is to allow mojo execution scoped components perform setup
* before and cleanup after mojo execution.
* <p>
* TODO decide if Mojo should be passed as parameter of callback methods
*
* @author igor
* @since 3.1.2
* @provisional This interface is part of work in progress and can be changed or removed without notice.
*/
public interface MojoExecutionListener
{
// TODO decide if this is needed
// public void beforeExecution() throws MojoExecutionException;
public void afterMojoExecutionSuccess()
throws MojoExecutionException;
// TODO decide if this is needed.
// public void afterExecutionFailure(Throwable t) throws MojoExecutionException;
public void afterMojoExecutionAlways()
throws MojoExecutionException;
}

View File

@ -0,0 +1,42 @@
package org.apache.maven.execution.scope;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.google.inject.ScopeAnnotation;
/**
* Indicates that annotated component should be instantiated before mojo execution starts and discarded after mojo
* execution completes.
*
* @author igor
* @since 3.1.2
*/
@Target( { TYPE } )
@Retention( RUNTIME )
@ScopeAnnotation
public @interface MojoExecutionScoped
{
}

View File

@ -0,0 +1,45 @@
package org.apache.maven.execution.scope.internal;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import javax.inject.Named;
import org.apache.maven.execution.scope.MojoExecutionScoped;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.name.Names;
@Named
public class MojoExecutionModule
implements Module
{
public void configure( Binder binder )
{
final MojoExecutionScope executionScope = new MojoExecutionScope();
// tell Guice about the scope
binder.bindScope( MojoExecutionScoped.class, executionScope );
// make our scope instance injectable
binder.bind( MojoExecutionScope.class ).annotatedWith( Names.named( MojoExecutionScope.SCOPE_NAME ) ).toInstance( executionScope );
}
}

View File

@ -0,0 +1,200 @@
package org.apache.maven.execution.scope.internal;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.LinkedList;
import java.util.Map;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.scope.MojoExecutionListener;
import org.apache.maven.execution.scope.MojoExecutionScoped;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.Module;
import com.google.inject.OutOfScopeException;
import com.google.inject.Provider;
import com.google.inject.Scope;
import com.google.inject.util.Providers;
public class MojoExecutionScope
implements Scope
{
public static final String SCOPE_NAME = "mojoExecution";
private static final Provider<Object> SEEDED_KEY_PROVIDER = new Provider<Object>()
{
public Object get()
{
throw new IllegalStateException();
}
};
private static final class ScopeState
{
public final Map<Key<?>, Provider<?>> seeded = Maps.newHashMap();
public final Map<Key<?>, Object> provided = Maps.newHashMap();
}
private final ThreadLocal<LinkedList<ScopeState>> values = new ThreadLocal<LinkedList<ScopeState>>();
public MojoExecutionScope()
{
}
public void enter()
{
LinkedList<ScopeState> stack = values.get();
if ( stack == null )
{
stack = new LinkedList<ScopeState>();
values.set( stack );
}
stack.addFirst( new ScopeState() );
}
private ScopeState getScopeState()
{
LinkedList<ScopeState> stack = values.get();
if ( stack == null || stack.isEmpty() )
{
throw new IllegalStateException();
}
return stack.getFirst();
}
public void exit()
throws MojoExecutionException
{
final LinkedList<ScopeState> stack = values.get();
if ( stack == null || stack.isEmpty() )
{
throw new IllegalStateException();
}
stack.removeFirst();
if ( stack.isEmpty() )
{
values.remove();
}
}
public <T> void seed( Class<T> clazz, Provider<T> value )
{
getScopeState().seeded.put( Key.get( clazz ), value );
}
public <T> void seed( Class<T> clazz, final T value )
{
getScopeState().seeded.put( Key.get( clazz ), Providers.of( value ) );
}
public <T> Provider<T> scope( final Key<T> key, final Provider<T> unscoped )
{
return new Provider<T>()
{
@SuppressWarnings( "unchecked" )
public T get()
{
LinkedList<ScopeState> stack = values.get();
if ( stack == null || stack.isEmpty() )
{
throw new OutOfScopeException( "Cannot access " + key + " outside of a scoping block" );
}
ScopeState state = stack.getFirst();
Provider<?> seeded = state.seeded.get( key );
if ( seeded != null )
{
return (T) seeded.get();
}
T provided = (T) state.provided.get( key );
if ( provided == null )
{
provided = unscoped.get();
state.provided.put( key, provided );
}
return provided;
}
};
}
@SuppressWarnings( { "unchecked" } )
public static <T> Provider<T> seededKeyProvider()
{
return (Provider<T>) SEEDED_KEY_PROVIDER;
}
public static Module getScopeModule( PlexusContainer container )
throws ComponentLookupException
{
final MojoExecutionScope scope = container.lookup( MojoExecutionScope.class );
return new AbstractModule()
{
@Override
protected void configure()
{
bindScope( MojoExecutionScoped.class, scope );
// standard scope bindings
bind( MavenSession.class ).toProvider( MojoExecutionScope.<MavenSession> seededKeyProvider() ).in( scope );
bind( MavenProject.class ).toProvider( MojoExecutionScope.<MavenProject> seededKeyProvider() ).in( scope );
bind( MojoExecution.class ).toProvider( MojoExecutionScope.<MojoExecution> seededKeyProvider() ).in( scope );
}
};
}
public void afterExecutionSuccess()
throws MojoExecutionException
{
for ( Object provided : getScopeState().provided.values() )
{
if ( provided instanceof MojoExecutionListener )
{
( (MojoExecutionListener) provided ).afterMojoExecutionSuccess();
// TODO maybe deal with multiple MojoExecutionExceptions
}
}
}
public void afterExecutionAlways()
throws MojoExecutionException
{
for ( Object provided : getScopeState().provided.values() )
{
if ( provided instanceof MojoExecutionListener )
{
( (MojoExecutionListener) provided ).afterMojoExecutionAlways();
// TODO maybe deal with multiple MojoExecutionExceptions
}
}
}
}

View File

@ -24,6 +24,7 @@ import java.io.PrintStream;
import java.util.List; import java.util.List;
import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.scope.internal.MojoExecutionScope;
import org.apache.maven.model.Plugin; import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.descriptor.MojoDescriptor; import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor; import org.apache.maven.plugin.descriptor.PluginDescriptor;
@ -48,8 +49,10 @@ public class DefaultBuildPluginManager
@Requirement @Requirement
private LegacySupport legacySupport; private LegacySupport legacySupport;
@Requirement( hint = MojoExecutionScope.SCOPE_NAME )
private MojoExecutionScope scope;
/** /**
*
* @param plugin * @param plugin
* @param repositories * @param repositories
* @param session * @param session
@ -92,8 +95,14 @@ public class DefaultBuildPluginManager
MavenSession oldSession = legacySupport.getSession(); MavenSession oldSession = legacySupport.getSession();
scope.enter();
try try
{ {
scope.seed( MavenSession.class, session );
scope.seed( MavenProject.class, project );
scope.seed( MojoExecution.class, mojoExecution );
mojo = mavenPluginManager.getConfiguredMojo( Mojo.class, session, mojoExecution ); mojo = mavenPluginManager.getConfiguredMojo( Mojo.class, session, mojoExecution );
legacySupport.setSession( session ); legacySupport.setSession( session );
@ -104,6 +113,8 @@ public class DefaultBuildPluginManager
try try
{ {
mojo.execute(); mojo.execute();
scope.afterExecutionSuccess();
} }
catch ( ClassCastException e ) catch ( ClassCastException e )
{ {
@ -155,8 +166,12 @@ public class DefaultBuildPluginManager
} }
finally finally
{ {
scope.afterExecutionAlways();
mavenPluginManager.releaseMojo( mojo, mojoExecution ); mavenPluginManager.releaseMojo( mojo, mojoExecution );
scope.exit();
Thread.currentThread().setContextClassLoader( oldClassLoader ); Thread.currentThread().setContextClassLoader( oldClassLoader );
legacySupport.setSession( oldSession ); legacySupport.setSession( oldSession );

View File

@ -41,6 +41,7 @@ import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.Artifact;
import org.apache.maven.classrealm.ClassRealmManager; import org.apache.maven.classrealm.ClassRealmManager;
import org.apache.maven.execution.MavenSession; import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.scope.internal.MojoExecutionScope;
import org.apache.maven.model.Plugin; import org.apache.maven.model.Plugin;
import org.apache.maven.monitor.logging.DefaultLog; import org.apache.maven.monitor.logging.DefaultLog;
import org.apache.maven.plugin.ContextEnabled; import org.apache.maven.plugin.ContextEnabled;
@ -66,6 +67,7 @@ import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder;
import org.apache.maven.project.MavenProject; import org.apache.maven.project.MavenProject;
import org.apache.maven.rtinfo.RuntimeInformation; import org.apache.maven.rtinfo.RuntimeInformation;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Component;
@ -389,9 +391,10 @@ public class DefaultMavenPluginManager
container.addComponentDescriptor( componentDescriptor ); container.addComponentDescriptor( componentDescriptor );
} }
container.discoverComponents( pluginRealm ); ( (DefaultPlexusContainer) container ).discoverComponents( pluginRealm,
MojoExecutionScope.getScopeModule( container ) );
} }
catch ( PlexusConfigurationException e ) catch ( ComponentLookupException e )
{ {
throw new PluginContainerException( plugin, pluginRealm, "Error in component graph of plugin " throw new PluginContainerException( plugin, pluginRealm, "Error in component graph of plugin "
+ plugin.getId() + ": " + e.getMessage(), e ); + plugin.getId() + ": " + e.getMessage(), e );

View File

@ -33,6 +33,7 @@ import java.util.Set;
import org.apache.maven.artifact.InvalidRepositoryException; import org.apache.maven.artifact.InvalidRepositoryException;
import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.classrealm.ClassRealmManager; import org.apache.maven.classrealm.ClassRealmManager;
import org.apache.maven.execution.scope.internal.MojoExecutionScope;
import org.apache.maven.model.Build; import org.apache.maven.model.Build;
import org.apache.maven.model.Extension; import org.apache.maven.model.Extension;
import org.apache.maven.model.Model; import org.apache.maven.model.Model;
@ -47,6 +48,7 @@ import org.apache.maven.plugin.version.PluginVersionRequest;
import org.apache.maven.plugin.version.PluginVersionResolutionException; import org.apache.maven.plugin.version.PluginVersionResolutionException;
import org.apache.maven.plugin.version.PluginVersionResolver; import org.apache.maven.plugin.version.PluginVersionResolver;
import org.apache.maven.repository.RepositorySystem; import org.apache.maven.repository.RepositorySystem;
import org.codehaus.plexus.DefaultPlexusContainer;
import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.classworlds.realm.ClassRealm; import org.codehaus.plexus.classworlds.realm.ClassRealm;
import org.codehaus.plexus.component.annotations.Component; import org.codehaus.plexus.component.annotations.Component;
@ -266,7 +268,8 @@ public class DefaultProjectBuildingHelper
try try
{ {
container.discoverComponents( extensionRealm ); ( (DefaultPlexusContainer) container ).discoverComponents( extensionRealm,
MojoExecutionScope.getScopeModule( container ) );
} }
catch ( Exception e ) catch ( Exception e )
{ {

View File

@ -44,6 +44,7 @@ import org.apache.maven.project.ProjectBuildingRequest;
import org.apache.maven.repository.RepositorySystem; import org.apache.maven.repository.RepositorySystem;
import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.apache.maven.repository.internal.MavenRepositorySystemUtils;
import org.codehaus.plexus.ContainerConfiguration; import org.codehaus.plexus.ContainerConfiguration;
import org.codehaus.plexus.PlexusConstants;
import org.codehaus.plexus.PlexusTestCase; import org.codehaus.plexus.PlexusTestCase;
import org.codehaus.plexus.component.annotations.Requirement; import org.codehaus.plexus.component.annotations.Requirement;
import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.FileUtils;
@ -98,7 +99,7 @@ public abstract class AbstractCoreMavenComponentTestCase
*/ */
protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration ) protected void customizeContainerConfiguration( ContainerConfiguration containerConfiguration )
{ {
containerConfiguration.setAutoWiring( true ); containerConfiguration.setAutoWiring( true ).setClassPathScanning( PlexusConstants.SCANNING_INDEX );;
} }
protected MavenExecutionRequest createMavenExecutionRequest( File pom ) protected MavenExecutionRequest createMavenExecutionRequest( File pom )

View File

@ -0,0 +1,53 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.maven.execution.scope.internal;
import junit.framework.TestCase;
import com.google.inject.Key;
public class MojoExecutionScopeTest
extends TestCase
{
public void testNestedEnter()
throws Exception
{
MojoExecutionScope scope = new MojoExecutionScope();
scope.enter();
Object o1 = new Object();
scope.seed( Object.class, o1 );
assertSame( o1, scope.scope( Key.get( Object.class ), null ).get() );
scope.enter();
Object o2 = new Object();
scope.seed( Object.class, o2 );
assertSame( o2, scope.scope( Key.get( Object.class ), null ).get() );
scope.exit();
assertSame( o1, scope.scope( Key.get( Object.class ), null ).get() );
scope.exit();
try
{
scope.exit();
}
catch ( IllegalStateException expected )
{
}
}
}