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.plugins.site.render;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.util.ArrayList;
24  import java.util.Collection;
25  import java.util.Date;
26  import java.util.HashMap;
27  import java.util.Iterator;
28  import java.util.LinkedHashMap;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  
33  import org.apache.commons.lang3.StringUtils;
34  import org.apache.maven.archiver.MavenArchiver;
35  import org.apache.maven.artifact.Artifact;
36  import org.apache.maven.doxia.site.Menu;
37  import org.apache.maven.doxia.site.MenuItem;
38  import org.apache.maven.doxia.site.SiteModel;
39  import org.apache.maven.doxia.siterenderer.DocumentRenderer;
40  import org.apache.maven.doxia.siterenderer.DocumentRenderingContext;
41  import org.apache.maven.doxia.siterenderer.RendererException;
42  import org.apache.maven.doxia.siterenderer.SiteRenderer;
43  import org.apache.maven.doxia.siterenderer.SiteRenderingContext;
44  import org.apache.maven.doxia.tools.SiteTool;
45  import org.apache.maven.doxia.tools.SiteToolException;
46  import org.apache.maven.execution.MavenSession;
47  import org.apache.maven.model.ReportPlugin;
48  import org.apache.maven.model.Reporting;
49  import org.apache.maven.plugin.MojoExecution;
50  import org.apache.maven.plugin.MojoExecutionException;
51  import org.apache.maven.plugin.MojoFailureException;
52  import org.apache.maven.plugins.annotations.Component;
53  import org.apache.maven.plugins.annotations.Parameter;
54  import org.apache.maven.plugins.site.descriptor.AbstractSiteDescriptorMojo;
55  import org.apache.maven.project.MavenProject;
56  import org.apache.maven.reporting.MavenReport;
57  import org.apache.maven.reporting.exec.MavenReportExecution;
58  import org.apache.maven.reporting.exec.MavenReportExecutor;
59  import org.apache.maven.reporting.exec.MavenReportExecutorRequest;
60  import org.codehaus.plexus.util.ReaderFactory;
61  
62  import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
63  
64  /**
65   * Base class for site rendering mojos.
66   *
67   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
68   *
69   */
70  public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMojo {
71      /**
72       * Module type exclusion mappings
73       * ex: <code>fml  -> **&#47;*-m1.fml</code>  (excludes fml files ending in '-m1.fml' recursively)
74       * <p/>
75       * The configuration looks like this:
76       * <pre>
77       *   &lt;moduleExcludes&gt;
78       *     &lt;moduleType&gt;filename1.ext,**&#47;*sample.ext&lt;/moduleType&gt;
79       *     &lt;!-- moduleType can be one of 'apt', 'fml' or 'xdoc'. --&gt;
80       *     &lt;!-- The value is a comma separated list of           --&gt;
81       *     &lt;!-- filenames or fileset patterns.                   --&gt;
82       *     &lt;!-- Here's an example:                               --&gt;
83       *     &lt;xdoc&gt;changes.xml,navigation.xml&lt;/xdoc&gt;
84       *   &lt;/moduleExcludes&gt;
85       * </pre>
86       */
87      @Parameter
88      private Map<String, String> moduleExcludes;
89  
90      /**
91       * Additional template properties for rendering the site. See
92       * <a href="/doxia/doxia-sitetools/doxia-site-renderer/">Doxia Site Renderer</a>.
93       */
94      @Parameter
95      private Map<String, Object> attributes;
96  
97      /**
98       * Site renderer.
99       */
100     @Component
101     protected SiteRenderer siteRenderer;
102 
103     /**
104      * Directory containing generated documentation in source format (Doxia supported markup).
105      * This is used to pick up other source docs that might have been generated at build time (by reports or any other
106      * build time mean).
107      * This directory is expected to have the same structure as <code>siteDirectory</code>
108      * (ie. one directory per Doxia-source-supported markup types).
109      *
110      * todo should we deprecate in favour of reports directly using Doxia Sink API, without this Doxia source
111      * intermediate step?
112      */
113     @Parameter(alias = "workingDirectory", defaultValue = "${project.build.directory}/generated-site")
114     protected File generatedSiteDirectory;
115 
116     /**
117      * The current Maven session.
118      */
119     @Parameter(defaultValue = "${session}", readonly = true, required = true)
120     protected MavenSession mavenSession;
121 
122     /**
123      * The mojo execution
124      */
125     @Parameter(defaultValue = "${mojoExecution}", readonly = true, required = true)
126     protected MojoExecution mojoExecution;
127 
128     /**
129      * replaces previous reportPlugins parameter, that was injected by Maven core from
130      * reporting section: but this new configuration format has been abandoned.
131      *
132      * @since 3.7.1
133      */
134     @Parameter(defaultValue = "${project.reporting}", readonly = true)
135     private Reporting reporting;
136 
137     /**
138      * Whether to generate the summary page for project reports: project-info.html.
139      *
140      * @since 2.3
141      */
142     @Parameter(property = "generateProjectInfo", defaultValue = "true")
143     private boolean generateProjectInfo;
144 
145     /**
146      * Generate a sitemap. The result will be a "sitemap.html" file at the site root.
147      *
148      * @since 2.1
149      */
150     @Parameter(property = "generateSitemap", defaultValue = "false")
151     private boolean generateSitemap;
152 
153     /**
154      * Specifies the input encoding.
155      *
156      * @since 2.3
157      */
158     @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}")
159     private String inputEncoding;
160 
161     /**
162      * Specifies the output encoding.
163      *
164      * @since 2.3
165      */
166     @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}")
167     private String outputEncoding;
168 
169     @Component
170     protected MavenReportExecutor mavenReportExecutor;
171 
172     /**
173      * Gets the input files encoding.
174      *
175      * @return The input files encoding, never <code>null</code>.
176      */
177     protected String getInputEncoding() {
178         return (StringUtils.isEmpty(inputEncoding)) ? ReaderFactory.FILE_ENCODING : inputEncoding;
179     }
180 
181     /**
182      * Gets the effective reporting output files encoding.
183      *
184      * @return The effective reporting output file encoding, never <code>null</code>.
185      */
186     protected String getOutputEncoding() {
187         return (outputEncoding == null) ? ReaderFactory.UTF_8 : outputEncoding;
188     }
189 
190     /**
191      * Whether to save Velocity processed Doxia content (<code>*.&lt;ext&gt;.vm</code>)
192      * to <code>${generatedSiteDirectory}/processed</code>.
193      *
194      * @since 3.5
195      */
196     @Parameter
197     private boolean saveProcessedContent;
198 
199     protected void checkInputEncoding() {
200         if (StringUtils.isEmpty(inputEncoding)) {
201             getLog().warn("Input file encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING
202                     + ", i.e. build is platform dependent!");
203         }
204     }
205 
206     protected List<MavenReportExecution> getReports() throws MojoExecutionException {
207         MavenReportExecutorRequest mavenReportExecutorRequest = new MavenReportExecutorRequest();
208         mavenReportExecutorRequest.setMavenSession(mavenSession);
209         mavenReportExecutorRequest.setExecutionId(mojoExecution.getExecutionId());
210         mavenReportExecutorRequest.setProject(project);
211         mavenReportExecutorRequest.setReportPlugins(getReportingPlugins());
212 
213         List<MavenReportExecution> allReports = mavenReportExecutor.buildMavenReports(mavenReportExecutorRequest);
214 
215         // filter out reports that can't be generated
216         List<MavenReportExecution> reportExecutions = new ArrayList<>(allReports.size());
217         for (MavenReportExecution exec : allReports) {
218             if (exec.canGenerateReport()) {
219                 reportExecutions.add(exec);
220             }
221         }
222         return reportExecutions;
223     }
224 
225     /**
226      * Get the report plugins from reporting section, adding if necessary (i.e. not excluded)
227      * default reports (i.e. maven-project-info-reports)
228      *
229      * @return the effective list of reports
230      * @since 3.7.1
231      */
232     private ReportPlugin[] getReportingPlugins() {
233         List<ReportPlugin> reportingPlugins = reporting.getPlugins();
234 
235         // MSITE-806: add default report plugin like done in maven-model-builder DefaultReportingConverter
236         boolean hasMavenProjectInfoReportsPlugin = false;
237         for (ReportPlugin plugin : reportingPlugins) {
238             if ("org.apache.maven.plugins".equals(plugin.getGroupId())
239                     && "maven-project-info-reports-plugin".equals(plugin.getArtifactId())) {
240                 hasMavenProjectInfoReportsPlugin = true;
241                 break;
242             }
243         }
244 
245         if (!reporting.isExcludeDefaults() && !hasMavenProjectInfoReportsPlugin) {
246             ReportPlugin mpir = new ReportPlugin();
247             mpir.setArtifactId("maven-project-info-reports-plugin");
248             reportingPlugins.add(mpir);
249         }
250         return reportingPlugins.toArray(new ReportPlugin[0]);
251     }
252 
253     protected SiteRenderingContext createSiteRenderingContext(Locale locale)
254             throws MojoExecutionException, IOException, MojoFailureException {
255         SiteModel siteModel = prepareSiteModel(locale);
256         if (attributes == null) {
257             attributes = new HashMap<>();
258         }
259 
260         if (attributes.get("project") == null) {
261             attributes.put("project", project);
262         }
263 
264         if (attributes.get("inputEncoding") == null) {
265             attributes.put("inputEncoding", getInputEncoding());
266         }
267 
268         if (attributes.get("outputEncoding") == null) {
269             attributes.put("outputEncoding", getOutputEncoding());
270         }
271 
272         // Put any of the properties in directly into the Velocity context
273         for (Map.Entry<Object, Object> entry : project.getProperties().entrySet()) {
274             attributes.put((String) entry.getKey(), entry.getValue());
275         }
276 
277         SiteRenderingContext context;
278         try {
279             Artifact skinArtifact =
280                     siteTool.getSkinArtifactFromRepository(repoSession, remoteProjectRepositories, siteModel.getSkin());
281 
282             getLog().info(buffer().a("Rendering content with ")
283                     .strong(skinArtifact.getId() + " skin")
284                     .toString());
285 
286             context = siteRenderer.createContextForSkin(skinArtifact, attributes, siteModel, project.getName(), locale);
287         } catch (SiteToolException e) {
288             throw new MojoExecutionException("SiteToolException while preparing skin: " + e.getMessage(), e);
289         } catch (RendererException e) {
290             throw new MojoExecutionException(
291                     "RendererException while preparing context for skin: " + e.getMessage(), e);
292         }
293 
294         // Add publish date
295         MavenProject p = attributes.get("project") != null ? (MavenProject) attributes.get("project") : project;
296         String outputTimestamp = p.getProperties().getProperty("project.build.outputTimestamp");
297         MavenArchiver.parseBuildOutputTimestamp(outputTimestamp).ifPresent(v -> {
298             context.setPublishDate(Date.from(v));
299         });
300 
301         // Generate static site
302         context.setRootDirectory(project.getBasedir());
303         if (!locale.equals(SiteTool.DEFAULT_LOCALE)) {
304             context.addSiteDirectory(new File(siteDirectory, locale.toString()));
305         } else {
306             context.addSiteDirectory(siteDirectory);
307         }
308 
309         if (moduleExcludes != null) {
310             context.setModuleExcludes(moduleExcludes);
311         }
312 
313         if (saveProcessedContent) {
314             File processedDir = new File(generatedSiteDirectory, "processed");
315             if (!locale.equals(SiteTool.DEFAULT_LOCALE)) {
316                 context.setProcessedContentOutput(new File(processedDir, locale.toString()));
317             } else {
318                 context.setProcessedContentOutput(processedDir);
319             }
320         }
321 
322         return context;
323     }
324 
325     /**
326      * Go through the list of reports and process each one like this:
327      * <ul>
328      * <li>Add the report to a map of reports keyed by filename having the report itself as value
329      * <li>If the report is not yet in the map of documents, add it together with a suitable renderer
330      * </ul>
331      *
332      * @param reports A List of MavenReports
333      * @param documents A Map of documents, keyed by filename
334      * @param locale the Locale the reports are processed for.
335      * @return A map with all reports keyed by filename having the report itself as value.
336      * The map will be used to populate a menu.
337      */
338     protected Map<String, MavenReport> locateReports(
339             List<MavenReportExecution> reports, Map<String, DocumentRenderer> documents, Locale locale) {
340         Map<String, MavenReport> reportsByOutputName = new LinkedHashMap<>();
341         for (MavenReportExecution mavenReportExecution : reports) {
342             MavenReport report = mavenReportExecution.getMavenReport();
343 
344             String outputName = report.getOutputName();
345             String filename = outputName + ".html";
346 
347             // Always add the report to the menu, see MSITE-150
348             reportsByOutputName.put(outputName, report);
349 
350             if (documents.containsKey(filename)) {
351                 String reportMojoInfo = mavenReportExecution.getGoal() == null
352                         ? ""
353                         : (" (" + mavenReportExecution.getPlugin().getArtifactId() + ':'
354                                 + mavenReportExecution.getPlugin().getVersion() + ':' + mavenReportExecution.getGoal()
355                                 + ')');
356 
357                 getLog().info("Skipped \"" + report.getName(locale) + "\" report" + reportMojoInfo + ", file \""
358                         + filename + "\" already exists.");
359             } else {
360                 String generator = mavenReportExecution.getGoal() == null
361                         ? null
362                         : mavenReportExecution.getPlugin().getId() + ':' + mavenReportExecution.getGoal();
363                 DocumentRenderingContext docRenderingContext =
364                         new DocumentRenderingContext(siteDirectory, outputName, generator);
365                 DocumentRenderer docRenderer =
366                         new ReportDocumentRenderer(mavenReportExecution, docRenderingContext, getLog());
367                 documents.put(filename, docRenderer);
368             }
369         }
370         return reportsByOutputName;
371     }
372 
373     /**
374      * Go through the collection of reports and put each report into a list for the appropriate category. The list is
375      * put into a map keyed by the name of the category.
376      *
377      * @param reports A Collection of MavenReports
378      * @return A map keyed category having the report itself as value
379      */
380     protected Map<String, List<MavenReport>> categoriseReports(Collection<MavenReport> reports) {
381         Map<String, List<MavenReport>> categories = new LinkedHashMap<>();
382         for (MavenReport report : reports) {
383             List<MavenReport> categoryReports = categories.get(report.getCategoryName());
384             if (categoryReports == null) {
385                 categoryReports = new ArrayList<>();
386                 categories.put(report.getCategoryName(), categoryReports);
387             }
388             categoryReports.add(report);
389         }
390         return categories;
391     }
392 
393     /**
394      * Locate every document to be rendered for given locale:<ul>
395      * <li>handwritten content, ie Doxia files,</li>
396      * <li>reports,</li>
397      * <li>"Project Information" and "Project Reports" category summaries.</li>
398      * </ul>
399      *
400      * @param context the site context
401      * @param reports the documents
402      * @param locale the locale
403      * @return the documents and their renderers
404      * @throws IOException in case of file reading issue
405      * @throws RendererException in case of Doxia rendering issue
406      * @see CategorySummaryDocumentRenderer
407      */
408     protected Map<String, DocumentRenderer> locateDocuments(
409             SiteRenderingContext context, List<MavenReportExecution> reports, Locale locale)
410             throws IOException, RendererException {
411         Map<String, DocumentRenderer> documents = siteRenderer.locateDocumentFiles(context, true);
412 
413         Map<String, MavenReport> reportsByOutputName = locateReports(reports, documents, locale);
414 
415         // TODO: I want to get rid of categories eventually. There's no way to add your own in a fully i18n manner
416         Map<String, List<MavenReport>> categories = categoriseReports(reportsByOutputName.values());
417 
418         siteTool.populateReportsMenu(context.getSiteModel(), locale, categories);
419         populateReportItems(context.getSiteModel(), locale, reportsByOutputName);
420 
421         if (categories.containsKey(MavenReport.CATEGORY_PROJECT_INFORMATION) && generateProjectInfo) {
422             // add "Project Information" category summary document
423             List<MavenReport> categoryReports = categories.get(MavenReport.CATEGORY_PROJECT_INFORMATION);
424             MojoExecution subMojoExecution =
425                     new MojoExecution(mojoExecution.getPlugin(), "project-info", mojoExecution.getExecutionId());
426             DocumentRenderingContext docRenderingContext = new DocumentRenderingContext(
427                     siteDirectory,
428                     subMojoExecution.getGoal(),
429                     subMojoExecution.getPlugin().getId() + ':' + subMojoExecution.getGoal());
430             String title = i18n.getString("site-plugin", locale, "report.information.title");
431             String desc1 = i18n.getString("site-plugin", locale, "report.information.description1");
432             String desc2 = i18n.getString("site-plugin", locale, "report.information.description2");
433             DocumentRenderer docRenderer = new CategorySummaryDocumentRenderer(
434                     subMojoExecution, docRenderingContext, title, desc1, desc2, i18n, categoryReports, getLog());
435 
436             String filename = docRenderer.getOutputName();
437             if (!documents.containsKey(filename)) {
438                 documents.put(filename, docRenderer);
439             } else {
440                 getLog().info("Skipped \"" + title + "\" report; file \"" + filename + "\" already exists.");
441             }
442         }
443 
444         if (categories.containsKey(MavenReport.CATEGORY_PROJECT_REPORTS)) {
445             // add "Project Reports" category summary document
446             List<MavenReport> categoryReports = categories.get(MavenReport.CATEGORY_PROJECT_REPORTS);
447             MojoExecution subMojoExecution =
448                     new MojoExecution(mojoExecution.getPlugin(), "project-reports", mojoExecution.getExecutionId());
449             DocumentRenderingContext docRenderingContext = new DocumentRenderingContext(
450                     siteDirectory,
451                     subMojoExecution.getGoal(),
452                     subMojoExecution.getPlugin().getId() + ':' + subMojoExecution.getGoal());
453             String title = i18n.getString("site-plugin", locale, "report.project.title");
454             String desc1 = i18n.getString("site-plugin", locale, "report.project.description1");
455             String desc2 = i18n.getString("site-plugin", locale, "report.project.description2");
456             DocumentRenderer docRenderer = new CategorySummaryDocumentRenderer(
457                     subMojoExecution, docRenderingContext, title, desc1, desc2, i18n, categoryReports, getLog());
458 
459             String filename = docRenderer.getOutputName();
460             if (!documents.containsKey(filename)) {
461                 documents.put(filename, docRenderer);
462             } else {
463                 getLog().info("Skipped \"" + title + "\" report; file \"" + filename + "\" already exists.");
464             }
465         }
466 
467         if (generateSitemap) {
468             MojoExecution subMojoExecution =
469                     new MojoExecution(mojoExecution.getPlugin(), "sitemap", mojoExecution.getExecutionId());
470             DocumentRenderingContext docRenderingContext = new DocumentRenderingContext(
471                     siteDirectory,
472                     subMojoExecution.getGoal(),
473                     subMojoExecution.getPlugin().getId() + ':' + subMojoExecution.getGoal());
474             String title = i18n.getString("site-plugin", locale, "site.sitemap.title");
475             DocumentRenderer docRenderer = new SitemapDocumentRenderer(
476                     subMojoExecution, docRenderingContext, title, context.getSiteModel(), i18n, getLog());
477 
478             String filename = docRenderer.getOutputName();
479             if (!documents.containsKey(filename)) {
480                 documents.put(filename, docRenderer);
481             } else {
482                 getLog().info("Skipped \"" + title + "\" report; file \"" + filename + "\" already exists.");
483             }
484         }
485 
486         return documents;
487     }
488 
489     protected void populateReportItems(
490             SiteModel siteModel, Locale locale, Map<String, MavenReport> reportsByOutputName) {
491         for (Menu menu : siteModel.getMenus()) {
492             populateItemRefs(menu.getItems(), locale, reportsByOutputName);
493         }
494     }
495 
496     private void populateItemRefs(List<MenuItem> items, Locale locale, Map<String, MavenReport> reportsByOutputName) {
497         for (Iterator<MenuItem> i = items.iterator(); i.hasNext(); ) {
498             MenuItem item = i.next();
499 
500             if (item.getRef() != null) {
501                 MavenReport report = reportsByOutputName.get(item.getRef());
502 
503                 if (report != null) {
504                     if (item.getName() == null) {
505                         item.setName(report.getName(locale));
506                     }
507 
508                     if (item.getHref() == null || item.getHref().length() == 0) {
509                         item.setHref(report.getOutputName() + ".html");
510                     }
511                 } else {
512                     getLog().warn("Unrecognised reference: '" + item.getRef() + "'");
513                     i.remove();
514                 }
515             }
516 
517             populateItemRefs(item.getItems(), locale, reportsByOutputName);
518         }
519     }
520 }