assuring the dependencies are in the classpath in a maven plugin

In maven2 you can create plugins for any actions which are not supported out-of-the-box.
Unfortunately though, this is not always as straightforward as you would expect.

In the plugin, you may expect that the classpath contains all the dependencies for your module which is being built, but this is not the case. In fact, the dependencies are not even know by default.

To fix this, you have to assure that the dependency resolution has been done by maven. This can easily be done by adding an annotation in your mojo header.

/**
 * My maven plugin
 *
 * @goal generate
 * @phase generate-sources
 * @requiresDependencyResolution compile
 * @description my maven plugin
 */

You can choose which dependencies should be included, “compile”, “test” or “runtime”.

While this makes the dependencies available for queries by the plugin, this still does not assure that the classpath contains these dependencies. For this, you need to do some more plumbing, building your own classloader which included the dependencies and have your plugin run using that classloader.

    /**
     * @parameter expression="${project.compileClasspathElements}"
     */
    private List<String> classpathElements;

    public void execute()
        throws MojoExecutionException
    {
        Thread runner = new Thread()
        {
            public void run()
            {
                // do your stuff here
            }
        };
        URLClassLoader classloader = new URLClassLoader( createClassPath(),
                                                         Thread.currentThread().getContextClassLoader() );
        runner.setContextClassLoader( classloader );
        runner.start();
        try
        {
            runner.join();
        }
        catch ( InterruptedException ie )
        {
            throw new MojoExecutionException( "equanda generation was interrupted" );
        }
    }

    protected URL[] createClassPath()
    {
        List<URL> list = new ArrayList<URL>();

        // Add the projects dependencies
        if ( classpathElements != null )
        {
            for ( String cpel : classpathElements )
            {
                try
                {
                    list.add( new File( cpel ).toURI().toURL() );
                }
                catch ( MalformedURLException mue )
                {/*ignore*/}
            }
        }
        return list.toArray( new URL[list.size()] );
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

question razz sad evil exclaim smile redface biggrin surprised eek confused cool lol mad twisted rolleyes wink idea arrow neutral cry mrgreen

*