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.html 861484 2013-05-09 23:10:16Z hboutemy $
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( defaultValue = "${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 <b>used internally</b> 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 (and read-only since 3.3)
182      */
183     @Parameter( readonly = true )
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                 // MSITE-658
302                 final String localeUrl =
303                     locale.equals( Locale.getDefault() ) ? url : url + "/" + locale.getLanguage();
304                 getLog().info( "Relativizing decoration links with respect to project URL: " + localeUrl );
305                 assembler.resolvePaths( decorationModel, localeUrl );
306             }
307         }
308 
309         if ( template != null )
310         {
311             if ( templateFile != null )
312             {
313                 getLog().warn( "'template' configuration is ignored when 'templateFile' is set" );
314             }
315             else
316             {
317                 templateFile = new File( templateDirectory, template );
318             }
319         }
320 
321         File skinFile;
322         try
323         {
324             Artifact skinArtifact =
325                 siteTool.getSkinArtifactFromRepository( localRepository, repositories, decorationModel );
326             getLog().info( "Rendering site with " + skinArtifact.getId() + " skin." );
327 
328             skinFile = skinArtifact.getFile();
329         }
330         catch ( SiteToolException e )
331         {
332             throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e );
333         }
334         SiteRenderingContext context;
335         if ( templateFile != null )
336         {
337             if ( !templateFile.exists() )
338             {
339                 throw new MojoFailureException( "Template file '" + templateFile + "' does not exist" );
340             }
341             context = siteRenderer.createContextForTemplate( templateFile, skinFile, attributes, decorationModel,
342                                                              project.getName(), locale );
343         }
344         else
345         {
346             context = siteRenderer.createContextForSkin( skinFile, attributes, decorationModel, project.getName(),
347                                                          locale );
348         }
349 
350         // Generate static site
351         if ( !locale.getLanguage().equals( Locale.getDefault().getLanguage() ) )
352         {
353             context.addSiteDirectory( new File( siteDirectory, locale.getLanguage() ) );
354             context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "xdoc" );
355             context.addModuleDirectory( new File( xdocDirectory, locale.getLanguage() ), "fml" );
356         }
357         else
358         {
359             context.addSiteDirectory( siteDirectory );
360             context.addModuleDirectory( xdocDirectory, "xdoc" );
361             context.addModuleDirectory( xdocDirectory, "fml" );
362         }
363 
364         if ( moduleExcludes != null )
365         {
366             context.setModuleExcludes( moduleExcludes );
367         }
368 
369         return context;
370     }
371 
372     /**
373      * Go through the list of reports and process each one like this:
374      * <ul>
375      * <li>Add the report to a map of reports keyed by filename having the report itself as value
376      * <li>If the report is not yet in the map of documents, add it together with a suitable renderer
377      * </ul>
378      *
379      * @param reports A List of MavenReports
380      * @param documents A Map of documents, keyed by filename
381      * @param locale the Locale the reports are processed for.
382      * @return A map with all reports keyed by filename having the report itself as value.
383      * The map will be used to populate a menu.
384      */
385     protected Map<String, MavenReport> locateReports( List<MavenReportExecution> reports,
386                                                       Map<String, DocumentRenderer> documents, Locale locale )
387     {
388         // copy Collection to prevent ConcurrentModificationException
389         List<MavenReportExecution> filtered = new ArrayList<MavenReportExecution>( reports );
390 
391         Map<String, MavenReport> reportsByOutputName = new LinkedHashMap<String, MavenReport>();
392         for ( MavenReportExecution mavenReportExecution : filtered )
393         {
394             MavenReport report = mavenReportExecution.getMavenReport();
395 
396             String outputName = report.getOutputName() + ".html";
397 
398             // Always add the report to the menu, see MSITE-150
399             reportsByOutputName.put( report.getOutputName(), report );
400 
401             if ( documents.containsKey( outputName ) )
402             {
403                 String displayLanguage = locale.getDisplayLanguage( Locale.ENGLISH );
404 
405                 getLog().info( "Skipped \"" + report.getName( locale ) + "\" report, file \"" + outputName
406                                    + "\" already exists for the " + displayLanguage + " version." );
407                 reports.remove( mavenReportExecution );
408             }
409             else
410             {
411                 RenderingContext renderingContext = new RenderingContext( siteDirectory, outputName );
412                 DocumentRenderer renderer = new ReportDocumentRenderer( mavenReportExecution, renderingContext, getLog() );
413                 documents.put( outputName, renderer );
414             }
415         }
416         return reportsByOutputName;
417     }
418 
419     /**
420      * Go through the collection of reports and put each report into a list for the appropriate category. The list is
421      * put into a map keyed by the name of the category.
422      *
423      * @param reports A Collection of MavenReports
424      * @return A map keyed category having the report itself as value
425      */
426     protected Map<String, List<MavenReport>> categoriseReports( Collection<MavenReport> reports )
427     {
428         Map<String, List<MavenReport>> categories = new LinkedHashMap<String, List<MavenReport>>();
429         for ( MavenReport report : reports )
430         {
431             List<MavenReport> categoryReports = categories.get( report.getCategoryName() );
432             if ( categoryReports == null )
433             {
434                 categoryReports = new ArrayList<MavenReport>();
435                 categories.put( report.getCategoryName(), categoryReports );
436             }
437             categoryReports.add( report );
438         }
439         return categories;
440     }
441 
442     protected Map<String, DocumentRenderer> locateDocuments( SiteRenderingContext context, List<MavenReportExecution> reports,
443                                                              Locale locale )
444         throws IOException, RendererException
445     {
446         Map<String, DocumentRenderer> documents = siteRenderer.locateDocumentFiles( context );
447 
448         Map<String, MavenReport> reportsByOutputName = locateReports( reports, documents, locale );
449 
450         // TODO: I want to get rid of categories eventually. There's no way to add your own in a fully i18n manner
451         Map<String, List<MavenReport>> categories = categoriseReports( reportsByOutputName.values() );
452 
453         siteTool.populateReportsMenu( context.getDecoration(), locale, categories );
454         populateReportItems( context.getDecoration(), locale, reportsByOutputName );
455 
456         if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_INFORMATION ) && generateProjectInfo )
457         {
458             List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_INFORMATION );
459 
460             RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-info.html" );
461             String title = i18n.getString( "site-plugin", locale, "report.information.title" );
462             String desc1 = i18n.getString( "site-plugin", locale, "report.information.description1" );
463             String desc2 = i18n.getString( "site-plugin", locale, "report.information.description2" );
464             DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2,
465                                                                              i18n, categoryReports, getLog() );
466 
467             if ( !documents.containsKey( renderer.getOutputName() ) )
468             {
469                 documents.put( renderer.getOutputName(), renderer );
470             }
471             else
472             {
473                 getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" );
474             }
475         }
476 
477         if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_REPORTS ) )
478         {
479             List<MavenReport> categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_REPORTS );
480             RenderingContext renderingContext = new RenderingContext( siteDirectory, "project-reports.html" );
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     protected void populateReportItems( DecorationModel decorationModel, Locale locale,
500                                         Map<String, MavenReport> reportsByOutputName )
501     {
502         for ( Menu menu : decorationModel.getMenus() )
503         {
504             populateItemRefs( menu.getItems(), locale, reportsByOutputName );
505         }
506     }
507 
508     private void populateItemRefs( List<MenuItem> items, Locale locale, Map<String, MavenReport> reportsByOutputName )
509     {
510         for ( Iterator<MenuItem> i = items.iterator(); i.hasNext(); )
511         {
512             MenuItem item = i.next();
513 
514             if ( item.getRef() != null )
515             {
516                 MavenReport report = reportsByOutputName.get( item.getRef() );
517 
518                 if ( report != null )
519                 {
520                     if ( item.getName() == null )
521                     {
522                         item.setName( report.getName( locale ) );
523                     }
524 
525                     if ( item.getHref() == null || item.getHref().length() == 0 )
526                     {
527                         item.setHref( report.getOutputName() + ".html" );
528                     }
529                 }
530                 else
531                 {
532                     getLog().warn( "Unrecognised reference: '" + item.getRef() + "'" );
533                     i.remove();
534                 }
535             }
536 
537             populateItemRefs( item.getItems(), locale, reportsByOutputName );
538         }
539     }
540 }