net.sourceforge.basher.maven.plugins.BasherMojo Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of maven-basher-plugin Show documentation
Show all versions of maven-basher-plugin Show documentation
A plugin for Maven that enables the running of Basher as part of the normal build cycle.
package net.sourceforge.basher.maven.plugins;
/*
* Copyright 2001-2005 The Apache Software Foundation.
*
* 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.
*/
import java.io.File;
import java.util.*;
import net.sourceforge.basher.BasherContext;
import net.sourceforge.basher.booter.*;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.*;
import org.apache.maven.artifact.resolver.filter.*;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.plugin.*;
import org.apache.maven.project.MavenProject;
import org.apache.maven.surefire.booter.ForkConfiguration;
import org.apache.maven.toolchain.*;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
/**
* Basher main entry point. Mojo will instantiate and run Basher for all tasks registered within the Gaderian registry.
* The original functionality of this plugin was copied from the Maven SureFire plugin.
*
* @goal initiate-run
* @phase test
*/
public class BasherMojo extends AbstractMojo
{
/**
* Base directory where all reports are written to.
*
* @parameter expression="${project.build.directory}/basher-reports"
*/
private File reportsDirectory;
/**
* The plugin remote repositories declared in the pom.
*
* @parameter expression="${project.pluginArtifactRepositories}"
*/
private List remoteRepositories;
/**
* For retrieval of artifact's metadata.
*
* @component
*/
private ArtifactMetadataSource metadataSource;
/**
* Resolves the artifacts needed.
*
* @component
*/
private ArtifactResolver artifactResolver;
/**
* Map of of plugin artifacts.
*
* @parameter expression="${plugin.artifactMap}"
* @required
* @readonly
*/
private Map pluginArtifactMap;
/**
* Creates the artifact
*
* @component
*/
private ArtifactFactory artifactFactory;
/**
* ArtifactRepository of the localRepository. To obtain the directory of localRepository in tasks use
* System.setProperty( "localRepository").
*
* @parameter expression="${localRepository}"
* @required
* @readonly
*/
private ArtifactRepository localRepository;
/**
* Location of the build directory.
*
* @parameter expression="${project.build.outputDirectory}"
* @required
*/
private File classesDirectory;
/**
* Location of the build directory.
*
* @parameter expression="${project.build.testOutputDirectory}"
* @required
*/
private File buildDirectory;
/**
* The classpath elements of the project being tested.
*
* @parameter expression="${project.testClasspathElements}"
* @required
* @readonly
*/
private List classpathElements;
/**
* List of patterns (separated by commas) used to specify the tasks that should be included in the Basher run. When not
* specified and when the task
parameter is not specified, the default includes will be
* **/Task*.java **/*Task.java
.
*
* @parameter
*/
private List includes;
/**
* List of patterns (separated by commas) used to specify the tasks that should be excluded in the Basher run. When not
* specified and when the task
parameter is not specified, the default excludes will be
* **/*$*
(which excludes all inner classes).
*
* @parameter
*/
private List excludes;
/**
* List of System properties to pass to the Basher tasks.
*
* @parameter
*/
private Properties systemProperties;
private Properties originalSystemProperties;
/**
* List of Basher contexts which can be used for a run.
*
* @parameter
*/
private List basherContexts = new ArrayList();
/**
* The profiler to enable. Can be "yourkit" or "none".
*
* Note: Currently not supported.
*
* To enable profiling at the moment,please use the 'argLine' parameter.
*
* @parameter default-value="none"
*/
private String profiler;
/**
* The name of the Basher context to use
*
* @parameter default-value="default"
*/
private String activeBasherContext;
/**
* The Maven Project Object
*
* @parameter expression="${project}"
* @required
* @readonly
*/
protected MavenProject project;
/**
* Option to specify the forking mode. Can be "never" or "once".
*
* @parameter expression="${forkMode}" default-value="once"
*/
private String forkMode;
/**
* Option to specify the jvm (or path to the java executable) to use with the forking options. For the default, the
* jvm will be the same as the one used to run Maven.
*
* @parameter expression="${jvm}"
*/
private String jvm;
/**
* Option to pass dependencies to the system's classloader instead of using an isolated class loader when forking.
* Prevents problems with JDKs which implement the service provider lookup mechanism by using the system's
* classloader. Default value is "true".
*
* @parameter expression="${basher.useSystemClassLoader}"
*/
private Boolean useSystemClassLoader;
/**
* By default, Basher forks your run using a manifest-only jar; set this parameter
* to "false" to force it to launch your Basher run with a plain old Java classpath.
* (See http://maven.apache.org/plugins/maven-surefire-plugin/examples/class-loading.html
* for a more detailed explanation of manifest-only jars and their benefits.)
*
* Default value is "true". Beware, setting this to "false" may cause your tasks to
* fail on Windows if your classpath is too long.
*
* @parameter expression="${basher.useManifestOnlyJar}" default-value="true"
*/
private boolean useManifestOnlyJar;
/**
* Attach a debugger to the forked JVM. If set to "true", the process will suspend and
* wait for a debugger to attach on port 5005. If set to some other string, that
* string will be appended to the argLine, allowing you to configure arbitrary
* debuggability options (without overwriting the other options specified in the argLine).
*
* @parameter expression="${maven.basher.debug}"
*/
private String debugForkedProcess;
/**
* Command line working directory.
*
* @parameter expression="${basedir}"
*/
private File workingDirectory;
/**
* The base directory of the project being used. This can be obtained in your Basher tasks by
* System.getProperty("basedir").
*
* @parameter expression="${basedir}"
* @required
*/
private File basedir;
/**
* Arbitrary JVM options to set on the command line.
*
* @parameter expression="${argLine}"
*/
private String argLine;
/**
* Additional environments to set on the command line.
*
* @parameter
*/
private Map environmentVariables = new HashMap();
/**
* By default, Basher enables JVM assertions for the execution of your tasks. To disable the assertions, set
* this flag to false
.
*
* @parameter expression="${enableAssertions}" default-value="true"
*/
private boolean enableAssertions;
/**
* The current build session instance.
*
* @parameter expression="${session}"
* @required
* @readonly
*/
private MavenSession session;
/** Defines the timeout to use for monitoring a forked of Basher run.
*
*
* @parameter expression="${processTimeOut}" default-value="0"
*/
private int processTimeOut = 0;
public void execute()
throws MojoExecutionException
{
try
{
BasherBooter basherBooter = new BasherBooter();
Artifact basherBooterArtifact = (Artifact) pluginArtifactMap.get("net.sourceforge.basher:basher-booter");
if (basherBooterArtifact == null)
{
throw new MojoExecutionException("Unable to locate basher-booter in the list of plugin artifacts");
}
addArtifact(basherBooter, basherBooterArtifact);
if (!project.getBuild().getOutputDirectory().equals(classesDirectory.getAbsolutePath()))
{
classpathElements.remove(project.getBuild().getOutputDirectory());
classpathElements.add(classesDirectory.getAbsolutePath());
}
if (!project.getBuild().getTestOutputDirectory().equals(buildDirectory.getAbsolutePath()))
{
classpathElements.remove(project.getBuild().getTestOutputDirectory());
classpathElements.add(buildDirectory.getAbsolutePath());
}
for (Iterator i = classpathElements.iterator(); i.hasNext();)
{
String classpathElement = (String) i.next();
getLog().debug(" " + classpathElement);
basherBooter.addClassPathUrl(classpathElement);
}
Toolchain tc = getToolchain();
if (tc != null)
{
getLog().info("Toolchain in basher-plugin: " + tc);
if (ForkConfiguration.FORK_NEVER.equals(forkMode))
{
forkMode = ForkConfiguration.FORK_ONCE;
}
if (jvm != null)
{
getLog().warn("Toolchains are ignored, 'executable' parameter is set to " + jvm);
}
else
{
jvm = tc.findTool("java"); //NOI18N
}
}
/*
if (additionalClasspathElements != null)
{
for (Iterator i = additionalClasspathElements.iterator(); i.hasNext();)
{
String classpathElement = (String) i.next();
getLog().debug(" " + classpathElement);
surefireBooter.addClassPathUrl(classpathElement);
}
}
*/
// ----------------------------------------------------------------------
// Forking
// ----------------------------------------------------------------------
BasherForkConfiguration fork = new BasherForkConfiguration();
fork.setForkMode(forkMode);
processSystemProperties(!fork.isForking());
/*
if (getLog().isDebugEnabled())
{
showMap(systemProperties, "system property");
}
*/
if (fork.isForking())
{
getLog().info("Initiating forking run");
useSystemClassLoader = useSystemClassLoader == null ? Boolean.TRUE : useSystemClassLoader;
fork.setUseSystemClassLoader(useSystemClassLoader.booleanValue());
fork.setUseManifestOnlyJar(useManifestOnlyJar);
fork.setSystemProperties(systemProperties);
if ("true".equals(debugForkedProcess))
{
debugForkedProcess = "-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=5005";
}
fork.setDebugLine(debugForkedProcess);
if (jvm == null || "".equals(jvm))
{
// use the same JVM as the one used to run Maven (the "java.home" one)
jvm = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
getLog().debug("Using JVM: " + jvm);
}
fork.setJvmExecutable(jvm);
if (workingDirectory != null)
{
fork.setWorkingDirectory(workingDirectory);
}
else
{
fork.setWorkingDirectory(basedir);
}
fork.setArgLine(argLine);
fork.setEnvironmentVariables(environmentVariables);
if (getLog().isDebugEnabled())
{
// showMap(environmentVariables, "environment variable");
fork.setDebug(true);
}
if (argLine != null)
{
List args = Arrays.asList(argLine.split(" "));
if (args.contains("-da") || args.contains("-disableassertions"))
{
enableAssertions = false;
}
}
}
basherBooter.setFailIfNoTasks(Boolean.FALSE);
basherBooter.setForkedProcessTimeoutInSeconds(processTimeOut);
basherBooter.setRedirectTasksOutputToFile(false);
basherBooter.setForkConfiguration(fork);
basherBooter.setEnableAssertions(enableAssertions);
basherBooter.setBasherContexts(basherContexts);
basherBooter.setActiveBasherContext(activeBasherContext);
basherBooter.setReportsDirectory(reportsDirectory);
// addReporters(surefireBooter, fork.isForking());
int result = basherBooter.run();
System.out.println("Result: " + result);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private Toolchain getToolchain()
{
Toolchain tc = null;
try
{
if (session != null) //session is null in tests..
{
ToolchainManager toolchainManager = (ToolchainManager) session.getContainer().lookup(ToolchainManager.ROLE);
if (toolchainManager != null)
{
tc = toolchainManager.getToolchainFromBuildContext("jdk", session);
}
}
}
catch (ComponentLookupException componentLookupException)
{
//just ignore, could happen in pre-3.0.9 builds..
}
return tc;
}
protected void processSystemProperties(boolean setInSystem)
{
if (systemProperties == null)
{
systemProperties = new Properties();
}
originalSystemProperties = (Properties) System.getProperties().clone();
// We used to take all of our system properties and dump them in with the
// user specified properties for SUREFIRE-121, causing SUREFIRE-491.
// Not gonna do THAT any more... but I'm leaving this code here in case
// we need it later when we try to fix SUREFIRE-121 again.
// Get the properties from the MavenSession instance to make embedded use work correctly
Properties userSpecifiedProperties = (Properties) session.getExecutionProperties().clone();
userSpecifiedProperties.putAll(systemProperties);
//systemProperties = userSpecifiedProperties;
systemProperties.setProperty("basedir", basedir.getAbsolutePath());
systemProperties.setProperty("user.dir", workingDirectory.getAbsolutePath());
systemProperties.setProperty("localRepository", localRepository.getBasedir());
if (setInSystem)
{
// Add all system properties configured by the user
Iterator iter = systemProperties.keySet().iterator();
while (iter.hasNext())
{
String key = (String) iter.next();
String value = systemProperties.getProperty(key);
System.setProperty(key, value);
}
}
}
private void addArtifact(final BasherBooter basherBooter, final Artifact basherArtifact)
throws ArtifactNotFoundException, ArtifactResolutionException
{
ArtifactResolutionResult result = resolveArtifact(null, basherArtifact);
for (Iterator i = result.getArtifacts().iterator(); i.hasNext();)
{
Artifact artifact = (Artifact) i.next();
getLog().debug("Adding to basher booter classpath: " + artifact.getFile().getAbsolutePath());
basherBooter.addBasherBootClassPathUrl(artifact.getFile().getAbsolutePath());
}
}
private ArtifactResolutionResult resolveArtifact(final Artifact filteredArtifact, Artifact providerArtifact)
throws ArtifactResolutionException, ArtifactNotFoundException
{
ArtifactFilter filter = null;
if (filteredArtifact != null)
{
filter =
new ExcludesArtifactFilter(Collections.singletonList(filteredArtifact.getGroupId() + ":" +
filteredArtifact.getArtifactId()));
}
Artifact originatingArtifact = artifactFactory.createBuildArtifact("dummy", "dummy", "1.0", "jar");
return artifactResolver.resolveTransitively(Collections.singleton(providerArtifact), originatingArtifact,
localRepository, remoteRepositories, metadataSource, filter);
}
}