View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.maven.reporting.exec;
20  
21  import javax.inject.Inject;
22  import javax.inject.Named;
23  import javax.inject.Singleton;
24  
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Collections;
28  import java.util.HashSet;
29  import java.util.List;
30  import java.util.Objects;
31  import java.util.Set;
32  
33  import org.apache.maven.lifecycle.LifecycleExecutor;
34  import org.apache.maven.model.Build;
35  import org.apache.maven.model.Plugin;
36  import org.apache.maven.plugin.MavenPluginManager;
37  import org.apache.maven.plugin.Mojo;
38  import org.apache.maven.plugin.MojoExecution;
39  import org.apache.maven.plugin.MojoExecutionException;
40  import org.apache.maven.plugin.MojoNotFoundException;
41  import org.apache.maven.plugin.PluginConfigurationException;
42  import org.apache.maven.plugin.PluginContainerException;
43  import org.apache.maven.plugin.descriptor.MojoDescriptor;
44  import org.apache.maven.plugin.descriptor.PluginDescriptor;
45  import org.apache.maven.plugin.version.DefaultPluginVersionRequest;
46  import org.apache.maven.plugin.version.PluginVersionRequest;
47  import org.apache.maven.plugin.version.PluginVersionResolutionException;
48  import org.apache.maven.plugin.version.PluginVersionResolver;
49  import org.apache.maven.plugin.version.PluginVersionResult;
50  import org.apache.maven.project.MavenProject;
51  import org.apache.maven.reporting.MavenReport;
52  import org.codehaus.plexus.configuration.PlexusConfiguration;
53  import org.codehaus.plexus.util.StringUtils;
54  import org.codehaus.plexus.util.xml.Xpp3Dom;
55  import org.codehaus.plexus.util.xml.Xpp3DomUtils;
56  import org.slf4j.Logger;
57  import org.slf4j.LoggerFactory;
58  
59  import static java.util.Objects.requireNonNull;
60  
61  /**
62   * <p>
63   * This component will build some {@link MavenReportExecution} from {@link MavenReportExecutorRequest}. If a
64   * {@link MavenReport} needs to fork a lifecycle, this fork is executed here. It will ask the core to get some
65   * informations in order to correctly setup {@link MavenReport}.
66   * </p>
67   * <p>
68   * <b>Note</b> if no version is defined in the report plugin, the version will be searched with
69   * {@link #resolvePluginVersion(ReportPlugin, MavenReportExecutorRequest) resolvePluginVersion(...)} method:
70   * </p>
71   * <ol>
72   * <li>use the one defined in the reportPlugin configuration,</li>
73   * <li>search similar (same groupId and artifactId) plugin in the build/plugins section of the pom,</li>
74   * <li>search similar (same groupId and artifactId) plugin in the build/pluginManagement section of the pom,</li>
75   * <li>ask {@link PluginVersionResolver} to get a fallback version (display a warning as it's not a recommended use).
76   * </li>
77   * </ol>
78   * <p>
79   * Following steps are done:
80   * </p>
81   * <ul>
82   * <li>get {@link PluginDescriptor} from the {@link MavenPluginManager} (through
83   * {@link MavenPluginManagerHelper#getPluginDescriptor(Plugin, org.apache.maven.execution.MavenSession)
84   * MavenPluginManagerHelper.getPluginDescriptor(...)} to protect from core API change)</li>
85   * <li>setup a {@link ClassLoader}, with the Site plugin classloader as parent for the report execution. <br>
86   * Notice that some classes are imported from the current Site plugin ClassRealm: see {@link #IMPORTS}. Corresponding
87   * artifacts are excluded from the artifact resolution: <code>doxia-site-renderer</code>, <code>doxia-sink-api</code>
88   *  and <code>maven-reporting-api</code>.<br>
89   * Work is done using {@link MavenPluginManager} (through
90   * {@link MavenPluginManagerHelper#setupPluginRealm(PluginDescriptor, MavenSession, ClassLoader, List, List)
91   * MavenPluginManagerHelper.setupPluginRealm(...)} to protect from core API change)</li>
92   * <li>setup the mojo using {@link MavenPluginManager#getConfiguredMojo(Class, MavenSession, MojoExecution)
93   * MavenPluginManager.getConfiguredMojo(...)}</li>
94   * <li>verify with {@link LifecycleExecutor#calculateForkedExecutions(MojoExecution, MavenSession)
95   * LifecycleExecutor.calculateForkedExecutions(...)} if any forked execution is needed: if yes, execute the forked
96   * execution here</li>
97   * </ul>
98   *
99   * @author Olivier Lamy
100  */
101 @Singleton
102 @Named
103 public class DefaultMavenReportExecutor implements MavenReportExecutor {
104     private static final Logger LOGGER = LoggerFactory.getLogger(DefaultMavenReportExecutor.class);
105 
106     private final MavenPluginManager mavenPluginManager;
107 
108     private final MavenPluginManagerHelper mavenPluginManagerHelper;
109 
110     private final LifecycleExecutor lifecycleExecutor;
111 
112     private final PluginVersionResolver pluginVersionResolver;
113 
114     private static final List<String> IMPORTS = Arrays.asList(
115             "org.apache.maven.reporting.MavenReport",
116             "org.apache.maven.reporting.MavenMultiPageReport",
117             // TODO Will be removed after Doxia 2.0.0
118             "org.apache.maven.doxia.siterenderer.Renderer",
119             "org.apache.maven.doxia.siterenderer.SiteRenderer",
120             "org.apache.maven.doxia.sink.SinkFactory",
121             // TODO Will be removed after Doxia 2.0.0
122             "org.codehaus.doxia.sink.Sink",
123             "org.apache.maven.doxia.sink.Sink",
124             "org.apache.maven.doxia.sink.SinkEventAttributes",
125             // TODO Will be removed with Doxia 2.0.0
126             "org.apache.maven.doxia.logging.LogEnabled",
127             // TODO Will be removed with Doxia 2.0.0
128             "org.apache.maven.doxia.logging.Log");
129 
130     private static final List<String> EXCLUDES =
131             Arrays.asList("doxia-site-renderer", "doxia-sink-api", "maven-reporting-api");
132 
133     @Inject
134     public DefaultMavenReportExecutor(
135             MavenPluginManager mavenPluginManager,
136             MavenPluginManagerHelper mavenPluginManagerHelper,
137             LifecycleExecutor lifecycleExecutor,
138             PluginVersionResolver pluginVersionResolver) {
139         this.mavenPluginManager = requireNonNull(mavenPluginManager);
140         this.mavenPluginManagerHelper = requireNonNull(mavenPluginManagerHelper);
141         this.lifecycleExecutor = requireNonNull(lifecycleExecutor);
142         this.pluginVersionResolver = requireNonNull(pluginVersionResolver);
143     }
144 
145     @Override
146     public List<MavenReportExecution> buildMavenReports(MavenReportExecutorRequest mavenReportExecutorRequest)
147             throws MojoExecutionException {
148         if (mavenReportExecutorRequest.getReportPlugins() == null) {
149             return Collections.emptyList();
150         }
151 
152         Set<String> reportPluginKeys = new HashSet<>();
153         List<MavenReportExecution> reportExecutions = new ArrayList<>();
154 
155         String pluginKey = "";
156         try {
157             for (ReportPlugin reportPlugin : mavenReportExecutorRequest.getReportPlugins()) {
158                 pluginKey = reportPlugin.getGroupId() + ':' + reportPlugin.getArtifactId();
159 
160                 if (!reportPluginKeys.add(pluginKey)) {
161                     LOGGER.info("Plugin {} will be executed more than one time", pluginKey);
162                 }
163 
164                 reportExecutions.addAll(buildReportPlugin(mavenReportExecutorRequest, reportPlugin));
165             }
166         } catch (Exception e) {
167             throw new MojoExecutionException("Failed to get report for " + pluginKey, e);
168         }
169 
170         return reportExecutions;
171     }
172 
173     protected List<MavenReportExecution> buildReportPlugin(
174             MavenReportExecutorRequest mavenReportExecutorRequest, ReportPlugin reportPlugin) throws Exception {
175         // step 1: prepare the plugin
176         Plugin plugin = new Plugin();
177         plugin.setGroupId(reportPlugin.getGroupId());
178         plugin.setArtifactId(reportPlugin.getArtifactId());
179         plugin.setVersion(resolvePluginVersion(reportPlugin, mavenReportExecutorRequest));
180         LOGGER.info("Configuring report plugin {}:{}", plugin.getArtifactId(), plugin.getVersion());
181 
182         mergePluginToReportPlugin(mavenReportExecutorRequest, plugin, reportPlugin);
183 
184         PluginDescriptor pluginDescriptor =
185                 mavenPluginManagerHelper.getPluginDescriptor(plugin, mavenReportExecutorRequest.getMavenSession());
186 
187         // step 2: prepare the goals
188         List<GoalWithConf> goalsWithConfiguration = new ArrayList<>();
189         boolean hasUserDefinedReports = prepareGoals(reportPlugin, pluginDescriptor, goalsWithConfiguration);
190 
191         // step 3: prepare the reports
192         List<MavenReportExecution> reports = new ArrayList<>(goalsWithConfiguration.size());
193         for (GoalWithConf report : goalsWithConfiguration) {
194             MavenReportExecution mavenReportExecution =
195                     prepareReportExecution(mavenReportExecutorRequest, report, hasUserDefinedReports);
196 
197             if (mavenReportExecution != null) {
198                 // ok, report is ready to generate
199                 reports.add(mavenReportExecution);
200             }
201         }
202 
203         if (!reports.isEmpty()) {
204             // log reports, either configured or detected
205             StringBuilder buff = new StringBuilder();
206             for (MavenReportExecution mre : reports) {
207                 if (buff.length() > 0) {
208                     buff.append(", ");
209                 }
210                 buff.append(mre.getGoal());
211             }
212             LOGGER.info(
213                     "{} {} report{} for {}:{}: {}",
214                     (hasUserDefinedReports ? "Configured" : "Detected"),
215                     reports.size(),
216                     (reports.size() > 1 ? "s" : ""),
217                     plugin.getArtifactId(),
218                     plugin.getVersion(),
219                     buff);
220         } else if (!hasUserDefinedReports) {
221             LOGGER.warn("Ignoring report plugin {}:{},"
222                     + " it does not contain any report goals: should be removed from reporting configuration in POM",
223                     plugin.getArtifactId(), plugin.getVersion());
224         }
225 
226         return reports;
227     }
228 
229     private boolean prepareGoals(
230             ReportPlugin reportPlugin, PluginDescriptor pluginDescriptor, List<GoalWithConf> goalsWithConfiguration) {
231         if (reportPlugin.getReportSets().isEmpty() && reportPlugin.getReports().isEmpty()) {
232             // by default, use every goal which will be filtered later to only keep reporting goals
233             List<MojoDescriptor> mojoDescriptors = pluginDescriptor.getMojos();
234             for (MojoDescriptor mojoDescriptor : mojoDescriptors) {
235                 goalsWithConfiguration.add(new GoalWithConf(
236                         reportPlugin, pluginDescriptor, mojoDescriptor.getGoal(), mojoDescriptor.getConfiguration()));
237             }
238 
239             return false;
240         }
241 
242         Set<String> goals = new HashSet<>();
243         for (String report : reportPlugin.getReports()) {
244             if (goals.add(report)) {
245                 goalsWithConfiguration.add(
246                         new GoalWithConf(reportPlugin, pluginDescriptor, report, reportPlugin.getConfiguration()));
247             } else {
248                 LOGGER.warn("{} report is declared twice in default reports", report);
249             }
250         }
251 
252         for (ReportSet reportSet : reportPlugin.getReportSets()) {
253             goals = new HashSet<>();
254             for (String report : reportSet.getReports()) {
255                 if (goals.add(report)) {
256                     goalsWithConfiguration.add(
257                             new GoalWithConf(reportPlugin, pluginDescriptor, report, reportSet.getConfiguration()));
258                 } else {
259                     LOGGER.warn("{} report is declared twice in {} reportSet", report, reportSet.getId());
260                 }
261             }
262         }
263 
264         return true;
265     }
266 
267     private MavenReportExecution prepareReportExecution(
268             MavenReportExecutorRequest mavenReportExecutorRequest, GoalWithConf report, boolean hasUserDefinedReports)
269             throws Exception {
270         ReportPlugin reportPlugin = report.getReportPlugin();
271         PluginDescriptor pluginDescriptor = report.getPluginDescriptor();
272 
273         MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(report.getGoal());
274         if (mojoDescriptor == null) {
275             throw new MojoNotFoundException(report.getGoal(), pluginDescriptor);
276         }
277 
278         MavenProject project = mavenReportExecutorRequest.getProject();
279         if (!hasUserDefinedReports && mojoDescriptor.isAggregator() && !canAggregate(project)) {
280             // aggregator mojos automatically added from plugin are only run at execution root
281             return null;
282         }
283 
284         MojoExecution mojoExecution = new MojoExecution(
285                 pluginDescriptor.getPlugin(), report.getGoal(), mavenReportExecutorRequest.getExecutionId());
286 
287         mojoExecution.setMojoDescriptor(mojoDescriptor);
288 
289         mavenPluginManagerHelper.setupPluginRealm(
290                 pluginDescriptor,
291                 mavenReportExecutorRequest.getMavenSession(),
292                 Thread.currentThread().getContextClassLoader(),
293                 IMPORTS,
294                 EXCLUDES);
295 
296         if (!isMavenReport(mojoExecution, pluginDescriptor)) {
297             if (hasUserDefinedReports) {
298                 // reports were explicitly written in the POM
299                 LOGGER.warn("Ignoring {}:{}"
300                                 + " goal since it is not a report: should be removed from reporting configuration in POM",
301                                 mojoExecution.getPlugin().getId(), report.getGoal());
302             } else {
303                 LOGGER.debug("Ignoring {}:{} goal since it is not a report",
304                         mojoExecution.getPlugin().getId(), report.getGoal());
305             }
306             return null;
307         }
308 
309         Xpp3Dom pluginMgmtConfiguration = null;
310         if (project.getBuild() != null && project.getBuild().getPluginManagement() != null) {
311             Plugin pluginMgmt =
312                     find(reportPlugin, project.getBuild().getPluginManagement().getPlugins());
313 
314             if (pluginMgmt != null) {
315                 pluginMgmtConfiguration = (Xpp3Dom) pluginMgmt.getConfiguration();
316             }
317         }
318 
319         mojoExecution.setConfiguration(mergeConfiguration(
320                 mojoDescriptor.getMojoConfiguration(),
321                 pluginMgmtConfiguration,
322                 reportPlugin.getConfiguration(),
323                 report.getConfiguration(),
324                 mojoDescriptor.getParameterMap().keySet()));
325 
326         MavenReport mavenReport = getConfiguredMavenReport(mojoExecution, pluginDescriptor, mavenReportExecutorRequest);
327 
328         MavenReportExecution mavenReportExecution = new MavenReportExecution(
329                 report.getGoal(), mojoExecution.getPlugin(), mavenReport, pluginDescriptor.getClassRealm());
330 
331         lifecycleExecutor.calculateForkedExecutions(mojoExecution, mavenReportExecutorRequest.getMavenSession());
332 
333         if (!mojoExecution.getForkedExecutions().isEmpty()) {
334             String reportDescription = pluginDescriptor.getArtifactId() + ":" + report.getGoal() + " report";
335 
336             String execution;
337             if (StringUtils.isNotEmpty(mojoDescriptor.getExecutePhase())) {
338                 // forked phase
339                 execution = "'"
340                         + (StringUtils.isEmpty(mojoDescriptor.getExecuteLifecycle())
341                                 ? ""
342                                 : ('[' + mojoDescriptor.getExecuteLifecycle() + ']'))
343                         + mojoDescriptor.getExecutePhase() + "' forked phase execution";
344             } else {
345                 // forked goal
346                 execution = "'" + mojoDescriptor.getExecuteGoal() + "' forked goal execution";
347             }
348 
349             LOGGER.info("Preparing {} requires {}", reportDescription, execution);
350 
351             lifecycleExecutor.executeForkedExecutions(mojoExecution, mavenReportExecutorRequest.getMavenSession());
352 
353             LOGGER.info("{} for {} preparation done", execution, reportDescription);
354         }
355 
356         return mavenReportExecution;
357     }
358 
359     private boolean canAggregate(MavenProject project) {
360         return project.isExecutionRoot()
361                 && "pom".equals(project.getPackaging())
362                 && (project.getModules() != null)
363                 && !project.getModules().isEmpty();
364     }
365 
366     private MavenReport getConfiguredMavenReport(
367             MojoExecution mojoExecution,
368             PluginDescriptor pluginDescriptor,
369             MavenReportExecutorRequest mavenReportExecutorRequest)
370             throws PluginContainerException, PluginConfigurationException {
371         try {
372             Mojo mojo = mavenPluginManager.getConfiguredMojo(
373                     Mojo.class, mavenReportExecutorRequest.getMavenSession(), mojoExecution);
374 
375             return (MavenReport) mojo;
376         } catch (ClassCastException e) {
377             if (LOGGER.isDebugEnabled()) {
378                 LOGGER.warn("Skipping ClassCastException", e);
379             } else {
380                 LOGGER.warn("Skipping ClassCastException");
381             }
382             return null;
383         }
384     }
385 
386     private boolean isMavenReport(MojoExecution mojoExecution, PluginDescriptor pluginDescriptor) {
387         ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
388 
389         // get the plugin's goal Mojo class
390         Class<?> mojoClass;
391         try {
392             Thread.currentThread()
393                     .setContextClassLoader(mojoExecution.getMojoDescriptor().getRealm());
394 
395             mojoClass = pluginDescriptor
396                     .getClassRealm()
397                     .loadClass(mojoExecution.getMojoDescriptor().getImplementation());
398         } catch (ClassNotFoundException e) {
399             if (LOGGER.isDebugEnabled()) {
400                 LOGGER.warn("Skipping ClassNotFoundException mojoExecution.goal {}", mojoExecution.getGoal(), e);
401             } else {
402                 LOGGER.warn("Skipping ClassNotFoundException mojoExecution.goal {}", mojoExecution.getGoal());
403             }
404             return false;
405         } finally {
406             Thread.currentThread().setContextClassLoader(originalClassLoader);
407         }
408 
409         // check if it is a report
410         try {
411             Thread.currentThread()
412                     .setContextClassLoader(mojoExecution.getMojoDescriptor().getRealm());
413             MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(mojoExecution.getGoal());
414 
415             boolean isMavenReport = MavenReport.class.isAssignableFrom(mojoClass);
416 
417             if (LOGGER.isDebugEnabled()) {
418                 if (mojoDescriptor != null && mojoDescriptor.getImplementationClass() != null) {
419                     LOGGER.debug("Class {} is {}a MavenReport",
420                             mojoDescriptor.getImplementationClass().getName(),
421                             isMavenReport ? "" : "NOT ");
422                 }
423 
424                 if (!isMavenReport) {
425                     LOGGER.debug(
426                             "Skipping non-MavenReport {}",
427                             mojoExecution.getMojoDescriptor().getId());
428                 }
429             }
430 
431             return isMavenReport;
432         } catch (LinkageError e) {
433             if (LOGGER.isDebugEnabled()) {
434                 LOGGER.warn("Skipping LinkageError mojoExecution.goal {}", mojoExecution.getGoal(), e);
435             } else {
436                 LOGGER.warn("Skipping LinkageError mojoExecution.goal {}", mojoExecution.getGoal());
437             }
438             return false;
439         } finally {
440             Thread.currentThread().setContextClassLoader(originalClassLoader);
441         }
442     }
443 
444     /**
445      * Merge plugin configuration and reportset configuration to mojo configuration to get effective
446      * mojo configuration.
447      *
448      * @param mojoConf configuration done at mojo descriptor level
449      * @param pluginMgmtConfig configuration done at build.pluginManagement level
450      * @param pluginConf configuration done at reporting plugin level
451      * @param reportSetConf configuration done at reportSet level
452      * @param parameters set of supported parameters: any other parameter will be removed
453      * @return the effective configuration to be used
454      */
455     private Xpp3Dom mergeConfiguration(
456             PlexusConfiguration mojoConf,
457             Xpp3Dom pluginMgmtConfig,
458             PlexusConfiguration pluginConf,
459             PlexusConfiguration reportSetConf,
460             Set<String> parameters) {
461         Xpp3Dom mojoConfig = (mojoConf != null) ? convert(mojoConf) : new Xpp3Dom("configuration");
462 
463         if (pluginMgmtConfig != null || pluginConf != null || reportSetConf != null) {
464             Xpp3Dom pluginConfig = (pluginConf == null) ? new Xpp3Dom("fake") : convert(pluginConf);
465 
466             // merge pluginConf into reportSetConf
467             Xpp3Dom mergedConfig = Xpp3DomUtils.mergeXpp3Dom(convert(reportSetConf), pluginConfig);
468             // then merge pluginMgmtConfig
469             mergedConfig = Xpp3DomUtils.mergeXpp3Dom(mergedConfig, pluginMgmtConfig);
470             // then merge mojoConf
471             mergedConfig = Xpp3DomUtils.mergeXpp3Dom(mergedConfig, mojoConfig);
472 
473             // clean result
474             Xpp3Dom cleanedConfig = new Xpp3Dom("configuration");
475             if (mergedConfig.getChildren() != null) {
476                 for (Xpp3Dom parameter : mergedConfig.getChildren()) {
477                     if (parameters.contains(parameter.getName())) {
478                         cleanedConfig.addChild(parameter);
479                     }
480                 }
481             }
482 
483             mojoConfig = cleanedConfig;
484         }
485 
486         return mojoConfig;
487     }
488 
489     private Xpp3Dom convert(PlexusConfiguration config) {
490         if (config == null) {
491             return null;
492         }
493 
494         Xpp3Dom dom = new Xpp3Dom(config.getName());
495         dom.setValue(config.getValue(null));
496 
497         for (String attrib : config.getAttributeNames()) {
498             dom.setAttribute(attrib, config.getAttribute(attrib, null));
499         }
500 
501         for (int n = config.getChildCount(), i = 0; i < n; i++) {
502             dom.addChild(convert(config.getChild(i)));
503         }
504 
505         return dom;
506     }
507 
508     /**
509      * Resolve report plugin version. Steps to find a plugin version stop after each step if a non <code>null</code>
510      * value has been found:
511      * <ol>
512      * <li>use the one defined in the reportPlugin configuration,</li>
513      * <li>search similar (same groupId and artifactId) mojo in the build/plugins section of the pom,</li>
514      * <li>search similar (same groupId and artifactId) mojo in the build/pluginManagement section of the pom,</li>
515      * <li>ask {@link PluginVersionResolver} to get a fallback version and display a warning as it's not a recommended
516      * use.</li>
517      * </ol>
518      *
519      * @param reportPlugin the report plugin to resolve the version
520      * @param mavenReportExecutorRequest the current report execution context
521      * @return the report plugin version
522      * @throws PluginVersionResolutionException on plugin version resolution issue
523      */
524     protected String resolvePluginVersion(
525             ReportPlugin reportPlugin, MavenReportExecutorRequest mavenReportExecutorRequest)
526             throws PluginVersionResolutionException {
527         String reportPluginKey = reportPlugin.getGroupId() + ':' + reportPlugin.getArtifactId();
528         LOGGER.debug("Resolving version for {}", reportPluginKey);
529 
530         // look for version defined in the reportPlugin configuration
531         if (reportPlugin.getVersion() != null) {
532             LOGGER.debug(
533                     "Resolved {} version from the reporting.plugins section: {}",
534                     reportPluginKey,
535                     reportPlugin.getVersion());
536             return reportPlugin.getVersion();
537         }
538 
539         MavenProject project = mavenReportExecutorRequest.getProject();
540 
541         // search in the build section
542         if (project.getBuild() != null) {
543             Plugin plugin = find(reportPlugin, project.getBuild().getPlugins());
544 
545             if (plugin != null && plugin.getVersion() != null) {
546                 LOGGER.debug(
547                         "Resolved {} version from the build.plugins section: {}", reportPluginKey, plugin.getVersion());
548                 return plugin.getVersion();
549             }
550         }
551 
552         // search in pluginManagement section
553         if (project.getBuild() != null && project.getBuild().getPluginManagement() != null) {
554             Plugin plugin =
555                     find(reportPlugin, project.getBuild().getPluginManagement().getPlugins());
556 
557             if (plugin != null && plugin.getVersion() != null) {
558                 LOGGER.debug(
559                         "Resolved {} version from the build.pluginManagement.plugins section: {}",
560                         reportPluginKey,
561                         plugin.getVersion());
562                 return plugin.getVersion();
563             }
564         }
565 
566         LOGGER.warn("Report plugin {} has an empty version.", reportPluginKey);
567         LOGGER.warn("");
568         LOGGER.warn("It is highly recommended to fix these problems"
569                 + " because they threaten the stability of your build.");
570         LOGGER.warn("");
571         LOGGER.warn("For this reason, future Maven versions might no"
572                 + " longer support building such malformed projects.");
573 
574         Plugin plugin = new Plugin();
575         plugin.setGroupId(reportPlugin.getGroupId());
576         plugin.setArtifactId(reportPlugin.getArtifactId());
577 
578         PluginVersionRequest pluginVersionRequest =
579                 new DefaultPluginVersionRequest(plugin, mavenReportExecutorRequest.getMavenSession());
580 
581         PluginVersionResult result = pluginVersionResolver.resolve(pluginVersionRequest);
582         LOGGER.debug("Resolved {} version from repository: {}", reportPluginKey, result.getVersion());
583         return result.getVersion();
584     }
585 
586     /**
587      * Search similar (same groupId and artifactId) plugin as a given report plugin.
588      *
589      * @param reportPlugin the report plugin to search for a similar plugin
590      * @param plugins the candidate plugins
591      * @return the first similar plugin
592      */
593     private Plugin find(ReportPlugin reportPlugin, List<Plugin> plugins) {
594         if (plugins == null) {
595             return null;
596         }
597         for (Plugin plugin : plugins) {
598             if (Objects.equals(plugin.getArtifactId(), reportPlugin.getArtifactId())
599                     && Objects.equals(plugin.getGroupId(), reportPlugin.getGroupId())) {
600                 return plugin;
601             }
602         }
603         return null;
604     }
605 
606     /**
607      * TODO other stuff to merge ?
608      * <p>
609      * this method will "merge" some part of the plugin declaration existing in the build section to the fake plugin
610      * build for report execution:
611      * <ul>
612      * <li>dependencies</li>
613      * </ul>
614      * </p>
615      * The plugin could only be present in the dependency management section.
616      *
617      * @param mavenReportExecutorRequest
618      * @param buildPlugin
619      * @param reportPlugin
620      */
621     private void mergePluginToReportPlugin(
622             MavenReportExecutorRequest mavenReportExecutorRequest, Plugin buildPlugin, ReportPlugin reportPlugin) {
623         Build build = mavenReportExecutorRequest.getProject().getBuild();
624         Plugin configuredPlugin = find(reportPlugin, build.getPlugins());
625         if (configuredPlugin == null && build.getPluginManagement() != null) {
626             configuredPlugin = find(reportPlugin, build.getPluginManagement().getPlugins());
627         }
628         if (configuredPlugin != null) {
629             if (!configuredPlugin.getDependencies().isEmpty()) {
630                 buildPlugin.getDependencies().addAll(configuredPlugin.getDependencies());
631             }
632         }
633     }
634 
635     private static class GoalWithConf {
636         private final String goal;
637 
638         private final PlexusConfiguration configuration;
639 
640         private final ReportPlugin reportPlugin;
641 
642         private final PluginDescriptor pluginDescriptor;
643 
644         GoalWithConf(
645                 ReportPlugin reportPlugin,
646                 PluginDescriptor pluginDescriptor,
647                 String goal,
648                 PlexusConfiguration configuration) {
649             this.reportPlugin = reportPlugin;
650             this.pluginDescriptor = pluginDescriptor;
651             this.goal = goal;
652             this.configuration = configuration;
653         }
654 
655         public ReportPlugin getReportPlugin() {
656             return reportPlugin;
657         }
658 
659         public PluginDescriptor getPluginDescriptor() {
660             return pluginDescriptor;
661         }
662 
663         public String getGoal() {
664             return goal;
665         }
666 
667         public PlexusConfiguration getConfiguration() {
668             return configuration;
669         }
670     }
671 }