-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Hi James & James,

The classpath element list is simply a list of strings (to locations
within the repository).  Please see attached Mojo for a simple example.

One issue with this is that some classes (in your case, most likely the
spring classes) will be loaded in the URLClassloader as well as in the
Mojo class loader.  So you may have to add a reference to the parent
loader in this case (and filter out any duplicate libraries from the
above list.  Did that make sense?

Cheers,

Johan

> James CE Johnson wrote:
> James, Johan,
> 
> Please copy me on this if it goes off-list. I'm trying to write a MoJo that
> uses a utility that uses Spring and I'm getting what I think is a
> classloader issue. If you solve it for your case I suspect I can use the
> same solution for my own issue: http://rafb.net/p/fOEW5I52.html
> 
> Thanks!
> James
> 
>> Sorry, forget exactly what it is but if you can wait 12 hours I can look
>> it up ;)
>>
>> Found it in some of the maven APIs if that helps.
>>
>> And no, not on every list ;)
>>
>> Johan
>>
>> I forget what it is - not at work an
>>
>> James Carman wrote:
>>> Johan,
>>>
>>> What kind of objects should I expect in that list?
>>>
>>> James
>>>
>>> p.s. Are you on every mailing list? :-)
>>>
>>>
>>> On 4/3/07, Johan Lindquist <[EMAIL PROTECTED]> wrote:
>>>> Hi James,
>>>>
>>>> Try using the following property in you Mojo.
>>>>
>>>>     /**
>>>>      * The classpath elements of the project.
>>>>      *
>>>>      * @parameter expression="${project.runtimeClasspathElements}" *
>>>> @required
>>>>      * @readonly
>>>>      */
>>>>     private List classpathElements;
>>>>
>>>> I think in this case, you would have to provide your own classloader
>>>> for spring - the classloader for the Mojo does (as far as I understand)
>>>> not see the project dependencies.
>>>>
>>>> cheers,
>>>>
>>>> Johan
>>>>
>>>>
>>>> James Carman wrote:
>>>>> Franz,
>>>>>
>>>>> Thanks for replying.  Let me explain it a bit more.  I was trying to
>>>> gloss
>>>>> over things a bit.  Basically, I'm using Spring to instantiate the
>>>> bean:
>>>>> public class RunLoaderMojo extends AbstractMojo
>>>>> {
>>>>>    /**
>>>>>     * @parameter property="loaderBean" expression="${loaderBean}" *
>>>> @required
>>>>>     */
>>>>>    private String loaderBean;
>>>>>
>>>>>    public void execute() throws MojoExecutionException
>>>>>    {
>>>>>        // Load all META-INF/beans.xml files on classpath!
>>>>>        ClassPathXmlApplicationContext ctx = new
>>>>> ClassPathXmlApplicationContext("classpath*:META-INF/beans.xml");
>>>>>        getLog().info("Running loader '" + loaderBean + "'..."); final
>>>> Loader loader = ( Loader )ctx.getBean(loaderBean,
>>>> Loader.class
>>>>> );
>>>>>        loader.execute();
>>>>>    }
>>>>>
>>>>>    public String getLoaderBean()
>>>>>    {
>>>>>        return loaderBean;
>>>>>    }
>>>>>
>>>>>    public void setLoaderBean(String loaderBean)
>>>>>    {
>>>>>        this.loaderBean = loaderBean;
>>>>>    }
>>>>> }
>>>>>
>>>>> That's my mojo class.  Then, I want to use it in a project like this:
>>>>>
>>>>> <plugin>
>>>>>  <groupId>com.myco.myproj</groupId>
>>>>>  <artifactId>maven-loader-plugin</artifactId>
>>>>> </plugin>
>>>>>
>>>>> Then, I try executing the plugin like this (from the project dir):
>>>>>
>>>>> mvn loader:run -DloaderBean=exampleLoader
>>>>>
>>>>> If I try to use a beans.xml file that's defined within my project, it
>>>> doesn't even see it on the classpath.  If I put it into one of my
>>>> project's
>>>>> dependencies (another module of mine), then it sees it fine.  It just
>>>> doesn't see anything within the enclosing project.  Does that make
>>>> sense?
>>>>> James
>>>>>
>>>>> On 4/3/07, franz see <[EMAIL PROTECTED]> wrote:
>>>>>>
>>>>>> Good day to you, James,
>>>>>>
>>>>>> Not sure how you're instantiating those classes. Anyway, try adding
>>>> those
>>>>>> classes in your plugin's dependency ( see [1] ). And if you need the
>>>> path
>>>>>> to
>>>>>> those binaries, see Getting dependency artifact path of [2].
>>>>>>
>>>>>> Cheers,
>>>>>> Franz
>>>>>>
>>>>>> [1]
>>>>>>
>>>> http://maven.apache.org/ref/current/maven-model/maven.html#class_plugin
>>>>>> [2] http://docs.codehaus.org/display/MAVENUSER/
>>>>>>
>>>>>>
>>>>>> James Carman-3 wrote:
>>>>>>> All,
>>>>>>>
>>>>>>> I am developing a simple mojo which needs to access classes
>>>> defined
>>>>>> within
>>>>>>> the project in which it is used.  But, they don't seem to be
>>>>>> visible.  I
>>>>>>> am
>>>>>>> writing a mojo that can execute a "loader" (loads data into our
>>>>>> database)
>>>>>>> object.  It takes a parameter that tells which loader class to
>>>> use. Anyway,
>>>>>>> I now want to use that mojo within another project to run a loader
>>>>>> defined
>>>>>>> within that project.  When I try to instantiate that class, it's
>>>> not available.  Is there something special I need to do to tell
>>>> Maven to include
>>>>>>> the current project's classpath in my mojo's environment?
>>>>>>>
>>>>>>> James
>>>>>>>
>>>>>>>
>>>>>> --
>>>>>> View this message in context:
>>>>>>
>>>> http://www.nabble.com/Using-containing-project%27s-classpath-within-mojo...-tf3519722s177.html#a9821549
>>>>
>>>>>> Sent from the Maven - Users mailing list archive at Nabble.com.
>>>>>>
>>>>>>
>>>>>> ---------------------------------------------------------------------
>>>> To unsubscribe, e-mail: [EMAIL PROTECTED]
>>>>>> For additional commands, e-mail: [EMAIL PROTECTED]
>>>>>>
>>>>>>
>>>> --
>>>> you too?
>>>>
>>>> ---------------------------------------------------------------------
>>>> To unsubscribe, e-mail: [EMAIL PROTECTED]
>>>> For additional commands, e-mail: [EMAIL PROTECTED]
>>>>
>>>>
>> --
>> you too?
>>
>> --------------------------------------------------------------------- To
>> unsubscribe, e-mail: [EMAIL PROTECTED]
>> For additional commands, e-mail: [EMAIL PROTECTED]
> 
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: [EMAIL PROTECTED]
> For additional commands, e-mail: [EMAIL PROTECTED]
> 
> 

- --
you too?
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFGE04z1Tv8wj7aQ34RAiRkAJ49FAUcqoTmbq75O1QbQ7sBslATZACggZ8J
rzFTCXR2donhJ6vXVAEB7/A=
=h/ze
-----END PGP SIGNATURE-----
package org.apache.hivemind.mojo.verifier;

import java.io.File;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.*;

import org.apache.commons.logging.Log;
import org.apache.hivemind.ApplicationRuntimeException;
import org.apache.hivemind.ErrorHandler;
import org.apache.hivemind.Location;
import org.apache.hivemind.impl.DefaultClassResolver;
import org.apache.hivemind.impl.RegistryBuilder;
import org.apache.hivemind.impl.XmlModuleDescriptorProvider;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.project.MavenProject;

/**
 * @goal verify
 *
 *
 */
public class HivemoduleVerifierMojo extends AbstractMojo
{

    /**
     * The maven project.
     *
     * @parameter expression="${project}"
     * @required
     * @readonly
     */
    private MavenProject _project = null;

    /**
     * @parameter alias="includeDependantJars"
     */
    private boolean _includeDependantJars = false;

    /** Defines the action to take when a Hivemodule is detected as missing.  Possible values are "warn", "fail" and "ignore".
     * Default value is "fail".
     * @parameter alias="missingHivemoduleAction" default-value="fail"
     *
     */
    private String _missingHivemoduleAction = "fail";


    /**
     * @parameter alias="ignoreExternalErrors"
     */
    private boolean _ignoreExternalErrors = false;

    /**
     * @parameter alias="skipValidation"
     */
    private boolean _skipValidation = false;

    public void execute() throws MojoExecutionException, MojoFailureException
    {
        if (_skipValidation || Boolean.getBoolean("maven.hivemind.verifier.skip"))
        {
            getLog().info("Skipping Hivemind module verification on request");
            return;
        }

        getLog().info("Starting Hivemind module verification");

        if ("pom".equals(_project.getPackaging()))
        {
            getLog().info("Ignoring project with packaging 'pom'");
            return;
        }

        validateSettings();

         // has been ignored in favor of existing definition from


        final Status status = new Status();


        final RegistryBuilder registryBuilder = new RegistryBuilder(new ErrorHandler()
        {
            public void error(final Log log, final String string, final Location location, final Throwable throwable)

            {
                if (location != null)
                {
                    final boolean isExternalError = location.getResource().getPath().indexOf(_project.getBuild().getOutputDirectory()) == -1;
                    if (isExternalError && _ignoreExternalErrors)
                    {
                        // Location is outside of scope ...
                        getLog().debug("Ignoring external Hivemind error");
                    }
                    else
                    {
                        getLog().error("Error found in hivemodule " + location.getResource() + " at + " +location.getLineNumber() + " : " + string);
                        status.setHasFailures(true);
                    }
                }
                else
                {
                    getLog().error("Error found: " + string);
                    status.setHasFailures(true);
                }

            }
        });

        try
        {

            final File classesDirectory = resolveClassesDirectory();

            File rootHivemodule = new File(classesDirectory,"META-INF/hivemodule.xml");
            if (!rootHivemodule.exists())
            {
                // Ok, hivemodule not present - check what we need to do ...
                if ("warn".equals(_missingHivemoduleAction))
                {
                    getLog().warn("");
                    getLog().warn("##################### WARNING #########################");
                    getLog().warn("Hivemodule missing, you may want to verify your setup");
                    getLog().warn("########################################################");
                    getLog().warn("");
                }
                else if ("fail".equals(_missingHivemoduleAction))
                {
                    getLog().error("");
                    getLog().error("##################### ERROR ###########################");
                    getLog().error("Hivemodule missing, please verify your setup");
                    getLog().error("#######################################################");
                    getLog().error("");
                    status.setHasFailures(true);
                }
                else
                {
                    // Must be ignore i guess ...
                }
                checkFailure(status);
                return;
            }


            Set urlList = new HashSet();

            urlList.add(classesDirectory.toURL());

            if (_includeDependantJars)
            {

                final List classPathElements = _project.getRuntimeClasspathElements();
                int i = 0;
                for (Iterator iterator = classPathElements.iterator(); iterator.hasNext();)
                {
                    final String classPathElement = (String) iterator.next();
                    File f = new File(classPathElement);
                    final URL url = f.toURL();
                    if (!urlList.add(url))
                    {
                        getLog().debug("Ignoring project output directory");
                    }
                    else
                    {
                        getLog().debug("Added class path element: " + classPathElement);
                    }
                }
            }

            // FIXME: The class loading issue here causes a class cast exception within HiveMind ...
            // By adding the class loader of this class, the problem is sorted, but then instead we have
            // two HiveMind class path entries.
            registryBuilder.addModuleDescriptorProvider(new XmlModuleDescriptorProvider(new DefaultClassResolver(new URLClassLoader((URL[]) urlList.toArray(new URL[0])))));
            registryBuilder.constructRegistry(Locale.getDefault());
        }
        catch (ClassCastException e)
        {
            getLog().debug(e.getMessage(),e);
            getLog().debug("Ignoring classcast exception caused by class loader issues");
            checkFailure(status);
            return;
        }
        catch (ApplicationRuntimeException e)
        {
            getLog().debug("Ignoring application runtime exception");
            checkFailure(status);
            return;
        }
        catch(Exception e)
        {
            getLog().error(e.getMessage(),e);
            throw new MojoExecutionException(e.getMessage());
        }

        checkFailure(status);


    }

    private File resolveClassesDirectory()
    {
        getLog().debug("Resolving class location for project with packaging '" + _project.getPackaging() + "'");
        if ("jar".equals(_project.getPackaging()))
        {
            final File file = new File(_project.getBuild().getOutputDirectory());
            getLog().debug("Resolved class location for project with packaging '" + _project.getPackaging() + "' to " + file.getAbsolutePath());
            return file;
        }
        if ("war".equals(_project.getPackaging()))
        {
            final File file = new File(_project.getBuild().getOutputDirectory() + "/WEB-INF/classes/");
            getLog().debug("Resolved class location for project with packaging '" + _project.getPackaging() + "' to " + file.getAbsolutePath());
            return file;
        }
        else
        {
            getLog().info("Unknown (to this plugin) packaging type '" + _project.getPackaging() + "' - will use default output directory");
            return new File(_project.getBuild().getOutputDirectory());
        }
    }

    private void validateSettings() throws MojoExecutionException
    {
        if (_missingHivemoduleAction != null)
        {
            if (!_missingHivemoduleAction.equals("ignore") && !_missingHivemoduleAction.equals("warn") && !_missingHivemoduleAction.equals("fail"))
            {
                throw new MojoExecutionException("Invalid action specified for missing Hivemodule: " + _missingHivemoduleAction);
            }
        }
    }

    private void checkFailure(final Status status)  throws MojoExecutionException
    {
        getLog().info("Hivemind module verification completed with status: " + (status.hasFailures() ? "FAILED" : "OK"));
        if (status.hasFailures())
        {
            throw new MojoExecutionException("Hivemind module verification fails, please see error listed above");
        }
    }

    private class Status {
        boolean _hasFailures;

        public boolean hasFailures()
        {
            return _hasFailures;
        }

        public void setHasFailures(final boolean hasFailures)
        {
            _hasFailures = hasFailures;
        }
    }

}

---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to