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.maven.plugins.javadoc;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.net.HttpURLConnection;
24  import java.net.URL;
25  import java.nio.charset.Charset;
26  import java.nio.charset.StandardCharsets;
27  import java.nio.file.Files;
28  import java.nio.file.Path;
29  import java.nio.file.Paths;
30  import java.util.Collections;
31  import java.util.HashMap;
32  import java.util.List;
33  import java.util.Map;
34  import java.util.Objects;
35  
36  import org.apache.commons.lang3.StringUtils;
37  import org.apache.maven.execution.MavenSession;
38  import org.apache.maven.model.Plugin;
39  import org.apache.maven.plugin.LegacySupport;
40  import org.apache.maven.plugin.MojoExecution;
41  import org.apache.maven.plugin.MojoExecutionException;
42  import org.apache.maven.plugin.MojoFailureException;
43  import org.apache.maven.plugin.testing.AbstractMojoTestCase;
44  import org.apache.maven.plugin.testing.stubs.MavenProjectStub;
45  import org.apache.maven.plugins.javadoc.ProxyServer.AuthAsyncProxyServlet;
46  import org.apache.maven.project.MavenProject;
47  import org.apache.maven.project.ProjectBuildingRequest;
48  import org.apache.maven.settings.Proxy;
49  import org.apache.maven.settings.Settings;
50  import org.apache.maven.shared.utils.io.FileUtils;
51  import org.codehaus.plexus.languages.java.version.JavaVersion;
52  import org.eclipse.aether.DefaultRepositorySystemSession;
53  import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory;
54  import org.eclipse.aether.repository.LocalRepository;
55  import org.hamcrest.MatcherAssert;
56  import org.junit.AssumptionViolatedException;
57  import org.slf4j.Logger;
58  import org.slf4j.LoggerFactory;
59  
60  import static org.apache.commons.io.FileUtils.copyDirectory;
61  import static org.apache.commons.io.FileUtils.deleteDirectory;
62  import static org.assertj.core.api.Assertions.assertThat;
63  import static org.hamcrest.CoreMatchers.anyOf;
64  import static org.hamcrest.CoreMatchers.containsString;
65  import static org.hamcrest.CoreMatchers.is;
66  import static org.junit.Assume.assumeThat;
67  import static org.mockito.Mockito.mock;
68  import static org.mockito.Mockito.spy;
69  import static org.mockito.Mockito.when;
70  
71  /**
72   * Test {@link org.apache.maven.plugins.javadoc.JavadocReport} class.
73   *
74   * @author <a href="mailto:oching@apache.org">Maria Odea Ching</a>
75   * @author <a href="mailto:vincent.siveton@gmail.com">Vincent Siveton</a>
76   */
77  public class JavadocReportTest extends AbstractMojoTestCase {
78  
79      private static final char LINE_SEPARATOR = ' ';
80  
81      public static final String OPTIONS_UMLAUT_ENCODING = "Options Umlaut Encoding ö ä ü ß";
82  
83      private Path unit;
84  
85      private File localRepo;
86  
87      private static final Logger LOGGER = LoggerFactory.getLogger(JavadocReportTest.class);
88  
89      @Override
90      protected void setUp() throws Exception {
91          super.setUp();
92  
93          Path tempDirectory = Files.createTempDirectory("JavadocReportTest");
94          localRepo = tempDirectory.resolve(Paths.get("target/local-repo/")).toFile();
95          unit = new File(getBasedir(), "src/test/resources/unit").toPath();
96  
97          createTestRepo();
98      }
99  
100     @Override
101     protected void tearDown() throws Exception {
102         try {
103             deleteDirectory(localRepo);
104         } catch (IOException ex) {
105             // CI servers can have problems deleting files.
106             // It will get cleared out eventually, and since
107             // temporary directories have unique names,
108             // it shouldn't affect subsequent tests.
109         }
110 
111         super.tearDown();
112     }
113 
114     private JavadocReport lookupMojo(Path testPom) throws Exception {
115         JavadocReport mojo = (JavadocReport) lookupMojo("javadoc", testPom.toFile());
116 
117         Plugin p = new Plugin();
118         p.setGroupId("org.apache.maven.plugins");
119         p.setArtifactId("maven-javadoc-plugin");
120         MojoExecution mojoExecution = new MojoExecution(p, "javadoc", null);
121 
122         setVariableValueToObject(mojo, "mojoExecution", mojoExecution);
123 
124         MavenProject currentProject = new MavenProjectStub();
125         currentProject.setGroupId("GROUPID");
126         currentProject.setArtifactId("ARTIFACTID");
127 
128         List<MavenProject> reactorProjects =
129                 mojo.getReactorProjects() != null ? mojo.getReactorProjects() : Collections.emptyList();
130         MavenSession session = newMavenSession(currentProject);
131         setVariableValueToObject(mojo, "session", session);
132         setVariableValueToObject(mojo, "repoSession", session.getRepositorySession());
133         setVariableValueToObject(mojo, "reactorProjects", reactorProjects);
134         return mojo;
135     }
136 
137     /**
138      * Create test repository in target directory.
139      *
140      * @throws IOException if any
141      */
142     private void createTestRepo() throws IOException {
143         assertTrue(localRepo.mkdirs());
144 
145         // ----------------------------------------------------------------------
146         // UMLGraph
147         // ----------------------------------------------------------------------
148 
149         Path sourceDir = unit.resolve("doclet-test/artifact-doclet");
150         assertThat(sourceDir).exists();
151         copyDirectory(sourceDir.toFile(), localRepo);
152 
153         // ----------------------------------------------------------------------
154         // UMLGraph-bis
155         // ----------------------------------------------------------------------
156 
157         sourceDir = unit.resolve("doclet-path-test/artifact-doclet");
158         assertThat(sourceDir).exists();
159         copyDirectory(sourceDir.toFile(), localRepo);
160 
161         // ----------------------------------------------------------------------
162         // commons-attributes-compiler
163         // https://www.tullmann.org/pat/taglets/
164         // ----------------------------------------------------------------------
165 
166         sourceDir = unit.resolve("taglet-test/artifact-taglet");
167         assertThat(sourceDir).exists();
168         copyDirectory(sourceDir.toFile(), localRepo);
169 
170         // ----------------------------------------------------------------------
171         // stylesheetfile-test
172         // ----------------------------------------------------------------------
173 
174         sourceDir = unit.resolve("stylesheetfile-test/artifact-stylesheetfile");
175         assertThat(sourceDir).exists();
176         copyDirectory(sourceDir.toFile(), localRepo);
177 
178         // ----------------------------------------------------------------------
179         // helpfile-test
180         // ----------------------------------------------------------------------
181 
182         sourceDir = unit.resolve("helpfile-test/artifact-helpfile");
183         assertThat(sourceDir).exists();
184         copyDirectory(sourceDir.toFile(), localRepo);
185 
186         // Remove SCM files
187         List<String> files = FileUtils.getFileAndDirectoryNames(
188                 localRepo, FileUtils.getDefaultExcludesAsString(), null, true, true, true, true);
189         for (String filename : files) {
190             File file = new File(filename);
191 
192             if (file.isDirectory()) {
193                 deleteDirectory(file);
194             } else {
195                 file.delete();
196             }
197         }
198     }
199 
200     /**
201      * Convenience method that reads the contents of the specified file object into a string with a
202      * <code>space</code> as line separator.
203      *
204      * @see #LINE_SEPARATOR
205      * @param file the file to be read
206      * @return a String object that contains the contents of the file
207      * @throws IOException if any
208      */
209     private static String readFile(Path file) throws IOException {
210         return readFile(file, StandardCharsets.UTF_8);
211     }
212 
213     /**
214      * Convenience method that reads the contents of the specified file object into a string with a
215      * <code>space</code> as line separator.
216      *
217      * @see #LINE_SEPARATOR
218      * @param file the file to be read
219      * @param cs charset to use
220      * @return a String object that contains the contents of the file
221      * @throws IOException if any
222      */
223     private static String readFile(Path file, Charset cs) throws IOException {
224         StringBuilder str = new StringBuilder((int) Files.size(file));
225 
226         for (String strTmp : Files.readAllLines(file, cs)) {
227             str.append(LINE_SEPARATOR);
228             str.append(strTmp);
229         }
230 
231         return str.toString();
232     }
233 
234     /**
235      * Test when default configuration is provided for the plugin
236      *
237      * @throws Exception if any
238      */
239     public void testDefaultConfiguration() throws Exception {
240         Path testPom = unit.resolve("default-configuration/default-configuration-plugin-config.xml");
241         JavadocReport mojo = lookupMojo(testPom);
242         mojo.execute();
243 
244         // package level generated javadoc files
245         Path apidocs = new File(getBasedir(), "target/test/unit/default-configuration/target/site/apidocs").toPath();
246 
247         String appHtml = "def/configuration/App.html";
248         Path generatedFile = apidocs.resolve(appHtml);
249         assertThat(generatedFile).exists();
250 
251         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("16")) {
252             String url = Objects.requireNonNull(mojo.getDefaultJavadocApiLink()).getUrl();
253             HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
254             connection.setRequestMethod("HEAD");
255             try {
256                 // only test when URL can be reached
257                 if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
258                     try {
259                         assumeThat(connection.getURL().toString(), is(url));
260 
261                         // https://bugs.openjdk.java.net/browse/JDK-8216497
262                         MatcherAssert.assertThat(
263                                 url + " available, but " + appHtml + " is missing link to java.lang.Object",
264                                 new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8),
265                                 anyOf(
266                                         containsString("/docs/api/java/lang/Object.html"),
267                                         containsString("/docs/api/java.base/java/lang/Object.html")));
268                     } catch (AssumptionViolatedException e) {
269                         LOGGER.warn("ignoring defaultAPI check: {}", e.getMessage());
270                     }
271                 }
272             } catch (Exception e) {
273                 LOGGER.error("error connecting to javadoc URL: {}", url);
274                 throw e;
275             }
276         } else {
277             MatcherAssert.assertThat(
278                     new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8),
279                     containsString("/docs/api/java.base/java/lang/Object.html"));
280         }
281 
282         assertThat(apidocs.resolve("def/configuration/AppSample.html")).exists();
283         assertThat(apidocs.resolve("def/configuration/package-summary.html")).exists();
284         assertThat(apidocs.resolve("def/configuration/package-tree.html")).exists();
285         assertThat(apidocs.resolve("def/configuration/package-use.html")).exists();
286 
287         // package-frame and allclasses-(no)frame not generated anymore since Java 11
288         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) {
289             assertThat(apidocs.resolve("def/configuration/package-frame.html")).exists();
290             assertThat(apidocs.resolve("allclasses-frame.html"))
291                     .exists()
292                     .content()
293                     .containsOnlyOnce("def/configuration/App.html")
294                     .containsOnlyOnce("def/configuration/AppSample.html");
295             assertThat(apidocs.resolve("allclasses-noframe.html"))
296                     .exists()
297                     .content()
298                     .containsOnlyOnce("def/configuration/App.html")
299                     .containsOnlyOnce("def/configuration/AppSample.html");
300         }
301 
302         // class level generated javadoc files
303         assertThat(apidocs.resolve("def/configuration/class-use/App.html")).exists();
304         assertThat(apidocs.resolve("def/configuration/class-use/AppSample.html"))
305                 .exists();
306 
307         // project level generated javadoc files
308         assertThat(apidocs.resolve("constant-values.html")).exists();
309         assertThat(apidocs.resolve("deprecated-list.html")).exists();
310         assertThat(apidocs.resolve("help-doc.html")).exists();
311         assertThat(apidocs.resolve("index-all.html")).exists();
312         assertThat(apidocs.resolve("index.html")).exists();
313         assertThat(apidocs.resolve("overview-tree.html")).exists();
314         assertThat(apidocs.resolve("stylesheet.css")).exists();
315 
316         if (JavaVersion.JAVA_VERSION.isAtLeast("10")) {
317             assertThat(apidocs.resolve("element-list")).exists();
318         } else {
319             assertThat(apidocs.resolve("package-list")).exists();
320         }
321     }
322 
323     /**
324      * Method for testing the subpackages and excludePackageNames parameter
325      *
326      * @throws Exception if any
327      */
328     public void testSubpackages() throws Exception {
329         Path testPom = unit.resolve("subpackages-test/subpackages-test-plugin-config.xml");
330         JavadocReport mojo = lookupMojo(testPom);
331         mojo.execute();
332 
333         Path apidocs = new File(getBasedir(), "target/test/unit/subpackages-test/target/site/apidocs").toPath();
334 
335         // check the excluded packages
336         assertThat(apidocs.resolve("subpackages/test/excluded")).doesNotExist();
337         assertThat(apidocs.resolve("subpackages/test/included/exclude")).doesNotExist();
338 
339         // check if the classes in the specified subpackages were included
340         assertThat(apidocs.resolve("subpackages/test/App.html")).exists();
341         assertThat(apidocs.resolve("subpackages/test/AppSample.html")).exists();
342         assertThat(apidocs.resolve("subpackages/test/included/IncludedApp.html"))
343                 .exists();
344         assertThat(apidocs.resolve("subpackages/test/included/IncludedAppSample.html"))
345                 .exists();
346     }
347 
348     public void testIncludesExcludes() throws Exception {
349         Path testPom = unit.resolve("file-include-exclude-test/file-include-exclude-plugin-config.xml");
350         JavadocReport mojo = lookupMojo(testPom);
351         mojo.execute();
352 
353         Path apidocs =
354                 new File(getBasedir(), "target/test/unit/file-include-exclude-test/target/site/apidocs").toPath();
355 
356         // check if the classes in the specified subpackages were included
357         assertThat(apidocs.resolve("subpackages/test/App.html")).exists();
358         assertThat(apidocs.resolve("subpackages/test/AppSample.html")).exists();
359         assertThat(apidocs.resolve("subpackages/test/included/IncludedApp.html"))
360                 .exists();
361         assertThat(apidocs.resolve("subpackages/test/included/IncludedAppSample.html"))
362                 .exists();
363         assertThat(apidocs.resolve("subpackages/test/PariahApp.html")).doesNotExist();
364     }
365 
366     /**
367      * Test the recursion and exclusion of the doc-files subdirectories.
368      *
369      * @throws Exception if any
370      */
371     public void testDocfiles() throws Exception {
372         // Should be an assumption, but not supported by TestCase
373         // Seems like a bug in Javadoc 9 and above
374         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9")) {
375             return;
376         }
377 
378         Path testPom = unit.resolve("docfiles-test/docfiles-test-plugin-config.xml");
379         JavadocReport mojo = lookupMojo(testPom);
380         mojo.execute();
381 
382         Path apidocs = new File(getBasedir(), "target/test/unit/docfiles-test/target/site/apidocs/").toPath();
383 
384         // check if the doc-files subdirectories were copied
385         assertThat(apidocs.resolve("docfiles/test/doc-files")).exists();
386         assertThat(apidocs.resolve("docfiles/test/doc-files/included-dir1/sample-included1.gif"))
387                 .exists();
388         assertThat(apidocs.resolve("docfiles/test/doc-files/included-dir2/sample-included2.gif"))
389                 .exists();
390         assertThat(apidocs.resolve("docfiles/test/doc-files/excluded-dir1")).doesNotExist();
391         assertThat(apidocs.resolve("docfiles/test/doc-files/excluded-dir2")).doesNotExist();
392 
393         testPom = unit.resolve("docfiles-with-java-test/docfiles-with-java-test-plugin-config.xml");
394         mojo = lookupMojo(testPom);
395         mojo.execute();
396     }
397 
398     /**
399      * Test javadoc plugin using custom configuration. noindex, notree and nodeprecated parameters
400      * were set to true.
401      *
402      * @throws Exception if any
403      */
404     public void testCustomConfiguration() throws Exception {
405         Path testPom = unit.resolve("custom-configuration/custom-configuration-plugin-config.xml");
406         JavadocReport mojo = lookupMojo(testPom);
407         mojo.execute();
408 
409         Path apidocs = new File(getBasedir(), "target/test/unit/custom-configuration/target/site/apidocs").toPath();
410 
411         // check if there is a tree page generated (notree == true)
412         assertThat(apidocs.resolve("overview-tree.html")).doesNotExist();
413         assertThat(apidocs.resolve("custom/configuration/package-tree.html")).doesNotExist();
414 
415         // check if the main index page was generated (noindex == true)
416         assertThat(apidocs.resolve("index-all.html")).doesNotExist();
417 
418         // check if the deprecated list and the deprecated api were generated (nodeprecated == true)
419         // @todo Fix: the class-use of the deprecated api is still created eventhough the deprecated api of that class
420         // is no longer generated
421         assertThat(apidocs.resolve("deprecated-list.html")).doesNotExist();
422         assertThat(apidocs.resolve("custom/configuration/App.html")).doesNotExist();
423 
424         // read the contents of the html files based on some of the parameter values
425         // author == false
426         String str = readFile(apidocs.resolve("custom/configuration/AppSample.html"));
427         assertFalse(str.toLowerCase().contains("author"));
428 
429         // bottom
430         assertTrue(str.toUpperCase().contains("SAMPLE BOTTOM CONTENT"));
431 
432         // offlineLinks
433         if (JavaVersion.JAVA_VERSION.isBefore("11.0.2")) {
434             assertThat(str)
435                     .containsIgnoringCase("href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/string.html");
436         } else {
437             assertTrue(str.toLowerCase()
438                     .contains("href=\"http://java.sun.com/j2se/1.4.2/docs/api/java.base/java/lang/string.html"));
439         }
440 
441         // header
442         assertTrue(str.toUpperCase().contains("MAVEN JAVADOC PLUGIN TEST"));
443 
444         // footer
445         if (JavaVersion.JAVA_VERSION.isBefore("16-ea")
446                 && !System.getProperty("java.vm.name").contains("OpenJ9")) {
447             assertTrue(str.toUpperCase().contains("MAVEN JAVADOC PLUGIN TEST FOOTER"));
448         }
449 
450         // nohelp == true
451         assertFalse(str.toUpperCase().contains("/HELP-DOC.HTML"));
452 
453         // check the wildcard (*) package exclusions -- excludePackageNames parameter
454         assertThat(apidocs.resolve("custom/configuration/exclude1/Exclude1App.html"))
455                 .exists();
456         assertThat(apidocs.resolve("custom/configuration/exclude1/subexclude/SubexcludeApp.html"))
457                 .doesNotExist();
458         assertThat(apidocs.resolve("custom/configuration/exclude2/Exclude2App.html"))
459                 .doesNotExist();
460 
461         assertThat(apidocs.resolve("options")).isRegularFile();
462 
463         String contentOptions = new String(Files.readAllBytes(apidocs.resolve("options")), StandardCharsets.UTF_8);
464 
465         assertNotNull(contentOptions);
466         assertThat(contentOptions).contains("-link").contains("http://java.sun.com/j2se/");
467     }
468 
469     /**
470      * Method to test the doclet artifact configuration
471      *
472      * @throws Exception if any
473      */
474     public void testDoclets() throws Exception {
475         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("13")) {
476             // As of JDK 13, the com.sun.javadoc API is no longer supported.
477             return;
478         }
479 
480         // ----------------------------------------------------------------------
481         // doclet-test: check if the file generated by UmlGraph exists and if
482         // doclet path contains the UmlGraph artifact
483         // ----------------------------------------------------------------------
484 
485         Path testPom = unit.resolve("doclet-test/doclet-test-plugin-config.xml");
486         JavadocReport mojo = lookupMojo(testPom);
487 
488         MavenSession session = spy(newMavenSession(mojo.project));
489         ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
490         when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
491         when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
492         DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
493         repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
494                 .newInstance(repositorySession, new LocalRepository(localRepo)));
495         when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
496         when(session.getRepositorySession()).thenReturn(repositorySession);
497         LegacySupport legacySupport = lookup(LegacySupport.class);
498         legacySupport.setSession(session);
499 
500         setVariableValueToObject(mojo, "session", session);
501         setVariableValueToObject(mojo, "repoSession", repositorySession);
502         mojo.execute();
503 
504         Path generatedFile =
505                 new File(getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot").toPath();
506         assertThat(generatedFile).exists();
507 
508         Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath();
509         assertThat(optionsFile).exists();
510         String options = readFile(optionsFile);
511         assertThat(options).contains("/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar");
512 
513         // ----------------------------------------------------------------------
514         // doclet-path: check if the file generated by UmlGraph exists and if
515         // doclet path contains the twice UmlGraph artifacts
516         // ----------------------------------------------------------------------
517 
518         testPom = unit.resolve("doclet-path-test/doclet-path-test-plugin-config.xml");
519         mojo = lookupMojo(testPom);
520         setVariableValueToObject(mojo, "session", session);
521         setVariableValueToObject(mojo, "repoSession", repositorySession);
522         mojo.execute();
523 
524         generatedFile = new File(getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot").toPath();
525         assertThat(generatedFile).exists();
526 
527         optionsFile = new File(mojo.getOutputDirectory(), "options").toPath();
528         assertThat(optionsFile).exists();
529         options = readFile(optionsFile);
530         assertThat(options)
531                 .contains("/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar")
532                 .contains("/target/local-repo/umlgraph/UMLGraph-bis/2.1/UMLGraph-bis-2.1.jar");
533     }
534 
535     /**
536      * Method to test when the path to the project sources has an apostrophe (')
537      *
538      * @throws Exception if any
539      */
540     public void testQuotedPath() throws Exception {
541         Path testPom = unit.resolve("quotedpath'test/quotedpath-test-plugin-config.xml");
542         JavadocReport mojo = lookupMojo(testPom);
543         mojo.execute();
544 
545         Path apidocs = new File(getBasedir(), "target/test/unit/quotedpath'test/target/site/apidocs").toPath();
546 
547         // package level generated javadoc files
548         assertThat(apidocs.resolve("quotedpath/test/App.html")).exists();
549         assertThat(apidocs.resolve("quotedpath/test/AppSample.html")).exists();
550 
551         // project level generated javadoc files
552         assertThat(apidocs.resolve("index-all.html")).exists();
553         assertThat(apidocs.resolve("index.html")).exists();
554         assertThat(apidocs.resolve("overview-tree.html")).exists();
555         assertThat(apidocs.resolve("stylesheet.css")).exists();
556 
557         if (JavaVersion.JAVA_VERSION.isBefore("10")) {
558             assertThat(apidocs.resolve("package-list")).exists();
559         } else {
560             assertThat(apidocs.resolve("element-list")).exists();
561         }
562     }
563 
564     /**
565      * Method to test when the options file has umlauts.
566      *
567      * @throws Exception if any
568      */
569     public void testOptionsUmlautEncoding() throws Exception {
570         Path testPom = unit.resolve("optionsumlautencoding-test/optionsumlautencoding-test-plugin-config.xml");
571         JavadocReport mojo = lookupMojo(testPom);
572         mojo.execute();
573 
574         Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath();
575         assertThat(optionsFile).exists();
576 
577         // check for a part of the window title
578         String content;
579         String expected;
580         if (JavaVersion.JAVA_VERSION.isAtLeast("9") && JavaVersion.JAVA_VERSION.isBefore("12")) {
581             content = readFile(optionsFile, StandardCharsets.UTF_8);
582             expected = OPTIONS_UMLAUT_ENCODING;
583         } else {
584             content = readFile(optionsFile, Charset.defaultCharset());
585             expected = new String(OPTIONS_UMLAUT_ENCODING.getBytes(Charset.defaultCharset()));
586         }
587 
588         assertThat(content).contains(expected);
589 
590         Path apidocs =
591                 new File(getBasedir(), "target/test/unit/optionsumlautencoding-test/target/site/apidocs").toPath();
592 
593         // package level generated javadoc files
594         assertThat(apidocs.resolve("optionsumlautencoding/test/App.html")).exists();
595         assertThat(apidocs.resolve("optionsumlautencoding/test/AppSample.html")).exists();
596 
597         // project level generated javadoc files
598         assertThat(apidocs.resolve("index-all.html")).exists();
599         assertThat(apidocs.resolve("index.html")).exists();
600         assertThat(apidocs.resolve("overview-tree.html")).exists();
601         assertThat(apidocs.resolve("stylesheet.css")).exists();
602 
603         if (JavaVersion.JAVA_VERSION.isBefore("10")) {
604             assertThat(apidocs.resolve("package-list")).exists();
605         } else {
606             assertThat(apidocs.resolve("element-list")).exists();
607         }
608     }
609 
610     /**
611      * Method to test the taglet artifact configuration
612      *
613      * @throws Exception if any
614      */
615     public void testTaglets() throws Exception {
616         // ----------------------------------------------------------------------
617         // taglet-test: check if a taglet is used
618         // ----------------------------------------------------------------------
619 
620         // Should be an assumption, but not supported by TestCase
621         // com.sun.tools.doclets.Taglet not supported by Java9 anymore
622         // Should be refactored with jdk.javadoc.doclet.Taglet
623         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("10")) {
624             return;
625         }
626 
627         Path testPom = unit.resolve("taglet-test/taglet-test-plugin-config.xml");
628         JavadocReport mojo = lookupMojo(testPom);
629 
630         MavenSession session = spy(newMavenSession(mojo.project));
631         ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
632         when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
633         when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
634         DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
635         repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
636                 .newInstance(repositorySession, new LocalRepository(localRepo)));
637         when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
638         when(session.getRepositorySession()).thenReturn(repositorySession);
639         LegacySupport legacySupport = lookup(LegacySupport.class);
640         legacySupport.setSession(session);
641 
642         setVariableValueToObject(mojo, "session", session);
643         setVariableValueToObject(mojo, "repoSession", repositorySession);
644 
645         mojo.execute();
646 
647         Path apidocs = new File(getBasedir(), "target/test/unit/taglet-test/target/site/apidocs").toPath();
648 
649         assertThat(apidocs.resolve("index.html")).exists();
650 
651         Path appFile = apidocs.resolve("taglet/test/App.html");
652         assertThat(appFile).exists();
653         String appString = readFile(appFile);
654         assertThat(appString).contains("<b>To Do:</b>");
655     }
656 
657     /**
658      * Method to test the jdk5 javadoc
659      *
660      * @throws Exception if any
661      */
662     public void testJdk5() throws Exception {
663         // Should be an assumption, but not supported by TestCase
664         // Java 5 not supported by Java9 anymore
665         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9")) {
666             return;
667         }
668 
669         Path testPom = unit.resolve("jdk5-test/jdk5-test-plugin-config.xml");
670         JavadocReport mojo = lookupMojo(testPom);
671         mojo.execute();
672 
673         Path apidocs = new File(getBasedir(), "target/test/unit/jdk5-test/target/site/apidocs").toPath();
674 
675         assertThat(apidocs.resolve("index.html")).exists();
676 
677         Path overviewSummary = apidocs.resolve("overview-summary.html");
678         assertThat(overviewSummary).exists();
679         String content = readFile(overviewSummary);
680         assertThat(content).contains("<b>Test the package-info</b>");
681 
682         Path packageSummary = apidocs.resolve("jdk5/test/package-summary.html");
683         assertThat(packageSummary).exists();
684         content = readFile(packageSummary);
685         assertThat(content).contains("<b>Test the package-info</b>");
686     }
687 
688     /**
689      * Test to find the javadoc executable when <code>java.home</code> is not in the JDK_HOME. In this case, try to
690      * use the <code>JAVA_HOME</code> environment variable.
691      *
692      * @throws Exception if any
693      */
694     public void testToFindJavadoc() throws Exception {
695         String oldJreHome = System.getProperty("java.home");
696         System.setProperty("java.home", "foo/bar");
697 
698         Path testPom = unit.resolve("javaHome-test/javaHome-test-plugin-config.xml");
699         JavadocReport mojo = lookupMojo(testPom);
700         mojo.execute();
701 
702         System.setProperty("java.home", oldJreHome);
703     }
704 
705     /**
706      * Test the javadoc resources.
707      *
708      * @throws Exception if any
709      */
710     public void testJavadocResources() throws Exception {
711         Path testPom = unit.resolve("resources-test/resources-test-plugin-config.xml");
712         JavadocReport mojo = lookupMojo(testPom);
713         mojo.execute();
714 
715         Path apidocs = new File(getBasedir(), "target/test/unit/resources-test/target/site/apidocs/").toPath();
716 
717         Path app = apidocs.resolve("resources/test/App.html");
718         assertThat(app).exists();
719         String content = readFile(app);
720         assertThat(content).contains("<img src=\"doc-files/maven-feather.png\" alt=\"Maven\">");
721         assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png"))
722                 .exists();
723 
724         Path app2 = apidocs.resolve("resources/test2/App2.html");
725         assertThat(app2).exists();
726         content = readFile(app2);
727         assertThat(content).contains("<img src=\"doc-files/maven-feather.png\" alt=\"Maven\">");
728         assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png"))
729                 .doesNotExist();
730 
731         // with excludes
732         testPom = unit.resolve("resources-with-excludes-test/resources-with-excludes-test-plugin-config.xml");
733         mojo = lookupMojo(testPom);
734         mojo.execute();
735 
736         apidocs = new File(getBasedir(), "target/test/unit/resources-with-excludes-test/target/site/apidocs").toPath();
737 
738         app = apidocs.resolve("resources/test/App.html");
739         assertThat(app).exists();
740         content = readFile(app);
741         assertThat(content).contains("<img src=\"doc-files/maven-feather.png\" alt=\"Maven\">");
742 
743         JavaVersion javadocVersion = (JavaVersion) getVariableValueFromObject(mojo, "javadocRuntimeVersion");
744         if (javadocVersion.isAtLeast("1.8") /* && javadocVersion.isBefore( "14" ) */) {
745             // https://bugs.openjdk.java.net/browse/JDK-8032205
746             assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png"))
747                     .as("Javadoc runtime version: " + javadocVersion
748                             + "\nThis bug appeared in JDK8 and was planned to be fixed in JDK9, see JDK-8032205")
749                     .exists();
750         } else {
751             assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png"))
752                     .doesNotExist();
753         }
754         assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png"))
755                 .exists();
756 
757         app2 = apidocs.resolve("resources/test2/App2.html");
758         assertThat(app2).exists();
759         content = readFile(app2);
760         assertThat(content).contains("<img src=\"doc-files/maven-feather.png\" alt=\"Maven\">");
761         assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png"))
762                 .exists();
763     }
764 
765     /**
766      * Test the javadoc for a POM project.
767      *
768      * @throws Exception if any
769      */
770     public void testPom() throws Exception {
771         Path testPom = unit.resolve("pom-test/pom-test-plugin-config.xml");
772         JavadocReport mojo = lookupMojo(testPom);
773         mojo.execute();
774 
775         assertThat(new File(getBasedir(), "target/test/unit/pom-test/target/site"))
776                 .doesNotExist();
777     }
778 
779     /**
780      * Test the javadoc with tag.
781      *
782      * @throws Exception if any
783      */
784     public void testTag() throws Exception {
785         Path testPom = unit.resolve("tag-test/tag-test-plugin-config.xml");
786         JavadocReport mojo = lookupMojo(testPom);
787         mojo.execute();
788 
789         Path app = new File(getBasedir(), "target/test/unit/tag-test/target/site/apidocs/tag/test/App.html").toPath();
790         assertThat(app).exists();
791         String readed = readFile(app);
792         assertThat(readed).contains(">To do something:</").contains(">Generator Class:</");
793 
794         // In javadoc-options-javadoc-resources.xml tag 'version' has only a name,
795         // which is not enough for Java 11 anymore
796         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) {
797             assertThat(readed).contains(">Version:</");
798             assertTrue(readed.toLowerCase().contains("</dt>" + LINE_SEPARATOR + "  <dd>1.0</dd>")
799                     || readed.toLowerCase().contains("</dt>" + LINE_SEPARATOR + "<dd>1.0</dd>" /* JDK 8 */));
800         }
801     }
802 
803     /**
804      * Test newline in the header/footer parameter
805      *
806      * @throws Exception if any
807      */
808     public void testHeaderFooter() throws Exception {
809         Path testPom = unit.resolve("header-footer-test/header-footer-test-plugin-config.xml");
810         JavadocReport mojo = lookupMojo(testPom);
811         try {
812             mojo.execute();
813         } catch (MojoExecutionException e) {
814             fail("Doesnt handle correctly newline for header or footer parameter");
815         }
816     }
817 
818     /**
819      * Test newline in various string parameters
820      *
821      * @throws Exception if any
822      */
823     public void testNewline() throws Exception {
824         Path testPom = unit.resolve("newline-test/newline-test-plugin-config.xml");
825         JavadocReport mojo = lookupMojo(testPom);
826         try {
827             mojo.execute();
828         } catch (MojoExecutionException e) {
829             fail("Doesn't handle correctly newline for string parameters. See options and packages files.");
830         }
831     }
832 
833     /**
834      * Method to test the jdk6 javadoc
835      *
836      * @throws Exception if any
837      */
838     public void testJdk6() throws Exception {
839         // Should be an assumption, but not supported by TestCase
840         // Java 6 not supported by Java 12 anymore
841         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("12")) {
842             return;
843         }
844 
845         Path testPom = unit.resolve("jdk6-test/jdk6-test-plugin-config.xml");
846         JavadocReport mojo = lookupMojo(testPom);
847         mojo.execute();
848 
849         Path apidocs = new File(getBasedir(), "target/test/unit/jdk6-test/target/site/apidocs").toPath();
850         assertThat(apidocs.resolve("index.html")).exists();
851 
852         Path overview;
853         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) {
854             overview = apidocs.resolve("overview-summary.html");
855         } else {
856             overview = apidocs.resolve("index.html");
857         }
858 
859         assertThat(overview).exists();
860         String content = readFile(overview);
861         assertThat(content)
862                 .contains("Top - Copyright &#169; All rights reserved.")
863                 .contains("Header - Copyright &#169; All rights reserved.");
864         // IBM dist of adopt-openj9 does not support the footer param
865         if (!System.getProperty("java.vm.name").contains("OpenJ9")) {
866             assertThat(content).contains("Footer - Copyright &#169; All rights reserved.");
867         }
868 
869         Path packageSummary = apidocs.resolve("jdk6/test/package-summary.html");
870         assertThat(packageSummary).exists();
871         content = readFile(packageSummary);
872         assertThat(content)
873                 .contains("Top - Copyright &#169; All rights reserved.")
874                 .contains("Header - Copyright &#169; All rights reserved.");
875 
876         // IBM dist of adopt-openj9 does not support the footer param
877         if (!System.getProperty("java.vm.name").contains("OpenJ9")) {
878             assertThat(content).contains("Footer - Copyright &#169; All rights reserved.");
879         }
880     }
881 
882     /**
883      * Method to test proxy support in the javadoc
884      *
885      * @throws Exception if any
886      */
887     public void testProxy() throws Exception {
888         Settings settings = new Settings();
889         Proxy proxy = new Proxy();
890 
891         // dummy proxy
892         proxy.setActive(true);
893         proxy.setHost("127.0.0.1");
894         proxy.setPort(80);
895         proxy.setProtocol("http");
896         proxy.setUsername("toto");
897         proxy.setPassword("toto");
898         proxy.setNonProxyHosts("www.google.com|*.somewhere.com");
899         settings.addProxy(proxy);
900 
901         Path testPom =
902                 new File(getBasedir(), "src/test/resources/unit/proxy-test/proxy-test-plugin-config.xml").toPath();
903         JavadocReport mojo = lookupMojo(testPom);
904 
905         MavenSession session = spy(newMavenSession(mojo.project));
906         ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
907         when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
908         when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
909         DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
910         repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
911                 .newInstance(repositorySession, new LocalRepository(localRepo)));
912         when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
913         when(session.getRepositorySession()).thenReturn(repositorySession);
914         LegacySupport legacySupport = lookup(LegacySupport.class);
915         legacySupport.setSession(session);
916 
917         setVariableValueToObject(mojo, "settings", settings);
918         setVariableValueToObject(mojo, "session", session);
919         setVariableValueToObject(mojo, "repoSession", repositorySession);
920         mojo.execute();
921 
922         Path commandLine = new File(
923                         getBasedir(),
924                         "target/test/unit/proxy-test/target/site/apidocs/javadoc."
925                                 + (SystemUtils.IS_OS_WINDOWS ? "bat" : "sh"))
926                 .toPath();
927         assertThat(commandLine).exists();
928         String readed = readFile(commandLine);
929         assertThat(readed).contains("-J-Dhttp.proxyHost=127.0.0.1").contains("-J-Dhttp.proxyPort=80");
930         if (SystemUtils.IS_OS_WINDOWS) {
931             assertThat(readed).contains(" -J-Dhttp.nonProxyHosts=\"www.google.com^|*.somewhere.com\" ");
932         } else {
933             assertThat(readed).contains(" \"-J-Dhttp.nonProxyHosts=\\\"www.google.com^|*.somewhere.com\\\"\" ");
934         }
935 
936         Path options = new File(getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/options").toPath();
937         assertThat(options).exists();
938         String optionsContent = readFile(options);
939         // NO -link expected
940         assertThat(optionsContent).doesNotContain("-link");
941 
942         // real proxy
943         ProxyServer proxyServer = null;
944         AuthAsyncProxyServlet proxyServlet;
945         try {
946             proxyServlet = new AuthAsyncProxyServlet();
947             proxyServer = new ProxyServer(proxyServlet);
948             proxyServer.start();
949 
950             settings = new Settings();
951             proxy = new Proxy();
952             proxy.setActive(true);
953             proxy.setHost(proxyServer.getHostName());
954             proxy.setPort(proxyServer.getPort());
955             proxy.setProtocol("http");
956             settings.addProxy(proxy);
957 
958             mojo = lookupMojo(testPom);
959             setVariableValueToObject(mojo, "settings", settings);
960             setVariableValueToObject(mojo, "session", session);
961             setVariableValueToObject(mojo, "repoSession", repositorySession);
962             mojo.execute();
963             readed = readFile(commandLine);
964             assertTrue(readed.contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName()));
965             assertTrue(readed.contains("-J-Dhttp.proxyPort=" + proxyServer.getPort()));
966 
967             optionsContent = readFile(options);
968             // -link expected
969             // TODO: This got disabled for now!
970             // This test fails since the last commit but I actually think it only ever worked by accident.
971             // It did rely on a commons-logging-1.0.4.pom which got resolved by a test which did run previously.
972             // But after updating to commons-logging.1.1.1 there is no pre-resolved artifact available in
973             // target/local-repo anymore, thus the javadoc link info cannot get built and the test fails
974             // I'll for now just disable this line of code, because the test as far as I can see _never_
975             // did go upstream. The remoteRepository list used is always empty!.
976             //
977             //            assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) );
978         } finally {
979             if (proxyServer != null) {
980                 proxyServer.stop();
981             }
982         }
983 
984         // auth proxy
985         Map<String, String> authentications = new HashMap<>();
986         authentications.put("foo", "bar");
987         try {
988             proxyServlet = new AuthAsyncProxyServlet(authentications);
989             proxyServer = new ProxyServer(proxyServlet);
990             proxyServer.start();
991 
992             settings = new Settings();
993             proxy = new Proxy();
994             proxy.setActive(true);
995             proxy.setHost(proxyServer.getHostName());
996             proxy.setPort(proxyServer.getPort());
997             proxy.setProtocol("http");
998             proxy.setUsername("foo");
999             proxy.setPassword("bar");
1000             settings.addProxy(proxy);
1001 
1002             mojo = lookupMojo(testPom);
1003             setVariableValueToObject(mojo, "settings", settings);
1004             setVariableValueToObject(mojo, "session", session);
1005             setVariableValueToObject(mojo, "repoSession", repositorySession);
1006             mojo.execute();
1007             readed = readFile(commandLine);
1008             assertThat(readed)
1009                     .contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName())
1010                     .contains("-J-Dhttp.proxyPort=" + proxyServer.getPort());
1011 
1012             optionsContent = readFile(options);
1013             // -link expected
1014             // see comment above (line 829)
1015             //             assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) );
1016         } finally {
1017             if (proxyServer != null) {
1018                 proxyServer.stop();
1019             }
1020         }
1021     }
1022 
1023     /**
1024      * Method to test error or conflict in Javadoc options and in standard doclet options.
1025      *
1026      * @throws Exception if any
1027      */
1028     public void testValidateOptions() throws Exception {
1029         // encoding
1030         Path testPom = unit.resolve("validate-options-test/wrong-encoding-test-plugin-config.xml");
1031         JavadocReport mojo = lookupMojo(testPom);
1032         try {
1033             mojo.execute();
1034             fail("No wrong encoding catch");
1035         } catch (MojoExecutionException e) {
1036             assertTrue("No wrong encoding catch", e.getMessage().contains("Unsupported option <encoding/>"));
1037         }
1038         testPom = unit.resolve("validate-options-test/wrong-docencoding-test-plugin-config.xml");
1039         mojo = lookupMojo(testPom);
1040         try {
1041             mojo.execute();
1042             fail("No wrong docencoding catch");
1043         } catch (MojoExecutionException e) {
1044             assertTrue("No wrong docencoding catch", e.getMessage().contains("Unsupported option <docencoding/>"));
1045         }
1046         testPom = unit.resolve("validate-options-test/wrong-charset-test-plugin-config.xml");
1047         mojo = lookupMojo(testPom);
1048         try {
1049             mojo.execute();
1050             fail("No wrong charset catch");
1051         } catch (MojoExecutionException e) {
1052             assertTrue("No wrong charset catch", e.getMessage().contains("Unsupported option <charset/>"));
1053         }
1054 
1055         // locale
1056         testPom = unit.resolve("validate-options-test/wrong-locale-test-plugin-config.xml");
1057         mojo = lookupMojo(testPom);
1058         try {
1059             mojo.execute();
1060             fail("No wrong locale catch");
1061         } catch (MojoExecutionException e) {
1062             assertTrue("No wrong locale catch", e.getMessage().contains("Unsupported option <locale/>"));
1063         }
1064         testPom = unit.resolve("validate-options-test/wrong-locale-with-variant-test-plugin-config.xml");
1065         mojo = lookupMojo(testPom);
1066         mojo.execute();
1067         assertTrue("No wrong locale catch", true);
1068 
1069         // conflict options
1070         testPom = unit.resolve("validate-options-test/conflict-options-test-plugin-config.xml");
1071         mojo = lookupMojo(testPom);
1072         try {
1073             mojo.execute();
1074             fail("No conflict catch");
1075         } catch (MojoExecutionException e) {
1076             assertTrue("No conflict catch", e.getMessage().contains("Option <nohelp/> conflicts with <helpfile/>"));
1077         }
1078     }
1079 
1080     /**
1081      * Method to test the <code>&lt;tagletArtifacts/&gt;</code> parameter.
1082      *
1083      * @throws Exception if any
1084      */
1085     public void testTagletArtifacts() throws Exception {
1086         // Should be an assumption, but not supported by TestCase
1087         // com.sun.tools.doclets.Taglet not supported by Java 10 anymore
1088         if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("10")) {
1089             return;
1090         }
1091 
1092         Path testPom = unit.resolve("tagletArtifacts-test/tagletArtifacts-test-plugin-config.xml");
1093         JavadocReport mojo = lookupMojo(testPom);
1094 
1095         MavenSession session = newMavenSession(mojo.project);
1096         DefaultRepositorySystemSession repoSysSession = (DefaultRepositorySystemSession) session.getRepositorySession();
1097         repoSysSession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
1098                 .newInstance(session.getRepositorySession(), new LocalRepository(new File("target/local-repo"))));
1099         // Ensure remote repo connection uses SSL
1100         File globalSettingsFile = new File(getBasedir(), "target/test-classes/unit/settings.xml");
1101         session.getRequest().setGlobalSettingsFile(globalSettingsFile);
1102         LegacySupport legacySupport = lookup(LegacySupport.class);
1103         legacySupport.setSession(session);
1104         setVariableValueToObject(mojo, "session", session);
1105         setVariableValueToObject(mojo, "repoSession", repoSysSession);
1106         mojo.execute();
1107 
1108         Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath();
1109         assertThat(optionsFile).exists();
1110         String options = readFile(optionsFile);
1111         // count -taglet
1112         assertThat(StringUtils.countMatches(options, LINE_SEPARATOR + "-taglet" + LINE_SEPARATOR))
1113                 .isEqualTo(3);
1114         assertThat(options)
1115                 .contains("org.codehaus.plexus.javadoc.PlexusConfigurationTaglet")
1116                 .contains("org.codehaus.plexus.javadoc.PlexusRequirementTaglet")
1117                 .contains("org.codehaus.plexus.javadoc.PlexusComponentTaglet");
1118     }
1119 
1120     /**
1121      * Method to test the <code>&lt;stylesheetfile/&gt;</code> parameter.
1122      *
1123      * @throws Exception if any
1124      */
1125     public void testStylesheetfile() throws Exception {
1126         Path testPom = unit.resolve("stylesheetfile-test/pom.xml");
1127 
1128         JavadocReport mojo = lookupMojo(testPom);
1129         assertNotNull(mojo);
1130 
1131         MavenSession session = spy(newMavenSession(mojo.project));
1132         ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
1133         when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
1134         when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
1135         DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
1136         repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
1137                 .newInstance(repositorySession, new LocalRepository(localRepo)));
1138         when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
1139         when(session.getRepositorySession()).thenReturn(repositorySession);
1140         LegacySupport legacySupport = lookup(LegacySupport.class);
1141         legacySupport.setSession(session);
1142         setVariableValueToObject(mojo, "session", session);
1143         setVariableValueToObject(mojo, "repoSession", repositorySession);
1144 
1145         Path apidocs = new File(getBasedir(), "target/test/unit/stylesheetfile-test/target/site/apidocs").toPath();
1146 
1147         Path stylesheetfile = apidocs.resolve("stylesheet.css");
1148         Path options = apidocs.resolve("options");
1149 
1150         // stylesheet == maven OR java
1151         setVariableValueToObject(mojo, "stylesheet", "javamaven");
1152 
1153         try {
1154             mojo.execute();
1155             fail();
1156         } catch (MojoExecutionException | MojoFailureException e) {
1157         }
1158 
1159         // stylesheet == java
1160         setVariableValueToObject(mojo, "stylesheet", "java");
1161         mojo.execute();
1162 
1163         String content = readFile(stylesheetfile);
1164         if (JavaVersion.JAVA_VERSION.isAtLeast("13-ea")) {
1165             assertTrue(content.contains("/*" + LINE_SEPARATOR + " * Javadoc style sheet" + LINE_SEPARATOR + " */"));
1166         } else if (JavaVersion.JAVA_VERSION.isAtLeast("10")) {
1167             assertTrue(content.contains("/* " + LINE_SEPARATOR + " * Javadoc style sheet" + LINE_SEPARATOR + " */"));
1168         } else {
1169             assertTrue(content.contains("/* Javadoc style sheet */"));
1170         }
1171 
1172         String optionsContent = readFile(options);
1173         assertFalse(optionsContent.contains("-stylesheetfile"));
1174 
1175         // stylesheetfile defined as a project resource
1176         setVariableValueToObject(mojo, "stylesheet", null);
1177         setVariableValueToObject(mojo, "stylesheetfile", "com/mycompany/app/javadoc/css/stylesheet.css");
1178         mojo.execute();
1179 
1180         content = readFile(stylesheetfile);
1181         assertTrue(content.contains("/* Custom Javadoc style sheet in project */"));
1182 
1183         optionsContent = readFile(options);
1184         assertTrue(optionsContent.contains("-stylesheetfile"));
1185         Path stylesheetResource =
1186                 unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css/stylesheet.css");
1187         assertTrue(optionsContent.contains(
1188                 "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1189 
1190         // stylesheetfile defined in a javadoc plugin dependency
1191         setVariableValueToObject(mojo, "stylesheetfile", "com/mycompany/app/javadoc/css2/stylesheet.css");
1192         mojo.execute();
1193 
1194         content = readFile(stylesheetfile);
1195         assertTrue(content.contains("/* Custom Javadoc style sheet in artefact */"));
1196 
1197         optionsContent = readFile(options);
1198         assertTrue(optionsContent.contains("-stylesheetfile"));
1199         assertTrue(optionsContent.contains(
1200                 "'" + stylesheetfile.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1201 
1202         // stylesheetfile defined as file
1203         Path css = unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css");
1204         setVariableValueToObject(mojo, "stylesheetfile", css.toFile().getAbsolutePath());
1205         mojo.execute();
1206 
1207         content = readFile(stylesheetfile);
1208         assertTrue(content.contains("/* Custom Javadoc style sheet as file */"));
1209 
1210         optionsContent = readFile(options);
1211         assertTrue(optionsContent.contains("-stylesheetfile"));
1212         stylesheetResource =
1213                 unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css");
1214         assertTrue(optionsContent.contains(
1215                 "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1216     }
1217 
1218     /**
1219      * Method to test the <code>&lt;helpfile/&gt;</code> parameter.
1220      *
1221      * @throws Exception if any
1222      */
1223     public void testHelpfile() throws Exception {
1224         Path testPom = unit.resolve("helpfile-test/pom.xml");
1225 
1226         JavadocReport mojo = lookupMojo(testPom);
1227         assertNotNull(mojo);
1228 
1229         MavenSession session = spy(newMavenSession(mojo.project));
1230         ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class);
1231         when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories());
1232         when(session.getProjectBuildingRequest()).thenReturn(buildingRequest);
1233         DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession();
1234         repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory()
1235                 .newInstance(repositorySession, new LocalRepository(localRepo)));
1236         when(buildingRequest.getRepositorySession()).thenReturn(repositorySession);
1237         when(session.getRepositorySession()).thenReturn(repositorySession);
1238         LegacySupport legacySupport = lookup(LegacySupport.class);
1239         legacySupport.setSession(session);
1240         setVariableValueToObject(mojo, "session", session);
1241         setVariableValueToObject(mojo, "repoSession", repositorySession);
1242 
1243         Path apidocs = new File(getBasedir(), "target/test/unit/helpfile-test/target/site/apidocs").toPath();
1244 
1245         Path helpfile = apidocs.resolve("help-doc.html");
1246         Path options = apidocs.resolve("options");
1247 
1248         // helpfile by default
1249         mojo.execute();
1250 
1251         String content = readFile(helpfile);
1252         assertTrue(content.contains("<!-- Generated by javadoc"));
1253 
1254         String optionsContent = readFile(options);
1255         assertFalse(optionsContent.contains("-helpfile"));
1256 
1257         // helpfile defined in a javadoc plugin dependency
1258         setVariableValueToObject(mojo, "helpfile", "com/mycompany/app/javadoc/helpfile/help-doc.html");
1259 
1260         setVariableValueToObject(mojo, "session", session);
1261         setVariableValueToObject(mojo, "repoSession", repositorySession);
1262 
1263         mojo.execute();
1264 
1265         content = readFile(helpfile);
1266         assertTrue(content.contains("<!--  Help file from artefact -->"));
1267 
1268         optionsContent = readFile(options);
1269         assertTrue(optionsContent.contains("-helpfile"));
1270         Path help = apidocs.resolve("help-doc.html");
1271         assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1272 
1273         // helpfile defined as a project resource
1274         setVariableValueToObject(mojo, "helpfile", "com/mycompany/app/javadoc/helpfile2/help-doc.html");
1275         mojo.execute();
1276 
1277         content = readFile(helpfile);
1278         assertTrue(content.contains("<!--  Help file from file -->"));
1279 
1280         optionsContent = readFile(options);
1281         assertTrue(optionsContent.contains("-helpfile"));
1282         help = unit.resolve("helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html");
1283         assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1284 
1285         // helpfile defined as file
1286         help = unit.resolve("helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html");
1287         setVariableValueToObject(mojo, "helpfile", help.toFile().getAbsolutePath());
1288         mojo.execute();
1289 
1290         content = readFile(helpfile);
1291         assertTrue(content.contains("<!--  Help file from file -->"));
1292 
1293         optionsContent = readFile(options);
1294         assertTrue(optionsContent.contains("-helpfile"));
1295         assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'"));
1296     }
1297 }