From dceafbbf7b37ad8bf7b7bf2c25f76b0ce4d8336a Mon Sep 17 00:00:00 2001 From: olamy Date: Thu, 4 Nov 2010 22:39:27 +0000 Subject: [PATCH] [HUDSON-4988] push some stuff to be able to get in an other place (sure git could be better :-) ) some issue when using maven 2 some stuff to do more in maven 3 build (recording mojo execution etc...) git-svn-id: https://hudson.dev.java.net/svn/hudson/branches/main-maven3-support@36643 71c3de6d-444a-0410-be80-ed276b4c234a --- core/pom.xml | 1 - core/src/main/java/hudson/PluginManager.java | 7 + maven-agent/pom.xml | 37 +- .../main/java/hudson/maven/agent/Main.java | 244 ++- .../hudson/maven/agent/classworlds-2.0.6.conf | 4 + .../hudson/maven/agent/classworlds.conf | 6 +- maven-interceptor/pom.xml | 14 +- .../maven/agent/DefaultPluginManager.java | 1546 +++++++++++++++++ .../maven/agent/PluginManagerInterceptor.java | 1 - maven-plugin/pom.xml | 357 ++-- .../hudson/maven/AbstractMavenBuilder.java | 88 + .../java/hudson/maven/EmbedderLoggerImpl.java | 21 +- .../main/java/hudson/maven/Maven3Builder.java | 328 ++++ .../hudson/maven/Maven3ProcessFactory.java | 396 +++++ .../main/java/hudson/maven/MavenBuilder.java | 112 +- .../hudson/maven/MavenComputerListener.java | 13 +- .../hudson/maven/MavenModuleSetBuild.java | 120 +- .../hudson/maven/MavenProcessFactory.java | 25 +- .../src/main/java/hudson/maven/MavenUtil.java | 78 +- .../hudson/maven/MavenVersionCallable.java | 63 + .../src/main/java/hudson/maven/MojoInfo.java | 4 +- .../java/hudson/maven/RedeployPublisher.java | 16 +- .../MavenAbstractArtifactRecord.java | 33 +- .../MavenAggregatedArtifactRecord.java | 9 +- .../hudson/maven/reporters/MavenArtifact.java | 15 +- .../maven/reporters/MavenArtifactRecord.java | 25 +- maven3-agent/.gitignore | 5 + maven3-agent/pom.xml | 37 + .../jvnet/hudson/maven3/agent/Maven3Main.java | 177 ++ .../maven3/agent/RealFilterOutputStream.java | 51 + .../hudson/maven3/agent/classworlds.conf | 11 + maven3-listener/.gitignore | 5 + maven3-listener/pom.xml | 55 + .../DefaultMavenExecutionRequestBuilder.java | 792 +++++++++ .../cli/MavenExecutionRequestBuilder.java | 36 + ...avenExecutionRequestsBuilderException.java | 33 + .../maven3/launcher/Maven3Launcher.java | 118 ++ .../listeners/HudsonMavenExecutionResult.java | 61 + .../listeners/MavenProjectBuildResult.java | 50 + .../maven3/listeners/MavenProjectInfo.java | 119 ++ pom.xml | 84 +- .../java/hudson/remoting/UserRequest.java | 2 + .../org/jvnet/hudson/test/HudsonTestCase.java | 5 +- 43 files changed, 4839 insertions(+), 365 deletions(-) create mode 100644 maven-interceptor/src/main/java/hudson/maven/agent/DefaultPluginManager.java create mode 100644 maven-plugin/src/main/java/hudson/maven/AbstractMavenBuilder.java create mode 100644 maven-plugin/src/main/java/hudson/maven/Maven3Builder.java create mode 100644 maven-plugin/src/main/java/hudson/maven/Maven3ProcessFactory.java create mode 100644 maven-plugin/src/main/java/hudson/maven/MavenVersionCallable.java create mode 100755 maven3-agent/.gitignore create mode 100755 maven3-agent/pom.xml create mode 100755 maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/Maven3Main.java create mode 100755 maven3-agent/src/main/java/org/jvnet/hudson/maven3/agent/RealFilterOutputStream.java create mode 100755 maven3-agent/src/main/resources/org/jvnet/hudson/maven3/agent/classworlds.conf create mode 100755 maven3-listener/.gitignore create mode 100755 maven3-listener/pom.xml create mode 100755 maven3-listener/src/main/java/org/apache/maven/cli/DefaultMavenExecutionRequestBuilder.java create mode 100755 maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestBuilder.java create mode 100755 maven3-listener/src/main/java/org/apache/maven/cli/MavenExecutionRequestsBuilderException.java create mode 100755 maven3-listener/src/main/java/org/jvnet/hudson/maven3/launcher/Maven3Launcher.java create mode 100755 maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/HudsonMavenExecutionResult.java create mode 100755 maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectBuildResult.java create mode 100755 maven3-listener/src/main/java/org/jvnet/hudson/maven3/listeners/MavenProjectInfo.java diff --git a/core/pom.xml b/core/pom.xml index 0d0c407a4b..f28f19630c 100644 --- a/core/pom.xml +++ b/core/pom.xml @@ -461,7 +461,6 @@ THE SOFTWARE. org.apache.ant ant - 1.8.0 javax.servlet diff --git a/core/src/main/java/hudson/PluginManager.java b/core/src/main/java/hudson/PluginManager.java index 3784009fca..4a7c9cb03c 100644 --- a/core/src/main/java/hudson/PluginManager.java +++ b/core/src/main/java/hudson/PluginManager.java @@ -626,6 +626,13 @@ public abstract class PluginManager extends AbstractModelObject { } return Collections.enumeration(resources); } + + @Override + public String toString() + { + // only for debugging purpose + return "classLoader " + getClass().getName(); + } } private static final Logger LOGGER = Logger.getLogger(PluginManager.class.getName()); diff --git a/maven-agent/pom.xml b/maven-agent/pom.xml index e473dc8ce8..a3c29b4cdf 100644 --- a/maven-agent/pom.xml +++ b/maven-agent/pom.xml @@ -73,25 +73,52 @@ THE SOFTWARE. org.jvnet.hudson.main maven-interceptor ${project.version} + + + org.codehaus.plexus + plexus-classworlds + + - classworlds - classworlds - 1.1 - + org.codehaus.plexus + plexus-classworlds + + + org.apache.ant + ant + commons-httpclient commons-httpclient 3.1-rc1 + + + org.apache.ant + ant + 1.8.0 + org.apache.maven maven-core - ${maven.version} + 2.0.9 test + + + classworlds + classworlds + + org.jvnet.hudson.main diff --git a/maven-agent/src/main/java/hudson/maven/agent/Main.java b/maven-agent/src/main/java/hudson/maven/agent/Main.java index 27cd4c7c2a..f6f8837fff 100644 --- a/maven-agent/src/main/java/hudson/maven/agent/Main.java +++ b/maven-agent/src/main/java/hudson/maven/agent/Main.java @@ -23,25 +23,36 @@ */ package hudson.maven.agent; -import org.codehaus.classworlds.ClassRealm; -import org.codehaus.classworlds.ClassWorld; -import org.codehaus.classworlds.DefaultClassRealm; -import org.codehaus.classworlds.Launcher; -import org.codehaus.classworlds.NoSuchRealmException; - +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; import java.io.File; +import java.io.FilenameFilter; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.net.MalformedURLException; import java.net.Socket; +import java.net.URL; +import java.net.URLClassLoader; +import java.util.Arrays; +import java.util.Enumeration; import java.util.HashSet; import java.util.Iterator; import java.util.Set; +import org.apache.tools.ant.AntClassLoader; +import org.codehaus.classworlds.ClassWorldAdapter; +import org.codehaus.plexus.classworlds.ClassWorld; +import org.codehaus.plexus.classworlds.launcher.ConfigurationException; +import org.codehaus.plexus.classworlds.launcher.Launcher; +import org.codehaus.plexus.classworlds.realm.ClassRealm; +import org.codehaus.plexus.classworlds.realm.DuplicateRealmException; +import org.codehaus.plexus.classworlds.realm.NoSuchRealmException; + + /** * Entry point for launching Maven and Hudson remoting in the same VM, * in the classloader layout that Maven expects. @@ -100,26 +111,43 @@ public class Main { // I don't know how classworlds react to undefined variable, so (interceptorOverrideJar!=null?interceptorOverrideJar:interceptorJar).getPath()); + // FIXME change stuff for 206 earlier ! + boolean is206OrLater = !new File(m2Home,"core").exists(); - + + // load the default realms launcher = new Launcher(); launcher.setSystemClassLoader(Main.class.getClassLoader()); - launcher.configure(Main.class.getResourceAsStream( - is206OrLater?"classworlds-2.0.6.conf":"classworlds.conf")); - + + configureLauncher( m2Home, remotingJar, interceptorJar, interceptorOverrideJar, is206OrLater ); + + System.out.println( "realms size " + launcher.getWorld().getRealms().size() ); + for (Iterator iter = launcher.getWorld().getRealms().iterator();iter.hasNext();) + { + ClassRealm realm = (ClassRealm) iter.next(); + System.out.println( "realm " + realm + " urls " + Arrays.asList( realm.getURLs() ) ); + } + // have it eventually delegate to this class so that this can be visible - // create a realm for loading remoting subsystem. // this needs to be able to see maven. - ClassRealm remoting = new DefaultClassRealm(launcher.getWorld(),"hudson-remoting", launcher.getSystemClassLoader()); - remoting.setParent(launcher.getWorld().getRealm("plexus.core.maven")); - remoting.addConstituent(remotingJar.toURI().toURL()); + + System.out.print( "Main classLoader " + Main.class.getClassLoader() ); + //test en changeant le parent en plexus.core.maven ? + ClassRealm remoting = launcher.getWorld().newRealm( "hudson-remoting", launcher.getWorld().getClassRealm( "plexus.core" ) ); + remoting.importFrom( "plexus.core.maven", "org.apache.maven" ); + //remoting.setParentClassLoader( launcher.getWorld().getClassRealm( "plexus.core.maven" ) ); + 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, + + Method mainMethod = remotingLauncher.getMethod("main",new Class[]{InputStream.class,OutputStream.class}); + + mainMethod.invoke(null, new Object[]{ // do partial close, since socket.getInputStream and getOutputStream doesn't do it by new BufferedInputStream(new FilterInputStream(s.getInputStream()) { @@ -133,6 +161,7 @@ public class Main { } }) }); + System.out.println(" remoting classLoader " + remoting.toString() ); System.exit(0); } @@ -153,17 +182,129 @@ public class Main { } } } + + /** + * old one + * @throws ConfigurationException + * @throws IOException + * @throws NoSuchRealmException + * @throws DuplicateRealmException + */ + private static void configureLauncher(File m2Home, File remotingJar, File interceptorJar, File interceptorOverrideJar, boolean is206OrLater) + throws DuplicateRealmException, NoSuchRealmException, IOException, ConfigurationException { + + launcher.configure(Main.class.getResourceAsStream(is206OrLater?"classworlds-2.0.6.conf":"classworlds.conf")); + } /** - * Called by the code in remoting to launch. + * with various classLoader hierarchy stuff + * @throws MalformedURLException + * @throws DuplicateRealmException */ - public static int launch(String[] args) throws NoSuchMethodException, IllegalAccessException, NoSuchRealmException, InvocationTargetException, ClassNotFoundException { + private static void configureLauncher2(File m2Home, File remotingJar, File interceptorJar, File interceptorOverrideJar, boolean is206OrLater) + throws MalformedURLException, DuplicateRealmException { + ClassWorld world = new ClassWorld(); + launcher.setWorld( world ); + ClassRealm plexusCore = world.newRealm( "plexus.core" ); + plexusCore.setParentClassLoader( Main.class.getClassLoader() ); + File mavenCore = new File(m2Home, is206OrLater ? "boot" : "core"); + + String[] coreJars = mavenCore.list( new FilenameFilter() + { + + public boolean accept( File dir, String name ) + { + return name.endsWith( ".jar" ); + } + }); + + for (int i = 0,size = coreJars.length;i org.apache.maven maven-core - ${maven.version} + 2.0.9 + provided + + + classworlds + classworlds + + + + + org.codehaus.plexus + plexus-classworlds + diff --git a/maven-interceptor/src/main/java/hudson/maven/agent/DefaultPluginManager.java b/maven-interceptor/src/main/java/hudson/maven/agent/DefaultPluginManager.java new file mode 100644 index 0000000000..2bbc34d261 --- /dev/null +++ b/maven-interceptor/src/main/java/hudson/maven/agent/DefaultPluginManager.java @@ -0,0 +1,1546 @@ + +package hudson.maven.agent; + +/* + * 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.net.URL; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.maven.MavenArtifactFilterManager; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.factory.ArtifactFactory; +import org.apache.maven.artifact.metadata.ArtifactMetadataRetrievalException; +import org.apache.maven.artifact.metadata.ArtifactMetadataSource; +import org.apache.maven.artifact.metadata.ResolutionGroup; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.resolver.ArtifactNotFoundException; +import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.artifact.resolver.ArtifactResolutionResult; +import org.apache.maven.artifact.resolver.ArtifactResolver; +import org.apache.maven.artifact.resolver.MultipleArtifactsNotFoundException; +import org.apache.maven.artifact.resolver.filter.ArtifactFilter; +import org.apache.maven.artifact.resolver.filter.ScopeArtifactFilter; +import org.apache.maven.artifact.versioning.DefaultArtifactVersion; +import org.apache.maven.artifact.versioning.InvalidVersionSpecificationException; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.execution.RuntimeInformation; +import org.apache.maven.model.Plugin; +import org.apache.maven.model.ReportPlugin; +import org.apache.maven.monitor.event.EventDispatcher; +import org.apache.maven.monitor.event.MavenEvents; +import org.apache.maven.monitor.logging.DefaultLog; +import org.apache.maven.plugin.ContextEnabled; +import org.apache.maven.plugin.DebugConfigurationListener; +import org.apache.maven.plugin.InvalidPluginException; +import org.apache.maven.plugin.MavenPluginCollector; +import org.apache.maven.plugin.Mojo; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugin.PluginConfigurationException; +import org.apache.maven.plugin.PluginManager; +import org.apache.maven.plugin.PluginManagerException; +import org.apache.maven.plugin.PluginMappingManager; +import org.apache.maven.plugin.PluginNotFoundException; +import org.apache.maven.plugin.PluginParameterException; +import org.apache.maven.plugin.PluginParameterExpressionEvaluator; +import org.apache.maven.plugin.descriptor.MojoDescriptor; +import org.apache.maven.plugin.descriptor.Parameter; +import org.apache.maven.plugin.descriptor.PluginDescriptor; +import org.apache.maven.plugin.descriptor.PluginDescriptorBuilder; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugin.version.PluginVersionManager; +import org.apache.maven.plugin.version.PluginVersionNotFoundException; +import org.apache.maven.plugin.version.PluginVersionResolutionException; +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.MavenProjectBuilder; +import org.apache.maven.project.ProjectBuildingException; +import org.apache.maven.project.artifact.InvalidDependencyVersionException; +import org.apache.maven.project.artifact.MavenMetadataSource; +import org.apache.maven.project.path.PathTranslator; +import org.apache.maven.reporting.MavenReport; +import org.apache.maven.settings.Settings; +import org.codehaus.classworlds.ClassRealm; +import org.codehaus.classworlds.NoSuchRealmException; +import org.codehaus.plexus.PlexusConstants; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.PlexusContainerException; +import org.codehaus.plexus.component.configurator.ComponentConfigurationException; +import org.codehaus.plexus.component.configurator.ComponentConfigurator; +import org.codehaus.plexus.component.configurator.ConfigurationListener; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluationException; +import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator; +import org.codehaus.plexus.component.repository.exception.ComponentLifecycleException; +import org.codehaus.plexus.component.repository.exception.ComponentLookupException; +import org.codehaus.plexus.configuration.PlexusConfiguration; +import org.codehaus.plexus.configuration.xml.XmlPlexusConfiguration; +import org.codehaus.plexus.context.Context; +import org.codehaus.plexus.context.ContextException; +import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; +import org.codehaus.plexus.personality.plexus.lifecycle.phase.Initializable; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.xml.Xpp3Dom; + +/** + * olamy : code removed in maven 3 so imported sources + * from maven 2.0.9 tag : /maven-core/src/main/java/org/apache/maven/plugin/DefaultPluginManager.java + * really hackhish ! + * @author olamy + * + */ +public class DefaultPluginManager + extends AbstractLogEnabled + implements PluginManager, Initializable, Contextualizable +{ + protected PlexusContainer container; + + protected PluginDescriptorBuilder pluginDescriptorBuilder; + + protected ArtifactFilter artifactFilter; + + private Log mojoLogger; + + private Map resolvedCoreArtifactFiles = new HashMap(); + + // component requirements + protected PathTranslator pathTranslator; + + protected MavenPluginCollector pluginCollector; + + protected PluginVersionManager pluginVersionManager; + + protected ArtifactFactory artifactFactory; + + protected ArtifactResolver artifactResolver; + + protected ArtifactMetadataSource artifactMetadataSource; + + protected RuntimeInformation runtimeInformation; + + protected MavenProjectBuilder mavenProjectBuilder; + + protected PluginMappingManager pluginMappingManager; + + // END component requirements + + public DefaultPluginManager() + { + pluginDescriptorBuilder = new PluginDescriptorBuilder(); + } + + // ---------------------------------------------------------------------- + // + // ---------------------------------------------------------------------- + + public PluginDescriptor getPluginDescriptorForPrefix( String prefix ) + { + return pluginCollector.getPluginDescriptorForPrefix( prefix ); + } + + public Plugin getPluginDefinitionForPrefix( String prefix, + MavenSession session, + MavenProject project ) + { + // TODO: since this is only used in the lifecycle executor, maybe it should be moved there? There is no other + // use for the mapping manager in here + return pluginMappingManager.getByPrefix( prefix, session.getSettings().getPluginGroups(), + project.getPluginArtifactRepositories(), + session.getLocalRepository() ); + } + + public PluginDescriptor verifyPlugin( Plugin plugin, + MavenProject project, + Settings settings, + ArtifactRepository localRepository ) + throws ArtifactResolutionException, PluginVersionResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, + PluginVersionNotFoundException + { + // TODO: this should be possibly outside + // All version-resolution logic has been moved to DefaultPluginVersionManager. + if ( plugin.getVersion() == null ) + { + String version = pluginVersionManager.resolvePluginVersion( plugin.getGroupId(), plugin.getArtifactId(), + project, settings, localRepository ); + plugin.setVersion( version ); + } + + return verifyVersionedPlugin( plugin, project, localRepository ); + } + + private PluginDescriptor verifyVersionedPlugin( Plugin plugin, + MavenProject project, + ArtifactRepository localRepository ) + throws PluginVersionResolutionException, ArtifactNotFoundException, ArtifactResolutionException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException + { + // TODO: this might result in an artifact "RELEASE" being resolved continuously + // FIXME: need to find out how a plugin gets marked as 'installed' + // and no ChildContainer exists. The check for that below fixes + // the 'Can't find plexus container for plugin: xxx' error. + try + { + VersionRange versionRange = VersionRange.createFromVersionSpec( plugin.getVersion() ); + + List remoteRepositories = new ArrayList(); + remoteRepositories.addAll( project.getPluginArtifactRepositories() ); + remoteRepositories.addAll( project.getRemoteArtifactRepositories() ); + + checkRequiredMavenVersion( plugin, localRepository, remoteRepositories ); + + Artifact pluginArtifact = + artifactFactory.createPluginArtifact( plugin.getGroupId(), plugin.getArtifactId(), versionRange ); + + pluginArtifact = project.replaceWithActiveArtifact( pluginArtifact ); + + artifactResolver.resolve( pluginArtifact, project.getPluginArtifactRepositories(), localRepository ); + + PlexusContainer pluginContainer = container.getChildContainer( plugin.getKey() ); + + File pluginFile = pluginArtifact.getFile(); + + if ( !pluginCollector.isPluginInstalled( plugin ) || ( pluginContainer == null ) ) + { + addPlugin( plugin, pluginArtifact, project, localRepository ); + } + else if ( pluginFile.lastModified() > pluginContainer.getCreationDate().getTime() ) + { + getLogger().info( + "Reloading plugin container for: " + plugin.getKey() + ". The plugin artifact has changed." ); + + pluginContainer.dispose(); + + pluginCollector.flushPluginDescriptor( plugin ); + + addPlugin( plugin, pluginArtifact, project, localRepository ); + } + + project.addPlugin( plugin ); + } + catch ( ArtifactNotFoundException e ) + { + String groupId = plugin.getGroupId(); + String artifactId = plugin.getArtifactId(); + String version = plugin.getVersion(); + + if ( ( groupId == null ) || ( artifactId == null ) || ( version == null ) ) + { + throw new PluginNotFoundException( e ); + } + else if ( groupId.equals( e.getGroupId() ) && artifactId.equals( e.getArtifactId() ) && + version.equals( e.getVersion() ) && "maven-plugin".equals( e.getType() ) ) + { + throw new PluginNotFoundException( e ); + } + else + { + throw e; + } + } + + return pluginCollector.getPluginDescriptor( plugin ); + } + + /** + * @todo would be better to store this in the plugin descriptor, but then it won't be available to the version + * manager which executes before the plugin is instantiated + */ + private void checkRequiredMavenVersion( Plugin plugin, + ArtifactRepository localRepository, + List remoteRepositories ) + throws PluginVersionResolutionException, InvalidPluginException + { + try + { + Artifact artifact = artifactFactory.createProjectArtifact( plugin.getGroupId(), plugin.getArtifactId(), + plugin.getVersion() ); + MavenProject project = + mavenProjectBuilder.buildFromRepository( artifact, remoteRepositories, localRepository, false ); + // if we don't have the required Maven version, then ignore an update + if ( ( project.getPrerequisites() != null ) && ( project.getPrerequisites().getMaven() != null ) ) + { + DefaultArtifactVersion requiredVersion = + new DefaultArtifactVersion( project.getPrerequisites().getMaven() ); + if ( runtimeInformation.getApplicationVersion().compareTo( requiredVersion ) < 0 ) + { + throw new PluginVersionResolutionException( plugin.getGroupId(), plugin.getArtifactId(), + "Plugin requires Maven version " + requiredVersion ); + } + } + } + catch ( ProjectBuildingException e ) + { + throw new InvalidPluginException( + "Unable to build project for plugin '" + plugin.getKey() + "': " + e.getMessage(), e ); + } + } + + protected void addPlugin( Plugin plugin, + Artifact pluginArtifact, + MavenProject project, + ArtifactRepository localRepository ) + throws PluginManagerException, InvalidPluginException + { + PlexusContainer child; + + try + { + child = container.createChildContainer( plugin.getKey(), + Collections.singletonList( pluginArtifact.getFile() ), + Collections.EMPTY_MAP, + Collections.singletonList( pluginCollector ) ); + try + { + child.getContainerRealm().importFrom( "plexus.core", "org.codehaus.plexus.util.xml.Xpp3Dom" ); + child.getContainerRealm().importFrom( "plexus.core", "org.codehaus.plexus.util.xml.pull" ); + + // MNG-2878 + child.getContainerRealm().importFrom( "plexus.core", "/default-report.xml" ); + } + catch ( NoSuchRealmException e ) + { + // won't happen + } + } + catch ( PlexusContainerException e ) + { + throw new PluginManagerException( + "Failed to create plugin container for plugin '" + plugin + "': " + e.getMessage(), e ); + } + + // this plugin's descriptor should have been discovered in the child creation, so we should be able to + // circle around and set the artifacts and class realm + PluginDescriptor addedPlugin = pluginCollector.getPluginDescriptor( plugin ); + + if ( addedPlugin == null ) + { + throw new IllegalStateException( "The PluginDescriptor for the plugin " + plugin + " was not found." ); + } + + addedPlugin.setClassRealm( child.getContainerRealm() ); + + // we're only setting the plugin's artifact itself as the artifact list, to allow it to be retrieved + // later when the plugin is first invoked. Retrieving this artifact will in turn allow us to + // transitively resolve its dependencies, and add them to the plugin container... + addedPlugin.setArtifacts( Collections.singletonList( pluginArtifact ) ); + + try + { + // the only Plugin instance which will have dependencies is the one specified in the project. + // We need to look for a Plugin instance there, in case the instance we're using didn't come from + // the project. + Plugin projectPlugin = (Plugin) project.getBuild().getPluginsAsMap().get( plugin.getKey() ); + + if ( projectPlugin == null ) + { + projectPlugin = plugin; + } + + Set artifacts = MavenMetadataSource.createArtifacts( artifactFactory, projectPlugin.getDependencies(), null, + null, project ); + +// Set artifacts = +// MavenMetadataSource.createArtifacts( artifactFactory, plugin.getDependencies(), null, null, project ); + + addedPlugin.setIntroducedDependencyArtifacts( artifacts ); + } + catch ( InvalidDependencyVersionException e ) + { + throw new InvalidPluginException( "Plugin '" + plugin + "' is invalid: " + e.getMessage(), e ); + } + } + + // ---------------------------------------------------------------------- + // Mojo execution + // ---------------------------------------------------------------------- + + public void executeMojo( MavenProject project, + MojoExecution mojoExecution, + MavenSession session ) + throws ArtifactResolutionException, MojoExecutionException, MojoFailureException, ArtifactNotFoundException, + InvalidDependencyVersionException, PluginManagerException, PluginConfigurationException + { + MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); + + // NOTE: I'm putting these checks in here, since this is the central point of access for + // anything that wants to execute a mojo. + if ( mojoDescriptor.isProjectRequired() && !session.isUsingPOMsFromFilesystem() ) + { + throw new MojoExecutionException( "Cannot execute mojo: " + mojoDescriptor.getGoal() + + ". It requires a project with an existing pom.xml, but the build is not using one." ); + } + + if ( mojoDescriptor.isOnlineRequired() && session.getSettings().isOffline() ) + { + // TODO: Should we error out, or simply warn and skip?? + throw new MojoExecutionException( "Mojo: " + mojoDescriptor.getGoal() + + " requires online mode for execution. Maven is currently offline." ); + } + + if ( mojoDescriptor.isDependencyResolutionRequired() != null ) + { + Collection projects; + + if ( mojoDescriptor.isAggregator() ) + { + projects = session.getSortedProjects(); + } + else + { + projects = Collections.singleton( project ); + } + + for ( Iterator i = projects.iterator(); i.hasNext(); ) + { + MavenProject p = (MavenProject) i.next(); + + resolveTransitiveDependencies( session, artifactResolver, + mojoDescriptor.isDependencyResolutionRequired(), artifactFactory, p, mojoDescriptor.isAggregator() ); + } + + downloadDependencies( project, session, artifactResolver ); + } + + String goalName = mojoDescriptor.getFullGoalName(); + + Mojo plugin; + + PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); + String goalId = mojoDescriptor.getGoal(); + String groupId = pluginDescriptor.getGroupId(); + String artifactId = pluginDescriptor.getArtifactId(); + String executionId = mojoExecution.getExecutionId(); + Xpp3Dom dom = project.getGoalConfiguration( groupId, artifactId, executionId, goalId ); + Xpp3Dom reportDom = project.getReportConfiguration( groupId, artifactId, executionId ); + dom = Xpp3Dom.mergeXpp3Dom( dom, reportDom ); + if ( mojoExecution.getConfiguration() != null ) + { + dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); + } + + plugin = getConfiguredMojo( session, dom, project, false, mojoExecution ); + + // Event monitoring. + String event = MavenEvents.MOJO_EXECUTION; + EventDispatcher dispatcher = session.getEventDispatcher(); + + String goalExecId = goalName; + + if ( mojoExecution.getExecutionId() != null ) + { + goalExecId += " {execution: " + mojoExecution.getExecutionId() + "}"; + } + + dispatcher.dispatchStart( event, goalExecId ); + + ClassLoader oldClassLoader = Thread.currentThread().getContextClassLoader(); + + try + { + Thread.currentThread().setContextClassLoader( + mojoDescriptor.getPluginDescriptor().getClassRealm().getClassLoader() ); + + plugin.execute(); + + dispatcher.dispatchEnd( event, goalExecId ); + } + catch ( MojoExecutionException e ) + { + session.getEventDispatcher().dispatchError( event, goalExecId, e ); + + throw e; + } + catch ( MojoFailureException e ) + { + session.getEventDispatcher().dispatchError( event, goalExecId, e ); + + throw e; + } + catch ( LinkageError e ) + { + if ( getLogger().isFatalErrorEnabled() ) + { + getLogger().fatalError( + plugin.getClass().getName() + "#execute() caused a linkage error (" + + e.getClass().getName() + ") and may be out-of-date. Check the realms:" ); + + ClassRealm pluginRealm = mojoDescriptor.getPluginDescriptor().getClassRealm(); + StringBuffer sb = new StringBuffer(); + sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' ); + for ( int i = 0; i < pluginRealm.getConstituents().length; i++ ) + { + sb.append( "urls[" + i + "] = " + pluginRealm.getConstituents()[i] ); + if ( i != ( pluginRealm.getConstituents().length - 1 ) ) + { + sb.append( '\n' ); + } + } + getLogger().fatalError( sb.toString() ); + + ClassRealm containerRealm = container.getContainerRealm(); + sb = new StringBuffer(); + sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' ); + for ( int i = 0; i < containerRealm.getConstituents().length; i++ ) + { + sb.append( "urls[" + i + "] = " + containerRealm.getConstituents()[i] ); + if ( i != ( containerRealm.getConstituents().length - 1 ) ) + { + sb.append( '\n' ); + } + } + getLogger().fatalError( sb.toString() ); + } + + session.getEventDispatcher().dispatchError( event, goalExecId, e ); + + throw e; + } + finally + { + + Thread.currentThread().setContextClassLoader( oldClassLoader ); + + try + { + PlexusContainer pluginContainer = getPluginContainer( mojoDescriptor.getPluginDescriptor() ); + + pluginContainer.release( plugin ); + } + catch ( ComponentLifecycleException e ) + { + if ( getLogger().isErrorEnabled() ) + { + getLogger().error( "Error releasing plugin - ignoring.", e ); + } + } + } + } + + public MavenReport getReport( MavenProject project, + MojoExecution mojoExecution, + MavenSession session ) + throws ArtifactNotFoundException, PluginConfigurationException, PluginManagerException, + ArtifactResolutionException + { + MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); + PluginDescriptor descriptor = mojoDescriptor.getPluginDescriptor(); + Xpp3Dom dom = project.getReportConfiguration( descriptor.getGroupId(), descriptor.getArtifactId(), + mojoExecution.getExecutionId() ); + if ( mojoExecution.getConfiguration() != null ) + { + dom = Xpp3Dom.mergeXpp3Dom( dom, mojoExecution.getConfiguration() ); + } + + return (MavenReport) getConfiguredMojo( session, dom, project, true, mojoExecution ); + } + + public PluginDescriptor verifyReportPlugin( ReportPlugin reportPlugin, + MavenProject project, + MavenSession session ) + throws PluginVersionResolutionException, ArtifactResolutionException, ArtifactNotFoundException, + InvalidVersionSpecificationException, InvalidPluginException, PluginManagerException, PluginNotFoundException, + PluginVersionNotFoundException + { + String version = reportPlugin.getVersion(); + + if ( version == null ) + { + version = pluginVersionManager.resolveReportPluginVersion( reportPlugin.getGroupId(), + reportPlugin.getArtifactId(), project, + session.getSettings(), + session.getLocalRepository() ); + reportPlugin.setVersion( version ); + } + + Plugin forLookup = new Plugin(); + + forLookup.setGroupId( reportPlugin.getGroupId() ); + forLookup.setArtifactId( reportPlugin.getArtifactId() ); + forLookup.setVersion( version ); + + return verifyVersionedPlugin( forLookup, project, session.getLocalRepository() ); + } + + private PlexusContainer getPluginContainer( PluginDescriptor pluginDescriptor ) + throws PluginManagerException + { + String pluginKey = pluginDescriptor.getPluginLookupKey(); + + PlexusContainer pluginContainer = container.getChildContainer( pluginKey ); + + if ( pluginContainer == null ) + { + throw new PluginManagerException( "Cannot find Plexus container for plugin: " + pluginKey ); + } + + return pluginContainer; + } + + private Mojo getConfiguredMojo( MavenSession session, + Xpp3Dom dom, + MavenProject project, + boolean report, + MojoExecution mojoExecution ) + throws PluginConfigurationException, ArtifactNotFoundException, PluginManagerException, + ArtifactResolutionException + { + MojoDescriptor mojoDescriptor = mojoExecution.getMojoDescriptor(); + + PluginDescriptor pluginDescriptor = mojoDescriptor.getPluginDescriptor(); + + PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); + + // if this is the first time this plugin has been used, the plugin's container will only + // contain the plugin's artifact in isolation; we need to finish resolving the plugin's + // dependencies, and add them to the container. + ensurePluginContainerIsComplete( pluginDescriptor, pluginContainer, project, session ); + + Mojo plugin; + try + { + plugin = (Mojo) pluginContainer.lookup( Mojo.ROLE, mojoDescriptor.getRoleHint() ); + if ( report && !( plugin instanceof MavenReport ) ) + { + // TODO: the mojoDescriptor should actually capture this information so we don't get this far + return null; + } + } + catch ( ComponentLookupException e ) + { + throw new PluginManagerException( "Unable to find the mojo '" + mojoDescriptor.getRoleHint() + + "' in the plugin '" + pluginDescriptor.getPluginLookupKey() + "'", e ); + } + + if ( plugin instanceof ContextEnabled ) + { + Map pluginContext = session.getPluginContext( pluginDescriptor, project ); + + ( (ContextEnabled) plugin ).setPluginContext( pluginContext ); + } + + plugin.setLog( mojoLogger ); + + XmlPlexusConfiguration pomConfiguration; + if ( dom == null ) + { + pomConfiguration = new XmlPlexusConfiguration( "configuration" ); + } + else + { + pomConfiguration = new XmlPlexusConfiguration( dom ); + } + + // Validate against non-editable (@readonly) parameters, to make sure users aren't trying to + // override in the POM. + validatePomConfiguration( mojoDescriptor, pomConfiguration ); + + PlexusConfiguration mergedConfiguration = mergeMojoConfiguration( pomConfiguration, mojoDescriptor ); + + // TODO: plexus changes to make this more like the component descriptor so this can be used instead + // PlexusConfiguration mergedConfiguration = mergeConfiguration( pomConfiguration, + // mojoDescriptor.getConfiguration() ); + + ExpressionEvaluator expressionEvaluator = new PluginParameterExpressionEvaluator( session, mojoExecution, + pathTranslator, getLogger(), + project, + session.getExecutionProperties() ); + + PlexusConfiguration extractedMojoConfiguration = + extractMojoConfiguration( mergedConfiguration, mojoDescriptor ); + + checkRequiredParameters( mojoDescriptor, extractedMojoConfiguration, expressionEvaluator ); + + populatePluginFields( plugin, mojoDescriptor, extractedMojoConfiguration, pluginContainer, + expressionEvaluator ); + return plugin; + } + + private void ensurePluginContainerIsComplete( PluginDescriptor pluginDescriptor, + PlexusContainer pluginContainer, + MavenProject project, + MavenSession session ) + throws ArtifactNotFoundException, PluginManagerException, ArtifactResolutionException + { + // if the plugin's already been used once, don't re-do this step... + // otherwise, we have to finish resolving the plugin's classpath and start the container. + if ( ( pluginDescriptor.getArtifacts() != null ) && ( pluginDescriptor.getArtifacts().size() == 1 ) ) + { + Artifact pluginArtifact = (Artifact) pluginDescriptor.getArtifacts().get( 0 ); + + ArtifactRepository localRepository = session.getLocalRepository(); + + ResolutionGroup resolutionGroup; + try + { + resolutionGroup = artifactMetadataSource.retrieve( pluginArtifact, localRepository, + project.getPluginArtifactRepositories() ); + } + catch ( ArtifactMetadataRetrievalException e ) + { + throw new ArtifactResolutionException( "Unable to download metadata from repository for plugin '" + + pluginArtifact.getId() + "': " + e.getMessage(), pluginArtifact, e ); + } + + checkPlexusUtils( resolutionGroup, artifactFactory ); + + // [jdcasey; 20-March-2008]: + // This is meant to eliminate the introduction of duplicated artifacts. + // Since much of the reasoning for reversing the order of introduction of + // plugin dependencies rests on the notion that we need to be able to + // introduce upgraded versions of plugin dependencies on a case-by-case + // basis, we need to remove the original version prior to artifact + // resolution. This is consistent with recent thinking on duplicated + // dependency specifications within a POM, where that case should + // throw a model validation exception. + // + // Here, we just want to remove any chance that the ArtifactCollector + // could make a bad choice, and use the old version in spite of our + // explicit preference otherwise. + + // First, we're going to accumulate plugin dependencies in an ordered map, + // keyed by dependencyConflictId (the ordered map is meant to preserve relative + // ordering of the dependencies that do make the cut). + Map dependencyMap = new LinkedHashMap(); + + // Next, we need to accumulate all dependencies in a List, to make it + // simpler to iterate through them all and add them to the map. + List all = new ArrayList(); + + // plugin-level dependencies from the consuming POM override dependencies + // from the plugin's own POM. + all.addAll( pluginDescriptor.getIntroducedDependencyArtifacts() ); + + // add in the deps from the plugin POM now. + all.addAll( resolutionGroup.getArtifacts() ); + + for ( Iterator it = all.iterator(); it.hasNext(); ) + { + Artifact artifact = (Artifact) it.next(); + String conflictId = artifact.getDependencyConflictId(); + + // if the map already contains this dependencyConflictId, it constitutes an + // overridden dependency. Don't use the old one (we know it's old from the + // order in which dependencies were added to this list). + if ( !dependencyMap.containsKey( conflictId ) ) + { + dependencyMap.put( conflictId, artifact ); + } + } + + // Create an ordered set of dependencies from the ordered map we used above, to feed into the resolver. + Set dependencies = new LinkedHashSet( dependencyMap.values() ); + + if ( getLogger().isDebugEnabled() ) + { + // list all dependencies to be used by this plugin (first-level deps, not transitive ones). + getLogger().debug( "Plugin dependencies for:\n\n" + pluginDescriptor.getId() + + "\n\nare:\n\n" + + StringUtils.join( dependencies.iterator(), "\n" ) + "\n\n" ); + } + + List repositories = new ArrayList(); + repositories.addAll( resolutionGroup.getResolutionRepositories() ); + repositories.addAll( project.getRemoteArtifactRepositories() ); + + /* get plugin managed versions */ + Map pluginManagedDependencies = new HashMap(); + try + { + MavenProject pluginProject = + mavenProjectBuilder.buildFromRepository( pluginArtifact, project.getRemoteArtifactRepositories(), + localRepository ); + if ( pluginProject != null ) + { + pluginManagedDependencies = pluginProject.getManagedVersionMap(); + } + } + catch ( ProjectBuildingException e ) + { + // this can't happen, it would have blowed up at artifactMetadataSource.retrieve() + } + + ArtifactResolutionResult result = artifactResolver.resolveTransitively( dependencies, pluginArtifact, + pluginManagedDependencies, + localRepository, repositories, + artifactMetadataSource, + artifactFilter ); + + Set resolved = result.getArtifacts(); + + for ( Iterator it = resolved.iterator(); it.hasNext(); ) + { + Artifact artifact = (Artifact) it.next(); + + if ( !artifact.equals( pluginArtifact ) ) + { + artifact = project.replaceWithActiveArtifact( artifact ); + + try + { + pluginContainer.addJarResource( artifact.getFile() ); + } + catch ( PlexusContainerException e ) + { + throw new PluginManagerException( "Error adding plugin dependency '" + + artifact.getDependencyConflictId() + "' into plugin manager: " + e.getMessage(), e ); + } + } + } + + pluginDescriptor.setClassRealm( pluginContainer.getContainerRealm() ); + + List unresolved = new ArrayList( dependencies ); + + unresolved.removeAll( resolved ); + + if ( getLogger().isDebugEnabled() ) + { + // list all artifacts that were filtered out during the resolution process. + // these are already present in the core container. + getLogger().debug( " The following artifacts were filtered out for plugin: " + + pluginDescriptor.getId() + + " because they're already in the core of Maven:\n\n" + + StringUtils.join( unresolved.iterator(), "\n" ) + + "\n\nThese will use the artifact files already in the core ClassRealm instead, to allow them to be included in PluginDescriptor.getArtifacts().\n\n" ); + } + + // Grab a file for all filtered artifacts, even if it means resolving them. This + // is necessary in order to present a full complement of a plugin's transitive + // dependencies to anyone who calls PluginDescriptor.getArtifacts(). + resolveCoreArtifacts( unresolved, localRepository, resolutionGroup.getResolutionRepositories() ); + + // Re-join resolved and filtered-but-now-resolved artifacts. + // NOTE: The process of filtering then re-adding some artifacts will + // result in different ordering within the PluginDescriptor.getArtifacts() + // List than should have happened if none had been filtered. All filtered + // artifacts will be listed last... + List allResolved = new ArrayList( resolved.size() + unresolved.size() ); + + allResolved.addAll( resolved ); + allResolved.addAll( unresolved ); + + pluginDescriptor.setArtifacts( allResolved ); + } + } + + public static void checkPlexusUtils( ResolutionGroup resolutionGroup, ArtifactFactory artifactFactory ) + { + // ---------------------------------------------------------------------------- + // If the plugin already declares a dependency on plexus-utils then we're all + // set as the plugin author is aware of its use. If we don't have a dependency + // on plexus-utils then we must protect users from stupid plugin authors who + // did not declare a direct dependency on plexus-utils because the version + // Maven uses is hidden from downstream use. We will also bump up any + // anything below 1.1 to 1.1 as this mimics the behaviour in 2.0.5 where + // plexus-utils 1.1 was being forced into use. + // ---------------------------------------------------------------------------- + + VersionRange vr = null; + + try + { + vr = VersionRange.createFromVersionSpec( "[1.1,)" ); + } + catch ( InvalidVersionSpecificationException e ) + { + // Won't happen + } + + boolean plexusUtilsPresent = false; + + for ( Iterator i = resolutionGroup.getArtifacts().iterator(); i.hasNext(); ) + { + Artifact a = (Artifact) i.next(); + + if ( a.getArtifactId().equals( "plexus-utils" ) && + vr.containsVersion( new DefaultArtifactVersion( a.getVersion() ) ) ) + { + plexusUtilsPresent = true; + + break; + } + } + + if ( !plexusUtilsPresent ) + { + // We will add plexus-utils as every plugin was getting this anyway from Maven itself. We will set the + // version to the latest version we know that works as of the 2.0.6 release. We set the scope to runtime + // as this is what's implicitly happening in 2.0.6. + + resolutionGroup.getArtifacts().add( artifactFactory.createArtifact( "org.codehaus.plexus", + "plexus-utils", "1.1", + Artifact.SCOPE_RUNTIME, "jar" ) ); + } + } + + private void resolveCoreArtifacts( List unresolved, + ArtifactRepository localRepository, + List resolutionRepositories ) + throws ArtifactResolutionException, ArtifactNotFoundException + { + for ( Iterator it = unresolved.iterator(); it.hasNext(); ) + { + Artifact artifact = (Artifact) it.next(); + + File artifactFile = (File) resolvedCoreArtifactFiles.get( artifact.getId() ); + + if ( artifactFile == null ) + { + String resource = + "/META-INF/maven/" + artifact.getGroupId() + "/" + artifact.getArtifactId() + "/pom.xml"; + + URL resourceUrl = container.getContainerRealm().getResource( resource ); + + if ( resourceUrl == null ) + { + artifactResolver.resolve( artifact, resolutionRepositories, localRepository ); + + artifactFile = artifact.getFile(); + } + else + { + String artifactPath = resourceUrl.getPath(); + + if ( artifactPath.startsWith( "file:" ) ) + { + artifactPath = artifactPath.substring( "file:".length() ); + } + + artifactPath = artifactPath.substring( 0, artifactPath.length() - resource.length() ); + + if ( artifactPath.endsWith( "/" ) ) + { + artifactPath = artifactPath.substring( 0, artifactPath.length() - 1 ); + } + + if ( artifactPath.endsWith( "!" ) ) + { + artifactPath = artifactPath.substring( 0, artifactPath.length() - 1 ); + } + + artifactFile = new File( artifactPath ).getAbsoluteFile(); + } + + resolvedCoreArtifactFiles.put( artifact.getId(), artifactFile ); + } + + artifact.setFile( artifactFile ); + } + } + + private PlexusConfiguration extractMojoConfiguration( PlexusConfiguration mergedConfiguration, + MojoDescriptor mojoDescriptor ) + { + Map parameterMap = mojoDescriptor.getParameterMap(); + + PlexusConfiguration[] mergedChildren = mergedConfiguration.getChildren(); + + XmlPlexusConfiguration extractedConfiguration = new XmlPlexusConfiguration( "configuration" ); + + for ( int i = 0; i < mergedChildren.length; i++ ) + { + PlexusConfiguration child = mergedChildren[i]; + + if ( parameterMap.containsKey( child.getName() ) ) + { + extractedConfiguration.addChild( copyConfiguration( child ) ); + } + else + { + // TODO: I defy anyone to find these messages in the '-X' output! Do we need a new log level? + // ideally, this would be elevated above the true debug output, but below the default INFO level... + // [BP] (2004-07-18): need to understand the context more but would prefer this could be either WARN or + // removed - shouldn't need DEBUG to diagnose a problem most of the time. + getLogger().debug( "*** WARNING: Configuration \'" + child.getName() + "\' is not used in goal \'" + + mojoDescriptor.getFullGoalName() + "; this may indicate a typo... ***" ); + } + } + + return extractedConfiguration; + } + + private void checkRequiredParameters( MojoDescriptor goal, + PlexusConfiguration configuration, + ExpressionEvaluator expressionEvaluator ) + throws PluginConfigurationException + { + // TODO: this should be built in to the configurator, as we presently double process the expressions + + List parameters = goal.getParameters(); + + if ( parameters == null ) + { + return; + } + + List invalidParameters = new ArrayList(); + + for ( int i = 0; i < parameters.size(); i++ ) + { + Parameter parameter = (Parameter) parameters.get( i ); + + if ( parameter.isRequired() ) + { + // the key for the configuration map we're building. + String key = parameter.getName(); + + Object fieldValue = null; + String expression = null; + PlexusConfiguration value = configuration.getChild( key, false ); + try + { + if ( value != null ) + { + expression = value.getValue( null ); + + fieldValue = expressionEvaluator.evaluate( expression ); + + if ( fieldValue == null ) + { + fieldValue = value.getAttribute( "default-value", null ); + } + } + + if ( ( fieldValue == null ) && StringUtils.isNotEmpty( parameter.getAlias() ) ) + { + value = configuration.getChild( parameter.getAlias(), false ); + if ( value != null ) + { + expression = value.getValue( null ); + fieldValue = expressionEvaluator.evaluate( expression ); + if ( fieldValue == null ) + { + fieldValue = value.getAttribute( "default-value", null ); + } + } + } + } + catch ( ExpressionEvaluationException e ) + { + throw new PluginConfigurationException( goal.getPluginDescriptor(), e.getMessage(), e ); + } + + // only mark as invalid if there are no child nodes + if ( ( fieldValue == null ) && ( ( value == null ) || ( value.getChildCount() == 0 ) ) ) + { + parameter.setExpression( expression ); + invalidParameters.add( parameter ); + } + } + } + + if ( !invalidParameters.isEmpty() ) + { + throw new PluginParameterException( goal, invalidParameters ); + } + } + + private void validatePomConfiguration( MojoDescriptor goal, + PlexusConfiguration pomConfiguration ) + throws PluginConfigurationException + { + List parameters = goal.getParameters(); + + if ( parameters == null ) + { + return; + } + + for ( int i = 0; i < parameters.size(); i++ ) + { + Parameter parameter = (Parameter) parameters.get( i ); + + // the key for the configuration map we're building. + String key = parameter.getName(); + + PlexusConfiguration value = pomConfiguration.getChild( key, false ); + + if ( ( value == null ) && StringUtils.isNotEmpty( parameter.getAlias() ) ) + { + key = parameter.getAlias(); + value = pomConfiguration.getChild( key, false ); + } + + if ( value != null ) + { + // Make sure the parameter is either editable/configurable, or else is NOT specified in the POM + if ( !parameter.isEditable() ) + { + StringBuffer errorMessage = new StringBuffer() + .append( "ERROR: Cannot override read-only parameter: " ); + errorMessage.append( key ); + errorMessage.append( " in goal: " ).append( goal.getFullGoalName() ); + + throw new PluginConfigurationException( goal.getPluginDescriptor(), errorMessage.toString() ); + } + + String deprecated = parameter.getDeprecated(); + if ( StringUtils.isNotEmpty( deprecated ) ) + { + getLogger().warn( "DEPRECATED [" + parameter.getName() + "]: " + deprecated ); + } + } + } + } + + private PlexusConfiguration mergeMojoConfiguration( XmlPlexusConfiguration fromPom, + MojoDescriptor mojoDescriptor ) + { + XmlPlexusConfiguration result = new XmlPlexusConfiguration( fromPom.getName() ); + result.setValue( fromPom.getValue( null ) ); + + if ( mojoDescriptor.getParameters() != null ) + { + PlexusConfiguration fromMojo = mojoDescriptor.getMojoConfiguration(); + + for ( Iterator it = mojoDescriptor.getParameters().iterator(); it.hasNext(); ) + { + Parameter parameter = (Parameter) it.next(); + + String paramName = parameter.getName(); + String alias = parameter.getAlias(); + String implementation = parameter.getImplementation(); + + PlexusConfiguration pomConfig = fromPom.getChild( paramName ); + PlexusConfiguration aliased = null; + + if ( alias != null ) + { + aliased = fromPom.getChild( alias ); + } + + PlexusConfiguration mojoConfig = fromMojo.getChild( paramName, false ); + + // first we'll merge configurations from the aliased and real params. + // TODO: Is this the right thing to do? + if ( aliased != null ) + { + if ( pomConfig == null ) + { + pomConfig = new XmlPlexusConfiguration( paramName ); + } + + pomConfig = buildTopDownMergedConfiguration( pomConfig, aliased ); + } + + PlexusConfiguration toAdd = null; + + if ( pomConfig != null ) + { + pomConfig = buildTopDownMergedConfiguration( pomConfig, mojoConfig ); + + if ( StringUtils.isNotEmpty( pomConfig.getValue( null ) ) || ( pomConfig.getChildCount() > 0 ) ) + { + toAdd = pomConfig; + } + } + + if ( ( toAdd == null ) && ( mojoConfig != null ) ) + { + toAdd = copyConfiguration( mojoConfig ); + } + + if ( toAdd != null ) + { + if ( ( implementation != null ) && ( toAdd.getAttribute( "implementation", null ) == null ) ) + { + + XmlPlexusConfiguration implementationConf = new XmlPlexusConfiguration( paramName ); + + implementationConf.setAttribute( "implementation", parameter.getImplementation() ); + + toAdd = buildTopDownMergedConfiguration( toAdd, implementationConf ); + } + + result.addChild( toAdd ); + } + } + } + return result; + } + + private XmlPlexusConfiguration buildTopDownMergedConfiguration( PlexusConfiguration dominant, + PlexusConfiguration recessive ) + { + XmlPlexusConfiguration result = new XmlPlexusConfiguration( dominant.getName() ); + + String value = dominant.getValue( null ); + + if ( StringUtils.isEmpty( value ) && ( recessive != null ) ) + { + value = recessive.getValue( null ); + } + + if ( StringUtils.isNotEmpty( value ) ) + { + result.setValue( value ); + } + + String[] attributeNames = dominant.getAttributeNames(); + + for ( int i = 0; i < attributeNames.length; i++ ) + { + String attributeValue = dominant.getAttribute( attributeNames[i], null ); + + result.setAttribute( attributeNames[i], attributeValue ); + } + + if ( recessive != null ) + { + attributeNames = recessive.getAttributeNames(); + + for ( int i = 0; i < attributeNames.length; i++ ) + { + String attributeValue = recessive.getAttribute( attributeNames[i], null ); + // TODO: recessive seems to be dominant here? + result.setAttribute( attributeNames[i], attributeValue ); + } + } + + PlexusConfiguration[] children = dominant.getChildren(); + + for ( int i = 0; i < children.length; i++ ) + { + PlexusConfiguration childDom = children[i]; + PlexusConfiguration childRec = recessive == null ? null : recessive.getChild( childDom.getName(), false ); + + if ( childRec != null ) + { + result.addChild( buildTopDownMergedConfiguration( childDom, childRec ) ); + } + else + { // FIXME: copy, or use reference? + result.addChild( copyConfiguration( childDom ) ); + } + } + + return result; + } + + public static PlexusConfiguration copyConfiguration( PlexusConfiguration src ) + { + // TODO: shouldn't be necessary + XmlPlexusConfiguration dom = new XmlPlexusConfiguration( src.getName() ); + dom.setValue( src.getValue( null ) ); + + String[] attributeNames = src.getAttributeNames(); + for ( int i = 0; i < attributeNames.length; i++ ) + { + String attributeName = attributeNames[i]; + dom.setAttribute( attributeName, src.getAttribute( attributeName, null ) ); + } + + PlexusConfiguration[] children = src.getChildren(); + for ( int i = 0; i < children.length; i++ ) + { + dom.addChild( copyConfiguration( children[i] ) ); + } + + return dom; + } + + // ---------------------------------------------------------------------- + // Mojo Parameter Handling + // ---------------------------------------------------------------------- + + private void populatePluginFields( Mojo plugin, + MojoDescriptor mojoDescriptor, + PlexusConfiguration configuration, + PlexusContainer pluginContainer, + ExpressionEvaluator expressionEvaluator ) + throws PluginConfigurationException + { + ComponentConfigurator configurator = null; + + try + { + String configuratorId = mojoDescriptor.getComponentConfigurator(); + + // TODO: could the configuration be passed to lookup and the configurator known to plexus via the descriptor + // so that this meethod could entirely be handled by a plexus lookup? + if ( StringUtils.isNotEmpty( configuratorId ) ) + { + configurator = + (ComponentConfigurator) pluginContainer.lookup( ComponentConfigurator.ROLE, configuratorId ); + } + else + { + configurator = (ComponentConfigurator) pluginContainer.lookup( ComponentConfigurator.ROLE ); + } + + ConfigurationListener listener = new DebugConfigurationListener( getLogger() ); + + getLogger().debug( "Configuring mojo '" + mojoDescriptor.getId() + "' -->" ); + configurator.configureComponent( plugin, configuration, expressionEvaluator, + pluginContainer.getContainerRealm(), listener ); + getLogger().debug( "-- end configuration --" ); + } + catch ( ComponentConfigurationException e ) + { + throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), + "Unable to parse the created DOM for plugin configuration", e ); + } + catch ( ComponentLookupException e ) + { + throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), + "Unable to retrieve component configurator for plugin configuration", + e ); + } + catch ( LinkageError e ) + { + if ( getLogger().isFatalErrorEnabled() ) + { + getLogger().fatalError( + configurator.getClass().getName() + "#configureComponent(...) caused a linkage error (" + + e.getClass().getName() + ") and may be out-of-date. Check the realms:" ); + + ClassRealm pluginRealm = mojoDescriptor.getPluginDescriptor().getClassRealm(); + StringBuffer sb = new StringBuffer(); + sb.append( "Plugin realm = " + pluginRealm.getId() ).append( '\n' ); + for ( int i = 0; i < pluginRealm.getConstituents().length; i++ ) + { + sb.append( "urls[" + i + "] = " + pluginRealm.getConstituents()[i] ); + if ( i != ( pluginRealm.getConstituents().length - 1 ) ) + { + sb.append( '\n' ); + } + } + getLogger().fatalError( sb.toString() ); + + ClassRealm containerRealm = container.getContainerRealm(); + sb = new StringBuffer(); + sb.append( "Container realm = " + containerRealm.getId() ).append( '\n' ); + for ( int i = 0; i < containerRealm.getConstituents().length; i++ ) + { + sb.append( "urls[" + i + "] = " + containerRealm.getConstituents()[i] ); + if ( i != ( containerRealm.getConstituents().length - 1 ) ) + { + sb.append( '\n' ); + } + } + getLogger().fatalError( sb.toString() ); + } + + throw new PluginConfigurationException( mojoDescriptor.getPluginDescriptor(), + e.getClass().getName() + ": " + e.getMessage(), e ); + } + finally + { + if ( configurator != null ) + { + try + { + pluginContainer.release( configurator ); + } + catch ( ComponentLifecycleException e ) + { + getLogger().debug( "Failed to release plugin container - ignoring." ); + } + } + } + } + + public static String createPluginParameterRequiredMessage( MojoDescriptor mojo, + Parameter parameter, + String expression ) + { + StringBuffer message = new StringBuffer(); + + message.append( "The '" ); + message.append( parameter.getName() ); + message.append( "' parameter is required for the execution of the " ); + message.append( mojo.getFullGoalName() ); + message.append( " mojo and cannot be null." ); + if ( expression != null ) + { + message.append( " The retrieval expression was: " ).append( expression ); + } + + return message.toString(); + } + + // ---------------------------------------------------------------------- + // Lifecycle + // ---------------------------------------------------------------------- + + public void contextualize( Context context ) + throws ContextException + { + container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); + + mojoLogger = new DefaultLog( container.getLoggerManager().getLoggerForComponent( Mojo.ROLE ) ); + } + + public void initialize() + { + artifactFilter = MavenArtifactFilterManager.createStandardFilter(); + } + + // ---------------------------------------------------------------------- + // Artifact resolution + // ---------------------------------------------------------------------- + + private void resolveTransitiveDependencies( MavenSession context, + ArtifactResolver artifactResolver, + String scope, + ArtifactFactory artifactFactory, + MavenProject project, boolean isAggregator ) + throws ArtifactResolutionException, ArtifactNotFoundException, InvalidDependencyVersionException + { + ArtifactFilter filter = new ScopeArtifactFilter( scope ); + + // TODO: such a call in MavenMetadataSource too - packaging not really the intention of type + Artifact artifact = artifactFactory.createBuildArtifact( project.getGroupId(), project.getArtifactId(), + project.getVersion(), project.getPackaging() ); + + // TODO: we don't need to resolve over and over again, as long as we are sure that the parameters are the same + // check this with yourkit as a hot spot. + // Don't recreate if already created - for effeciency, and because clover plugin adds to it + if ( project.getDependencyArtifacts() == null ) + { + project.setDependencyArtifacts( project.createArtifacts( artifactFactory, null, null ) ); + } + + Set resolvedArtifacts; + try + { + ArtifactResolutionResult result = artifactResolver.resolveTransitively( project.getDependencyArtifacts(), + artifact, + project.getManagedVersionMap(), + context.getLocalRepository(), + project.getRemoteArtifactRepositories(), + artifactMetadataSource, filter ); + resolvedArtifacts = result.getArtifacts(); + } + catch (MultipleArtifactsNotFoundException me) + { + /*only do this if we are an aggregating plugin: MNG-2277 + if the dependency doesn't yet exist but is in the reactor, then + all we can do is warn and skip it. A better fix can be inserted into 2.1*/ + if (isAggregator && checkMissingArtifactsInReactor( context.getSortedProjects(), me.getMissingArtifacts() )) + { + resolvedArtifacts = new HashSet(me.getResolvedArtifacts()); + } + else + { + //we can't find all the artifacts in the reactor so bubble the exception up. + throw me; + } + } + project.setArtifacts( resolvedArtifacts ); + } + + /** + * This method is checking to see if the artifacts that can't be resolved are all + * part of this reactor. This is done to prevent a chicken or egg scenario with + * fresh projects that have a plugin that is an aggregator and requires dependencies. See + * MNG-2277 for more info. + * @param projects the sibling projects in the reactor + * @param missing the artifacts that can't be found + * @return true if ALL missing artifacts are found in the reactor. + */ + private boolean checkMissingArtifactsInReactor(Collection projects, Collection missing) + { + Collection foundInReactor = new HashSet(); + Iterator iter = missing.iterator(); + while (iter.hasNext()) + { + Artifact mArtifact = (Artifact) iter.next(); + Iterator pIter = projects.iterator(); + while (pIter.hasNext()) + { + MavenProject p = (MavenProject) pIter.next(); + if (p.getArtifactId().equals( mArtifact.getArtifactId()) && + p.getGroupId().equals( mArtifact.getGroupId()) && + p.getVersion().equals( mArtifact.getVersion())) + { + //TODO: the packaging could be different, but the exception doesn't contain that info + //most likely it would be produced by the project we just found in the reactor since all + //the other info matches. Assume it's ok. + getLogger().warn( "The dependency: "+ p.getId()+" can't be resolved but has been found in the reactor.\nThis dependency has been excluded from the plugin execution. You should rerun this mojo after executing mvn install.\n" ); + + //found it, move on. + foundInReactor.add( p ); + break; + } + } + } + + //if all of them have been found, we can continue. + return foundInReactor.size() == missing.size(); + } + + + // ---------------------------------------------------------------------- + // Artifact downloading + // ---------------------------------------------------------------------- + + private void downloadDependencies( MavenProject project, + MavenSession context, + ArtifactResolver artifactResolver ) + throws ArtifactResolutionException, ArtifactNotFoundException + { + ArtifactRepository localRepository = context.getLocalRepository(); + List remoteArtifactRepositories = project.getRemoteArtifactRepositories(); + + for ( Iterator it = project.getArtifacts().iterator(); it.hasNext(); ) + { + Artifact artifact = (Artifact) it.next(); + + artifactResolver.resolve( artifact, remoteArtifactRepositories, localRepository ); + } + } + + public Object getPluginComponent( Plugin plugin, + String role, + String roleHint ) + throws PluginManagerException, ComponentLookupException + { + PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( plugin ); + + PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); + + return pluginContainer.lookup( role, roleHint ); + } + + public Map getPluginComponents( Plugin plugin, + String role ) + throws ComponentLookupException, PluginManagerException + { + PluginDescriptor pluginDescriptor = pluginCollector.getPluginDescriptor( plugin ); + + PlexusContainer pluginContainer = getPluginContainer( pluginDescriptor ); + + return pluginContainer.lookupMap( role ); + } +} \ No newline at end of file diff --git a/maven-interceptor/src/main/java/hudson/maven/agent/PluginManagerInterceptor.java b/maven-interceptor/src/main/java/hudson/maven/agent/PluginManagerInterceptor.java index 34477eed18..94131b9721 100644 --- a/maven-interceptor/src/main/java/hudson/maven/agent/PluginManagerInterceptor.java +++ b/maven-interceptor/src/main/java/hudson/maven/agent/PluginManagerInterceptor.java @@ -26,7 +26,6 @@ package hudson.maven.agent; import org.apache.maven.artifact.resolver.ArtifactNotFoundException; import org.apache.maven.artifact.resolver.ArtifactResolutionException; import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.DefaultPluginManager; import org.apache.maven.plugin.MojoExecution; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; diff --git a/maven-plugin/pom.xml b/maven-plugin/pom.xml index e66aed0343..af8b0d5d24 100644 --- a/maven-plugin/pom.xml +++ b/maven-plugin/pom.xml @@ -37,165 +37,206 @@ THE SOFTWARE. Now it is a plug-in that is installed by default, but can be disabled. http://wiki.hudson-ci.org/display/HUDSON/Maven+2+Project+Plugin - - - org.jvnet.hudson.main - hudson-core - ${project.version} - provided - - - javax.servlet - servlet-api - 2.4 - provided - - - - ${project.groupId} - maven-agent - ${project.version} - - - org.jvnet.hudson - maven2.1-interceptor - 1.2 - - - org.jvnet.hudson - maven-embedder - 2.0.4-hudson-1 - - - - jtidy - jtidy - - - commons-cli - commons-cli - - - xml-apis - xml-apis - - - - org.apache.maven.wagon - wagon-webdav - - - - - - - org.jvnet.hudson + + + org.jvnet.hudson.main + hudson-core + ${project.version} + provided + + + javax.servlet + servlet-api + 2.4 + provided + + + + ${project.groupId} + maven-agent + ${project.version} + + + + org.jvnet.hudson.main + maven-interceptor + ${project.version} + + + + org.jvnet.hudson + maven2.1-interceptor + 1.2 + + + + org.jvnet.hudson.main + maven3-agent + ${project.version} + + + + org.jvnet.hudson.main + maven3-listener + ${project.version} + + + + org.apache.ant + ant + + + org.apache.maven + maven-core + + + org.apache.maven.reporting + maven-reporting-api + 3.0 + + + org.apache.maven + maven-compat + + + org.codehaus.plexus + plexus-classworlds + + + org.jvnet.hudson + maven-embedder + 3.0-SNAPSHOT + + + + jtidy + jtidy + + + commons-cli + commons-cli + + + xml-apis + xml-apis + + + + org.apache.maven.wagon wagon-webdav - 1.0-beta-2-hudson-1 - - - jdom - jdom - - - - + + + - - - ${project.artifactId} - package - - - org.jvnet.hudson.tools - maven-hpi-plugin - 1.54 - true - - true - true - - - - org.kohsuke.stapler - maven-stapler-plugin - 1.12 - true - - - org.jvnet.localizer - maven-localizer-plugin - 1.8 - - - - generate - - - Messages.properties - target/generated-sources/localizer - - - - - - - - - - cobertura2 - - - - org.codehaus.mojo - cobertura-maven-plugin - 2.4-apb-SNAPSHOT - true + + + org.jvnet.hudson + wagon-webdav + 1.0-beta-2-hudson-1 + + + jdom + jdom + + + + + + + + ${project.artifactId} + package + + + org.jvnet.hudson.tools + maven-hpi-plugin + 1.54 + true + + true + true + + + + org.kohsuke.stapler + maven-stapler-plugin + 1.12 + true + + + org.jvnet.localizer + maven-localizer-plugin + 1.8 + + + + generate + - - html - xml - + Messages.properties + target/generated-sources/localizer - - - coverage-instrument - process-test-classes - - instrument - - - - coverage-report - test - - generate-report - - - - - - - - - + + + + + + + + + cobertura2 + + + + org.codehaus.mojo + cobertura-maven-plugin + 2.4-apb-SNAPSHOT + true + + + html + xml + + + + + coverage-instrument + process-test-classes + + instrument + + + + coverage-report + test + + generate-report + + + + + + + + + diff --git a/maven-plugin/src/main/java/hudson/maven/AbstractMavenBuilder.java b/maven-plugin/src/main/java/hudson/maven/AbstractMavenBuilder.java new file mode 100644 index 0000000000..8dc469dfb0 --- /dev/null +++ b/maven-plugin/src/main/java/hudson/maven/AbstractMavenBuilder.java @@ -0,0 +1,88 @@ +/* + * 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 hudson.maven; + +import hudson.model.BuildListener; +import hudson.model.Hudson; +import hudson.model.Result; +import hudson.remoting.DelegatingCallable; + +import java.io.IOException; +import java.text.NumberFormat; +import java.util.List; +import java.util.Map; + +/** + * @author Olivier Lamy + * + */ +public abstract class AbstractMavenBuilder implements DelegatingCallable { + + /** + * Goals to be executed in this Maven execution. + */ + protected final List goals; + /** + * Hudson-defined system properties. These will be made available to Maven, + * and accessible as if they are specified as -Dkey=value + */ + protected final Map systemProps; + /** + * Where error messages and so on are sent. + */ + protected final BuildListener listener; + + protected AbstractMavenBuilder(BuildListener listener, List goals, Map systemProps) { + this.listener = listener; + this.goals = goals; + this.systemProps = systemProps; + } + + protected String formatArgs(List 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); + } + return buf.toString(); + } + + + + + protected 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; + } + +} diff --git a/maven-plugin/src/main/java/hudson/maven/EmbedderLoggerImpl.java b/maven-plugin/src/main/java/hudson/maven/EmbedderLoggerImpl.java index 5d61e704e8..57f08058a7 100644 --- a/maven-plugin/src/main/java/hudson/maven/EmbedderLoggerImpl.java +++ b/maven-plugin/src/main/java/hudson/maven/EmbedderLoggerImpl.java @@ -24,22 +24,25 @@ package hudson.maven; import hudson.model.TaskListener; -import org.apache.maven.embedder.AbstractMavenEmbedderLogger; -import org.apache.maven.embedder.MavenEmbedderLogger; import java.io.PrintStream; import java.util.StringTokenizer; +import org.apache.maven.cli.MavenLoggerManager; +import org.codehaus.plexus.logging.Logger; +import org.codehaus.plexus.logging.console.ConsoleLogger; + /** * {@link MavenEmbedderLogger} implementation that * sends output to {@link TaskListener}. * * @author Kohsuke Kawaguchi */ -public final class EmbedderLoggerImpl extends AbstractMavenEmbedderLogger { +public final class EmbedderLoggerImpl extends MavenLoggerManager { private final PrintStream logger; - public EmbedderLoggerImpl(TaskListener listener) { + public EmbedderLoggerImpl(TaskListener listener, int threshold) { + super(new ConsoleLogger( threshold, "hudson-logger" )); logger = listener.getLogger(); } @@ -57,22 +60,22 @@ public final class EmbedderLoggerImpl extends AbstractMavenEmbedderLogger { } public void debug(String message, Throwable throwable) { - print(message, throwable, LEVEL_DEBUG, "[DEBUG] "); + print(message, throwable, Logger.LEVEL_DEBUG, "[DEBUG] "); } public void info(String message, Throwable throwable) { - print(message, throwable, LEVEL_INFO, "[INFO ] "); + print(message, throwable, Logger.LEVEL_INFO, "[INFO ] "); } public void warn(String message, Throwable throwable) { - print(message, throwable, LEVEL_WARN, "[WARN ] "); + print(message, throwable, Logger.LEVEL_WARN, "[WARN ] "); } public void error(String message, Throwable throwable) { - print(message, throwable, LEVEL_ERROR, "[ERROR] "); + print(message, throwable, Logger.LEVEL_ERROR, "[ERROR] "); } public void fatalError(String message, Throwable throwable) { - print(message, throwable, LEVEL_FATAL, "[FATAL] "); + print(message, throwable, Logger.LEVEL_FATAL, "[FATAL] "); } } diff --git a/maven-plugin/src/main/java/hudson/maven/Maven3Builder.java b/maven-plugin/src/main/java/hudson/maven/Maven3Builder.java new file mode 100644 index 0000000000..a9ec111025 --- /dev/null +++ b/maven-plugin/src/main/java/hudson/maven/Maven3Builder.java @@ -0,0 +1,328 @@ +/* + * 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 hudson.maven; + +import hudson.model.BuildListener; +import hudson.model.Hudson; +import hudson.model.Result; +import hudson.remoting.Channel; +import hudson.remoting.DelegatingCallable; +import hudson.remoting.Future; +import hudson.util.IOException2; + +import java.io.IOException; +import java.io.PrintStream; +import java.io.Serializable; +import java.lang.reflect.InvocationTargetException; +import java.text.NumberFormat; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.concurrent.ExecutionException; + +import org.apache.maven.execution.AbstractExecutionListener; +import org.apache.maven.execution.ExecutionEvent; +import org.apache.maven.execution.ExecutionListener; +import org.jvnet.hudson.maven3.agent.Maven3Main; +import org.jvnet.hudson.maven3.launcher.Maven3Launcher; +import org.jvnet.hudson.maven3.listeners.HudsonMavenExecutionResult; + +/** + * @author Olivier Lamy + * + */ +public class Maven3Builder extends AbstractMavenBuilder implements DelegatingCallable { + + /** + * Flag needs to be set at the constructor, so that this reflects + * the setting at master. + */ + private final boolean profile = MavenProcessFactory.profile; + + /** + * Record all asynchronous executions as they are scheduled, + * to make sure they are all completed before we finish. + */ + protected transient /*final*/ List> futures; + + HudsonMavenExecutionResult mavenExecutionResult; + + protected Maven3Builder(BuildListener listener, List goals, Map systemProps) { + super( listener, goals, systemProps ); + } + + public Result call() + throws IOException + { + + try { + futures = new ArrayList>(); + MavenExecutionListener mavenExecutionListener = new MavenExecutionListener( this ); + Maven3Launcher.setMavenExecutionListener( mavenExecutionListener ); + + markAsSuccess = false; + + // working around NPE when someone puts a null value into systemProps. + for (Map.Entry 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
+ + + + + org.apache.maven + maven-core + 3.0 + + + org.apache.maven + maven-compat + 3.0 + + + org.apache.maven + maven-aether-provider + 3.0 + + + org.apache.maven + maven-embedder + 3.0 + + + org.sonatype.sisu + sisu-inject-plexus + 1.4.2 + + + org.codehaus.plexus + plexus-classworlds + 2.2.3 + + + org.apache.ant + ant + 1.8.0 + + + junit + junit + 4.8.1 + + + - 2.0.9 - 2.0.4 + 3.0 + UTF-8 @@ -348,6 +397,37 @@ THE SOFTWARE. + + m2e + + target + + + + m2e.version + + + + ${m2BuildDirectory} + + + org.maven.ide.eclipse + lifecycle-mapping + 0.10.0 + + customizable + + + + + + org.apache.maven.plugins:maven-resources-plugin:: + + + + + + diff --git a/remoting/src/main/java/hudson/remoting/UserRequest.java b/remoting/src/main/java/hudson/remoting/UserRequest.java index 693796171a..a95221fbd0 100644 --- a/remoting/src/main/java/hudson/remoting/UserRequest.java +++ b/remoting/src/main/java/hudson/remoting/UserRequest.java @@ -108,7 +108,9 @@ final class UserRequest extends Request