All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.codehaus.mojo.groovy.execute.ExecuteMojo Maven / Gradle / Ivy

Go to download

Provides support for execution, compilation and other facets of Groovy development.

The newest version!
/*
 * Copyright (C) 2006-2007 the original author or authors.
 *
 * Licensed 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.codehaus.mojo.groovy.execute;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.List;
import java.util.Map;

import org.apache.maven.artifact.DependencyResolutionRequiredException;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import org.apache.maven.execution.MavenSession;
import org.codehaus.mojo.groovy.ComponentMojoSupport;
import org.codehaus.mojo.groovy.feature.Component;
import org.codehaus.mojo.groovy.feature.Configuration;
import org.codehaus.mojo.groovy.runtime.ScriptExecutor;
import org.codehaus.mojo.groovy.runtime.support.util.ResourceLoaderImpl;
import org.codehaus.mojo.groovy.runtime.util.Callable;
import org.codehaus.mojo.groovy.runtime.util.ClassSource;
import org.codehaus.mojo.groovy.runtime.util.MagicAttribute;
import org.codehaus.mojo.groovy.runtime.util.ResourceLoader;
import org.codehaus.mojo.groovy.util.ArtifactItem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Executes a Groovy script.
 *
 * @goal execute
 * @requiresDependencyResolution runtime
 * @configurator override
 * @since 1.0-alpha-1
 *
 * @version $Id: ExecuteMojo.java 5691 2007-12-06 22:01:47Z user57 $
 * @author Jason Dillon
 */
public class ExecuteMojo
    extends ComponentMojoSupport
{
    /**
     * The source of the script to execute.  This can be a URL, File or script body.
     *
     * @parameter
     * @required
     *
     * @noinspection UnusedDeclaration
     */
    private Source source;

    /**
     * Additional artifacts to add to the scripts classpath.
     *
     * @parameter
     *
     * @noinspection UnusedDeclaration,MismatchedReadAndWriteOfArray
     */
    private ArtifactItem[] classpath;

    /**
     * Path to search for imported scripts.
     *
     * @parameter
     *
     * @noinspection UnusedDeclaration,MismatchedReadAndWriteOfArray
     */
    private File[] scriptpath;

    /**
     * A set of default project properties, which the values will be used only if
     * the project or system does not override.
     *
     * @parameter
     *
     * @noinspection UnusedDeclaration
     */
    private Map defaults;

    /**
     * A set of additional project properties.
     * 
     * @parameter
     *
     * @noinspection UnusedDeclaration
     */
    private Map properties;
    
    /**
     * Trap assertion errors and rethrow them as execution failures.
     *
     * @parameter default-value="true"
     *
     * @noinspection UnusedDeclaration
     */
    private boolean trapAssertionErrors;

    /**
     * Sanatize errors, stripping out Groovy internals.
     *
     * @parameter default-value="true"
     * @since 1.0-beta-3
     *
     * @noinspection UnusedDeclaration
     */
    private boolean sanitizeErrors;

    /**
     * @parameter expression="${session}"
     * @readonly
     * @required
     *
     * @noinspection UnusedDeclaration
     */
    private MavenSession session;
    
    public ExecuteMojo() {
        super(ScriptExecutor.KEY);
    }

    protected List getProjectClasspathElements() throws DependencyResolutionRequiredException {
        return project.getRuntimeClasspathElements();
    }

    protected ArtifactItem[] getUserClassspathElements() {
        return classpath;
    }

    protected void process(final Component component) throws Exception {
        assert component != null;

        ScriptExecutor executor = (ScriptExecutor)component;

        if (source.configuration.getChildCount() != 0) {
            throw new MojoExecutionException("Invalid value for 'source' parameter; contains nested elements");
        }
        
        ClassSource classSource = ClassSource.forValue(source.configuration.getValue());

        // Use the providers class-loader as a parent to resolve the Groovy runtime correctly
        ClassLoader parent = provider().getClass().getClassLoader();

        URLClassLoader classLoader = new URLClassLoader(createClassPath(), parent);

        ResourceLoader resourceLoader = new MojoResourceLoader(classLoader, classSource);

        Configuration context = createContext();

        log.debug("Executing {} w/context: {}", source, context);

        Object result = executor.execute(classSource, classLoader, resourceLoader, context);

        log.debug("Result: {}", result);
    }

    private Configuration createContext() {
        Configuration context = new Configuration();

        // Expose logging, give it a new logger that has better chances of being configured if needed
        // would be nice to get the execution id in here...
        Logger logger = LoggerFactory.getLogger(project.getGroupId() + "." + project.getArtifactId() + ".ExecuteMojo");
        context.set("log", logger);

        // Add a custom project to resolve properties
        MavenProject p = new GroovyMavenProjectAdapter(project, session, properties, defaults);
        context.set("project", p);
        context.set("pom", p);

        // Stuff in an Ant helper
        context.set("ant", MagicAttribute.ANT_BUILDER);

        // Stuff on a fail helper
        context.set("fail", new FailClosure());

        return context;
    }

    //
    // MojoResourceLoader
    //

    private class MojoResourceLoader
        extends ResourceLoaderImpl
    {
        private final ClassSource classSource;

        public MojoResourceLoader(final URLClassLoader classLoader, final ClassSource classSource) {
            super(classLoader);

            assert classSource != null;

            this.classSource = classSource;
        }

        protected URL resolve(final String className, final ClassLoader classLoader) throws MalformedURLException {
            assert className != null;
            assert classLoader != null;

            String resource = toResourceName(className);

            URL url;

            // First check the scriptpath
            if (scriptpath != null) {
                for (int i=0; i




© 2015 - 2025 Weber Informatics LLC | Privacy Policy