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