View Javadoc

1   package org.apache.maven.plugins.site;
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  
25  import java.util.ArrayList;
26  import java.util.Collection;
27  import java.util.HashMap;
28  import java.util.Iterator;
29  import java.util.LinkedHashMap;
30  import java.util.List;
31  import java.util.Locale;
32  import java.util.Map;
33  
34  import org.apache.maven.artifact.Artifact;
35  import org.apache.maven.artifact.repository.ArtifactRepository;
36  import org.apache.maven.doxia.sink.render.RenderingContext;
37  import org.apache.maven.doxia.site.decoration.DecorationModel;
38  import org.apache.maven.doxia.site.decoration.Menu;
39  import org.apache.maven.doxia.site.decoration.MenuItem;
40  import org.apache.maven.doxia.site.decoration.inheritance.DecorationModelInheritanceAssembler;
41  import org.apache.maven.doxia.siterenderer.DocumentRenderer;
42  import org.apache.maven.doxia.siterenderer.Renderer;
43  import org.apache.maven.doxia.siterenderer.RendererException;
44  import org.apache.maven.doxia.siterenderer.SiteRenderingContext;
45  import org.apache.maven.doxia.tools.SiteToolException;
46  import org.apache.maven.execution.MavenSession;
47  import org.apache.maven.plugin.MojoExecutionException;
48  import org.apache.maven.plugin.MojoFailureException;
49  import org.apache.maven.plugins.annotations.Component;
50  import org.apache.maven.plugins.annotations.Parameter;
51  import org.apache.maven.reporting.MavenReport;
52  import org.apache.maven.reporting.exec.MavenReportExecution;
53  import org.apache.maven.reporting.exec.MavenReportExecutor;
54  import org.apache.maven.reporting.exec.MavenReportExecutorRequest;
55  import org.apache.maven.reporting.exec.ReportPlugin;
56  import org.codehaus.plexus.PlexusConstants;
57  import org.codehaus.plexus.PlexusContainer;
58  import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
59  import org.codehaus.plexus.context.Context;
60  import org.codehaus.plexus.context.ContextException;
61  import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
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.java 1356796 2012-07-03 15:50:08Z olamy $
68   */
69  public abstract class AbstractSiteRenderingMojo
70      extends AbstractSiteMojo 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 component for assembling inheritance.
93       */
94      @Component
95      private DecorationModelInheritanceAssembler assembler;
96  
97      /**
98       * Remote repositories used for the project.
99       *
100      * @todo this is used for site descriptor resolution - it should relate to the actual project but for some reason they are not always filled in
101      */
102     @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true )
103     private List<ArtifactRepository> repositories;
104 
105     /**
106      * Directory containing the template page.
107      *
108      * @deprecated use templateFile or skinning instead
109      */
110     @Parameter( property = "templateDirectory", defaultValue = "src/site" )
111     private File templateDirectory;
112 
113     /**
114      * Default template page.
115      *
116      * @deprecated use templateFile or skinning instead
117      */
118     @Parameter( property = "template" )
119     private String template;
120 
121     /**
122      * The location of a Velocity template file to use. When used, skins and the default templates, CSS and images
123      * are disabled. It is highly recommended that you package this as a skin instead.
124      *
125      * @since 2.0-beta-5
126      */
127     @Parameter( property = "templateFile" )
128     private File templateFile;
129 
130     /**
131      * Additional template properties for rendering the site. See
132      * <a href="/doxia/doxia-sitetools/doxia-site-renderer/">Doxia Site Renderer</a>.
133      */
134     @Parameter
135     private Map<String, Object> attributes;
136 
137     /**
138      * Site renderer.
139      */
140     @Component
141     protected Renderer siteRenderer;
142 
143     /**
144      * Reports (Maven 2).
145      */
146     @Parameter( property = "reports", required = true, readonly = true )
147     protected List<MavenReport> reports;
148 
149     /**
150      * Alternative directory for xdoc source, useful for m1 to m2 migration
151      *
152      * @deprecated use the standard m2 directory layout
153      */
154     @Parameter( defaultValue = "${basedir}/xdocs" )
155     private File xdocDirectory;
156 
157     /**
158      * Directory containing generated documentation.
159      * This is used to pick up other source docs that might have been generated at build time.
160      *
161      * @todo should we deprecate in favour of reports?
162      */
163     @Parameter( alias = "workingDirectory", defaultValue = "${project.build.directory}/generated-site" )
164     protected File generatedSiteDirectory;
165 
166     /**
167      * The current Maven session.
168      */
169     @Component
170     protected MavenSession mavenSession;
171 
172     /**
173      * <p>Configuration section used internally by Maven 3.</p>
174      * <p>More details available here:
175      * <a href="http://maven.apache.org/plugins/maven-site-plugin/maven-3.html#Configuration_formats" target="_blank">
176      * http://maven.apache.org/plugins/maven-site-plugin/maven-3.html#Configuration_formats</a>
177      * </p>
178      * <p><b>Note:</b> using this field is not mandatory with Maven 3 as Maven core injects usual
179      * <code>&lt;reporting&gt;</code> section into this field.</p>
180      *
181      * @since 3.0-beta-1
182      */
183     @Parameter
184     private ReportPlugin[] reportPlugins;
185 
186     private PlexusContainer container;
187 
188     /**
189      * Make links in the site descriptor relative to the project URL.
190      * By default, any absolute links that appear in the site descriptor,
191      * e.g. banner hrefs, breadcrumbs, menu links, etc., will be made relative to project.url.
192      * <p/>
193      * Links will not be changed if this is set to false, or if the project has no URL defined.
194      *
195      * @since 2.3
196      */
197     @Parameter( property = "relativizeDecorationLinks", defaultValue = "true" )
198     private boolean relativizeDecorationLinks;
199 
200     /**
201      * Whether to generate the summary page for project reports: project-info.html.
202      *
203      * @since 2.3
204      */
205     @Parameter( property = "generateProjectInfo", defaultValue = "true" )
206     private boolean generateProjectInfo;
207 
208     /** {@inheritDoc} */
209     public void contextualize( Context context )
210         throws ContextException
211     {
212         container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY );
213     }
214 
215     protected List<MavenReportExecution> getReports()
216         throws MojoExecutionException
217     {
218         if ( isMaven3OrMore() )
219         {
220             MavenReportExecutorRequest mavenReportExecutorRequest = new MavenReportExecutorRequest();
221             mavenReportExecutorRequest.setLocalRepository( localRepository );
222             mavenReportExecutorRequest.setMavenSession( mavenSession );
223             mavenReportExecutorRequest.setProject( project );
224             mavenReportExecutorRequest.setReportPlugins( reportPlugins );
225 
226             MavenReportExecutor mavenReportExecutor;
227             try
228             {
229                 mavenReportExecutor = (MavenReportExecutor) container.lookup( MavenReportExecutor.class.getName() );
230             }
231             catch ( ComponentLookupException e )
232             {
233                 throw new MojoExecutionException( "could not get MavenReportExecutor component", e );
234             }
235             return mavenReportExecutor.buildMavenReports( mavenReportExecutorRequest );
236         }
237 
238         List<MavenReportExecution> reportExecutions = new ArrayList<MavenReportExecution>( reports.size() );
239         for ( MavenReport report : reports )
240         {
241             if ( report.canGenerateReport() )
242             {
243                 reportExecutions.add( new MavenReportExecution( report ) );
244             }
245         }
246         return reportExecutions;
247     }
248 
249     protected SiteRenderingContext createSiteRenderingContext( Locale locale )
250         throws MojoExecutionException, IOException, MojoFailureException
251     {
252         if ( attributes == null )
253         {
254             attributes = new HashMap<String, Object>();
255         }
256 
257         if ( attributes.get( "project" ) == null )
258         {
259             attributes.put( "project", project );
260         }
261 
262         if ( attributes.get( "inputEncoding" ) == null )
263         {
264             attributes.put( "inputEncoding", getInputEncoding() );
265         }
266 
267         if ( attributes.get( "outputEncoding" ) == null )
268         {
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         {
275             attributes.put( (String) entry.getKey(), entry.getValue() );
276         }
277 
278         DecorationModel decorationModel;
279         try
280         {
281             decorationModel = siteTool.getDecorationModel( project, reactorProjects, localRepository, repositories,
282                                                            siteTool.getRelativePath( siteDirectory.getAbsolutePath(),
283                                                            project.getBasedir().getAbsolutePath() ),
284                                                            locale, getInputEncoding(), getOutputEncoding() );
285         }
286         catch ( SiteToolException e )
287         {
288             throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e );
289         }
290 
291         if ( relativizeDecorationLinks )
292         {
293             final String url = project.getUrl();
294 
295             if ( url == null )
296             {
297                 getLog().warn( "No project URL defined - decoration links will not be relativized!" );
298             }
299             else
300             {
301                 getLog().info( "Relativizing decoration links with respect to project URL: " + url );
302                 assembler.resolvePaths( decorationModel, url );
303             }
304         }
305 
306         if ( template != null )
307         {
308             if ( templateFile != null )
309             {
310                 getLog().warn( "'template' configuration is ignored when 'templateFile' is set" );
311             }
312             else
313             {
314                 templateFile = new File( templateDirectory, template );
315             }
316         }
317 
318         File skinFile;
319         try
320         {
321             Artifact skinArtifact =
322                 siteTool.getSkinArtifactFromRepository( localRepository, repositories, decorationModel );
323             getLog().info( "Rendering site with " + skinArtifact.getId() + " skin." );
324 
325             skinFile = skinArtifact.getFile();
326         }
327         catch ( SiteToolException e )
328         {
329             throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e );
330         }
331         SiteRenderingContext context;
332         if ( templateFile != null )
333         {
334             if ( !templateFile.exists() )
335             {
336                 throw new MojoFailureException( "Template file '" + templateFile + "' does not exist" );
337             }
338             context = siteRenderer.createContextForTemplate( templateFile, skinFile, attributes, decorationModel,
339                                                              project.getName(), locale );
340         }
341         else
342         {
343             context = siteRenderer.createContextForSkin( skinFile, attributes, decorationModel, project.getName(),
344                                                          locale );
345         }
346 
347         // Generate static site
348         if ( !locale.getLanguage().equals( Locale.getDefault().getLanguage() ) )
349         {
350             context.addSiteDirectory( new File( siteDirectory, locale.getLanguage() ) );
351             context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "xdoc" );
352             context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "fml" );
353         }
354         else
355         {
356             context.addSiteDirectory( siteDirectory );
357             context.addModuleDirectory( xdocDirectory, "xdoc" );
358             context.addModuleDirectory( xdocDirectory, "fml" );
359         }
360 
361         if ( moduleExcludes != null )
362         {
363             context.setModuleExcludes( moduleExcludes );
364         }
365 
366         return context;
367     }
368 
369     /**
370      * Go through the list of reports and process each one like this:
371      * <ul>
372      * <li>Add the report to a map of reports keyed by filename having the report itself as value
373      * <li>If the report is not yet in the map of documents, add it together with a suitable renderer
374      * </ul>
375      *
376      * @param reports A List of MavenReports
377      * @param documents A Map of documents, keyed by filename
378      * @param locale the Locale the reports are processed for.
379      * @return A map with all reports keyed by filename having the report itself as value.
380      * The map will be used to populate a menu.
381      */
382     protected Map<String, MavenReport> locateReports( List<MavenReportExecution> reports,
383                                                       Map<String, DocumentRenderer> documents, Locale locale )
384     {
385         // copy Collection to prevent ConcurrentModificationException
386         List<MavenReportExecution> filtered = new ArrayList<MavenReportExecution>( reports );
387 
388         Map<String, MavenReport> reportsByOutputName = new LinkedHashMap<String, MavenReport>();
389         for ( MavenReportExecution mavenReportExecution : filtered )
390         {
391             MavenReport report = mavenReportExecution.getMavenReport();
392 
393             String outputName = report.getOutputName() + ".html";
394 
395             // Always add the report to the menu, see MSITE-150
396             reportsByOutputName.put( report.getOutputName(), report );
397 
398             if ( documents.containsKey( outputName ) )
399             {
400                 String displayLanguage = locale.getDisplayLanguage( Locale.ENGLISH );
401 
402                 getLog().info( "Skipped \"" + report.getName( locale ) + "\" report, file \"" + outputName
403                                    + "\" already exists for the " + displayLanguage + " version." );
404                 reports.remove( mavenReportExecution );
405             }
406             else
407             {
408                 RenderingContext renderingContext = new RenderingContext( siteDirectory, outputName );
409                 DocumentRenderer renderer = new ReportDocumentRenderer( mavenReportExecution, renderingContext, getLog() );
410                 documents.put( outputName, renderer );
411             }
412         }
413         return reportsByOutputName;
414     }
415 
416     /**
417      * Go through the collection of reports and put each report into a list for the appropriate category. The list is
418      * put into a map keyed by the name of the category.
419      *
420      * @param reports A Collection of MavenReports
421      * @return A map keyed category having the report itself as value
422      */
423     protected Map<String, List<MavenReport>> categoriseReports( Collection<MavenReport> reports )
424     {
425         Map<String, List<MavenReport>> categories = new LinkedHashMap<String, List<MavenReport>>();
426         for ( MavenReport report : reports )
427         {
428             List<MavenReport> categoryReports = categories.get( report.getCategoryName() );
429             if ( categoryReports == null )
430             {
431                 categoryReports = new ArrayList<MavenReport>();
432                 categories.put( report.getCategoryName(), categoryReports );
433             }
434             categoryReports.add( report );
435         }
436         return categories;
437     }
438 
439     protected Map<String, DocumentRenderer> locateDocuments( SiteRenderingContext context, List<MavenReportExecution> reports,
440                                                              Locale locale )
441         throws IOException, RendererException
442     {
443         Map<String, DocumentRenderer> documents = siteRenderer.locateDocumentFiles( context );
444 
445         Map<String, MavenReport> reportsByOutputName = locateReports( reports, documents, locale );
446 
447         // TODO: I want to get rid of categories eventually. There's no way to add your own in a fully i18n manner
448         Map<String, List<MavenReport>> categories = categoriseReports( reportsByOutputName.values() );
449 
450         siteTool.populateReportsMenu( context.getDecoration(), locale, categories );
451         populateReportItems( context.getDecoration(), locale, reportsByOutputName );
452 
453         if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_INFORMATION ) && generateProjectInfo )
454         {
455             List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_INFORMATION );
456 
457             RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-info.html" );
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             List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_REPORTS );
477             RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-reports.html" );
478             String title = i18n.getString( "site-plugin", locale, "report.project.title" );
479             String desc1 = i18n.getString( "site-plugin", locale, "report.project.description1" );
480             String desc2 = i18n.getString( "site-plugin", locale, "report.project.description2" );
481             DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2,
482                                                                              i18n, categoryReports, getLog() );
483 
484             if ( !documents.containsKey( renderer.getOutputName() ) )
485             {
486                 documents.put( renderer.getOutputName(), renderer );
487             }
488             else
489             {
490                 getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" );
491             }
492         }
493         return documents;
494     }
495 
496     protected void populateReportItems( DecorationModel decorationModel, Locale locale,
497                                         Map<String, MavenReport> reportsByOutputName )
498     {
499         for ( Menu menu : decorationModel.getMenus() )
500         {
501             populateItemRefs( menu.getItems(), locale, reportsByOutputName );
502         }
503     }
504 
505     private void populateItemRefs( List<MenuItem> items, Locale locale, Map<String, MavenReport> reportsByOutputName )
506     {
507         for ( Iterator<MenuItem> i = items.iterator(); i.hasNext(); )
508         {
509             MenuItem item = i.next();
510 
511             if ( item.getRef() != null )
512             {
513                 MavenReport report = reportsByOutputName.get( item.getRef() );
514 
515                 if ( report != null )
516                 {
517                     if ( item.getName() == null )
518                     {
519                         item.setName( report.getName( locale ) );
520                     }
521 
522                     if ( item.getHref() == null || item.getHref().length() == 0 )
523                     {
524                         item.setHref( report.getOutputName() + ".html" );
525                     }
526                 }
527                 else
528                 {
529                     getLog().warn( "Unrecognised reference: '" + item.getRef() + "'" );
530                     i.remove();
531                 }
532             }
533 
534             populateItemRefs( item.getItems(), locale, reportsByOutputName );
535         }
536     }
537 }