File D:\maven-qcr-plugin-testsunitaires\qcr4java\jenkins-master\target\site\qc\maven-plugin\src\main\java\hudson\maven\MavenBuilder.java.html

1 /*
2 * The MIT License
3 *
4 * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi,
5 * Olivier Lamy
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25 package hudson.maven;
26
27 import hudson.maven.agent.AbortException;
28 import hudson.maven.agent.Main;
29 import hudson.maven.agent.PluginManagerListener;
30 import hudson.maven.reporters.SurefireArchiver;
31 import hudson.model.BuildListener;
32 import hudson.model.Result;
33 import hudson.remoting.Callable;
34 import hudson.remoting.Channel;
35 import hudson.remoting.DelegatingCallable;
36 import hudson.util.IOException2;
37
38 import java.io.IOException;
39 import java.io.PrintStream;
40 import java.lang.reflect.InvocationTargetException;
41 import java.lang.reflect.Method;
42 import java.text.NumberFormat;
43 import java.util.Collection;
44 import java.util.List;
45 import java.util.Map;
46 import java.util.concurrent.ConcurrentHashMap;
47 import java.util.concurrent.atomic.AtomicBoolean;
48
49 import org.apache.maven.BuildFailureException;
50 import org.apache.maven.execution.MavenSession;
51 import org.apache.maven.execution.ReactorManager;
52 import org.apache.maven.lifecycle.LifecycleExecutionException;
53 import org.apache.maven.lifecycle.LifecycleExecutorListener;
54 import org.apache.maven.monitor.event.EventDispatcher;
55 import org.apache.maven.plugin.Mojo;
56 import org.apache.maven.plugin.MojoExecution;
57 import org.apache.maven.project.MavenProject;
58 import org.apache.maven.reporting.MavenReport;
59 import org.codehaus.classworlds.NoSuchRealmException;
60 import org.codehaus.plexus.component.configurator.expression.ExpressionEvaluator;
61 import org.codehaus.plexus.configuration.PlexusConfiguration;
62
63 /**
64 * {@link Callable} that invokes Maven CLI (in process) and drives a build.
65 *
66 * <p>
67 * As a callable, this function returns the build result.
68 *
69 * <p>
70 * This class defines a series of event callbacks, which are invoked during the build.
71 * This allows subclass to monitor the progress of a build.
72 *
73 * @author Kohsuke Kawaguchi
74 * @since 1.133
75 */
76 @SuppressWarnings("deprecation") // as we're restricted to Maven 2.x API here, but compile against Maven 3.x we cannot avoid deprecations
77 public abstract class MavenBuilder extends AbstractMavenBuilder implements DelegatingCallable<Result,IOException> {
78
79
80 /**
81 * Flag needs to be set at the constructor, so that this reflects
82 * the setting at master.
83 */
84 private final boolean profile = MavenProcessFactory.profile;
85
86 protected MavenBuilder(BuildListener listener, Collection<MavenModule> modules, List<String> goals, Map<String, String> systemProps) {
87 super( listener, modules, goals, systemProps );
88 }
89
90 /**
91 * Called before the whole build.
92 */
93 abstract void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException;
94
95 /**
96 * Called after the build has completed fully.
97 */
98 abstract void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException;
99
100 /**
101 * Called when a build enter another module.
102 */
103 abstract void preModule(MavenProject project) throws InterruptedException, IOException, AbortException;
104
105 /**
106 * Called when a build leaves a module.
107 */
108 abstract void postModule(MavenProject project) throws InterruptedException, IOException, AbortException;
109
110 /**
111 * Called before a mojo is executed
112 */
113 abstract void preExecute(MavenProject project, MojoInfo mojoInfo) throws IOException, InterruptedException, AbortException;
114
115 /**
116 * Called after a mojo has finished executing.
117 */
118 abstract void postExecute(MavenProject project, MojoInfo mojoInfo, Exception exception) throws IOException, InterruptedException, AbortException;
119
120 /**
121 * Called after a {@link MavenReport} is successfully generated.
122 */
123 abstract void onReportGenerated(MavenProject project, MavenReportInfo report) throws IOException, InterruptedException, AbortException;
124
125 private Class<?> pluginManagerInterceptorClazz;
126
127 private Class<?> lifecycleInterceptorClazz;
128
129 /**
130 * This code is executed inside the maven jail process.
131 */
132 public Result call() throws IOException {
133
134 // hold a ref on correct classloader for finally call as something is changing tccl
135 // and not restore it !
136 ClassLoader mavenJailProcessClassLoader = Thread.currentThread().getContextClassLoader();
137
138 try {
139
140 initializeAsynchronousExecutions();
141 Adapter a = new Adapter(this);
142 callSetListenerWithReflectOnInterceptors( a, mavenJailProcessClassLoader );
143
144 /*
145 PluginManagerInterceptor.setListener(a);
146 LifecycleExecutorInterceptor.setListener(a);
147 */
148
149 markAsSuccess = false;
150
151 registerSystemProperties();
152
153 listener.getLogger().println(formatArgs(goals));
154 int r = Main.launch(goals.toArray(new String[goals.size()]));
155
156 // now check the completion status of async ops
157 long startTime = System.nanoTime();
158
159 Result waitForAsyncExecutionsResult = waitForAsynchronousExecutions();
160 if (waitForAsyncExecutionsResult != null) {
161 return waitForAsyncExecutionsResult;
162 }
163
164 a.overheadTime += System.nanoTime()-startTime;
165
166 if(profile) {
167 NumberFormat n = NumberFormat.getInstance();
168 PrintStream logger = listener.getLogger();
169 logger.println("Total overhead was "+format(n,a.overheadTime)+"ms");
170 Channel ch = Channel.current();
171 logger.println("Class loading " +format(n,ch.classLoadingTime.get()) +"ms, "+ch.classLoadingCount+" classes");
172 logger.println("Resource loading "+format(n,ch.resourceLoadingTime.get())+"ms, "+ch.resourceLoadingCount+" times");
173 }
174
175 if(r==0){
176 if(a.hasBuildFailures()){
177 return Result.UNSTABLE;
178 }
179 return Result.SUCCESS;
180 }
181
182 if(markAsSuccess) {
183 listener.getLogger().println(Messages.MavenBuilder_Failed());
184 if(a.hasBuildFailures()){
185 return Result.UNSTABLE;
186 }
187 return Result.SUCCESS;
188 }
189 return Result.FAILURE;
190 } catch (NoSuchMethodException e) {
191 throw new IOException2(e);
192 } catch (IllegalAccessException e) {
193 throw new IOException2(e);
194 } catch (RuntimeException e) {
195 throw new IOException2(e);
196 } catch (InvocationTargetException e) {
197 throw new IOException2(e);
198 } catch (ClassNotFoundException e) {
199 throw new IOException2(e);
200 }
201 catch ( NoSuchRealmException e ) {
202 throw new IOException2(e);
203 } finally {
204 //PluginManagerInterceptor.setListener(null);
205 //LifecycleExecutorInterceptor.setListener(null);
206 callSetListenerWithReflectOnInterceptorsQuietly( null, mavenJailProcessClassLoader );
207 }
208 }
209
210 private void callSetListenerWithReflectOnInterceptors( PluginManagerListener pluginManagerListener, ClassLoader cl )
211 throws ClassNotFoundException, SecurityException, NoSuchMethodException, IllegalArgumentException,
212 IllegalAccessException, InvocationTargetException
213 {
214 if (pluginManagerInterceptorClazz == null)
215 {
216 pluginManagerInterceptorClazz = cl.loadClass( "hudson.maven.agent.PluginManagerInterceptor" );
217 }
218 Method setListenerMethod =
219 pluginManagerInterceptorClazz.getMethod( "setListener",
220 new Class[] { cl.loadClass( "hudson.maven.agent.PluginManagerListener" ) } );
221 setListenerMethod.invoke( null, new Object[] { pluginManagerListener } );
222
223 if (lifecycleInterceptorClazz == null)
224 {
225 lifecycleInterceptorClazz = cl.loadClass( "org.apache.maven.lifecycle.LifecycleExecutorInterceptor" );
226 }
227 setListenerMethod =
228 lifecycleInterceptorClazz.getMethod( "setListener",
229 new Class[] { cl.loadClass( "org.apache.maven.lifecycle.LifecycleExecutorListener" ) } );
230
231 setListenerMethod.invoke( null, new Object[] { pluginManagerListener } );
232 }
233
234 private void callSetListenerWithReflectOnInterceptorsQuietly( PluginManagerListener pluginManagerListener, ClassLoader cl )
235 {
236 try
237 {
238 callSetListenerWithReflectOnInterceptors(pluginManagerListener, cl);
239 }
240 catch ( SecurityException e )
241 {
242 throw new RuntimeException( e.getMessage(), e );
243 }
244 catch ( IllegalArgumentException e )
245 {
246 throw new RuntimeException( e.getMessage(), e );
247 }
248 catch ( ClassNotFoundException e )
249 {
250 throw new RuntimeException( e.getMessage(), e );
251 }
252 catch ( NoSuchMethodException e )
253 {
254 throw new RuntimeException( e.getMessage(), e );
255 }
256 catch ( IllegalAccessException e )
257 {
258 throw new RuntimeException( e.getMessage(), e );
259 }
260 catch ( InvocationTargetException e )
261 {
262 throw new RuntimeException( e.getMessage(), e );
263 }
264 }
265
266
267 /**
268 * Receives {@link PluginManagerListener} and {@link LifecycleExecutorListener} events
269 * and converts them to {@link MavenBuilder} events.
270 */
271 private static final class Adapter implements PluginManagerListener, LifecycleExecutorListener {
272 /**
273 * Used to detect when to fire {@link MavenReporter#enterModule}
274 */
275 private MavenProject lastModule;
276
277 private final MavenBuilder listener;
278 private final AtomicBoolean hasTestFailures = new AtomicBoolean();
279 private final Map<ModuleName, Long> currentMojoStartPerModuleName = new ConcurrentHashMap<ModuleName, Long>();
280
281 /**
282 * Number of total nanoseconds {@link MavenBuilder} spent.
283 */
284 long overheadTime;
285
286 public Adapter(MavenBuilder listener) {
287 this.listener = listener;
288 }
289
290 private long initMojoStartTime( MavenProject mavenProject) {
291 long mojoStartTime = System.currentTimeMillis();
292 this.currentMojoStartPerModuleName.put( new ModuleName( mavenProject), mojoStartTime);
293 return mojoStartTime;
294 }
295
296 private Long getMojoStartTime(MavenProject mavenProject) {
297 return currentMojoStartPerModuleName.get( new ModuleName(mavenProject) );
298 }
299
300 public void preBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException {
301 long startTime = System.nanoTime();
302 listener.preBuild(session, rm, dispatcher);
303 overheadTime += System.nanoTime()-startTime;
304 }
305
306 public void postBuild(MavenSession session, ReactorManager rm, EventDispatcher dispatcher) throws BuildFailureException, LifecycleExecutionException, IOException, InterruptedException {
307 long startTime = System.nanoTime();
308 fireLeaveModule();
309 listener.postBuild(session, rm, dispatcher);
310 overheadTime += System.nanoTime()-startTime;
311 }
312
313 public void endModule() throws InterruptedException, IOException {
314 long startTime = System.nanoTime();
315 fireLeaveModule();
316 overheadTime += System.nanoTime()-startTime;
317 }
318
319 public void preExecute(MavenProject project, MojoExecution exec, Mojo mojo, PlexusConfiguration mergedConfig, ExpressionEvaluator eval) throws IOException, InterruptedException {
320 long startTime = System.nanoTime();
321 if(lastModule!=project) {
322 // module change
323 fireLeaveModule();
324 fireEnterModule(project);
325 }
326
327 long mojoStartTime = initMojoStartTime(project);
328 listener.preExecute(project, new MojoInfo(exec, mojo, mergedConfig, eval, mojoStartTime));
329 overheadTime += System.nanoTime()-startTime;
330 }
331
332 public void postExecute(MavenProject project, MojoExecution exec, Mojo mojo, PlexusConfiguration mergedConfig, ExpressionEvaluator eval, Exception exception) throws IOException, InterruptedException {
333 long startTime = System.nanoTime();
334 listener.postExecute(project, new MojoInfo(exec, mojo, mergedConfig, eval, getMojoStartTime(project)),exception);
335 if(listener.hasBuildFailures())
336 hasTestFailures.compareAndSet(false, true);
337 overheadTime += System.nanoTime()-startTime;
338 }
339
340 public void onReportGenerated(MavenReport report, MojoExecution mojoExecution, PlexusConfiguration mergedConfig, ExpressionEvaluator eval) throws IOException, InterruptedException {
341 long startTime = System.nanoTime();
342 listener.onReportGenerated(lastModule,new MavenReportInfo(mojoExecution,report,mergedConfig,eval,
343 getMojoStartTime(lastModule)));
344 overheadTime += System.nanoTime()-startTime;
345 }
346
347 private void fireEnterModule(MavenProject project) throws InterruptedException, IOException {
348 lastModule = project;
349 listener.preModule(project);
350 }
351
352 private void fireLeaveModule() throws InterruptedException, IOException {
353 if(lastModule!=null) {
354 listener.postModule(lastModule);
355 lastModule = null;
356 }
357 }
358
359 public boolean hasBuildFailures() {
360 return hasTestFailures.get();
361 }
362 }
363
364 /**
365 * Used by selected {@link MavenReporter}s to notify the maven build agent
366 * that even though Maven is going to fail, we should report the build as
367 * success.
368 *
369 * <p>
370 * This rather ugly hook is necessary to mark builds as unstable, since
371 * maven considers a test failure to be a build failure, which will otherwise
372 * mark the build as FAILED.
373 *
374 * <p>
375 * It's OK for this field to be static, because the JVM where this is actually
376 * used is in the Maven JVM, so only one build is going on for the whole JVM.
377 *
378 * <p>
379 * Even though this field is public, please consider this field reserved
380 * for {@link SurefireArchiver}. Subject to change without notice.
381 */
382 public static boolean markAsSuccess;
383
384 private static final long serialVersionUID = 1L;
385
386 /**
387 * Whether there where test failures detected during the build.
388 * @since 1.496
389 */
390 public abstract boolean hasBuildFailures();
391 }
392