开发者

Add maven-build-classpath to plugin execution classpath

I am writing some code-gen maven-plugin.

I n开发者_C百科eed my project classpath be injected in to my plugin execution classpath.

I found this article. The solution there works but is quite long. Maybe someone of you know an out of the box solution.


Found the answer!

OK , Pascal is right , here it is for the foundation!!

So here is the cleanest way ( as far as i know ) to add the compile classpath to the execution of you plugin.

Here are some code samples from my code-gen plugin, that is actually generating some template code based on the code compiled. So I needed first the code compiled, then analyzed, generate some code, and then compiled again.

  1. Use @configurator in the Mojo class:

    /**
     * @goal generate
     * @phase process-classes
     * @configurator include-project-dependencies
     * @requiresDependencyResolution compile+runtime
     */
    public class CodeGenMojo
            extends AbstractMojo
    {
        public void execute()
                throws MojoExecutionException
        {
             // do work....   
        }
    }
    

    Please pay attention to the @configurator line in the javadoc header, it is essetial for the plexus IOC container and is not just another comment line.

  2. The implementation of the include-project-dependencies configurator. There is this very nice class that I took from some Brian Jackson, add it to the source of your plugin.

    /**
     * A custom ComponentConfigurator which adds the project's runtime classpath elements
     * to the
     *
     * @author Brian Jackson
     * @since Aug 1, 2008 3:04:17 PM
     *
     * @plexus.component role="org.codehaus.plexus.component.configurator.ComponentConfigurator"
     *                   role-hint="include-project-dependencies"
     * @plexus.requirement role="org.codehaus.plexus.component.configurator.converters.lookup.ConverterLookup"
     *                   role-hint="default"
     */
    public class IncludeProjectDependenciesComponentConfigurator extends AbstractComponentConfigurator { 
    
        private static final Logger LOGGER = Logger.getLogger(IncludeProjectDependenciesComponentConfigurator.class);
    
        public void configureComponent( Object component, PlexusConfiguration configuration,
                                        ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm,
                                        ConfigurationListener listener )
            throws ComponentConfigurationException {
    
            addProjectDependenciesToClassRealm(expressionEvaluator, containerRealm);
    
            converterLookup.registerConverter( new ClassRealmConverter( containerRealm ) );
    
            ObjectWithFieldsConverter converter = new ObjectWithFieldsConverter();
    
            converter.processConfiguration( converterLookup, component, containerRealm.getClassLoader(), configuration,
                                            expressionEvaluator, listener );
        }
    
        private void addProjectDependenciesToClassRealm(ExpressionEvaluator expressionEvaluator, ClassRealm containerRealm) throws ComponentConfigurationException {
            List<String> runtimeClasspathElements;
            try {
                //noinspection unchecked
                runtimeClasspathElements = (List<String>) expressionEvaluator.evaluate("${project.runtimeClasspathElements}");
            } catch (ExpressionEvaluationException e) {
                throw new ComponentConfigurationException("There was a problem evaluating: ${project.runtimeClasspathElements}", e);
            }
    
            // Add the project dependencies to the ClassRealm
            final URL[] urls = buildURLs(runtimeClasspathElements);
            for (URL url : urls) {
                containerRealm.addConstituent(url);
            }
        }
    
        private URL[] buildURLs(List<String> runtimeClasspathElements) throws ComponentConfigurationException {
            // Add the projects classes and dependencies
            List<URL> urls = new ArrayList<URL>(runtimeClasspathElements.size());
            for (String element : runtimeClasspathElements) {
                try {
                    final URL url = new File(element).toURI().toURL();
                    urls.add(url);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Added to project class loader: " + url);
                    }
                } catch (MalformedURLException e) {
                    throw new ComponentConfigurationException("Unable to access project dependency: " + element, e);
                }
            }
    
            // Add the plugin's dependencies (so Trove stuff works if Trove isn't on
            return urls.toArray(new URL[urls.size()]);
        }
    
    }
    
  3. Here is the build part of my plugin that you will have to add.

    <modelVersion>4.0.0</modelVersion>
    <groupId>com.delver</groupId>
    <artifactId>reference-gen-plugin</artifactId>
    <name>Reference Code Genration Maven Plugin</name>
    
    <packaging>maven-plugin</packaging>
    <version>1.2</version>
    
    <url>http://maven.apache.org</url>
    
    <properties>
        <maven.version>2.2.1</maven.version>
    </properties>
    
    <build>
        <plugins>
            <plugin>
                <groupId>org.codehaus.plexus</groupId>
                <artifactId>plexus-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>descriptor</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <dependencies>
    
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-artifact</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-plugin-api</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-project</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-model</artifactId>
            <version>${maven.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.maven</groupId>
            <artifactId>maven-core</artifactId>
            <version>2.0.9</version>
        </dependency>
    
    </dependencies>
    

    Here is the pom.xml of the plugin for these who need it. Should compile wihtout a problem now. ( something wrong with the header, so ignore it )


I took this approach and apparently it's working:

1 - a MavenProject parameter is needed within your Mojo class:

@Parameter(defaultValue = "${project}", required = true, readonly = true)
private MavenProject project;

2 - and then you can get the classpath elements from project instance:

try {
    Set<URL> urls = new HashSet<>();
    List<String> elements = project.getTestClasspathElements();
                                  //getRuntimeClasspathElements()
                                  //getCompileClasspathElements()
                                  //getSystemClasspathElements()  
    for (String element : elements) {
        urls.add(new File(element).toURI().toURL());
    }

    ClassLoader contextClassLoader = URLClassLoader.newInstance(
            urls.toArray(new URL[0]),
            Thread.currentThread().getContextClassLoader());

    Thread.currentThread().setContextClassLoader(contextClassLoader);

} catch (DependencyResolutionRequiredException e) {
    throw new RuntimeException(e);
} catch (MalformedURLException e) {
    throw new RuntimeException(e);
}


followed this link.... did very similar thing for my code... i have created a maven-fit-plugin I have used exactly the same pom.xml for my plugin, reusing the IncludeProjectDependenciesComponentConfigurator

I am using maven 2.2.0 if it can help, here's pom again

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/maven-v4_0_0.xsd">

<modelVersion>4.0.0</modelVersion>
<groupId>com.worldcorpservices.plugins</groupId>
<artifactId>maven-fit-plugin</artifactId>
<packaging>maven-plugin</packaging>
<version>1.0-SNAPSHOT</version>
<name>maven-fit-plugin Maven Mojo</name>
<url>http://maven.apache.org</url>

<properties>
    <fitlibrary.version>2.0</fitlibrary.version>
    <maven.version>2.2.0</maven.version>
</properties>


<dependencies>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>2.0</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.7</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging</artifactId>
        <version>1.1.1</version>
    </dependency>

    <dependency>
        <groupId>org.fitnesse</groupId>
        <artifactId>fitlibrary</artifactId>
        <version>${fitlibrary.version}</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.12</version>
    </dependency>
    <dependency>
        <groupId>poi</groupId>
        <artifactId>poi</artifactId>
        <version>3.7-20101029</version>
    </dependency>

    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-artifact</artifactId>
        <version>${maven.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-plugin-api</artifactId>
        <version>${maven.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-project</artifactId>
        <version>${maven.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-model</artifactId>
        <version>${maven.version}</version>
    </dependency>
    <dependency>
        <groupId>org.apache.maven</groupId>
        <artifactId>maven-core</artifactId>
        <version>2.0.9</version>
    </dependency>


</dependencies>
<build>

hope this helps

rgds marco

    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.codehaus.plexus</groupId>
            <artifactId>plexus-maven-plugin</artifactId>
            <executions>
                <execution>
                    <goals>
                        <goal>descriptor</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>


    </plugins>

</build>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜