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