View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.rat.mp;
20  
21  import static org.apache.maven.shared.utils.logging.MessageUtils.buffer;
22  
23  import java.io.ByteArrayOutputStream;
24  import java.io.File;
25  import java.io.IOException;
26  import java.io.OutputStreamWriter;
27  import java.io.Writer;
28  import java.nio.charset.StandardCharsets;
29  import java.nio.file.Files;
30  import java.util.HashMap;
31  import java.util.List;
32  import java.util.Locale;
33  import java.util.Map;
34  import java.util.ResourceBundle;
35  
36  import org.apache.maven.artifact.Artifact;
37  import org.apache.maven.artifact.repository.ArtifactRepository;
38  import org.apache.maven.doxia.sink.Sink;
39  import org.apache.maven.doxia.sink.SinkFactory;
40  import org.apache.maven.doxia.sink.impl.SinkEventAttributeSet;
41  import org.apache.maven.doxia.site.decoration.DecorationModel;
42  import org.apache.maven.doxia.siterenderer.Renderer;
43  import org.apache.maven.doxia.siterenderer.RendererException;
44  import org.apache.maven.doxia.siterenderer.RenderingContext;
45  import org.apache.maven.doxia.siterenderer.SiteRenderingContext;
46  import org.apache.maven.doxia.siterenderer.sink.SiteRendererSink;
47  import org.apache.maven.doxia.tools.SiteTool;
48  import org.apache.maven.doxia.tools.SiteToolException;
49  import org.apache.maven.execution.MavenSession;
50  import org.apache.maven.plugin.MojoExecutionException;
51  import org.apache.maven.plugins.annotations.Component;
52  import org.apache.maven.plugins.annotations.Mojo;
53  import org.apache.maven.plugins.annotations.Parameter;
54  import org.apache.maven.plugins.annotations.ResolutionScope;
55  import org.apache.maven.reporting.MavenMultiPageReport;
56  import org.apache.maven.reporting.MavenReportException;
57  import org.apache.rat.ReportConfiguration;
58  import org.apache.rat.Reporter;
59  import org.apache.rat.VersionInfo;
60  import org.apache.rat.license.LicenseSetFactory.LicenseFilter;
61  import org.codehaus.plexus.util.ReaderFactory;
62  
63  /**
64   * Generates a report with Rat's output.
65   */
66  @Mojo(name = "rat", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true)
67  public class RatReportMojo extends AbstractRatMojo implements MavenMultiPageReport {
68  
69      /**
70       * The output directory for the report. Note that this parameter is only
71       * evaluated if the goal is run directly from the command line. If the goal is
72       * run indirectly as part of a site generation, the output directory configured
73       * in the Maven Site Plugin is used instead.
74       */
75      @Parameter(defaultValue = "${project.reporting.outputDirectory}", readonly = true, required = true)
76      protected File outputDirectory;
77  
78      /**
79       * Specifies the input encoding.
80       */
81      @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}", readonly = true)
82      private String inputEncoding;
83  
84      /**
85       * Specifies the output encoding.
86       */
87      @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}", readonly = true)
88      private String outputEncoding;
89  
90      /**
91       * The local repository.
92       */
93      @Parameter(defaultValue = "${session}", readonly = true, required = true)
94      protected MavenSession session;
95  
96      /**
97       * Remote repositories used for the project.
98       */
99      @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true, required = true)
100     protected List<ArtifactRepository> remoteRepositories;
101 
102     /**
103      * SiteTool.
104      */
105     @Component
106     protected SiteTool siteTool;
107 
108     /**
109      * Doxia Site Renderer component.
110      */
111     @Component
112     protected Renderer siteRenderer;
113 
114     /**
115      * The current sink to use
116      */
117     private Sink sink;
118 
119     /**
120      * The sink factory to use
121      */
122     private SinkFactory sinkFactory;
123 
124     /**
125      * The current report output directory to use
126      */
127     private File reportOutputDirectory;
128 
129     /**
130      * This method is called when the report generation is invoked directly as a
131      * standalone Mojo.
132      *
133      * @throws MojoExecutionException if an error occurs when generating the report
134      * @see org.apache.maven.plugin.Mojo#execute()
135      */
136     @Override
137     public void execute() throws MojoExecutionException {
138         if (!canGenerateReport()) {
139             return;
140         }
141 
142         File outputDirectory = new File(getOutputDirectory());
143 
144         String filename = getOutputName() + ".html";
145 
146         Locale locale = Locale.getDefault();
147 
148         try {
149             SiteRenderingContext siteContext = createSiteRenderingContext(locale);
150 
151             // copy resources
152             getSiteRenderer().copyResources(siteContext, outputDirectory);
153 
154             // TODO Replace null with real value
155             RenderingContext docRenderingContext = new RenderingContext(outputDirectory, filename, null);
156 
157             SiteRendererSink sink = new SiteRendererSink(docRenderingContext);
158 
159             generate(sink, null, locale);
160 
161             // MSHARED-204: only render Doxia sink if not an external report
162             if (!isExternalReport()) {
163                 if (!outputDirectory.exists()) {
164                     if (!outputDirectory.mkdirs()) {
165                         getLog().error("Unable to create output directory: " + outputDirectory);
166                     }
167                 }
168 
169                 try (Writer writer = new OutputStreamWriter(
170                         Files.newOutputStream(new File(outputDirectory, filename).toPath()), getOutputEncoding())) {
171                     // render report
172                     getSiteRenderer().mergeDocumentIntoSite(writer, sink, siteContext);
173                 }
174             }
175 
176             // copy generated resources also
177             getSiteRenderer().copyResources(siteContext, outputDirectory);
178         } catch (RendererException | IOException | MavenReportException e) {
179             throw new MojoExecutionException(
180                     "An error has occurred in " + getName(Locale.ENGLISH) + " report generation.", e);
181         }
182     }
183 
184     private SiteRenderingContext createSiteRenderingContext(final Locale locale) throws MavenReportException, IOException {
185         DecorationModel decorationModel = new DecorationModel();
186 
187         Map<String, Object> templateProperties = new HashMap<>();
188         // We tell the skin that we are rendering in standalone mode
189         templateProperties.put("standalone", Boolean.TRUE);
190         templateProperties.put("project", getProject());
191         templateProperties.put("inputEncoding", getInputEncoding());
192         templateProperties.put("outputEncoding", getOutputEncoding());
193         // Put any of the properties in directly into the Velocity context
194         for (Map.Entry<Object, Object> entry : getProject().getProperties().entrySet()) {
195             templateProperties.put((String) entry.getKey(), entry.getValue());
196         }
197 
198         SiteRenderingContext context;
199         try {
200             Artifact skinArtifact = siteTool.getSkinArtifactFromRepository(session.getLocalRepository(),
201                     remoteRepositories, decorationModel);
202 
203             getLog().debug(buffer().a("Rendering content with ").strong(skinArtifact.getId() + " skin").a('.').build());
204 
205             context = siteRenderer.createContextForSkin(skinArtifact, templateProperties, decorationModel,
206                     project.getName(), locale);
207         } catch (SiteToolException e) {
208             throw new MavenReportException("Failed to retrieve skin artifact", e);
209         } catch (RendererException e) {
210             throw new MavenReportException("Failed to create context for skin", e);
211         }
212 
213         // Generate static site
214         context.setRootDirectory(project.getBasedir());
215 
216         return context;
217     }
218 
219     /**
220      * Generate a report.
221      *
222      * @param sink the sink to use for the generation.
223      * @param locale the wanted locale to generate the report, could be null.
224      * @throws MavenReportException if any
225      * @deprecated use {@link #generate(Sink, SinkFactory, Locale)} instead.
226      */
227     @Deprecated
228     @Override
229     public void generate(final org.codehaus.doxia.sink.Sink sink, final Locale locale) throws MavenReportException {
230         generate(sink, null, locale);
231     }
232 
233     /**
234      * Generate a report.
235      *
236      * @param sink the sink to use for the generation.
237      * @param locale the wanted locale to generate the report, could be null.
238      * @throws MavenReportException if any
239      * @deprecated use {@link #generate(Sink, SinkFactory, Locale)} instead.
240      */
241     @Deprecated
242     public void generate(final Sink sink, final Locale locale) throws MavenReportException {
243         generate(sink, null, locale);
244     }
245 
246     /**
247      * This method is called when the report generation is invoked by
248      * maven-site-plugin.
249      *
250      * @param sink the sink to use for the generation.
251      * @param sinkFactory the sink factory to use for the generation.
252      * @param locale the wanted locale to generate the report, could be null.
253      * @throws MavenReportException if any
254      */
255     @Override
256     public void generate(final Sink sink, final SinkFactory sinkFactory, final Locale locale) throws MavenReportException {
257         if (!canGenerateReport()) {
258             getLog().info("This report cannot be generated as part of the current build. "
259                     + "The report name should be referenced in this line of output.");
260             return;
261         }
262 
263         this.sink = sink;
264 
265         this.sinkFactory = sinkFactory;
266 
267         executeReport(locale);
268 
269         closeReport();
270     }
271 
272     /**
273      * @return CATEGORY_PROJECT_REPORTS
274      */
275     @Override
276     public String getCategoryName() {
277         return CATEGORY_PROJECT_REPORTS;
278     }
279 
280     @Override
281     public File getReportOutputDirectory() {
282         if (reportOutputDirectory == null) {
283             reportOutputDirectory = new File(getOutputDirectory());
284         }
285 
286         return reportOutputDirectory;
287     }
288 
289     @Override
290     public void setReportOutputDirectory(final File reportOutputDirectory) {
291         this.reportOutputDirectory = reportOutputDirectory;
292         this.outputDirectory = reportOutputDirectory;
293     }
294 
295     protected String getOutputDirectory() {
296         return outputDirectory.getAbsolutePath();
297     }
298 
299     protected Renderer getSiteRenderer() {
300         return siteRenderer;
301     }
302 
303     /**
304      * Gets the input files encoding.
305      *
306      * @return The input files encoding, never <code>null</code>.
307      */
308     protected String getInputEncoding() {
309         return (inputEncoding == null) ? ReaderFactory.FILE_ENCODING : inputEncoding;
310     }
311 
312     /**
313      * Gets the effective reporting output files encoding.
314      *
315      * @return The effective reporting output file encoding, never
316      * <code>null</code>.
317      */
318     protected String getOutputEncoding() {
319         return (outputEncoding == null) ? StandardCharsets.UTF_8.toString() : outputEncoding;
320     }
321 
322     /**
323      * Actions when closing the report.
324      */
325     protected void closeReport() {
326         sink.close();
327     }
328 
329     /**
330      * @return the sink factory used
331      */
332     public SinkFactory getSinkFactory() {
333         return sinkFactory;
334     }
335 
336     /**
337      * @return {@code false} by default.
338      * @see org.apache.maven.reporting.MavenReport#isExternalReport()
339      */
340     @Override
341     public boolean isExternalReport() {
342         return false;
343     }
344 
345     @Override
346     public boolean canGenerateReport() {
347         return !skip;
348     }
349 
350     /**
351      * Writes the report to the Doxia sink.
352      *
353      * @param locale The locale to use for writing the report.
354      * @throws MavenReportException Writing the report failed.
355      */
356     protected void executeReport(final Locale locale) throws MavenReportException {
357         ResourceBundle bundle = getBundle(locale);
358         final String title = bundle.getString("report.rat.title");
359         sink.head();
360         sink.title();
361         sink.text(title);
362         sink.title_();
363         sink.head_();
364 
365         sink.body();
366 
367         sink.section1();
368         sink.sectionTitle1();
369         sink.text(title);
370         sink.sectionTitle1_();
371 
372         sink.paragraph();
373         sink.text(bundle.getString("report.rat.link") + " ");
374         sink.link(bundle.getString("report.rat.url"));
375         sink.text(bundle.getString("report.rat.fullName"));
376         sink.link_();
377         final String ratVersion = new VersionInfo(RatReportMojo.class).toString();
378         if (ratVersion != null) {
379             sink.text(" " + ratVersion);
380         }
381         sink.text(".");
382         sink.paragraph_();
383 
384         sink.paragraph();
385         sink.verbatim(SinkEventAttributeSet.BOXED);
386         try {
387             ReportConfiguration config = getConfiguration();
388             config.setFrom(getDefaultsBuilder().build(config.getLog()));
389             logLicenses(config.getLicenses(LicenseFilter.ALL));
390             ByteArrayOutputStream baos = new ByteArrayOutputStream();
391             config.setOut(() -> baos);
392             new Reporter(config).output();
393             sink.text(baos.toString(StandardCharsets.UTF_8.name()));
394         } catch (Exception e) {
395             throw new MavenReportException(e.getMessage(), e);
396         }
397         sink.verbatim_();
398         sink.paragraph_();
399         sink.section1_();
400         sink.body_();
401     }
402 
403     /**
404      * Returns the reports bundle
405      *
406      * @param locale Requested locale of the bundle
407      * @return The bundle, which is used to read localized strings.
408      */
409     private ResourceBundle getBundle(final Locale locale) {
410         return ResourceBundle.getBundle("org/apache/rat/mp/rat-report", locale, getClass().getClassLoader());
411     }
412 
413     /**
414      * Returns the reports description.
415      *
416      * @param locale Requested locale of the bundle
417      * @return Report description, as given by the key "report.rat.description" in
418      * the bundle.
419      */
420     @Override
421     public String getDescription(final Locale locale) {
422         return getBundle(locale).getString("report.rat.description");
423     }
424 
425     /**
426      * Returns the reports name.
427      *
428      * @param locale Requested locale of the bundle
429      * @return Report name, as given by the key "report.rat.name" in the bundle.
430      */
431     @Override
432     public String getName(final Locale locale) {
433         return getBundle(locale).getString("report.rat.name");
434     }
435 
436     /**
437      * Returns the reports file name.
438      *
439      * @return "rat-report"
440      */
441     @Override
442     public String getOutputName() {
443         return "rat-report";
444     }
445 }