e : systemProps.entrySet()) {
+ if (e.getValue()==null)
+ throw new IllegalArgumentException("System property "+e.getKey()+" has a null value");
+ System.getProperties().put(e.getKey(), e.getValue());
+ }
+
+ listener.getLogger().println(formatArgs(goals));
+
+ int r = Maven3Main.launch( goals.toArray(new String[goals.size()]));
+
+ // now check the completion status of async ops
+ boolean messageReported = false;
+ long startTime = System.nanoTime();
+ for (Future> f : futures) {
+ try {
+ if(!f.isDone() && !messageReported) {
+ messageReported = true;
+ // FIXME messages
+ listener.getLogger().println("maven builder waiting");
+ }
+ f.get();
+ } catch (InterruptedException e) {
+ // attempt to cancel all asynchronous tasks
+ for (Future> g : futures)
+ g.cancel(true);
+ // FIXME messages
+ listener.getLogger().println("build aborted");
+ return Result.ABORTED;
+ } catch (ExecutionException e) {
+ // FIXME messages
+ e.printStackTrace(listener.error("async build failed"));
+ }
+ }
+ mavenExecutionListener.overheadTime += System.nanoTime()-startTime;
+ futures.clear();
+
+ if(profile) {
+ NumberFormat n = NumberFormat.getInstance();
+ PrintStream logger = listener.getLogger();
+ logger.println("Total overhead was "+format(n,mavenExecutionListener.overheadTime)+"ms");
+ Channel ch = Channel.current();
+ logger.println("Class loading " +format(n,ch.classLoadingTime.get()) +"ms, "+ch.classLoadingCount+" classes");
+ logger.println("Resource loading "+format(n,ch.resourceLoadingTime.get())+"ms, "+ch.resourceLoadingCount+" times");
+ }
+
+ mavenExecutionResult = Maven3Launcher.getMavenExecutionResult();
+
+ PrintStream logger = listener.getLogger();
+ logger.println("Maven3Builder classLoaderDebug");
+ logger.println("getClass().getClassLoader(): " + getClass().getClassLoader());
+
+
+ if(r==0) {
+ logger.print( "r==0" );
+ markAsSuccess = true;
+ }
+
+ if(markAsSuccess) {
+ // FIXME message
+ //listener.getLogger().println(Messages.MavenBuilder_Failed());
+ listener.getLogger().println("success");
+ return Result.SUCCESS;
+ }
+
+ return Result.FAILURE;
+ } catch (NoSuchMethodException e) {
+ throw new IOException2(e);
+ } catch (IllegalAccessException e) {
+ throw new IOException2(e);
+ } catch (InvocationTargetException e) {
+ throw new IOException2(e);
+ } catch (ClassNotFoundException e) {
+ throw new IOException2(e);
+ } catch (Exception e) {
+ throw new IOException2(e);
+ }
+ }
+
+ // since reporters might be from plugins, use the uberjar to resolve them.
+ public ClassLoader getClassLoader() {
+ return Hudson.getInstance().getPluginManager().uberClassLoader;
+ }
+
+
+
+ private static final class MavenExecutionListener extends AbstractExecutionListener implements Serializable, ExecutionListener {
+
+ private final Maven3Builder maven3Builder;
+
+ /**
+ * Number of total nanoseconds {@link Maven3Builder} spent.
+ */
+ long overheadTime;
+
+ public MavenExecutionListener(Maven3Builder listener) {
+ this.maven3Builder = listener;
+ }
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#projectDiscoveryStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void projectDiscoveryStarted( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#sessionStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void sessionStarted( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#sessionEnded(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void sessionEnded( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#projectSkipped(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void projectSkipped( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#projectStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void projectStarted( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println( "projectStarted in MavenExecutionListener "
+ + event.getProject().getGroupId() + ":"
+ + event.getProject().getArtifactId() );
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#projectSucceeded(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void projectSucceeded( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println("projectSucceeded in adapter" );
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#projectFailed(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void projectFailed( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println("projectFailed" );
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#mojoSkipped(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void mojoSkipped( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#mojoStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void mojoStarted( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println("mojoStarted " + event.getMojoExecution().getArtifactId());
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#mojoSucceeded(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void mojoSucceeded( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println("mojoSucceeded " + event.getMojoExecution().getArtifactId());
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#mojoFailed(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void mojoFailed( ExecutionEvent event )
+ {
+ maven3Builder.listener.getLogger().println("mojoFailed " + event.getMojoExecution().getArtifactId());
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkStarted( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkSucceeded(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkSucceeded( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkFailed(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkFailed( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkedProjectStarted(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkedProjectStarted( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkedProjectSucceeded(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkedProjectSucceeded( ExecutionEvent event )
+ {
+
+ }
+
+ /**
+ * @see org.apache.maven.execution.ExecutionListener#forkedProjectFailed(org.apache.maven.execution.ExecutionEvent)
+ */
+ public void forkedProjectFailed( ExecutionEvent event )
+ {
+
+ }
+
+ }
+
+ public static boolean markAsSuccess;
+
+ private static final long serialVersionUID = 1L;
+
+}
diff --git a/maven-plugin/src/main/java/hudson/maven/Maven3ProcessFactory.java b/maven-plugin/src/main/java/hudson/maven/Maven3ProcessFactory.java
new file mode 100644
index 0000000000..429408971c
--- /dev/null
+++ b/maven-plugin/src/main/java/hudson/maven/Maven3ProcessFactory.java
@@ -0,0 +1,396 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi, Olivier Lamy
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package hudson.maven;
+
+import static hudson.Util.fixNull;
+import hudson.AbortException;
+import hudson.EnvVars;
+import hudson.FilePath;
+import hudson.Launcher;
+import hudson.Proc;
+import hudson.model.BuildListener;
+import hudson.model.Computer;
+import hudson.model.Executor;
+import hudson.model.Hudson;
+import hudson.model.JDK;
+import hudson.model.Node;
+import hudson.model.Run.RunnerAbortedException;
+import hudson.model.TaskListener;
+import hudson.remoting.Callable;
+import hudson.remoting.Channel;
+import hudson.remoting.RemoteInputStream;
+import hudson.remoting.RemoteOutputStream;
+import hudson.remoting.SocketInputStream;
+import hudson.remoting.SocketOutputStream;
+import hudson.remoting.Which;
+import hudson.slaves.Channels;
+import hudson.tasks.Maven.MavenInstallation;
+import hudson.util.ArgumentListBuilder;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketTimeoutException;
+import java.util.Arrays;
+import java.util.logging.Logger;
+
+import org.jvnet.hudson.maven3.agent.Maven3Main;
+import org.jvnet.hudson.maven3.launcher.Maven3Launcher;
+import org.kohsuke.stapler.framework.io.IOException2;
+
+/**
+ * @author Olivier Lamy
+ *
+ */
+public class Maven3ProcessFactory implements ProcessCache.Factory
+{
+ private final MavenModuleSet mms;
+ private final Launcher launcher;
+ /**
+ * Environment variables to be set to the maven process.
+ * The same variables are exposed to the system property as well.
+ */
+ private final EnvVars envVars;
+
+ /**
+ * Optional working directory. Because of the process reuse, we can't always guarantee
+ * that the returned Maven process has this as the working directory. But for the
+ * aggregator style build, the process reuse is disabled, so in practice this always works.
+ *
+ * Also, Maven is supposed to work correctly regardless of the process current directory,
+ * so a good behaving maven project shouldn't rely on the current project.
+ */
+ private final FilePath workDir;
+
+ Maven3ProcessFactory(MavenModuleSet mms, Launcher launcher, EnvVars envVars, FilePath workDir) {
+ this.mms = mms;
+ this.launcher = launcher;
+ this.envVars = envVars;
+ this.workDir = workDir;
+ }
+
+ /**
+ * Represents a bi-directional connection.
+ *
+ *
+ * This implementation is remoting aware, so it can be safely sent to the remote callable object.
+ *
+ *
+ * When we run Maven on a slave, the master may not have a direct TCP/IP connectivty to the slave.
+ * That means the {@link Channel} between the master and the Maven needs to be tunneled through
+ * the channel between master and the slave, then go to TCP socket to the Maven.
+ */
+ private static final class Connection implements Serializable {
+ public InputStream in;
+ public OutputStream out;
+
+ Connection(InputStream in, OutputStream out) {
+ this.in = in;
+ this.out = out;
+ }
+
+ private Object writeReplace() {
+ return new Connection(new RemoteInputStream(in),new RemoteOutputStream(out));
+ }
+
+ private Object readResolve() {
+ // ObjectInputStream seems to access data at byte-level and do not do any buffering,
+ // so if we are remoted, buffering would be crucial.
+ this.in = new BufferedInputStream(in);
+ this.out = new BufferedOutputStream(out);
+ return this;
+ }
+
+ private static final long serialVersionUID = 1L;
+ }
+
+ interface Acceptor {
+ Connection accept() throws IOException;
+ int getPort();
+ }
+
+ /**
+ * Opens a server socket and returns {@link Acceptor} so that
+ * we can accept a connection later on it.
+ */
+ private static final class SocketHandler implements Callable {
+ public Acceptor call() throws IOException {
+ return new AcceptorImpl();
+ }
+
+ private static final long serialVersionUID = 1L;
+
+ static final class AcceptorImpl implements Acceptor, Serializable {
+ private transient final ServerSocket serverSocket;
+ private transient Socket socket;
+
+ AcceptorImpl() throws IOException {
+ // open a TCP socket to talk to the launched Maven process.
+ // let the OS pick up a random open port
+ this.serverSocket = new ServerSocket();
+ serverSocket.bind(null); // new InetSocketAddress(InetAddress.getLocalHost(),0));
+ // prevent a hang at the accept method in case the forked process didn't start successfully
+ serverSocket.setSoTimeout(MavenProcessFactory.socketTimeOut);
+ }
+
+ public Connection accept() throws IOException {
+ socket = serverSocket.accept();
+ // we'd only accept one connection
+ serverSocket.close();
+
+ return new Connection(new SocketInputStream(socket),new SocketOutputStream(socket));
+ }
+
+ public int getPort() {
+ return serverSocket.getLocalPort();
+ }
+
+ /**
+ * When sent to the remote node, send a proxy.
+ */
+ private Object writeReplace() {
+ return Channel.current().export(Acceptor.class, this);
+ }
+ }
+ }
+
+ /**
+ * Starts maven process.
+ */
+ public ProcessCache.NewProcess newProcess(BuildListener listener, OutputStream out) throws IOException, InterruptedException {
+ if(MavenProcessFactory.debug)
+ listener.getLogger().println("Using env variables: "+ envVars);
+ try {
+ final Acceptor acceptor = launcher.getChannel().call(new SocketHandler());
+
+ final ArgumentListBuilder cmdLine = buildMavenAgentCmdLine(listener,acceptor.getPort());
+ String[] cmds = cmdLine.toCommandArray();
+ final Proc proc = launcher.launch().cmds(cmds).envs(envVars).stdout(out).pwd(workDir).start();
+
+ Connection con;
+ try {
+ con = acceptor.accept();
+ } catch (SocketTimeoutException e) {
+ // failed to connect. Is the process dead?
+ // if so, the error should have been provided by the launcher already.
+ // so abort gracefully without a stack trace.
+ if(!proc.isAlive())
+ throw new AbortException("Failed to launch Maven. Exit code = "+proc.join());
+ throw e;
+ }
+
+ return new ProcessCache.NewProcess(
+ Channels.forProcess("Channel to Maven "+ Arrays.toString(cmds),
+ Computer.threadPoolForRemoting, new BufferedInputStream(con.in), new BufferedOutputStream(con.out),
+ listener.getLogger(), proc),
+ proc);
+ } catch (IOException e) {
+ if(fixNull(e.getMessage()).contains("java: not found")) {
+ // diagnose issue #659
+ JDK jdk = mms.getJDK();
+ if(jdk==null)
+ throw new IOException2(mms.getDisplayName()+" is not configured with a JDK, but your PATH doesn't include Java",e);
+ }
+ throw e;
+ }
+ }
+
+ /**
+ * Builds the command line argument list to launch the maven process.
+ *
+ */
+ private ArgumentListBuilder buildMavenAgentCmdLine(BuildListener listener,int tcpPort) throws IOException, InterruptedException {
+ MavenInstallation mvn = getMavenInstallation(listener);
+ if(mvn==null) {
+ listener.error("Maven version is not configured for this project. Can't determine which Maven to run");
+ throw new RunnerAbortedException();
+ }
+ if(mvn.getHome()==null) {
+ listener.error("Maven '%s' doesn't have its home set",mvn.getName());
+ throw new RunnerAbortedException();
+ }
+
+ // find classworlds.jar
+ String classWorldsJar = launcher.getChannel().call(new GetClassWorldsJar(mvn.getHome(),listener));
+
+ boolean isMaster = getCurrentNode()== Hudson.getInstance();
+ FilePath slaveRoot=null;
+ if(!isMaster)
+ slaveRoot = getCurrentNode().getRootPath();
+
+ ArgumentListBuilder args = new ArgumentListBuilder();
+ JDK jdk = getJava(listener);
+ if(jdk==null) {
+ args.add("java");
+ } else {
+ args.add(jdk.getHome()+"/bin/java"); // use JDK.getExecutable() here ?
+ }
+
+ if(MavenProcessFactory.debugPort!=0)
+ args.add("-Xrunjdwp:transport=dt_socket,server=y,address="+MavenProcessFactory.debugPort);
+ if(MavenProcessFactory.yjp)
+ args.add("-agentlib:yjpagent=tracing");
+
+ args.addTokenized(getMavenOpts());
+
+ args.add("-cp");
+ args.add(
+ (isMaster? Which.jarFile(Maven3Main.class).getAbsolutePath():slaveRoot.child("maven3-agent.jar").getRemote())+
+ (launcher.isUnix()?":":";")+classWorldsJar);
+ args.add(Maven3Main.class.getName());
+
+ // M2_HOME
+ args.add(mvn.getHome());
+
+ // remoting.jar
+ String remotingJar = launcher.getChannel().call(new GetRemotingJar());
+ if(remotingJar==null) {// this shouldn't be possible, but there are still reports indicating this, so adding a probe here.
+ listener.error("Failed to determine the location of slave.jar");
+ throw new RunnerAbortedException();
+ }
+ args.add(remotingJar);
+
+ args.add(isMaster?
+ Which.jarFile(Maven3Launcher.class).getAbsolutePath():
+ slaveRoot.child("maven3-listener.jar").getRemote());
+
+ // TCP/IP port to establish the remoting infrastructure
+ args.add(tcpPort);
+
+ return args;
+ }
+
+ public String getMavenOpts() {
+ String mavenOpts = mms.getMavenOpts();
+
+ if ((mavenOpts==null) || (mavenOpts.trim().length()==0)) {
+ Node n = getCurrentNode();
+ if (n!=null) {
+ try {
+ String localMavenOpts = n.toComputer().getEnvironment().get("MAVEN_OPTS");
+
+ if ((localMavenOpts!=null) && (localMavenOpts.trim().length()>0)) {
+ mavenOpts = localMavenOpts;
+ }
+ } catch (IOException e) {
+ } catch (InterruptedException e) {
+ // Don't do anything - this just means the slave isn't running, so we
+ // don't want to use its MAVEN_OPTS anyway.
+ }
+
+ }
+ }
+
+ return envVars.expand(mavenOpts);
+ }
+
+ public MavenInstallation getMavenInstallation(TaskListener log) throws IOException, InterruptedException {
+ MavenInstallation mi = mms.getMaven();
+ if (mi != null) mi = mi.forNode(getCurrentNode(), log).forEnvironment(envVars);
+ return mi;
+
+ }
+
+ public JDK getJava(TaskListener log) throws IOException, InterruptedException {
+ JDK jdk = mms.getJDK();
+ if (jdk != null) jdk = jdk.forNode(getCurrentNode(), log).forEnvironment(envVars);
+ return jdk;
+ }
+
+ /**
+ * Finds classworlds.jar
+ */
+ private static final class GetClassWorldsJar implements Callable {
+ private final String mvnHome;
+ private final TaskListener listener;
+
+ private GetClassWorldsJar(String mvnHome, TaskListener listener) {
+ this.mvnHome = mvnHome;
+ this.listener = listener;
+ }
+
+ public String call() throws IOException {
+ File home = new File(mvnHome);
+ if (MavenProcessFactory.debug)
+ listener.getLogger().println("Using mvnHome: "+ mvnHome);
+ File bootDir = new File(home, "boot");
+ File[] classworlds = bootDir.listFiles(CLASSWORLDS_FILTER);
+ if(classworlds==null || classworlds.length==0) {
+ // Maven 2.0.6 puts it to a different place
+ bootDir = new File(home, "boot");
+ classworlds = bootDir.listFiles(CLASSWORLDS_FILTER);
+ if(classworlds==null || classworlds.length==0) {
+ // FIXME use messages
+ //listener.error(Messages.MavenProcessFactory_ClassWorldsNotFound(home));
+ listener.error("classworld not found");
+ throw new RunnerAbortedException();
+ }
+ }
+ return classworlds[0].getAbsolutePath();
+ }
+ }
+
+ private static final class GetRemotingJar implements Callable {
+ public String call() throws IOException {
+ return Which.jarFile(hudson.remoting.Launcher.class).getPath();
+ }
+ }
+
+ /**
+ * Returns the current {@link Node} on which we are buildling.
+ */
+ private Node getCurrentNode() {
+ return Executor.currentExecutor().getOwner().getNode();
+ }
+
+ /**
+ * Locates classworlds jar file.
+ *
+ * Note that Maven 3.0 changed the name to plexus-classworlds
+ *
+ *
+ * $ find tools/ -name "plexus-classworlds*.jar"
+ * tools/maven-3.0-alpha-2/boot/plexus-classworlds-1.3.jar
+ * tools/maven-3.0-alpha-3/boot/plexus-classworlds-2.2.2.jar
+ * tools/maven-3.0-alpha-4/boot/plexus-classworlds-2.2.2.jar
+ * tools/maven-3.0-alpha-5/boot/plexus-classworlds-2.2.2.jar
+ * tools/maven-3.0-alpha-6/boot/plexus-classworlds-2.2.2.jar
+ *
+ */
+ private static final FilenameFilter CLASSWORLDS_FILTER = new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.contains("plexus-classworlds") && name.endsWith(".jar");
+ }
+ };
+
+ private static final Logger LOGGER = Logger.getLogger(MavenProcessFactory.class.getName());
+
+}
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenBuilder.java b/maven-plugin/src/main/java/hudson/maven/MavenBuilder.java
index 958ed55b86..0ff3223544 100644
--- a/maven-plugin/src/main/java/hudson/maven/MavenBuilder.java
+++ b/maven-plugin/src/main/java/hudson/maven/MavenBuilder.java
@@ -25,7 +25,6 @@ package hudson.maven;
import hudson.maven.agent.AbortException;
import hudson.maven.agent.Main;
-import hudson.maven.agent.PluginManagerInterceptor;
import hudson.maven.agent.PluginManagerListener;
import hudson.maven.reporters.SurefireArchiver;
import hudson.model.BuildListener;
@@ -40,6 +39,7 @@ import hudson.util.IOException2;
import java.io.IOException;
import java.io.PrintStream;
import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
@@ -50,14 +50,12 @@ import org.apache.maven.BuildFailureException;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ReactorManager;
import org.apache.maven.lifecycle.LifecycleExecutionException;
-import org.apache.maven.lifecycle.LifecycleExecutorInterceptor;
import org.apache.maven.lifecycle.LifecycleExecutorListener;
import org.apache.maven.monitor.event.EventDispatcher;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.project.MavenProject;
import org.apache.maven.reporting.MavenReport;
-import org.codehaus.classworlds.NoSuchRealmException;
import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
import org.codehaus.plexus.configuration.PlexusConfiguration;
@@ -74,20 +72,8 @@ import org.codehaus.plexus.configuration.PlexusConfiguration;
* @author Kohsuke Kawaguchi
* @since 1.133
*/
-public abstract class MavenBuilder implements DelegatingCallable {
- /**
- * Goals to be executed in this Maven execution.
- */
- private final List goals;
- /**
- * Hudson-defined system properties. These will be made available to Maven,
- * and accessible as if they are specified as -Dkey=value
- */
- private final Map systemProps;
- /**
- * Where error messages and so on are sent.
- */
- protected final BuildListener listener;
+public abstract class MavenBuilder extends AbstractMavenBuilder implements DelegatingCallable {
+
/**
* Flag needs to be set at the constructor, so that this reflects
@@ -102,9 +88,7 @@ public abstract class MavenBuilder implements DelegatingCallable> futures;
protected MavenBuilder(BuildListener listener, List goals, Map systemProps) {
- this.listener = listener;
- this.goals = goals;
- this.systemProps = systemProps;
+ super( listener, goals, systemProps );
}
/**
@@ -147,11 +131,17 @@ public abstract class MavenBuilder implements DelegatingCallable>();
Adapter a = new Adapter(this);
+ // FIXME are we using maven 2 or 3
+ callSetListenerWithReflectOnInterceptors( a );
+
+ /*
PluginManagerInterceptor.setListener(a);
LifecycleExecutorInterceptor.setListener(a);
-
+ */
+
markAsSuccess = false;
// working around NPE when someone puts a null value into systemProps.
@@ -202,46 +192,78 @@ public abstract class MavenBuilder implements DelegatingCallable args) {
- StringBuilder buf = new StringBuilder("Executing Maven: ");
- for (String arg : args) {
- final String argPassword = "-Dpassword=" ;
- String filteredArg = arg ;
- // check if current arg is password arg. Then replace password by *****
- if (arg.startsWith(argPassword)) {
- filteredArg=argPassword+"*********";
- }
- buf.append(' ').append(filteredArg);
+ private void callSetListenerWithReflectOnInterceptors( PluginManagerListener pluginManagerListener )
+ throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
+ IllegalAccessException, InvocationTargetException
+ {
+ Class> pluginManagerInterceptorClazz =
+ Thread.currentThread().getContextClassLoader().loadClass( "hudson.maven.agent.PluginManagerInterceptor" );
+ Method setListenerMethod =
+ pluginManagerInterceptorClazz.getMethod( "setListener",
+ new Class[] { Thread.currentThread().getContextClassLoader().loadClass( "hudson.maven.agent.PluginManagerListener" ) } );
+ setListenerMethod.invoke( null, new Object[] { pluginManagerListener } );
+
+ Class> lifecycleInterceptorClazz =
+ Thread.currentThread().getContextClassLoader().loadClass( "org.apache.maven.lifecycle.LifecycleExecutorInterceptor" );
+
+ setListenerMethod =
+ lifecycleInterceptorClazz.getMethod( "setListener",
+ new Class[] { Thread.currentThread().getContextClassLoader().loadClass( "org.apache.maven.lifecycle.LifecycleExecutorListener" ) } );
+
+ setListenerMethod.invoke( null, new Object[] { pluginManagerListener } );
+ }
+
+ private void callSetListenerWithReflectOnInterceptorsQuietly( PluginManagerListener pluginManagerListener )
+ {
+ try
+ {
+ callSetListenerWithReflectOnInterceptors(pluginManagerListener);
}
- return buf.toString();
- }
+ catch ( SecurityException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ catch ( IllegalArgumentException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ catch ( ClassNotFoundException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ catch ( NoSuchMethodException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ catch ( IllegalAccessException e )
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ catch ( InvocationTargetException e )
+ {
+ throw new RuntimeException( e.getMessage(), e );
+ }
+ }
- private String format(NumberFormat n, long nanoTime) {
- return n.format(nanoTime/1000000);
- }
-
- // since reporters might be from plugins, use the uberjar to resolve them.
- public ClassLoader getClassLoader() {
- return Hudson.getInstance().getPluginManager().uberClassLoader;
- }
/**
* Receives {@link PluginManagerListener} and {@link LifecycleExecutorListener} events
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenComputerListener.java b/maven-plugin/src/main/java/hudson/maven/MavenComputerListener.java
index 5d4c1ed3f8..63796a2dc8 100644
--- a/maven-plugin/src/main/java/hudson/maven/MavenComputerListener.java
+++ b/maven-plugin/src/main/java/hudson/maven/MavenComputerListener.java
@@ -26,8 +26,8 @@ package hudson.maven;
import hudson.Extension;
import hudson.FilePath;
import hudson.maven.agent.Main;
-import hudson.maven.agent.PluginManagerInterceptor;
import hudson.maven.agent.Maven21Interceptor;
+import hudson.maven.agent.PluginManagerInterceptor;
import hudson.model.Computer;
import hudson.model.TaskListener;
import hudson.remoting.Channel;
@@ -38,8 +38,12 @@ import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
-import org.apache.tools.ant.taskdefs.Zip;
+import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.Project;
+import org.apache.tools.ant.taskdefs.Zip;
+import org.codehaus.plexus.classworlds.ClassWorld;
+import org.jvnet.hudson.maven3.agent.Maven3Main;
+import org.jvnet.hudson.maven3.launcher.Maven3Launcher;
/**
* When a slave is connected, copy maven-agent.jar and maven-intercepter.jar
@@ -52,8 +56,13 @@ public class MavenComputerListener extends ComputerListener {
public void preOnline(Computer c, Channel channel,FilePath root, TaskListener listener) throws IOException, InterruptedException {
PrintStream logger = listener.getLogger();
copyJar(logger, root, Main.class, "maven-agent");
+ copyJar(logger, root, Maven3Main.class, "maven3-agent");
+ copyJar(logger, root, Maven3Launcher.class, "maven3-listener");
copyJar(logger, root, PluginManagerInterceptor.class, "maven-interceptor");
copyJar(logger, root, Maven21Interceptor.class, "maven2.1-interceptor");
+ // FIXME not needed
+ copyJar(logger, root, ClassWorld.class, "plexus-classworld");
+ copyJar(logger, root, AntClassLoader.class, "maven-plugin-ant");
}
/**
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java b/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
index 0da7313465..a19f972609 100644
--- a/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
+++ b/maven-plugin/src/main/java/hudson/maven/MavenModuleSetBuild.java
@@ -24,13 +24,29 @@
*/
package hudson.maven;
-import hudson.*;
+import static hudson.model.Result.FAILURE;
+import hudson.AbortException;
+import hudson.EnvVars;
+import hudson.FilePath;
import hudson.FilePath.FileCallable;
+import hudson.Launcher;
+import hudson.Util;
import hudson.maven.MavenBuild.ProxyImpl2;
import hudson.maven.reporters.MavenFingerprinter;
import hudson.maven.reporters.MavenMailer;
-import hudson.model.*;
+import hudson.model.AbstractProject;
+import hudson.model.Action;
+import hudson.model.Build;
+import hudson.model.BuildListener;
import hudson.model.Cause.UpstreamCause;
+import hudson.model.Computer;
+import hudson.model.Environment;
+import hudson.model.Fingerprint;
+import hudson.model.Hudson;
+import hudson.model.ParametersAction;
+import hudson.model.Result;
+import hudson.model.Run;
+import hudson.model.TaskListener;
import hudson.remoting.Channel;
import hudson.remoting.VirtualChannel;
import hudson.scm.ChangeLogSet;
@@ -40,8 +56,30 @@ import hudson.tasks.Maven.MavenInstallation;
import hudson.util.ArgumentListBuilder;
import hudson.util.IOUtils;
import hudson.util.StreamTaskListener;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InterruptedIOException;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.Serializable;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Properties;
+import java.util.Set;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+import org.apache.commons.io.FilenameUtils;
import org.apache.maven.BuildFailureException;
-import org.apache.maven.embedder.MavenEmbedderException;
+import org.apache.maven.artifact.versioning.ComparableVersion;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.execution.ReactorManager;
import org.apache.maven.lifecycle.LifecycleExecutionException;
@@ -50,15 +88,6 @@ import org.apache.maven.project.MavenProject;
import org.apache.maven.project.ProjectBuildingException;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.StaplerResponse;
-import org.apache.commons.io.FilenameUtils;
-
-import java.io.*;
-import java.util.*;
-import java.util.Map.Entry;
-import java.util.logging.Level;
-import java.util.logging.Logger;
-
-import static hudson.model.Result.FAILURE;
/**
* {@link Build} for {@link MavenModuleSet}.
@@ -371,6 +400,7 @@ public class MavenModuleSetBuild extends AbstractMavenBuild= 0;
+
+ if (maven3orLater)
+ {
+ LOGGER.info( "using maven 3 " + mavenVersion );
+ process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener,
+ new Maven3ProcessFactory(project,launcher,envVars,pom.getParent()));
+ } else
+ {
+ process = MavenBuild.mavenProcessCache.get(launcher.getChannel(), slistener,
new MavenProcessFactory(project,launcher,envVars,pom.getParent()));
-
+ }
ArgumentListBuilder margs = new ArgumentListBuilder().add("-B").add("-f", pom.getRemote());
if(project.usesPrivateRepository())
margs.add("-Dmaven.repo.local="+getWorkspace().child(".repository"));
@@ -471,18 +515,34 @@ public class MavenModuleSetBuild extends AbstractMavenBuild e = cl.getResources("META-INF/plexus/components.xml");
- while (e.hasMoreElements()) {
- URL url = e.nextElement();
- LOGGER.fine("components.xml from "+url);
- }
- }
+
+
+ MavenRequest mavenRequest = new MavenRequest();
+
// make sure ~/.m2 exists to avoid http://www.nabble.com/BUG-Report-tf3401736.html
File m2Home = new File(MavenEmbedder.userHome, ".m2");
m2Home.mkdirs();
@@ -170,15 +159,41 @@ public class MavenUtil {
"\nSee https://hudson.dev.java.net/cannot-create-.m2.html");
if (privateRepository!=null)
- maven.setLocalRepositoryDirectory(new File(privateRepository));
+ mavenRequest.setLocalRepositoryPath( privateRepository);
- maven.setProfiles(profiles);
+ if (profiles != null)
+ {
+ mavenRequest.setProfiles(Arrays.asList( StringUtils.split( profiles, "," ) ));
+ }
+
if (alternateSettings!=null)
- maven.setAlternateSettings(alternateSettings);
+ mavenRequest.setUserSettingsFile( alternateSettings.getAbsolutePath() );
- maven.setSystemProperties(systemProperties);
- maven.start();
+ // TODO olamy check this sould be userProperties
+ mavenRequest.setSystemProperties(systemProperties);
+
+
+ EmbedderLoggerImpl logger =
+ new EmbedderLoggerImpl( listener, debugMavenEmbedder ? org.codehaus.plexus.logging.Logger.LEVEL_DEBUG
+ : org.codehaus.plexus.logging.Logger.LEVEL_INFO );
+ mavenRequest.setMavenLoggerManager( logger );
+
+ ClassLoader cl = MavenUtil.class.getClassLoader();
+
+ // TODO check this MaskingClassLoader with maven 3 artifacts
+ MavenEmbedder maven = new MavenEmbedder( new MaskingClassLoader(cl), mavenRequest );
+
+
+ {
+ Enumeration e = cl.getResources("META-INF/plexus/components.xml");
+ while (e.hasMoreElements()) {
+ URL url = e.nextElement();
+ LOGGER.fine("components.xml from "+url);
+ }
+ }
+
+
return maven;
}
@@ -198,11 +213,12 @@ public class MavenUtil {
*
* @throws AbortException
* errors will be reported to the listener and the exception thrown.
+ * @throws MavenEmbedderException
*/
public static void resolveModules(MavenEmbedder embedder, MavenProject project,
String rel, Map relativePathInfo,
BuildListener listener, boolean nonRecursive) throws ProjectBuildingException,
- AbortException {
+ AbortException, MavenEmbedderException {
File basedir = project.getFile().getParentFile();
relativePathInfo.put(project,rel);
diff --git a/maven-plugin/src/main/java/hudson/maven/MavenVersionCallable.java b/maven-plugin/src/main/java/hudson/maven/MavenVersionCallable.java
new file mode 100644
index 0000000000..ef8238617b
--- /dev/null
+++ b/maven-plugin/src/main/java/hudson/maven/MavenVersionCallable.java
@@ -0,0 +1,63 @@
+package hudson.maven;
+
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2010, Sun Microsystems, Inc. Olivier Lamy
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+
+import hudson.remoting.Callable;
+
+import java.io.File;
+import java.io.IOException;
+
+import org.kohsuke.stapler.framework.io.IOException2;
+
+/**
+ *
+ * @author Olivier Lamy
+ *
+ */
+public class MavenVersionCallable
+ implements Callable
+{
+
+ private final String mavenHome;
+
+ public MavenVersionCallable( String mavenHome )
+ {
+ this.mavenHome = mavenHome;
+ }
+
+ public String call()
+ throws IOException
+ {
+ try
+ {
+ return MavenEmbedderUtils.getMavenVersion( new File(mavenHome) );
+ }
+ catch ( MavenEmbedderException e )
+ {
+ throw new IOException2( e );
+ }
+ }
+
+}
diff --git a/maven-plugin/src/main/java/hudson/maven/MojoInfo.java b/maven-plugin/src/main/java/hudson/maven/MojoInfo.java
index a46a2ba0dc..06e4ac41f5 100644
--- a/maven-plugin/src/main/java/hudson/maven/MojoInfo.java
+++ b/maven-plugin/src/main/java/hudson/maven/MojoInfo.java
@@ -126,13 +126,13 @@ public class MojoInfo {
public T getConfigurationValue(String configName, Class type) throws ComponentConfigurationException {
PlexusConfiguration child = configuration.getChild(configName);
if(child==null) return null; // no such config
-
+
ConfigurationConverter converter = converterLookup.lookupConverterForType(type);
return type.cast(converter.fromConfiguration(converterLookup,child,type,
// the implementation seems to expect the type of the bean for which the configuration is done
// in this parameter, but we have no such type. So passing in a dummy
Object.class,
- mojoExecution.getMojoDescriptor().getPluginDescriptor().getClassRealm().getClassLoader(),
+ mojoExecution.getMojoDescriptor().getPluginDescriptor().getClassRealm(),
expressionEvaluator));
}
diff --git a/maven-plugin/src/main/java/hudson/maven/RedeployPublisher.java b/maven-plugin/src/main/java/hudson/maven/RedeployPublisher.java
index 27574971ff..cfffe57972 100644
--- a/maven-plugin/src/main/java/hudson/maven/RedeployPublisher.java
+++ b/maven-plugin/src/main/java/hudson/maven/RedeployPublisher.java
@@ -23,8 +23,8 @@
*/
package hudson.maven;
-import hudson.Launcher;
import hudson.Extension;
+import hudson.Launcher;
import hudson.Util;
import hudson.maven.reporters.MavenAbstractArtifactRecord;
import hudson.model.AbstractBuild;
@@ -32,22 +32,23 @@ import hudson.model.AbstractProject;
import hudson.model.BuildListener;
import hudson.model.Result;
import hudson.tasks.BuildStepDescriptor;
+import hudson.tasks.BuildStepMonitor;
import hudson.tasks.Publisher;
import hudson.tasks.Recorder;
-import hudson.tasks.BuildStepMonitor;
import hudson.util.FormValidation;
+
+import java.io.IOException;
+
import net.sf.json.JSONObject;
+
import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
-import org.apache.maven.embedder.MavenEmbedderException;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.kohsuke.stapler.DataBoundConstructor;
-import org.kohsuke.stapler.StaplerRequest;
-
-import java.io.IOException;
import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
/**
* {@link Publisher} for {@link MavenModuleSetBuild} to deploy artifacts
@@ -108,7 +109,7 @@ public class RedeployPublisher extends Recorder {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener,build);
ArtifactRepositoryLayout layout =
- (ArtifactRepositoryLayout) embedder.getContainer().lookup( ArtifactRepositoryLayout.ROLE,"default");
+ (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.ROLE,"default");
ArtifactRepositoryFactory factory =
(ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE);
@@ -117,7 +118,6 @@ public class RedeployPublisher extends Recorder {
mar.deploy(embedder,repository,listener);
- embedder.stop();
return true;
} catch (MavenEmbedderException e) {
e.printStackTrace(listener.error(e.getMessage()));
diff --git a/maven-plugin/src/main/java/hudson/maven/reporters/MavenAbstractArtifactRecord.java b/maven-plugin/src/main/java/hudson/maven/reporters/MavenAbstractArtifactRecord.java
index f1e138d6a2..53725b8cec 100644
--- a/maven-plugin/src/main/java/hudson/maven/reporters/MavenAbstractArtifactRecord.java
+++ b/maven-plugin/src/main/java/hudson/maven/reporters/MavenAbstractArtifactRecord.java
@@ -25,34 +25,23 @@ package hudson.maven.reporters;
import hudson.console.AnnotatedLargeText;
import hudson.maven.MavenEmbedder;
+import hudson.maven.MavenEmbedderException;
import hudson.maven.MavenUtil;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.BallColor;
+import hudson.model.BuildBadgeAction;
import hudson.model.Result;
import hudson.model.TaskAction;
import hudson.model.TaskListener;
import hudson.model.TaskThread;
-import hudson.model.BuildBadgeAction;
import hudson.model.TaskThread.ListenerAndText;
-import hudson.security.Permission;
import hudson.security.ACL;
+import hudson.security.Permission;
import hudson.util.Iterators;
import hudson.widgets.HistoryWidget;
import hudson.widgets.HistoryWidget.Adapter;
-import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
-import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
-import org.apache.maven.embedder.MavenEmbedderException;
-import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
-import org.kohsuke.stapler.QueryParameter;
-import org.kohsuke.stapler.StaplerRequest;
-import org.kohsuke.stapler.StaplerResponse;
-import org.kohsuke.stapler.HttpResponse;
-import org.kohsuke.stapler.HttpRedirect;
-import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
@@ -60,6 +49,19 @@ import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.concurrent.CopyOnWriteArrayList;
+import javax.servlet.ServletException;
+
+import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.apache.maven.artifact.repository.ArtifactRepositoryFactory;
+import org.apache.maven.artifact.repository.layout.ArtifactRepositoryLayout;
+import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
+import org.kohsuke.stapler.HttpRedirect;
+import org.kohsuke.stapler.HttpResponse;
+import org.kohsuke.stapler.QueryParameter;
+import org.kohsuke.stapler.StaplerRequest;
+import org.kohsuke.stapler.StaplerResponse;
+
/**
* UI to redeploy artifacts after the fact.
*
@@ -204,7 +206,7 @@ public abstract class MavenAbstractArtifactRecord>
try {
MavenEmbedder embedder = MavenUtil.createEmbedder(listener,getBuild());
ArtifactRepositoryLayout layout =
- (ArtifactRepositoryLayout) embedder.getContainer().lookup( ArtifactRepositoryLayout.ROLE,"default");
+ (ArtifactRepositoryLayout) embedder.lookup( ArtifactRepositoryLayout.class,"default");
ArtifactRepositoryFactory factory =
(ArtifactRepositoryFactory) embedder.lookup(ArtifactRepositoryFactory.ROLE);
@@ -213,7 +215,6 @@ public abstract class MavenAbstractArtifactRecord>
deploy(embedder,repository,listener);
- embedder.stop();
record.result = Result.SUCCESS;
} finally {
if(record.result==null)
diff --git a/maven-plugin/src/main/java/hudson/maven/reporters/MavenAggregatedArtifactRecord.java b/maven-plugin/src/main/java/hudson/maven/reporters/MavenAggregatedArtifactRecord.java
index 4d91d08d05..03840985f1 100644
--- a/maven-plugin/src/main/java/hudson/maven/reporters/MavenAggregatedArtifactRecord.java
+++ b/maven-plugin/src/main/java/hudson/maven/reporters/MavenAggregatedArtifactRecord.java
@@ -26,20 +26,21 @@ package hudson.maven.reporters;
import hudson.maven.MavenAggregatedReport;
import hudson.maven.MavenBuild;
import hudson.maven.MavenEmbedder;
+import hudson.maven.MavenEmbedderException;
import hudson.maven.MavenModule;
import hudson.maven.MavenModuleSet;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Action;
import hudson.model.TaskListener;
-import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
-import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.embedder.MavenEmbedderException;
-import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import java.io.IOException;
import java.util.List;
import java.util.Map;
+import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
+import org.apache.maven.artifact.repository.ArtifactRepository;
+import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
+
/**
* Redeploy action for the entire {@link MavenModuleSetBuild}.
*
diff --git a/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifact.java b/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifact.java
index 0232687390..de8a7ac26f 100644
--- a/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifact.java
+++ b/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifact.java
@@ -36,11 +36,14 @@ import org.apache.maven.artifact.handler.ArtifactHandler;
import org.apache.maven.artifact.handler.DefaultArtifactHandler;
import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
+import com.google.common.collect.Maps;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
+import java.util.Map;
import java.util.logging.Logger;
/**
@@ -145,14 +148,14 @@ public final class MavenArtifact implements Serializable {
// in the repository during deployment. So simulate that behavior if that's necessary.
final String canonicalExtension = canonicalName.substring(canonicalName.lastIndexOf('.')+1);
ArtifactHandler ah = handlerManager.getArtifactHandler(type);
- // Fix for HUDSON-3814 - changed from comparing against canonical extension to canonicalName.endsWith.
- if(!canonicalName.endsWith(ah.getExtension())) {
- handlerManager.addHandlers(Collections.singletonMap(type,
- new DefaultArtifactHandler(type) {
+ Map handlers = Maps.newHashMap();
+ handlers.put( type, new DefaultArtifactHandler(type) {
public String getExtension() {
return canonicalExtension;
- }
- }));
+ } } );
+ // Fix for HUDSON-3814 - changed from comparing against canonical extension to canonicalName.endsWith.
+ if(!canonicalName.endsWith(ah.getExtension())) {
+ handlerManager.addHandlers(handlers);
}
Artifact a = factory.createArtifactWithClassifier(groupId, artifactId, version, type, classifier);
diff --git a/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifactRecord.java b/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifactRecord.java
index c6b5eec860..b82e8a1b19 100644
--- a/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifactRecord.java
+++ b/maven-plugin/src/main/java/hudson/maven/reporters/MavenArtifactRecord.java
@@ -27,10 +27,17 @@ import hudson.maven.AggregatableAction;
import hudson.maven.MavenAggregatedReport;
import hudson.maven.MavenBuild;
import hudson.maven.MavenEmbedder;
+import hudson.maven.MavenEmbedderException;
import hudson.maven.MavenModule;
import hudson.maven.MavenModuleSetBuild;
import hudson.model.Action;
import hudson.model.TaskListener;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.util.List;
+import java.util.Map;
+
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.deployer.ArtifactDeployer;
import org.apache.maven.artifact.deployer.ArtifactDeploymentException;
@@ -39,15 +46,9 @@ import org.apache.maven.artifact.handler.manager.ArtifactHandlerManager;
import org.apache.maven.artifact.installer.ArtifactInstallationException;
import org.apache.maven.artifact.installer.ArtifactInstaller;
import org.apache.maven.artifact.repository.ArtifactRepository;
-import org.apache.maven.embedder.MavenEmbedderException;
import org.apache.maven.project.artifact.ProjectArtifactMetadata;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
-import java.io.IOException;
-import java.io.PrintStream;
-import java.util.List;
-import java.util.Map;
-
/**
* {@link Action} that remembers {@link MavenArtifact artifact}s that are built.
*
@@ -105,9 +106,9 @@ public class MavenArtifactRecord extends MavenAbstractArtifactRecord
@Override
public void deploy(MavenEmbedder embedder, ArtifactRepository deploymentRepository, TaskListener listener) throws MavenEmbedderException, IOException, ComponentLookupException, ArtifactDeploymentException {
- ArtifactHandlerManager handlerManager = (ArtifactHandlerManager) embedder.lookup(ArtifactHandlerManager.ROLE);
- ArtifactDeployer deployer = (ArtifactDeployer) embedder.lookup(ArtifactDeployer.ROLE);
- ArtifactFactory factory = (ArtifactFactory) embedder.lookup(ArtifactFactory.ROLE);
+ ArtifactHandlerManager handlerManager = embedder.lookup(ArtifactHandlerManager.class);
+ ArtifactDeployer deployer = embedder.lookup(ArtifactDeployer.class);
+ ArtifactFactory factory = embedder.lookup(ArtifactFactory.class);
PrintStream logger = listener.getLogger();
Artifact main = mainArtifact.toArtifact(handlerManager,factory,parent);
@@ -129,9 +130,9 @@ public class MavenArtifactRecord extends MavenAbstractArtifactRecord
* Installs the artifact to the local Maven repository.
*/
public void install(MavenEmbedder embedder) throws MavenEmbedderException, IOException, ComponentLookupException, ArtifactInstallationException {
- ArtifactHandlerManager handlerManager = (ArtifactHandlerManager) embedder.lookup(ArtifactHandlerManager.ROLE);
- ArtifactInstaller installer = (ArtifactInstaller) embedder.lookup(ArtifactInstaller.class.getName());
- ArtifactFactory factory = (ArtifactFactory) embedder.lookup(ArtifactFactory.class.getName());
+ ArtifactHandlerManager handlerManager = embedder.lookup(ArtifactHandlerManager.class);
+ ArtifactInstaller installer = embedder.lookup(ArtifactInstaller.class);
+ ArtifactFactory factory = embedder.lookup(ArtifactFactory.class);
Artifact main = mainArtifact.toArtifact(handlerManager,factory,parent);
if(!isPOM())
diff --git a/maven3-agent/.gitignore b/maven3-agent/.gitignore
new file mode 100755
index 0000000000..e92bb49fdd
--- /dev/null
+++ b/maven3-agent/.gitignore
@@ -0,0 +1,5 @@
+.settings
+.project
+target
+.classpath
+build
diff --git a/maven3-agent/pom.xml b/maven3-agent/pom.xml
new file mode 100755
index 0000000000..70fc9f1efb
--- /dev/null
+++ b/maven3-agent/pom.xml
@@ -0,0 +1,37 @@
+
+
+ 4.0.0
+
+ org.jvnet.hudson.main
+ pom
+ 1.381-SNAPSHOT
+
+ maven3-agent
+ maven3-agent
+
+
+ org.jvnet.hudson.main
+ maven3-listener
+ provided
+ ${project.version}
+
+
+ org.apache.maven
+ maven-embedder
+
+
+ org.codehaus.plexus
+ plexus-classworlds
+
+
+ org.sonatype.sisu
+ sisu-inject-plexus
+
+
+ junit
+ junit
+ test
+
+
+
diff --git a/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/Maven3Main.java b/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/Maven3Main.java
new file mode 100755
index 0000000000..b90b305003
--- /dev/null
+++ b/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/Maven3Main.java
@@ -0,0 +1,177 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.jvnet.hudson.maven3.agent;
+
+import java.io.BufferedInputStream;
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import org.codehaus.plexus.classworlds.launcher.Launcher;
+import org.codehaus.plexus.classworlds.realm.ClassRealm;
+
+
+
+/**
+ * Entry point for launching Maven 3 and Hudson remoting in the same VM, in the
+ * classloader layout that Maven expects.
+ *
+ *
+ * The actual Maven execution will be started by the program sent through
+ * remoting.
+ *
+ *
+ * @author Kohsuke Kawaguchi
+ * @author Olivier Lamy
+ */
+public class Maven3Main {
+ /**
+ * Used to pass the classworld instance to the code running inside the
+ * remoting system.
+ */
+ private static Launcher launcher;
+
+ public static void main(String[] args) throws Exception {
+ main(new File(args[0]), new File(args[1]),new File(args[2]),
+ Integer.parseInt(args[3]));
+ }
+
+ /**
+ *
+ * @param m2Home
+ * Maven2 installation. This is where we find Maven jars that
+ * we'll run.
+ * @param remotingJar
+ * Hudson's remoting.jar that we'll load.
+ * @param listenerJar
+ * maven-listener.jar that we'll load.
+ * @param tcpPort
+ * TCP socket that the launching Hudson will be listening to.
+ * This is used for the remoting communication.
+ * @param projectBuildLaunch
+ * launch the projectBuilder and not a mavenExecution
+ */
+ public static void main(File m2Home, File remotingJar, File listenerJar,
+ int tcpPort) throws Exception {
+ // Unix master with Windows slave ends up passing path in Unix format,
+ // so convert it to Windows format now so that no one chokes with the
+ // path format later.
+ try {
+ m2Home = m2Home.getCanonicalFile();
+ } catch (IOException e) {
+ // ignore. We'll check the error later if m2Home exists anyway
+ }
+
+ if (!m2Home.exists()) {
+ System.err.println("No such directory exists: " + m2Home);
+ System.exit(1);
+ }
+
+ versionCheck();
+
+ // expose variables used in the classworlds configuration
+ System.setProperty("maven.home", m2Home.getPath());
+ System.setProperty("maven3.listener", (listenerJar != null ? listenerJar
+ : listenerJar).getPath());
+
+ // load the default realms
+ launcher = new Launcher();
+ launcher.setSystemClassLoader(Maven3Main.class.getClassLoader());
+ launcher.configure(Maven3Main.class
+ .getResourceAsStream("classworlds.conf"));
+
+
+ // create a realm for loading remoting subsystem.
+ // this needs to be able to see maven.
+ ClassRealm remoting = launcher.getWorld().newRealm( "hudson-remoting", launcher.getSystemClassLoader() );
+ remoting.setParentRealm(launcher.getWorld().getRealm("plexus.core"));
+ remoting.addURL(remotingJar.toURI().toURL());
+
+ final Socket s = new Socket((String) null, tcpPort);
+
+ Class remotingLauncher = remoting.loadClass("hudson.remoting.Launcher");
+ remotingLauncher.getMethod("main",
+ new Class[] { InputStream.class, OutputStream.class }).invoke(
+ null,
+ new Object[] {
+ // do partial close, since socket.getInputStream and
+ // getOutputStream doesn't do it by
+ new BufferedInputStream(new FilterInputStream(s
+ .getInputStream()) {
+ public void close() throws IOException {
+ s.shutdownInput();
+ }
+ }),
+ new BufferedOutputStream(new RealFilterOutputStream(s
+ .getOutputStream()) {
+ public void close() throws IOException {
+ s.shutdownOutput();
+ }
+ }) });
+ System.exit(0);
+ }
+
+ /**
+ * Called by the code in remoting to launch.
+ */
+ public static int launch(String[] args) throws Exception {
+
+ try {
+ launcher.launch(args);
+ } catch (Throwable e)
+ {
+ e.printStackTrace();
+ throw new Exception( e );
+ }
+ return launcher.getExitCode();
+ }
+
+ /**
+ * Makes sure that this is Java5 or later.
+ */
+ private static void versionCheck() {
+ String v = System.getProperty("java.class.version");
+ if (v != null) {
+ try {
+ if (Float.parseFloat(v) < 49.0) {
+ System.err
+ .println("Native maven support requires Java 1.5 or later, but this Maven is using "
+ + System.getProperty("java.home"));
+ System.err.println("Please use the freestyle project.");
+ System.exit(1);
+ }
+ } catch (NumberFormatException e) {
+ // couldn't check.
+ }
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/RealFilterOutputStream.java b/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/RealFilterOutputStream.java
new file mode 100755
index 0000000000..3cbc7f7662
--- /dev/null
+++ b/maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/RealFilterOutputStream.java
@@ -0,0 +1,51 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.jvnet.hudson.maven3.agent;
+
+import java.io.OutputStream;
+import java.io.IOException;
+import java.io.FilterOutputStream;
+
+/**
+ * JDK's {@link FilterOutputStream} has some real issues.
+ *
+ * @author Kohsuke Kawaguchi
+ */
+class RealFilterOutputStream extends FilterOutputStream {
+ public RealFilterOutputStream(OutputStream core) {
+ super(core);
+ }
+
+ public void write(byte[] b) throws IOException {
+ out.write(b);
+ }
+
+ public void write(byte[] b, int off, int len) throws IOException {
+ out.write(b, off, len);
+ }
+
+ public void close() throws IOException {
+ out.close();
+ }
+}
diff --git a/maven3-agent/src/main/resources/org/jvnet/hudson/maven3/agent/classworlds.conf b/maven3-agent/src/main/resources/org/jvnet/hudson/maven3/agent/classworlds.conf
new file mode 100755
index 0000000000..e2d3b6a041
--- /dev/null
+++ b/maven3-agent/src/main/resources/org/jvnet/hudson/maven3/agent/classworlds.conf
@@ -0,0 +1,11 @@
+#
+# mostly copied as-is from $MAVEN_HOME/bin/m2.conf
+#
+#main is org.apache.maven.cli.MavenCli from plexus.core.maven
+main is org.jvnet.hudson.maven3.launcher.Maven3Launcher from plexus.core
+
+set maven.home default ${user.home}/m2
+
+[plexus.core]
+load ${maven3.listener}
+load ${maven.home}/lib/*.jar
\ No newline at end of file
diff --git a/maven3-listener/.gitignore b/maven3-listener/.gitignore
new file mode 100755
index 0000000000..e92bb49fdd
--- /dev/null
+++ b/maven3-listener/.gitignore
@@ -0,0 +1,5 @@
+.settings
+.project
+target
+.classpath
+build
diff --git a/maven3-listener/pom.xml b/maven3-listener/pom.xml
new file mode 100755
index 0000000000..1d8cfe5a23
--- /dev/null
+++ b/maven3-listener/pom.xml
@@ -0,0 +1,55 @@
+
+
+ 4.0.0
+
+ org.jvnet.hudson.main
+ pom
+ 1.381-SNAPSHOT
+
+ maven3-listener
+ maven3-listener
+
+
+
+ org.apache.maven
+ maven-core
+
+
+ org.apache.maven
+ maven-embedder
+
+
+ org.apache.maven
+ maven-aether-provider
+
+
+
+ org.sonatype.sisu
+ sisu-inject-plexus
+
+
+
+ junit
+ junit
+ test
+
+
+
+
+
+
+ org.codehaus.plexus
+ plexus-component-metadata
+ 1.5.4
+
+
+
+ generate-metadata
+
+
+
+
+
+
+
diff --git a/maven3-listener/src/main/java/org/apache/maven/cli/DefaultMavenExecutionRequestBuilder.java b/maven3-listener/src/main/java/org/apache/maven/cli/DefaultMavenExecutionRequestBuilder.java
new file mode 100755
index 0000000000..84ac396200
--- /dev/null
+++ b/maven3-listener/src/main/java/org/apache/maven/cli/DefaultMavenExecutionRequestBuilder.java
@@ -0,0 +1,792 @@
+package org.apache.maven.cli;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.io.FileNotFoundException;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import java.util.StringTokenizer;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.ParseException;
+import org.apache.maven.execution.DefaultMavenExecutionRequest;
+import org.apache.maven.execution.MavenExecutionRequest;
+import org.apache.maven.execution.MavenExecutionRequestPopulationException;
+import org.apache.maven.execution.MavenExecutionRequestPopulator;
+import org.apache.maven.lifecycle.internal.LifecycleWeaveBuilder;
+import org.apache.maven.model.building.ModelProcessor;
+import org.apache.maven.properties.internal.EnvironmentUtils;
+import org.apache.maven.repository.internal.MavenRepositorySystemSession;
+import org.apache.maven.settings.building.DefaultSettingsBuildingRequest;
+import org.apache.maven.settings.building.SettingsBuilder;
+import org.apache.maven.settings.building.SettingsBuildingException;
+import org.apache.maven.settings.building.SettingsBuildingRequest;
+import org.apache.maven.settings.building.SettingsBuildingResult;
+import org.apache.maven.settings.building.SettingsProblem;
+import org.codehaus.plexus.PlexusContainer;
+import org.codehaus.plexus.classworlds.ClassWorld;
+import org.codehaus.plexus.component.annotations.Component;
+import org.codehaus.plexus.component.annotations.Requirement;
+import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
+import org.codehaus.plexus.logging.Logger;
+import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable;
+import org.codehaus.plexus.personality.plexus.lifecycle.phase.InitializationException;
+import org.codehaus.plexus.util.StringUtils;
+import org.sonatype.aether.impl.internal.EnhancedLocalRepositoryManager;
+import org.sonatype.aether.transfer.TransferListener;
+import org.sonatype.plexus.components.cipher.DefaultPlexusCipher;
+import org.sonatype.plexus.components.sec.dispatcher.DefaultSecDispatcher;
+import org.sonatype.plexus.components.sec.dispatcher.SecDispatcher;
+import org.sonatype.plexus.components.sec.dispatcher.SecUtil;
+import org.sonatype.plexus.components.sec.dispatcher.model.SettingsSecurity;
+
+/**
+ * Most of code is coming from asf svn repo waiting before having available
+ * @author Olivier Lamy
+ * @since
+ */
+@Component( role = MavenExecutionRequestBuilder.class)
+public class DefaultMavenExecutionRequestBuilder
+ implements MavenExecutionRequestBuilder, Initializable
+{
+
+ @Requirement
+ private SettingsBuilder settingsBuilder;
+
+ @Requirement
+ private MavenExecutionRequestPopulator executionRequestPopulator;
+
+ @Requirement
+ private Logger plexusLogger;
+
+ @Requirement
+ private ModelProcessor modelProcessor;
+
+ @Requirement
+ private PlexusContainer plexusContainer;
+
+ private DefaultSecDispatcher dispatcher;
+
+ public void initialize()
+ throws InitializationException
+ {
+ try
+ {
+ dispatcher = (DefaultSecDispatcher) plexusContainer.lookup( SecDispatcher.class, "maven" );
+ }
+ catch ( ComponentLookupException e )
+ {
+ throw new InitializationException( e.getMessage(), e );
+ }
+ }
+
+ /**
+ * @throws MavenExecutionRequestPopulationException
+ * @see org.jvnet.hudson.maven3.MavenExecutionRequestBuilder.MavenExecutionRequestsBuilder#getMavenExecutionRequest(java.lang.String[])
+ */
+ public MavenExecutionRequest getMavenExecutionRequest( String[] args, PrintStream printStream )
+ throws MavenExecutionRequestPopulationException, SettingsBuildingException,
+ MavenExecutionRequestsBuilderException
+ {
+ try
+ {
+ CliRequest cliRequest = new CliRequest( args, null );
+ initialize( cliRequest, printStream );
+ // Need to process cli options first to get possible logging options
+ cli( cliRequest );
+ logging( cliRequest );
+ commands( cliRequest );
+ properties( cliRequest );
+ // we are in a container so no need
+ //container( cliRequest );
+ settings( cliRequest );
+ populateRequest( cliRequest );
+ encryption( cliRequest );
+
+ MavenExecutionRequest request = executionRequestPopulator.populateDefaults( cliRequest.request );
+
+ // TODO move this in ASF sources ?
+
+ if (request.getProjectBuildingRequest().getRepositorySession()== null)
+ {
+ MavenRepositorySystemSession session = new MavenRepositorySystemSession();
+ if (session.getLocalRepositoryManager() == null)
+ {
+ session.setLocalRepositoryManager( new EnhancedLocalRepositoryManager( request.getLocalRepositoryPath() ) );
+ }
+ request.getProjectBuildingRequest().setRepositorySession( session );
+ }
+
+ return request;
+ }
+ catch ( Exception e )
+ {
+ throw new MavenExecutionRequestsBuilderException( e.getMessage(), e );
+ }
+
+ }
+
+ static File resolveFile( File file, String workingDirectory )
+ {
+ if ( file == null )
+ {
+ return null;
+ }
+ else if ( file.isAbsolute() )
+ {
+ return file;
+ }
+ else if ( file.getPath().startsWith( File.separator ) )
+ {
+ // drive-relative Windows path
+ return file.getAbsoluteFile();
+ }
+ else
+ {
+ return new File( workingDirectory, file.getPath() ).getAbsoluteFile();
+ }
+ }
+
+ private void initialize( CliRequest cliRequest, PrintStream printStream )
+ {
+ if ( cliRequest.stdout == null )
+ {
+ cliRequest.stdout = System.out;
+ }
+ if ( cliRequest.stderr == null )
+ {
+ cliRequest.stderr = System.err;
+ }
+
+ if ( cliRequest.logger == null )
+ {
+ cliRequest.logger = new PrintStreamLogger( cliRequest.stdout );
+ }
+ else
+ {
+ cliRequest.logger.setStream( cliRequest.stdout );
+ }
+
+ if ( cliRequest.workingDirectory == null )
+ {
+ cliRequest.workingDirectory = System.getProperty( "user.dir" );
+ }
+
+ //
+ // Make sure the Maven home directory is an absolute path to save us from confusion with say drive-relative
+ // Windows paths.
+ //
+ String mavenHome = System.getProperty( "maven.home" );
+
+ if ( mavenHome != null )
+ {
+ System.setProperty( "maven.home", new File( mavenHome ).getAbsolutePath() );
+ }
+ }
+
+ private void cli( CliRequest cliRequest )
+ throws Exception
+ {
+ CLIManager cliManager = new CLIManager();
+
+ try
+ {
+ cliRequest.commandLine = cliManager.parse( cliRequest.args );
+ }
+ catch ( ParseException e )
+ {
+ cliRequest.stderr.println( "Unable to parse command line options: " + e.getMessage() );
+ cliManager.displayHelp( cliRequest.stdout );
+ throw e;
+ }
+
+ // TODO: these should be moved out of here. Wrong place.
+ //
+ if ( cliRequest.commandLine.hasOption( CLIManager.HELP ) )
+ {
+ cliManager.displayHelp( cliRequest.stdout );
+ throw new MavenCli.ExitException( 0 );
+ }
+
+ if ( cliRequest.commandLine.hasOption( CLIManager.VERSION ) )
+ {
+ CLIReportingUtils.showVersion( cliRequest.stdout );
+ throw new MavenCli.ExitException( 0 );
+ }
+ }
+
+ private void logging( CliRequest cliRequest )
+ {
+ cliRequest.debug = cliRequest.commandLine.hasOption( CLIManager.DEBUG );
+ cliRequest.quiet = !cliRequest.debug && cliRequest.commandLine.hasOption( CLIManager.QUIET );
+ cliRequest.showErrors = cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.ERRORS );
+
+ if ( cliRequest.debug )
+ {
+ cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_DEBUG );
+ }
+ else if ( cliRequest.quiet )
+ {
+ // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level.
+ // Ideally, we could use Warn across the board
+ cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_ERROR );
+ // TODO:Additionally, we can't change the mojo level because the component key includes the version and
+ // it isn't known ahead of time. This seems worth changing.
+ }
+ else
+ {
+ cliRequest.request.setLoggingLevel( MavenExecutionRequest.LOGGING_LEVEL_INFO );
+ }
+
+ plexusLogger.setThreshold( cliRequest.request.getLoggingLevel() );
+
+ if ( cliRequest.commandLine.hasOption( CLIManager.LOG_FILE ) )
+ {
+ File logFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.LOG_FILE ) );
+ logFile = resolveFile( logFile, cliRequest.workingDirectory );
+
+ try
+ {
+ cliRequest.fileStream = new PrintStream( logFile );
+ cliRequest.logger.setStream( cliRequest.fileStream );
+ }
+ catch ( FileNotFoundException e )
+ {
+ cliRequest.stderr.println( e );
+ cliRequest.logger.setStream( cliRequest.stdout );
+ }
+ }
+ else
+ {
+ cliRequest.logger.setStream( cliRequest.stdout );
+ }
+
+ cliRequest.request.setExecutionListener( new ExecutionEventLogger( cliRequest.logger ) );
+ }
+
+ private void commands( CliRequest cliRequest )
+ {
+ if ( cliRequest.debug || cliRequest.commandLine.hasOption( CLIManager.SHOW_VERSION ) )
+ {
+ CLIReportingUtils.showVersion( cliRequest.stdout );
+ }
+
+ if ( cliRequest.showErrors )
+ {
+ cliRequest.logger.info( "Error stacktraces are turned on." );
+ }
+
+ //
+ // TODO: move checksum policies to
+ //
+ if ( MavenExecutionRequest.CHECKSUM_POLICY_WARN.equals( cliRequest.request.getGlobalChecksumPolicy() ) )
+ {
+ cliRequest.logger.info( "Disabling strict checksum verification on all artifact downloads." );
+ }
+ else if ( MavenExecutionRequest.CHECKSUM_POLICY_FAIL.equals( cliRequest.request.getGlobalChecksumPolicy() ) )
+ {
+ cliRequest.logger.info( "Enabling strict checksum verification on all artifact downloads." );
+ }
+ }
+
+ private void properties( CliRequest cliRequest )
+ {
+ populateProperties( cliRequest.commandLine, cliRequest.systemProperties, cliRequest.userProperties );
+ }
+
+ // ----------------------------------------------------------------------
+ // System properties handling
+ // ----------------------------------------------------------------------
+
+ static void populateProperties( CommandLine commandLine, Properties systemProperties, Properties userProperties )
+ {
+ EnvironmentUtils.addEnvVars( systemProperties );
+
+ // ----------------------------------------------------------------------
+ // Options that are set on the command line become system properties
+ // and therefore are set in the session properties. System properties
+ // are most dominant.
+ // ----------------------------------------------------------------------
+
+ if ( commandLine.hasOption( CLIManager.SET_SYSTEM_PROPERTY ) )
+ {
+ String[] defStrs = commandLine.getOptionValues( CLIManager.SET_SYSTEM_PROPERTY );
+
+ if ( defStrs != null )
+ {
+ for ( int i = 0; i < defStrs.length; ++i )
+ {
+ setCliProperty( defStrs[i], userProperties );
+ }
+ }
+ }
+
+ systemProperties.putAll( System.getProperties() );
+ }
+
+ private static void setCliProperty( String property, Properties properties )
+ {
+ String name;
+
+ String value;
+
+ int i = property.indexOf( "=" );
+
+ if ( i <= 0 )
+ {
+ name = property.trim();
+
+ value = "true";
+ }
+ else
+ {
+ name = property.substring( 0, i ).trim();
+
+ value = property.substring( i + 1 );
+ }
+
+ properties.setProperty( name, value );
+
+ // ----------------------------------------------------------------------
+ // I'm leaving the setting of system properties here as not to break
+ // the SystemPropertyProfileActivator. This won't harm embedding. jvz.
+ // ----------------------------------------------------------------------
+
+ System.setProperty( name, value );
+ }
+
+ private void settings( CliRequest cliRequest )
+ throws Exception
+ {
+ File userSettingsFile;
+
+ if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_USER_SETTINGS ) )
+ {
+ userSettingsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_USER_SETTINGS ) );
+ userSettingsFile = resolveFile( userSettingsFile, cliRequest.workingDirectory );
+
+ if ( !userSettingsFile.isFile() )
+ {
+ throw new FileNotFoundException( "The specified user settings file does not exist: " + userSettingsFile );
+ }
+ }
+ else
+ {
+ userSettingsFile = MavenCli.DEFAULT_USER_SETTINGS_FILE;
+ }
+
+ cliRequest.logger.debug( "Reading user settings from " + userSettingsFile );
+
+ File globalSettingsFile;
+
+ if ( cliRequest.commandLine.hasOption( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) )
+ {
+ globalSettingsFile = new File( cliRequest.commandLine.getOptionValue( CLIManager.ALTERNATE_GLOBAL_SETTINGS ) );
+ globalSettingsFile = resolveFile( globalSettingsFile, cliRequest.workingDirectory );
+
+ if ( !globalSettingsFile.isFile() )
+ {
+ throw new FileNotFoundException( "The specified global settings file does not exist: "
+ + globalSettingsFile );
+ }
+ }
+ else
+ {
+ globalSettingsFile = MavenCli.DEFAULT_GLOBAL_SETTINGS_FILE;
+ }
+
+ cliRequest.logger.debug( "Reading global settings from " + globalSettingsFile );
+
+ cliRequest.request.setGlobalSettingsFile( globalSettingsFile );
+ cliRequest.request.setUserSettingsFile( userSettingsFile );
+
+ SettingsBuildingRequest settingsRequest = new DefaultSettingsBuildingRequest();
+ settingsRequest.setGlobalSettingsFile( globalSettingsFile );
+ settingsRequest.setUserSettingsFile( userSettingsFile );
+ settingsRequest.setSystemProperties( cliRequest.systemProperties );
+ settingsRequest.setUserProperties( cliRequest.userProperties );
+
+ SettingsBuildingResult settingsResult = settingsBuilder.build( settingsRequest );
+
+ executionRequestPopulator.populateFromSettings( cliRequest.request, settingsResult.getEffectiveSettings() );
+
+ if ( !settingsResult.getProblems().isEmpty() && cliRequest.logger.isWarnEnabled() )
+ {
+ cliRequest.logger.warn( "" );
+ cliRequest.logger.warn( "Some problems were encountered while building the effective settings" );
+
+ for ( SettingsProblem problem : settingsResult.getProblems() )
+ {
+ cliRequest.logger.warn( problem.getMessage() + " @ " + problem.getLocation() );
+ }
+
+ cliRequest.logger.warn( "" );
+ }
+ }
+
+ private MavenExecutionRequest populateRequest( CliRequest cliRequest )
+ {
+ MavenExecutionRequest request = cliRequest.request;
+ CommandLine commandLine = cliRequest.commandLine;
+ String workingDirectory = cliRequest.workingDirectory;
+ boolean debug = cliRequest.debug;
+ boolean quiet = cliRequest.quiet;
+ boolean showErrors = cliRequest.showErrors;
+
+ String[] deprecatedOptions = { "up", "npu", "cpu", "npr" };
+ for ( String deprecatedOption : deprecatedOptions )
+ {
+ if ( commandLine.hasOption( deprecatedOption ) )
+ {
+ cliRequest.stdout.println( "[WARNING] Command line option -" + deprecatedOption
+ + " is deprecated and will be removed in future Maven versions." );
+ }
+ }
+
+ // ----------------------------------------------------------------------
+ // Now that we have everything that we need we will fire up plexus and
+ // bring the maven component to life for use.
+ // ----------------------------------------------------------------------
+
+ if ( commandLine.hasOption( CLIManager.BATCH_MODE ) )
+ {
+ request.setInteractiveMode( false );
+ }
+
+ boolean noSnapshotUpdates = false;
+ if ( commandLine.hasOption( CLIManager.SUPRESS_SNAPSHOT_UPDATES ) )
+ {
+ noSnapshotUpdates = true;
+ }
+
+ // ----------------------------------------------------------------------
+ //
+ // ----------------------------------------------------------------------
+
+ @SuppressWarnings("unchecked")
+ List goals = commandLine.getArgList();
+
+ boolean recursive = true;
+
+ // this is the default behavior.
+ String reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
+
+ if ( commandLine.hasOption( CLIManager.NON_RECURSIVE ) )
+ {
+ recursive = false;
+ }
+
+ if ( commandLine.hasOption( CLIManager.FAIL_FAST ) )
+ {
+ reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_FAST;
+ }
+ else if ( commandLine.hasOption( CLIManager.FAIL_AT_END ) )
+ {
+ reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_AT_END;
+ }
+ else if ( commandLine.hasOption( CLIManager.FAIL_NEVER ) )
+ {
+ reactorFailureBehaviour = MavenExecutionRequest.REACTOR_FAIL_NEVER;
+ }
+
+ if ( commandLine.hasOption( CLIManager.OFFLINE ) )
+ {
+ request.setOffline( true );
+ }
+
+ boolean updateSnapshots = false;
+
+ if ( commandLine.hasOption( CLIManager.UPDATE_SNAPSHOTS ) )
+ {
+ updateSnapshots = true;
+ }
+
+ String globalChecksumPolicy = null;
+
+ if ( commandLine.hasOption( CLIManager.CHECKSUM_FAILURE_POLICY ) )
+ {
+ globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_FAIL;
+ }
+ else if ( commandLine.hasOption( CLIManager.CHECKSUM_WARNING_POLICY ) )
+ {
+ globalChecksumPolicy = MavenExecutionRequest.CHECKSUM_POLICY_WARN;
+ }
+
+ File baseDirectory = new File( workingDirectory, "" ).getAbsoluteFile();
+
+ // ----------------------------------------------------------------------
+ // Profile Activation
+ // ----------------------------------------------------------------------
+
+ List activeProfiles = new ArrayList();
+
+ List inactiveProfiles = new ArrayList();
+
+ if ( commandLine.hasOption( CLIManager.ACTIVATE_PROFILES ) )
+ {
+ String[] profileOptionValues = commandLine.getOptionValues( CLIManager.ACTIVATE_PROFILES );
+ if ( profileOptionValues != null )
+ {
+ for ( int i = 0; i < profileOptionValues.length; ++i )
+ {
+ StringTokenizer profileTokens = new StringTokenizer( profileOptionValues[i], "," );
+
+ while ( profileTokens.hasMoreTokens() )
+ {
+ String profileAction = profileTokens.nextToken().trim();
+
+ if ( profileAction.startsWith( "-" ) || profileAction.startsWith( "!" ) )
+ {
+ inactiveProfiles.add( profileAction.substring( 1 ) );
+ }
+ else if ( profileAction.startsWith( "+" ) )
+ {
+ activeProfiles.add( profileAction.substring( 1 ) );
+ }
+ else
+ {
+ activeProfiles.add( profileAction );
+ }
+ }
+ }
+ }
+ }
+
+ TransferListener transferListener;
+
+ if ( quiet )
+ {
+ transferListener = new QuietMavenTransferListener( );
+ }
+ else if ( request.isInteractiveMode() )
+ {
+ transferListener = new ConsoleMavenTransferListener( cliRequest.stdout );
+ }
+ else
+ {
+ transferListener = new BatchModeMavenTransferListener( cliRequest.stdout );
+ }
+
+ //transferListener. .setShowChecksumEvents( false );
+
+ String alternatePomFile = null;
+ if ( commandLine.hasOption( CLIManager.ALTERNATE_POM_FILE ) )
+ {
+ alternatePomFile = commandLine.getOptionValue( CLIManager.ALTERNATE_POM_FILE );
+ }
+
+ int loggingLevel;
+
+ if ( debug )
+ {
+ loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_DEBUG;
+ }
+ else if ( quiet )
+ {
+ // TODO: we need to do some more work here. Some plugins use sys out or log errors at info level.
+ // Ideally, we could use Warn across the board
+ loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_ERROR;
+ // TODO:Additionally, we can't change the mojo level because the component key includes the version and
+ // it isn't known ahead of time. This seems worth changing.
+ }
+ else
+ {
+ loggingLevel = MavenExecutionRequest.LOGGING_LEVEL_INFO;
+ }
+
+ File userToolchainsFile;
+ if ( commandLine.hasOption( CLIManager.ALTERNATE_USER_TOOLCHAINS ) )
+ {
+ userToolchainsFile = new File( commandLine.getOptionValue( CLIManager.ALTERNATE_USER_TOOLCHAINS ) );
+ userToolchainsFile = resolveFile( userToolchainsFile, workingDirectory );
+ }
+ else
+ {
+ userToolchainsFile = MavenCli.DEFAULT_USER_TOOLCHAINS_FILE;
+ }
+
+ request.setBaseDirectory( baseDirectory ).setGoals( goals ).setSystemProperties( cliRequest.systemProperties )
+ .setUserProperties( cliRequest.userProperties ).setReactorFailureBehavior( reactorFailureBehaviour ) // default: fail fast
+ .setRecursive( recursive ) // default: true
+ .setShowErrors( showErrors ) // default: false
+ .addActiveProfiles( activeProfiles ) // optional
+ .addInactiveProfiles( inactiveProfiles ) // optional
+ .setLoggingLevel( loggingLevel ) // default: info
+ .setTransferListener( transferListener ) // default: batch mode which goes along with interactive
+ .setUpdateSnapshots( updateSnapshots ) // default: false
+ .setNoSnapshotUpdates( noSnapshotUpdates ) // default: false
+ .setGlobalChecksumPolicy( globalChecksumPolicy ) // default: warn
+ .setUserToolchainsFile( userToolchainsFile );
+
+ if ( alternatePomFile != null )
+ {
+ File pom = resolveFile( new File( alternatePomFile ), workingDirectory );
+
+ request.setPom( pom );
+ }
+ else
+ {
+ File pom = modelProcessor.locatePom( baseDirectory );
+
+ if ( pom.isFile() )
+ {
+ request.setPom( pom );
+ }
+ }
+
+ if ( ( request.getPom() != null ) && ( request.getPom().getParentFile() != null ) )
+ {
+ request.setBaseDirectory( request.getPom().getParentFile() );
+ }
+
+ if ( commandLine.hasOption( CLIManager.RESUME_FROM ) )
+ {
+ request.setResumeFrom( commandLine.getOptionValue( CLIManager.RESUME_FROM ) );
+ }
+
+ if ( commandLine.hasOption( CLIManager.PROJECT_LIST ) )
+ {
+ String projectList = commandLine.getOptionValue( CLIManager.PROJECT_LIST );
+ String[] projects = StringUtils.split( projectList, "," );
+ request.setSelectedProjects( Arrays.asList( projects ) );
+ }
+
+ if ( commandLine.hasOption( CLIManager.ALSO_MAKE ) && !commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) )
+ {
+ request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_UPSTREAM );
+ }
+ else if ( !commandLine.hasOption( CLIManager.ALSO_MAKE )
+ && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) )
+ {
+ request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_DOWNSTREAM );
+ }
+ else if ( commandLine.hasOption( CLIManager.ALSO_MAKE )
+ && commandLine.hasOption( CLIManager.ALSO_MAKE_DEPENDENTS ) )
+ {
+ request.setMakeBehavior( MavenExecutionRequest.REACTOR_MAKE_BOTH );
+ }
+
+ String localRepoProperty = request.getUserProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY );
+
+ if ( localRepoProperty == null )
+ {
+ localRepoProperty = request.getSystemProperties().getProperty( MavenCli.LOCAL_REPO_PROPERTY );
+ }
+
+ if ( localRepoProperty != null )
+ {
+ request.setLocalRepositoryPath( localRepoProperty );
+ }
+
+ final String threadConfiguration = commandLine.hasOption( CLIManager.THREADS ) ? commandLine
+ .getOptionValue( CLIManager.THREADS ) : request.getSystemProperties()
+ .getProperty( MavenCli.THREADS_DEPRECATED ); // TODO: Remove this setting. Note that the int-tests use it
+
+ if ( threadConfiguration != null )
+ {
+ request.setPerCoreThreadCount( threadConfiguration.contains( "C" ) );
+ if ( threadConfiguration.contains( "W" ) )
+ {
+ LifecycleWeaveBuilder.setWeaveMode( request.getUserProperties() );
+ }
+ request.setThreadCount( threadConfiguration.replace( "C", "" ).replace( "W", "" ).replace( "auto", "" ) );
+ }
+
+ return request;
+ }
+
+ private void encryption( CliRequest cliRequest )
+ throws Exception
+ {
+ if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_MASTER_PASSWORD ) )
+ {
+ String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_MASTER_PASSWORD );
+
+ DefaultPlexusCipher cipher = new DefaultPlexusCipher();
+
+ cliRequest.stdout.println( cipher.encryptAndDecorate( passwd,
+ DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION ) );
+
+ throw new MavenCli.ExitException( 0 );
+ }
+ else if ( cliRequest.commandLine.hasOption( CLIManager.ENCRYPT_PASSWORD ) )
+ {
+ String passwd = cliRequest.commandLine.getOptionValue( CLIManager.ENCRYPT_PASSWORD );
+
+ String configurationFile = dispatcher.getConfigurationFile();
+
+ if ( configurationFile.startsWith( "~" ) )
+ {
+ configurationFile = System.getProperty( "user.home" ) + configurationFile.substring( 1 );
+ }
+
+ String file = System.getProperty( DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION, configurationFile );
+
+ String master = null;
+
+ SettingsSecurity sec = SecUtil.read( file, true );
+ if ( sec != null )
+ {
+ master = sec.getMaster();
+ }
+
+ if ( master == null )
+ {
+ throw new IllegalStateException( "Master password is not set in the setting security file: " + file );
+ }
+
+ DefaultPlexusCipher cipher = new DefaultPlexusCipher();
+ String masterPasswd = cipher.decryptDecorated( master, DefaultSecDispatcher.SYSTEM_PROPERTY_SEC_LOCATION );
+ cliRequest.stdout.println( cipher.encryptAndDecorate( passwd, masterPasswd ) );
+
+ throw new MavenCli.ExitException( 0 );
+ }
+ }
+
+ static class CliRequest
+ {
+ String[] args;
+ CommandLine commandLine;
+ PrintStream stdout;
+ PrintStream stderr;
+ ClassWorld classWorld;
+ String workingDirectory;
+ boolean debug;
+ boolean quiet;
+ boolean showErrors = true;
+ PrintStream fileStream;
+ Properties userProperties = new Properties();
+ Properties systemProperties = new Properties();
+ MavenExecutionRequest request;
+ PrintStreamLogger logger;
+
+ CliRequest( String[] args, ClassWorld classWorld )
+ {
+ this.args = args;
+ this.classWorld = classWorld;
+ this.request = new DefaultMavenExecutionRequest();
+ }
+ }
+
+}
diff --git a/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestBuilder.java b/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestBuilder.java
new file mode 100755
index 0000000000..099337e8b6
--- /dev/null
+++ b/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestBuilder.java
@@ -0,0 +1,36 @@
+package org.apache.maven.cli;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.PrintStream;
+
+import org.apache.maven.execution.MavenExecutionRequest;
+import org.apache.maven.execution.MavenExecutionRequestPopulationException;
+import org.apache.maven.settings.building.SettingsBuildingException;
+
+/**
+ * @author Olivier Lamy
+ * @since
+ */
+public interface MavenExecutionRequestBuilder
+{
+ MavenExecutionRequest getMavenExecutionRequest( String[] args, PrintStream printStream )
+ throws MavenExecutionRequestPopulationException, SettingsBuildingException, MavenExecutionRequestsBuilderException;
+}
diff --git a/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestsBuilderException.java b/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestsBuilderException.java
new file mode 100755
index 0000000000..6b0a44aad4
--- /dev/null
+++ b/maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestsBuilderException.java
@@ -0,0 +1,33 @@
+package org.apache.maven.cli;
+
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you 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.
+ */
+
+/**
+ * @author Olivier Lamy
+ * @since
+ */
+public class MavenExecutionRequestsBuilderException
+ extends Exception
+{
+ public MavenExecutionRequestsBuilderException(String message, Throwable exception)
+ {
+ super( message, exception );
+ }
+}
diff --git a/maven3-listener/src/main/java/org/jvnet/hudson/maven3/launcher/Maven3Launcher.java b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/launcher/Maven3Launcher.java
new file mode 100755
index 0000000000..f1ce57b00f
--- /dev/null
+++ b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/launcher/Maven3Launcher.java
@@ -0,0 +1,118 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc.,
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
+ * associated documentation files (the "Software"), to deal in the Software without restriction,
+ * including without limitation the rights to use, copy, modify, merge, publish, distribute,
+ * sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all copies or
+ * substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
+ * NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+ * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+ * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+package org.jvnet.hudson.maven3.launcher;
+
+import org.apache.maven.Maven;
+import org.apache.maven.cli.MavenExecutionRequestBuilder;
+import org.apache.maven.cli.MavenLoggerManager;
+import org.apache.maven.cli.PrintStreamLogger;
+import org.apache.maven.execution.ExecutionListener;
+import org.apache.maven.execution.MavenExecutionRequest;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.codehaus.plexus.ContainerConfiguration;
+import org.codehaus.plexus.DefaultContainerConfiguration;
+import org.codehaus.plexus.DefaultPlexusContainer;
+import org.codehaus.plexus.classworlds.realm.ClassRealm;
+import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
+import org.jvnet.hudson.maven3.listeners.HudsonMavenExecutionResult;
+
+/**
+ * @author olamy
+ *
+ */
+public class Maven3Launcher
+{
+
+ private static HudsonMavenExecutionResult hudsonMavenExecutionResult;
+
+ private static ExecutionListener mavenExecutionListener;
+
+ public static ExecutionListener getMavenExecutionListener()
+ {
+ return mavenExecutionListener;
+ }
+
+ public static void setMavenExecutionListener( ExecutionListener listener )
+ {
+ mavenExecutionListener = listener;
+ }
+
+ public static HudsonMavenExecutionResult getMavenExecutionResult()
+ {
+ return hudsonMavenExecutionResult;
+ }
+
+ public static void setMavenExecutionResult( HudsonMavenExecutionResult result )
+ {
+ hudsonMavenExecutionResult = result;
+ }
+
+ public static int main( String[] args )
+ throws Exception
+ {
+ ClassLoader orig = Thread.currentThread().getContextClassLoader();
+ try
+ {
+
+ ClassRealm containerRealm = (ClassRealm) Thread.currentThread().getContextClassLoader();
+
+ ContainerConfiguration cc = new DefaultContainerConfiguration().setName( "maven" )
+ .setRealm( containerRealm );
+
+ DefaultPlexusContainer container = new DefaultPlexusContainer( cc );
+ MavenLoggerManager mavenLoggerManager = new MavenLoggerManager( new PrintStreamLogger( System.out ) );
+ container.setLoggerManager( mavenLoggerManager );
+
+ Maven maven = (Maven) container.lookup( "org.apache.maven.Maven", "default" );
+ MavenExecutionRequest request = getMavenExecutionRequest( args, container );
+
+ hudsonMavenExecutionResult = new HudsonMavenExecutionResult( maven.execute( request ) );
+ System.out.println("---- mavenExecutionResult ----");
+ System.out.println( "mavenExecutionResult.getMavenProjectInfos().size() " + hudsonMavenExecutionResult.getMavenProjectInfos().size() );
+ System.out.println("---- mavenExecutionResult ----");
+
+ // we don't care about cli mavenExecutionResult will be study in the the plugin
+ return 0;// cli.doMain( args, null );
+ }
+ catch ( ComponentLookupException e )
+ {
+ throw new Exception( e.getMessage(), e );
+ }
+ finally
+ {
+ Thread.currentThread().setContextClassLoader( orig );
+ }
+ }
+
+ private static MavenExecutionRequest getMavenExecutionRequest( String[] args, DefaultPlexusContainer container )
+ throws Exception
+ {
+ MavenExecutionRequestBuilder mavenExecutionRequestBuilder = container
+ .lookup( MavenExecutionRequestBuilder.class );
+ MavenExecutionRequest request = mavenExecutionRequestBuilder.getMavenExecutionRequest( args, System.out );
+ if ( mavenExecutionListener != null )
+ {
+ request.setExecutionListener( mavenExecutionListener );
+ }
+ return request;
+ }
+
+}
diff --git a/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/HudsonMavenExecutionResult.java b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/HudsonMavenExecutionResult.java
new file mode 100755
index 0000000000..e7c4d24830
--- /dev/null
+++ b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/HudsonMavenExecutionResult.java
@@ -0,0 +1,61 @@
+/**
+ *
+ */
+package org.jvnet.hudson.maven3.listeners;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.maven.execution.BuildSummary;
+import org.apache.maven.execution.MavenExecutionResult;
+import org.apache.maven.project.MavenProject;
+
+/**
+ * @author Olivier Lamy
+ * @since
+ */
+public class HudsonMavenExecutionResult implements Serializable
+{
+ List throwables = new ArrayList();
+
+ List mavenProjectInfos = new ArrayList();
+
+ public HudsonMavenExecutionResult(MavenExecutionResult mavenExecutionResult)
+ {
+ if (mavenExecutionResult == null)
+ {
+ return;
+ }
+ throwables = mavenExecutionResult.getExceptions();
+ List mavenProjects = mavenExecutionResult.getTopologicallySortedProjects();
+ for (MavenProject mavenProject : mavenProjects)
+ {
+ MavenProjectInfo mavenProjectInfo = new MavenProjectInfo( mavenProject );
+ mavenProjectInfos.add( mavenProjectInfo );
+ BuildSummary buildSummary = mavenExecutionResult.getBuildSummary( mavenProject );
+ mavenProjectInfo.setBuildTime( buildSummary.getTime() );
+
+ }
+ }
+
+ public List getThrowables()
+ {
+ return throwables;
+ }
+
+ public void setThrowables( List throwables )
+ {
+ this.throwables = throwables;
+ }
+
+ public List getMavenProjectInfos()
+ {
+ return mavenProjectInfos;
+ }
+
+ public void setMavenProjectInfos( List mavenProjectInfos )
+ {
+ this.mavenProjectInfos = mavenProjectInfos;
+ }
+}
diff --git a/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectBuildResult.java b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectBuildResult.java
new file mode 100755
index 0000000000..401ef433ff
--- /dev/null
+++ b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectBuildResult.java
@@ -0,0 +1,50 @@
+/**
+ *
+ */
+package org.jvnet.hudson.maven3.listeners;
+
+import java.io.Serializable;
+import java.util.List;
+
+import org.apache.maven.project.ProjectBuildingResult;
+
+/**
+ * @author olamy
+ * created 9 août 2010
+ * @since
+ * @version $Id$
+ */
+public class MavenProjectBuildResult implements Serializable
+{
+ private MavenProjectInfo mavenProjectInfo;
+
+ public MavenProjectBuildResult()
+ {
+ // no op
+ }
+
+ public MavenProjectBuildResult( ProjectBuildingResult projectBuildingResult )
+ {
+ // no op
+ this.mavenProjectInfo = new MavenProjectInfo( projectBuildingResult.getProject() );
+ }
+
+ public MavenProjectInfo getMavenProjectInfo()
+ {
+ return mavenProjectInfo;
+ }
+
+ public void setMavenProjectInfo( MavenProjectInfo mavenProjectInfo )
+ {
+ this.mavenProjectInfo = mavenProjectInfo;
+ }
+
+ @Override
+ public String toString()
+ {
+ return mavenProjectInfo == null ? "null mavenProjectInfo" : this.mavenProjectInfo.toString();
+ }
+
+
+
+}
diff --git a/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectInfo.java b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectInfo.java
new file mode 100755
index 0000000000..5b6fd1823f
--- /dev/null
+++ b/maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectInfo.java
@@ -0,0 +1,119 @@
+/*
+ * The MIT License
+ *
+ * Copyright (c) 2004-2009, Sun Microsystems, Inc., Olivier Lamy
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in
+ * all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ * THE SOFTWARE.
+ */
+package org.jvnet.hudson.maven3.listeners;
+
+import java.io.Serializable;
+
+import org.apache.maven.project.MavenProject;
+
+/**
+ * @author olamy
+ * created 9 août 2010
+ * @since
+ * @version $Id$
+ */
+public class MavenProjectInfo implements Serializable
+{
+
+ private String displayName;
+
+ private String groupId;
+
+ private String artifactId;
+
+ private String version;
+
+ private long buildTime;
+
+ public MavenProjectInfo()
+ {
+ // no-op
+ }
+
+ public MavenProjectInfo(MavenProject mavenProject)
+ {
+ this.displayName = mavenProject.getName();
+ this.groupId= mavenProject.getGroupId();
+ this.artifactId = mavenProject.getArtifactId();
+ this.version = mavenProject.getVersion();
+ }
+
+ public long getBuildTime()
+ {
+ return buildTime;
+ }
+
+ public void setBuildTime( long buildTime )
+ {
+ this.buildTime = buildTime;
+ }
+
+ public String getDisplayName()
+ {
+ return displayName;
+ }
+
+ public void setDisplayName( String displayName )
+ {
+ this.displayName = displayName;
+ }
+
+ public String getGroupId()
+ {
+ return groupId;
+ }
+
+ public void setGroupId( String groupId )
+ {
+ this.groupId = groupId;
+ }
+
+ public String getArtifactId()
+ {
+ return artifactId;
+ }
+
+ public void setArtifactId( String artifactId )
+ {
+ this.artifactId = artifactId;
+ }
+
+ public String getVersion()
+ {
+ return version;
+ }
+
+ public void setVersion( String version )
+ {
+ this.version = version;
+ }
+
+ @Override
+ public String toString()
+ {
+ return groupId + ":" + artifactId + ":" + version;
+ }
+
+
+}
diff --git a/pom.xml b/pom.xml
index d4423b8c93..48969c6c53 100644
--- a/pom.xml
+++ b/pom.xml
@@ -46,6 +46,8 @@ THE SOFTWARE.
ui-samples-plugin
maven-agent
maven-interceptor
+ maven3-agent
+ maven3-listener
war
test
cli
@@ -197,7 +199,9 @@ THE SOFTWARE.
+ org.apache.maven.plugins
maven-enforcer-plugin
+ 1.0-beta-1
@@ -248,10 +252,55 @@ THE SOFTWARE.
true