From d02fd90c799e12825448ac538bf09abf2a059d82 Mon Sep 17 00:00:00 2001 From: Michael Osipov Date: Sun, 12 Feb 2023 16:55:44 +0100 Subject: [PATCH] [MJAVADOC-740] Upgrade Parent to 39 --- pom.xml | 116 +- .../javadoc/AbstractFixJavadocMojo.java | 6924 ++++++++--------- .../plugins/javadoc/AbstractJavadocMojo.java | 4791 +++++------- .../plugins/javadoc/AdditionalDependency.java | 61 +- .../plugins/javadoc/AggregatorJavadocJar.java | 93 +- .../AggregatorJavadocNoForkReport.java | 12 +- .../javadoc/AggregatorJavadocReport.java | 88 +- .../javadoc/AggregatorTestJavadocJar.java | 93 +- .../AggregatorTestJavadocNoForkReport.java | 12 +- .../javadoc/AggregatorTestJavadocReport.java | 88 +- .../maven/plugins/javadoc/DependencyLink.java | 46 +- .../maven/plugins/javadoc/FixJavadocMojo.java | 77 +- .../javadoc/JavadocArchiveConfiguration.java | 12 +- .../maven/plugins/javadoc/JavadocJar.java | 593 +- .../maven/plugins/javadoc/JavadocModule.java | 39 +- .../plugins/javadoc/JavadocNoForkReport.java | 14 +- .../maven/plugins/javadoc/JavadocReport.java | 691 +- .../maven/plugins/javadoc/JavadocUtil.java | 3512 ++++----- .../maven/plugins/javadoc/JavadocVersion.java | 169 +- .../plugins/javadoc/ResourcesBundleMojo.java | 274 +- .../maven/plugins/javadoc/StaleHelper.java | 159 +- .../maven/plugins/javadoc/SystemUtils.java | 52 +- .../plugins/javadoc/TestFixJavadocMojo.java | 155 +- .../maven/plugins/javadoc/TestJavadocJar.java | 423 +- .../javadoc/TestJavadocNoForkReport.java | 14 +- .../plugins/javadoc/TestJavadocReport.java | 671 +- .../javadoc/TestResourcesBundleMojo.java | 131 +- .../javadoc/resolver/JavadocBundle.java | 118 +- .../javadoc/resolver/ResourceResolver.java | 843 +- .../resolver/SourceResolverConfig.java | 328 +- .../javadoc/AbstractFixJavadocMojoTest.java | 326 +- .../javadoc/AbstractJavadocMojoTest.java | 171 +- .../javadoc/AggregatorJavadocReportTest.java | 198 +- .../plugins/javadoc/FixJavadocMojoTest.java | 1272 ++- .../maven/plugins/javadoc/JavadocJarTest.java | 387 +- .../plugins/javadoc/JavadocReportTest.java | 1440 ++-- .../plugins/javadoc/JavadocUtilTest.java | 1376 ++-- .../plugins/javadoc/JavadocVersionTest.java | 133 +- .../maven/plugins/javadoc/ProxyServer.java | 428 +- .../javadoc/TestJavadocReportTest.java | 136 +- .../io/xpp3/JavadocOptionsXpp3ReaderTest.java | 24 +- ...bstractAggregateChildMavenProjectStub.java | 160 +- .../AbstractAggregateMavenProjectStub.java | 174 +- ...SubFolderProject1TestMavenProjectStub.java | 65 +- ...SubFolderProject2TestMavenProjectStub.java | 65 +- ...ateNotInSubFolderTestMavenProjectStub.java | 69 +- ...AggregateProject1TestMavenProjectStub.java | 140 +- ...AggregateProject2TestMavenProjectStub.java | 140 +- ...ResourcesProject1TestMavenProjectStub.java | 65 +- ...ResourcesProject2TestMavenProjectStub.java | 65 +- ...ggregateResourcesTestMavenProjectStub.java | 69 +- .../stubs/AggregateTestMavenProjectStub.java | 186 +- .../CustomConfigurationMavenProjectStub.java | 204 +- .../stubs/DefaultArtifactHandlerStub.java | 98 +- .../DefaultConfigurationMavenProjectStub.java | 159 +- .../stubs/DocfilesTestMavenProjectStub.java | 161 +- .../DocfilesWithJavaTestMavenProjectStub.java | 115 +- .../stubs/DocletPathTestMavenProjectStub.java | 159 +- .../stubs/DocletTestMavenProjectStub.java | 161 +- .../javadoc/stubs/FixMavenProjectStub.java | 198 +- .../HeaderFooterTestMavenProjectStub.java | 120 +- .../stubs/HelpFileMavenProjectStub.java | 160 +- .../JavadocJarArchiveConfigProjectStub.java | 73 +- .../JavadocJarDefaultMavenProjectStub.java | 173 +- ...JavadocJarFailOnErrorMavenProjectStub.java | 69 +- ...adocJarInvalidDestdirMavenProjectStub.java | 170 +- .../stubs/JavadocPluginArtifactStub.java | 290 +- .../stubs/Jdk5TestMavenProjectStub.java | 159 +- .../stubs/Jdk6TestMavenProjectStub.java | 159 +- .../stubs/NewlineTestMavenProjectStub.java | 120 +- ...OptionsUmlautEncodingMavenProjectStub.java | 65 +- .../javadoc/stubs/PomMavenProjectStub.java | 135 +- .../stubs/ProxyTestMavenProjectStub.java | 175 +- .../stubs/QuotedPathMavenProjectStub.java | 159 +- .../stubs/ResourcesTestMavenProjectStub.java | 120 +- ...urcesWithExcludesTestMavenProjectStub.java | 120 +- .../plugins/javadoc/stubs/SettingsStub.java | 105 +- ...etConflictOptionsTestMavenProjectStub.java | 120 +- .../stubs/StylesheetFileMavenProjectStub.java | 160 +- .../SubpackagesTestMavenProjectStub.java | 159 +- .../stubs/TagTestMavenProjectStub.java | 120 +- .../TagletArtifactsMavenProjectStub.java | 152 +- .../stubs/TagletTestMavenProjectStub.java | 159 +- .../stubs/TestJavadocMavenProjectStub.java | 187 +- ...ngEncodingOptionsTestMavenProjectStub.java | 120 +- 85 files changed, 14947 insertions(+), 17545 deletions(-) diff --git a/pom.xml b/pom.xml index 819788491..1a469ea62 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - + - 4.0.0 org.apache.maven.plugins maven-plugins - 37 + 39 @@ -34,53 +32,10 @@ under the License. maven-plugin Apache Maven Javadoc Plugin - - The Apache Maven Javadoc Plugin is a plugin that uses the javadoc tool for - generating javadocs for the specified project. - + The Apache Maven Javadoc Plugin is a plugin that uses the javadoc tool for + generating javadocs for the specified project. 2004 - - ${mavenVersion} - - - - scm:git:https://gitbox.apache.org/repos/asf/maven-javadoc-plugin.git - scm:git:https://gitbox.apache.org/repos/asf/maven-javadoc-plugin.git - https://github.com/apache/maven-javadoc-plugin/tree/${project.scm.tag} - HEAD - - - jira - https://issues.apache.org/jira/browse/MJAVADOC - - - Jenkins - https://ci-builds.apache.org/job/Maven/job/maven-box/job/maven-javadoc-plugin/ - - - - apache.website - scm:svn:https://svn.apache.org/repos/asf/maven/website/components/${maven.site.path} - - - - - 8 - 3.2.5 - 1.11.1 - 1.11.1 - 2.4 - 1.0.0.v20140518 - 1.1.0 - 9.4.43.v20210629 - - 3.12.1 - 3.2.2 - 2022-08-10T19:51:10Z - 1.7.36 - - Ben Speakmon @@ -129,6 +84,48 @@ under the License. + + ${mavenVersion} + + + + scm:git:https://gitbox.apache.org/repos/asf/maven-javadoc-plugin.git + scm:git:https://gitbox.apache.org/repos/asf/maven-javadoc-plugin.git + HEAD + https://github.com/apache/maven-javadoc-plugin/tree/${project.scm.tag} + + + jira + https://issues.apache.org/jira/browse/MJAVADOC + + + Jenkins + https://ci-builds.apache.org/job/Maven/job/maven-box/job/maven-javadoc-plugin/ + + + + apache.website + scm:svn:https://svn.apache.org/repos/asf/maven/website/components/${maven.site.path} + + + + + 8 + 3.2.5 + 1.11.1 + 1.11.1 + 2.4 + 1.0.0.v20140518 + + 1.1.0 + 9.4.43.v20210629 + + 3.12.1 + 3.2.2 + 2022-08-10T19:51:10Z + 1.7.36 + + @@ -160,7 +157,8 @@ under the License. - + + org.apache.maven maven-compat ${mavenVersion} @@ -433,6 +431,12 @@ under the License. org.codehaus.modello modello-maven-plugin + + 1.1.1 + + src/main/mdo/javadocOptions.mdo + + @@ -442,12 +446,6 @@ under the License. - - 1.1.1 - - src/main/mdo/javadocOptions.mdo - - org.eclipse.sisu @@ -486,7 +484,8 @@ under the License. examples/*/pom.xml - MJAVADOC-181/pom.xml + MJAVADOC-181/pom.xml + output-encoding/pom.xml @@ -571,7 +570,8 @@ under the License. true Fixed Type,Key - 1000 + 1000 + diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojo.java index 61ff1abe0..53987c95c 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojo.java @@ -1,3679 +1,3245 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.library.ClassLibraryBuilder; -import com.thoughtworks.qdox.library.OrderedClassLibraryBuilder; -import com.thoughtworks.qdox.model.DocletTag; -import com.thoughtworks.qdox.model.JavaAnnotatedElement; -import com.thoughtworks.qdox.model.JavaAnnotation; -import com.thoughtworks.qdox.model.JavaClass; -import com.thoughtworks.qdox.model.JavaConstructor; -import com.thoughtworks.qdox.model.JavaExecutable; -import com.thoughtworks.qdox.model.JavaField; -import com.thoughtworks.qdox.model.JavaGenericDeclaration; -import com.thoughtworks.qdox.model.JavaMember; -import com.thoughtworks.qdox.model.JavaMethod; -import com.thoughtworks.qdox.model.JavaParameter; -import com.thoughtworks.qdox.model.JavaType; -import com.thoughtworks.qdox.model.JavaTypeVariable; -import com.thoughtworks.qdox.parser.ParseException; -import com.thoughtworks.qdox.type.TypeResolver; - -import org.apache.commons.lang3.ClassUtils; -import org.apache.commons.text.StringEscapeUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Settings; -import org.apache.maven.shared.invoker.MavenInvocationException; -import org.codehaus.plexus.components.interactivity.InputHandler; -import org.codehaus.plexus.languages.java.version.JavaVersion; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.ReaderFactory; -import org.codehaus.plexus.util.StringUtils; - -import java.io.BufferedReader; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.io.StringReader; -import java.io.StringWriter; -import java.lang.reflect.Method; -import java.net.MalformedURLException; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -/** - * Abstract class to fix Javadoc documentation and tags in source files. - * @see Where Tags - * Can Be Used. - * @author Vincent Siveton - * @since 2.6 - */ -public abstract class AbstractFixJavadocMojo - extends AbstractMojo -{ - /** - * The vm line separator - */ - private static final String EOL = System.getProperty( "line.separator" ); - - /** - * Tag name for @author * - */ - private static final String AUTHOR_TAG = "author"; - - /** - * Tag name for @version * - */ - private static final String VERSION_TAG = "version"; - - /** - * Tag name for @since * - */ - private static final String SINCE_TAG = "since"; - - /** - * Tag name for @param * - */ - private static final String PARAM_TAG = "param"; - - /** - * Tag name for @return * - */ - private static final String RETURN_TAG = "return"; - - /** - * Tag name for @throws * - */ - private static final String THROWS_TAG = "throws"; - - /** - * Tag name for @link * - */ - private static final String LINK_TAG = "link"; - - /** - * Tag name for {@inheritDoc} * - */ - private static final String INHERITED_TAG = "{@inheritDoc}"; - - /** - * Start Javadoc String i.e. /** * - */ - private static final String START_JAVADOC = "/**"; - - /** - * End Javadoc String i.e. */ * - */ - private static final String END_JAVADOC = "*/"; - - /** - * Javadoc Separator i.e. * * - */ - private static final String SEPARATOR_JAVADOC = " * "; - - /** - * Inherited Javadoc i.e. /** {@inheritDoc} */ * - */ - private static final String INHERITED_JAVADOC = START_JAVADOC + " " + INHERITED_TAG + " " + END_JAVADOC; - - /** - * all parameter used by {@link #fixTags} * - */ - private static final String FIX_TAGS_ALL = "all"; - - /** - * public parameter used by {@link #level} * - */ - private static final String LEVEL_PUBLIC = "public"; - - /** - * protected parameter used by {@link #level} * - */ - private static final String LEVEL_PROTECTED = "protected"; - - /** - * package parameter used by {@link #level} * - */ - private static final String LEVEL_PACKAGE = "package"; - - /** - * private parameter used by {@link #level} * - */ - private static final String LEVEL_PRIVATE = "private"; - - /** - * The Clirr Maven plugin groupId org.codehaus.mojo * - */ - private static final String CLIRR_MAVEN_PLUGIN_GROUPID = "org.codehaus.mojo"; - - /** - * The Clirr Maven plugin artifactId clirr-maven-plugin * - */ - private static final String CLIRR_MAVEN_PLUGIN_ARTIFACTID = "clirr-maven-plugin"; - - /** - * The latest Clirr Maven plugin version 2.2.2 * - */ - private static final String CLIRR_MAVEN_PLUGIN_VERSION = "2.2.2"; - - /** - * The Clirr Maven plugin goal check * - */ - private static final String CLIRR_MAVEN_PLUGIN_GOAL = "check"; - - /** - * Java Files Pattern. - */ - public static final String JAVA_FILES = "**\\/*.java"; - - /** - * Default version value. - */ - public static final String DEFAULT_VERSION_VALUE = "\u0024Id: \u0024Id"; - - // ---------------------------------------------------------------------- - // Mojo components - // ---------------------------------------------------------------------- - - /** - * Input handler, needed for command line handling. - */ - @Component - private InputHandler inputHandler; - - // ---------------------------------------------------------------------- - // Mojo parameters - // ---------------------------------------------------------------------- - - /** - * Version to compare the current code against using the - * Clirr Maven Plugin. - *
- * See defaultSince. - */ - @Parameter ( property = "comparisonVersion", defaultValue = "(,${project.version})" ) - private String comparisonVersion; - - /** - * Default value for the Javadoc tag @author. - *
- * If not specified, the user.name defined in the System properties will be used. - */ - @Parameter ( property = "defaultAuthor" ) - private String defaultAuthor; - - /** - * Default value for the Javadoc tag @since. - */ - @Parameter ( property = "defaultSince", defaultValue = "${project.version}" ) - private String defaultSince; - - /** - * Default value for the Javadoc tag @version. - *
- * By default, it is $Id:$, corresponding to a - * SVN keyword. - * Refer to your SCM to use an other SCM keyword. - */ - @Parameter ( property = "defaultVersion", defaultValue = DEFAULT_VERSION_VALUE ) - private String defaultVersion = "\u0024Id: \u0024"; // can't use default-value="\u0024Id: \u0024" - - /** - * The file encoding to use when reading the source files. If the property - * project.build.sourceEncoding is not set, the platform default encoding is used. - */ - @Parameter ( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) - private String encoding; - - /** - * Comma separated excludes Java files, i.e. **/*Test.java. - */ - @Parameter ( property = "excludes" ) - private String excludes; - - /** - * Comma separated tags to fix in classes, interfaces or methods Javadoc comments. - * Possible values are: - *
    - *
  • all (fix all Javadoc tags)
  • - *
  • author (fix only @author tag)
  • - *
  • version (fix only @version tag)
  • - *
  • since (fix only @since tag)
  • - *
  • param (fix only @param tag)
  • - *
  • return (fix only @return tag)
  • - *
  • throws (fix only @throws tag)
  • - *
  • link (fix only @link tag)
  • - *
- */ - @Parameter ( property = "fixTags", defaultValue = "all" ) - private String fixTags; - - /** - * Flag to fix the classes or interfaces Javadoc comments according the level. - */ - @Parameter ( property = "fixClassComment", defaultValue = "true" ) - private boolean fixClassComment; - - /** - * Flag to fix the fields Javadoc comments according the level. - */ - @Parameter ( property = "fixFieldComment", defaultValue = "true" ) - private boolean fixFieldComment; - - /** - * Flag to fix the methods Javadoc comments according the level. - */ - @Parameter ( property = "fixMethodComment", defaultValue = "true" ) - private boolean fixMethodComment; - - /** - *

Flag to remove throws tags from unknown classes.

- *

NOTE:Since 3.1.0 the default value has been changed to {@code true}, - * due to JavaDoc 8 strictness. - */ - @Parameter ( property = "removeUnknownThrows", defaultValue = "true" ) - private boolean removeUnknownThrows; - - /** - * Forcing the goal execution i.e. skip warranty messages (not recommended). - */ - @Parameter ( property = "force" ) - private boolean force; - - /** - * Flag to ignore or not Clirr. - */ - @Parameter ( property = "ignoreClirr", defaultValue = "false" ) - protected boolean ignoreClirr; - - /** - * Comma separated includes Java files, i.e. **/*Test.java. - *

- * Note: default value is {@code **\/*.java}. - */ - @Parameter ( property = "includes", defaultValue = JAVA_FILES ) - private String includes; - - /** - * Specifies the access level for classes and members to show in the Javadocs. - * Possible values are: - *

    - *
  • public (shows only public classes and members)
  • - *
  • protected (shows only public and protected classes and members)
  • - *
  • package (shows all classes and members not marked private)
  • - *
  • private (shows all classes and members)
  • - *
- * @see private, protected, public, package options for Javadoc - */ - @Parameter ( property = "level", defaultValue = "protected" ) - private String level; - - /** - * The local repository where the artifacts are located, used by the tests. - */ - @Parameter ( property = "localRepository" ) - private ArtifactRepository localRepository; - - /** - * Output directory where Java classes will be rewritten. - */ - @Parameter ( property = "outputDirectory", defaultValue = "${project.build.sourceDirectory}" ) - private File outputDirectory; - - /** - * The Maven Project Object. - */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) - private MavenProject project; - - @Parameter ( defaultValue = "${session}", readonly = true, required = true ) - private MavenSession session; - - /** - * The current user system settings for use in Maven. - */ - @Parameter( defaultValue = "${settings}", readonly = true, required = true ) - private Settings settings; - - // ---------------------------------------------------------------------- - // Internal fields - // ---------------------------------------------------------------------- - - /** - * The current project class loader. - */ - private ClassLoader projectClassLoader; - - /** - * Split {@link #fixTags} by comma. - * - * @see #init() - */ - private String[] fixTagsSplitted; - - /** - * New classes found by Clirr. - */ - private List clirrNewClasses; - - /** - * New Methods in a Class (the key) found by Clirr. - */ - private Map> clirrNewMethods; - - /** - * List of classes where *since is added. Will be used to add or not this tag in the methods. - */ - private List sinceClasses; - - /** - * {@inheritDoc} - */ - @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( !fixClassComment && !fixFieldComment && !fixMethodComment ) - { - getLog().info( "Specified to NOT fix classes, fields and methods. Nothing to do." ); - return; - } - - // verify goal params - init(); - - if ( fixTagsSplitted.length == 0 ) - { - getLog().info( "No fix tag specified. Nothing to do." ); - return; - } - - // add warranty msg - if ( !preCheck() ) - { - return; - } - - // run clirr - try - { - executeClirr(); - } - catch ( MavenInvocationException e ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().error( "MavenInvocationException: " + e.getMessage(), e ); - } - else - { - getLog().error( "MavenInvocationException: " + e.getMessage() ); - } - getLog().info( "Clirr is ignored." ); - } - - // run qdox and process - try - { - Collection javaClasses = getQdoxClasses(); - - if ( javaClasses != null ) - { - for ( JavaClass javaClass : javaClasses ) - { - processFix( javaClass ); - } - } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "IOException: " + e.getMessage(), e ); - } - } - - // ---------------------------------------------------------------------- - // protected methods - // ---------------------------------------------------------------------- - - protected final MavenProject getProject() - { - return project; - } - - /** - * @param p not null maven project. - * @return the artifact type. - */ - protected String getArtifactType( MavenProject p ) - { - return p.getArtifact().getType(); - } - - /** - * @param p not null maven project. - * @return the list of source paths for the given project. - */ - protected List getProjectSourceRoots( MavenProject p ) - { - return ( p.getCompileSourceRoots() == null - ? Collections.emptyList() - : new LinkedList<>( p.getCompileSourceRoots() ) ); - } - - /** - * @param p not null - * @return the compile classpath elements - * @throws DependencyResolutionRequiredException - * if any - */ - protected List getCompileClasspathElements( MavenProject p ) - throws DependencyResolutionRequiredException - { - return ( p.getCompileClasspathElements() == null - ? Collections.emptyList() - : new LinkedList<>( p.getCompileClasspathElements() ) ); - } - - /** - * @param javaExecutable not null - * @return the fully qualify name of javaMethod with signature - */ - protected static String getJavaMethodAsString( JavaExecutable javaExecutable ) - { - return javaExecutable.getDeclaringClass().getFullyQualifiedName() + "#" + javaExecutable.getCallSignature(); - } - - // ---------------------------------------------------------------------- - // private methods - // ---------------------------------------------------------------------- - - /** - * Init goal parameters. - */ - private void init() - { - // defaultAuthor - if ( StringUtils.isEmpty( defaultAuthor ) ) - { - defaultAuthor = System.getProperty( "user.name" ); - } - - // defaultSince - int i = defaultSince.indexOf( "-" + Artifact.SNAPSHOT_VERSION ); - if ( i != -1 ) - { - defaultSince = defaultSince.substring( 0, i ); - } - - // fixTags - if ( !FIX_TAGS_ALL.equalsIgnoreCase( fixTags.trim() ) ) - { - String[] split = StringUtils.split( fixTags, "," ); - List filtered = new LinkedList<>(); - for ( String aSplit : split ) - { - String s = aSplit.trim(); - if ( JavadocUtil.equalsIgnoreCase( s, FIX_TAGS_ALL, AUTHOR_TAG, VERSION_TAG, SINCE_TAG, PARAM_TAG, - THROWS_TAG, LINK_TAG, RETURN_TAG ) ) - { - filtered.add( s ); - } - else - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unrecognized '" + s + "' for fixTags parameter. Ignored it!" ); - } - } - } - fixTags = StringUtils.join( filtered.iterator(), "," ); - } - fixTagsSplitted = StringUtils.split( fixTags, "," ); - - // encoding - if ( StringUtils.isEmpty( encoding ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING - + ", i.e. build is platform dependent!" ); - } - encoding = ReaderFactory.FILE_ENCODING; - } - - // level - level = level.trim(); - if ( !JavadocUtil.equalsIgnoreCase( level, LEVEL_PUBLIC, LEVEL_PROTECTED, LEVEL_PACKAGE, LEVEL_PRIVATE ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unrecognized '" + level + "' for level parameter, using 'protected' level." ); - } - level = "protected"; - } - } - - /** - * @return true if the user wants to proceed, false otherwise. - * @throws MojoExecutionException if any - */ - private boolean preCheck() - throws MojoExecutionException - { - if ( force ) - { - return true; - } - - if ( outputDirectory != null && !outputDirectory.getAbsolutePath().equals( - getProjectSourceDirectory().getAbsolutePath() ) ) - { - return true; - } - - if ( !settings.isInteractiveMode() ) - { - getLog().error( "Maven is not attempt to interact with the user for input. " - + "Verify the configuration in your settings." ); - return false; - } - - getLog().warn( "" ); - getLog().warn( " WARRANTY DISCLAIMER" ); - getLog().warn( "" ); - getLog().warn( "All warranties with regard to this Maven goal are disclaimed!" ); - getLog().warn( "The changes will be done directly in the source code." ); - getLog().warn( "The Maven Team strongly recommends the use of a SCM software BEFORE executing this goal." ); - getLog().warn( "" ); - - while ( true ) - { - getLog().info( "Are you sure to proceed? [Y]es [N]o" ); - - try - { - String userExpression = inputHandler.readLine(); - if ( userExpression == null || JavadocUtil.equalsIgnoreCase( userExpression, "Y", "Yes" ) ) - { - getLog().info( "OK, let's proceed..." ); - break; - } - if ( JavadocUtil.equalsIgnoreCase( userExpression, "N", "No" ) ) - { - getLog().info( "No changes in your sources occur." ); - return false; - } - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to read from standard input.", e ); - } - } - - return true; - } - - /** - * @return the source dir as File for the given project - */ - private File getProjectSourceDirectory() - { - return new File( project.getBuild().getSourceDirectory() ); - } - - /** - * Invoke Maven to run clirr-maven-plugin to find API differences. - * - * @throws MavenInvocationException if any - */ - private void executeClirr() - throws MavenInvocationException - { - if ( ignoreClirr ) - { - getLog().info( "Clirr is ignored." ); - return; - } - - String clirrGoal = getFullClirrGoal(); - - // http://mojo.codehaus.org/clirr-maven-plugin/check-mojo.html - File clirrTextOutputFile = - FileUtils.createTempFile( "clirr", ".txt", new File( project.getBuild().getDirectory() ) ); - Properties properties = new Properties(); - properties.put( "textOutputFile", clirrTextOutputFile.getAbsolutePath() ); - properties.put( "comparisonVersion", comparisonVersion ); - properties.put( "failOnError", "false" ); - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "8" ) ) - { - // ensure that Java7 picks up TLSv1.2 when connecting with Central - properties.put( "https.protocols", "TLSv1.2" ); - } - - File invokerDir = new File( project.getBuild().getDirectory(), "invoker" ); - invokerDir.mkdirs(); - File invokerLogFile = FileUtils.createTempFile( "clirr-maven-plugin", ".txt", invokerDir ); - - JavadocUtil.invokeMaven( getLog(), new File( localRepository.getBasedir() ), project.getFile(), - Collections.singletonList( clirrGoal ), properties, invokerLogFile, - session.getRequest().getGlobalSettingsFile() ); - - try - { - if ( invokerLogFile.exists() ) - { - String invokerLogContent = - StringUtils.unifyLineSeparators( FileUtils.fileRead( invokerLogFile, "UTF-8" ) ); - // see org.codehaus.mojo.clirr.AbstractClirrMojo#getComparisonArtifact() - final String artifactNotFoundMsg = "Unable to find a previous version of the project in the repository"; - if ( invokerLogContent.contains( artifactNotFoundMsg ) ) - { - getLog().warn( "No previous artifact has been deployed, Clirr is ignored." ); - return; - } - } - } - catch ( IOException e ) - { - getLog().debug( "IOException: " + e.getMessage() ); - } - - try - { - parseClirrTextOutputFile( clirrTextOutputFile ); - } - catch ( IOException e ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "IOException: " + e.getMessage(), e ); - } - getLog().info( "IOException when parsing Clirr output '" + clirrTextOutputFile.getAbsolutePath() - + "', Clirr is ignored." ); - } - } - - /** - * @param clirrTextOutputFile not null - * @throws IOException if any - */ - private void parseClirrTextOutputFile( File clirrTextOutputFile ) - throws IOException - { - if ( !clirrTextOutputFile.exists() ) - { - if ( getLog().isInfoEnabled() ) - { - getLog().info( - "No Clirr output file '" + clirrTextOutputFile.getAbsolutePath() + "' exists, Clirr is ignored." ); - } - return; - } - - if ( getLog().isInfoEnabled() ) - { - getLog().info( "Clirr output file was created: " + clirrTextOutputFile.getAbsolutePath() ); - } - - clirrNewClasses = new LinkedList<>(); - clirrNewMethods = new LinkedHashMap<>(); - - try ( BufferedReader reader = new BufferedReader( ReaderFactory.newReader( clirrTextOutputFile, "UTF-8" ) ) ) - { - - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - String[] split = StringUtils.split( line, ":" ); - if ( split.length != 4 ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Unable to parse the clirr line: " + line ); - } - continue; - } - - int code; - try - { - code = Integer.parseInt( split[1].trim() ); - } - catch ( NumberFormatException e ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Unable to parse the clirr line: " + line ); - } - continue; - } - - // http://clirr.sourceforge.net/clirr-core/exegesis.html - // 7011 - Method Added - // 7012 - Method Added to Interface - // 8000 - Class Added - - // CHECKSTYLE_OFF: MagicNumber - switch ( code ) - { - case 7011: - methodAdded( split ); - break; - case 7012: - methodAdded( split ); - break; - case 8000: - clirrNewClasses.add( split[2].trim() ); - break; - default: - break; - } - // CHECKSTYLE_ON: MagicNumber - } - } - if ( clirrNewClasses.isEmpty() && clirrNewMethods.isEmpty() ) - { - getLog().info( "Clirr NOT found API differences." ); - } - else - { - getLog().info( "Clirr found API differences, i.e. new classes/interfaces or methods." ); - } - } - - private void methodAdded( String[] split ) - { - List list = clirrNewMethods.get( split[2].trim() ); - if ( list == null ) - { - list = new ArrayList<>(); - } - String[] splits2 = StringUtils.split( split[3].trim(), "'" ); - if ( splits2.length != 3 ) - { - return; - } - list.add( splits2[1].trim() ); - clirrNewMethods.put( split[2].trim(), list ); - } - - /** - * @param tag not null - * @return true if tag is defined in {@link #fixTags}. - */ - private boolean fixTag( String tag ) - { - if ( fixTagsSplitted.length == 1 && fixTagsSplitted[0].equals( FIX_TAGS_ALL ) ) - { - return true; - } - - for ( String aFixTagsSplitted : fixTagsSplitted ) - { - if ( aFixTagsSplitted.trim().equals( tag ) ) - { - return true; - } - } - - return false; - } - - /** - * Calling Qdox to find {@link JavaClass} objects from the Maven project sources. - * Ignore java class if Qdox has parsing errors. - * - * @return an array of {@link JavaClass} found by QDox - * @throws IOException if any - * @throws MojoExecutionException if any - */ - private Collection getQdoxClasses() - throws IOException, MojoExecutionException - { - if ( "pom".equalsIgnoreCase( project.getPackaging() ) ) - { - getLog().warn( "This project has 'pom' packaging, no Java sources is available." ); - return null; - } - - List javaFiles = new LinkedList<>(); - for ( String sourceRoot : getProjectSourceRoots( project ) ) - { - File f = new File( sourceRoot ); - if ( f.isDirectory() ) - { - javaFiles.addAll( FileUtils.getFiles( f, includes, excludes, true ) ); - } - else - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( f + " doesn't exist. Ignored it." ); - } - } - } - - ClassLibraryBuilder classLibraryBuilder = new OrderedClassLibraryBuilder(); - classLibraryBuilder.appendClassLoader( getProjectClassLoader() ); - - JavaProjectBuilder builder = new JavaProjectBuilder( classLibraryBuilder ); - builder.setEncoding( encoding ); - for ( File f : javaFiles ) - { - if ( !f.getAbsolutePath().toLowerCase( Locale.ENGLISH ).endsWith( ".java" ) && getLog().isWarnEnabled() ) - { - getLog().warn( "'" + f + "' is not a Java file. Ignored it." ); - continue; - } - - try - { - builder.addSource( f ); - } - catch ( ParseException e ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "QDOX ParseException: " + e.getMessage() + ". Can't fix it." ); - } - } - } - - return builder.getClasses(); - } - - /** - * @return the classLoader for the given project using lazy instantiation. - * @throws MojoExecutionException if any - */ - private ClassLoader getProjectClassLoader() - throws MojoExecutionException - { - if ( projectClassLoader == null ) - { - List classPath; - try - { - classPath = getCompileClasspathElements( project ); - } - catch ( DependencyResolutionRequiredException e ) - { - throw new MojoExecutionException( "DependencyResolutionRequiredException: " + e.getMessage(), e ); - } - - List urls = new ArrayList<>( classPath.size() ); - for ( String filename : classPath ) - { - try - { - urls.add( new File( filename ).toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - throw new MojoExecutionException( "MalformedURLException: " + e.getMessage(), e ); - } - } - - projectClassLoader = new URLClassLoader( urls.toArray( new URL[urls.size()] ), null ); - } - - return projectClassLoader; - } - - /** - * Process the given {@link JavaClass}, ie add missing javadoc tags depending user parameters. - * - * @param javaClass not null - * @throws IOException if any - * @throws MojoExecutionException if any - */ - private void processFix( JavaClass javaClass ) - throws IOException, MojoExecutionException - { - // Skipping inner classes - if ( javaClass.isInner() ) - { - return; - } - - File javaFile; - try - { - javaFile = Paths.get( javaClass.getSource().getURL().toURI() ).toFile(); - } - catch ( URISyntaxException e ) - { - throw new MojoExecutionException( e.getMessage() ); - } - - // the original java content in memory - final String originalContent = StringUtils.unifyLineSeparators( FileUtils.fileRead( javaFile, encoding ) ); - - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Analyzing " + javaClass.getFullyQualifiedName() ); - } - - final StringWriter stringWriter = new StringWriter(); - boolean changeDetected = false; - try ( BufferedReader reader = new BufferedReader( new StringReader( originalContent ) ) ) - { - - int lineNumber = 0; - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - lineNumber++; - final String indent = autodetectIndentation( line ); - - // fixing classes - if ( javaClass.getComment() == null && javaClass.getAnnotations() != null - && !javaClass.getAnnotations().isEmpty() ) - { - if ( lineNumber == javaClass.getAnnotations().get( 0 ).getLineNumber() ) - { - changeDetected |= fixClassComment( stringWriter, originalContent, javaClass, indent ); - - takeCareSingleComment( stringWriter, originalContent, javaClass ); - } - } - else if ( lineNumber == javaClass.getLineNumber() ) - { - changeDetected |= fixClassComment( stringWriter, originalContent, javaClass, indent ); - - takeCareSingleComment( stringWriter, originalContent, javaClass ); - } - - // fixing fields - if ( javaClass.getFields() != null ) - { - for ( JavaField field : javaClass.getFields() ) - { - if ( lineNumber == field.getLineNumber() ) - { - changeDetected |= fixFieldComment( stringWriter, javaClass, field, indent ); - } - } - } - - // fixing methods - if ( javaClass.getConstructors() != null ) - { - for ( JavaConstructor method : javaClass.getConstructors() ) - { - if ( lineNumber == method.getLineNumber() ) - { - final boolean commentUpdated = - fixMethodComment( stringWriter, originalContent, method, indent ); - if ( commentUpdated ) - { - takeCareSingleComment( stringWriter, originalContent, method ); - } - changeDetected |= commentUpdated; - } - } - } - - - // fixing methods - for ( JavaMethod method : javaClass.getMethods() ) - { - int methodLineNumber; - if ( method.getComment() == null && !method.getAnnotations().isEmpty() ) - { - methodLineNumber = method.getAnnotations().get( 0 ).getLineNumber(); - } - else - { - methodLineNumber = method.getLineNumber(); - } - - if ( lineNumber == methodLineNumber ) - { - final boolean commentUpdated = - fixMethodComment( stringWriter, originalContent, method, indent ); - if ( commentUpdated ) - { - takeCareSingleComment( stringWriter, originalContent, method ); - } - changeDetected |= commentUpdated; - } - } - - stringWriter.write( line ); - stringWriter.write( EOL ); - } - } - - if ( changeDetected ) - { - if ( getLog().isInfoEnabled() ) - { - getLog().info( "Saving changes to " + javaClass.getFullyQualifiedName() ); - } - - if ( outputDirectory != null && !outputDirectory.getAbsolutePath().equals( - getProjectSourceDirectory().getAbsolutePath() ) ) - { - String path = StringUtils.replace( javaFile.getAbsolutePath().replaceAll( "\\\\", "/" ), - project.getBuild().getSourceDirectory().replaceAll( "\\\\", "/" ), "" ); - javaFile = new File( outputDirectory, path ); - javaFile.getParentFile().mkdirs(); - } - writeFile( javaFile, encoding, stringWriter.toString() ); - } - else - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "No changes made to " + javaClass.getFullyQualifiedName() ); - } - } - } - - /** - * Take care of block or single comments between Javadoc comment and entity declaration ie: - *
- * - * 1   - * /**
- * 2    - * * {Javadoc Comment}
- * 3    - * */
- * 4   - * /*
- * 5    - * * {Block Comment}
- * 6    - * */
- * 7   - * // {Single comment}
- * 8   - * public void  - * dummyMethod - * String s ){} - *
- * - * @param stringWriter not null - * @param originalContent not null - * @param entity not null - * @throws IOException if any - * @see #extractOriginalJavadoc - */ - private void takeCareSingleComment( final StringWriter stringWriter, final String originalContent, - final JavaAnnotatedElement entity ) - throws IOException - { - if ( entity.getComment() == null ) - { - return; - } - - String javadocComment = trimRight( extractOriginalJavadoc( originalContent, entity ) ); - String extraComment = javadocComment.substring( javadocComment.indexOf( END_JAVADOC ) + END_JAVADOC.length() ); - if ( StringUtils.isNotEmpty( extraComment ) ) - { - if ( extraComment.contains( EOL ) ) - { - stringWriter.write( extraComment.substring( extraComment.indexOf( EOL ) + EOL.length() ) ); - } - else - { - stringWriter.write( extraComment ); - } - stringWriter.write( EOL ); - } - } - - /** - * Add/update Javadoc class comment. - * - * @param stringWriter - * @param originalContent - * @param javaClass - * @param indent - * @return {@code true} if the comment is updated, otherwise {@code false} - * @throws MojoExecutionException - * @throws IOException - */ - private boolean fixClassComment( final StringWriter stringWriter, final String originalContent, - final JavaClass javaClass, final String indent ) - throws MojoExecutionException, IOException - { - if ( !fixClassComment ) - { - return false; - } - - if ( !isInLevel( javaClass.getModifiers() ) ) - { - return false; - } - - // add - if ( javaClass.getComment() == null ) - { - addDefaultClassComment( stringWriter, javaClass, indent ); - return true; - } - - // update - return updateEntityComment( stringWriter, originalContent, javaClass, indent ); - } - - /** - * @param modifiers list of modifiers (public, private, protected, package) - * @return true if modifier is align with level. - */ - private boolean isInLevel( List modifiers ) - { - if ( LEVEL_PUBLIC.equalsIgnoreCase( level.trim() ) ) - { - return modifiers.contains( LEVEL_PUBLIC ); - } - - if ( LEVEL_PROTECTED.equalsIgnoreCase( level.trim() ) ) - { - return ( modifiers.contains( LEVEL_PUBLIC ) || modifiers.contains( LEVEL_PROTECTED ) ); - } - - if ( LEVEL_PACKAGE.equalsIgnoreCase( level.trim() ) ) - { - return !modifiers.contains( LEVEL_PRIVATE ); - } - - // should be private (shows all classes and members) - return true; - } - - /** - * Add a default Javadoc for the given class, i.e.: - *
- * - * 1   - * /**
- * 2    - * * {Comment based on the class name}
- * 3    - * *
- * 4    - * @author  - * X {added if addMissingAuthor}
- * 5    - * @version  - * X {added if addMissingVersion}
- * 6    - * @since  - * X {added if addMissingSince and new classes - * from previous version}
- * 7    - * */
- * 8 public class  - * DummyClass {}
- * - * - * @param stringWriter not null - * @param javaClass not null - * @param indent not null - * @see #getDefaultClassJavadocComment(JavaClass) - * @see #appendDefaultAuthorTag(StringBuilder, String) - * @see #appendDefaultSinceTag(StringBuilder, String) - * @see #appendDefaultVersionTag(StringBuilder, String) - */ - private void addDefaultClassComment( final StringWriter stringWriter, final JavaClass javaClass, - final String indent ) - { - StringBuilder sb = new StringBuilder(); - - sb.append( indent ).append( START_JAVADOC ); - sb.append( EOL ); - sb.append( indent ).append( SEPARATOR_JAVADOC ); - sb.append( getDefaultClassJavadocComment( javaClass ) ); - sb.append( EOL ); - - appendSeparator( sb, indent ); - - appendDefaultAuthorTag( sb, indent ); - - appendDefaultVersionTag( sb, indent ); - - if ( fixTag( SINCE_TAG ) ) - { - if ( !ignoreClirr ) - { - if ( isNewClassFromLastVersion( javaClass ) ) - { - appendDefaultSinceTag( sb, indent ); - } - } - else - { - appendDefaultSinceTag( sb, indent ); - addSinceClasses( javaClass ); - } - } - - sb.append( indent ).append( " " ).append( END_JAVADOC ); - sb.append( EOL ); - - stringWriter.write( sb.toString() ); - } - - /** - * Add Javadoc field comment, only for static fields or interface fields. - * - * @param stringWriter not null - * @param javaClass not null - * @param field not null - * @param indent not null - * @return {@code true} if comment was updated, otherwise {@code false} - * @throws IOException if any - */ - private boolean fixFieldComment( final StringWriter stringWriter, final JavaClass javaClass, final JavaField field, - final String indent ) - throws IOException - { - if ( !fixFieldComment ) - { - return false; - } - - if ( !javaClass.isInterface() && ( !isInLevel( field.getModifiers() ) || !field.isStatic() ) ) - { - return false; - } - - // add - if ( field.getComment() == null ) - { - addDefaultFieldComment( stringWriter, field, indent ); - return true; - } - - // no update - return false; - } - - /** - * Add a default Javadoc for the given field, i.e.: - *
- * - * 1      - * /** Constant <code> - * MY_STRING_CONSTANT="value" - * </code> */
- * 2      - * public static final  - * String MY_STRING_CONSTANT =  - * "value"; - *
- * - * @param stringWriter not null - * @param field not null - * @param indent not null - * @throws IOException if any - */ - private void addDefaultFieldComment( final StringWriter stringWriter, final JavaField field, final String indent ) - throws IOException - { - StringBuilder sb = new StringBuilder(); - - sb.append( indent ).append( START_JAVADOC ).append( " " ); - sb.append( "Constant " ).append( field.getName() ); - - if ( StringUtils.isNotEmpty( field.getInitializationExpression() ) ) - { - String qualifiedName = field.getType().getFullyQualifiedName(); - - if ( qualifiedName.equals( Byte.TYPE.toString() ) || qualifiedName.equals( Short.TYPE.toString() ) - || qualifiedName.equals( Integer.TYPE.toString() ) || qualifiedName.equals( Long.TYPE.toString() ) - || qualifiedName.equals( Float.TYPE.toString() ) || qualifiedName.equals( Double.TYPE.toString() ) - || qualifiedName.equals( Boolean.TYPE.toString() ) || qualifiedName.equals( - Character.TYPE.toString() ) ) - { - sb.append( "=" ); - sb.append( StringEscapeUtils.escapeHtml4( field.getInitializationExpression().trim() ) ); - } - - if ( qualifiedName.equals( String.class.getName() ) ) - { - StringBuilder value = new StringBuilder(); - String[] lines = getLines( field.getInitializationExpression() ); - for ( String line : lines ) - { - StringTokenizer token = new StringTokenizer( line.trim(), "\"\n\r" ); - while ( token.hasMoreTokens() ) - { - String s = token.nextToken(); - - if ( s.trim().equals( "+" ) ) - { - continue; - } - if ( s.trim().endsWith( "\\" ) ) - { - s += "\""; - } - value.append( s ); - } - } - - sb.append( "=\"" ); - String escapedValue = StringEscapeUtils.escapeHtml4( value.toString() ); - // reduce the size - // CHECKSTYLE_OFF: MagicNumber - if ( escapedValue.length() < 40 ) - { - sb.append( escapedValue ).append( "\"" ); - } - else - { - sb.append( escapedValue, 0, 39 ).append( "\"{trunked}" ); - } - // CHECKSTYLE_ON: MagicNumber - } - } - - sb.append( " " ).append( END_JAVADOC ); - sb.append( EOL ); - - stringWriter.write( sb.toString() ); - } - - /** - * Add/update Javadoc method comment. - * - * @param stringWriter not null - * @param originalContent not null - * @param javaExecutable not null - * @param indent not null - * @return {@code true} if comment was updated, otherwise {@code false} - * @throws MojoExecutionException if any - * @throws IOException if any - */ - private boolean fixMethodComment( final StringWriter stringWriter, final String originalContent, - final JavaExecutable javaExecutable, final String indent ) - throws MojoExecutionException, IOException - { - if ( !fixMethodComment ) - { - return false; - } - - if ( !javaExecutable.getDeclaringClass().isInterface() && !isInLevel( javaExecutable.getModifiers() ) ) - { - return false; - } - - // add - if ( javaExecutable.getComment() == null ) - { - addDefaultMethodComment( stringWriter, javaExecutable, indent ); - return true; - } - - // update - return updateEntityComment( stringWriter, originalContent, javaExecutable, indent ); - } - - /** - * Add in the buffer a default Javadoc for the given class: - *
- * - * 1   - * /**
- * 2    - * * {Comment based on the method name}
- * 3    - * *
- * 4    - * @param  - * X {added if addMissingParam}
- * 5    - * @return  - * X {added if addMissingReturn}
- * 6    - * @throws  - * X {added if addMissingThrows}
- * 7    - * @since  - * X {added if addMissingSince and new classes - * from previous version}
- * 8    - * */
- * 9 public  - * void dummyMethod - * String s  - * ){} - *
- * - * @param stringWriter not null - * @param javaExecutable not null - * @param indent not null - * @throws MojoExecutionException if any - * @see #getDefaultMethodJavadocComment - * @see #appendDefaultSinceTag(StringBuilder, String) - */ - private void addDefaultMethodComment( final StringWriter stringWriter, final JavaExecutable javaExecutable, - final String indent ) - throws MojoExecutionException - { - StringBuilder sb = new StringBuilder(); - - // special case - if ( isInherited( javaExecutable ) ) - { - sb.append( indent ).append( INHERITED_JAVADOC ); - sb.append( EOL ); - - stringWriter.write( sb.toString() ); - return; - } - - sb.append( indent ).append( START_JAVADOC ); - sb.append( EOL ); - sb.append( indent ).append( SEPARATOR_JAVADOC ); - sb.append( getDefaultMethodJavadocComment( javaExecutable ) ); - sb.append( EOL ); - - boolean separatorAdded = false; - if ( fixTag( PARAM_TAG ) ) - { - if ( javaExecutable.getParameters() != null ) - { - for ( JavaParameter javaParameter : javaExecutable.getParameters() ) - { - separatorAdded = appendDefaultParamTag( sb, indent, separatorAdded, javaParameter ); - } - } - // is generic? - if ( javaExecutable.getTypeParameters() != null ) - { - for ( JavaTypeVariable typeParam : javaExecutable.getTypeParameters() ) - { - separatorAdded = appendDefaultParamTag( sb, indent, separatorAdded, typeParam ); - } - } - } - if ( javaExecutable instanceof JavaMethod ) - { - JavaMethod javaMethod = (JavaMethod) javaExecutable; - if ( fixTag( RETURN_TAG ) && javaMethod.getReturns() != null && !javaMethod.getReturns().isVoid() ) - { - separatorAdded = appendDefaultReturnTag( sb, indent, separatorAdded, javaMethod ); - } - - } - if ( fixTag( THROWS_TAG ) && javaExecutable.getExceptions() != null ) - { - for ( JavaType exception : javaExecutable.getExceptions() ) - { - separatorAdded = appendDefaultThrowsTag( sb, indent, separatorAdded, exception ); - } - } - if ( fixTag( SINCE_TAG ) && isNewMethodFromLastRevision( javaExecutable ) ) - { - separatorAdded = appendDefaultSinceTag( sb, indent, separatorAdded ); - } - - sb.append( indent ).append( " " ).append( END_JAVADOC ); - sb.append( EOL ); - - stringWriter.write( sb.toString() ); - } - - /** - * @param stringWriter not null - * @param originalContent not null - * @param entity not null - * @param indent not null - * @return the updated changeDetected flag - * @throws MojoExecutionException if any - * @throws IOException if any - */ - private boolean updateEntityComment( final StringWriter stringWriter, final String originalContent, - final JavaAnnotatedElement entity, final String indent ) - throws MojoExecutionException, IOException - { - boolean changeDetected = false; - - String old = null; - String s = stringWriter.toString(); - int i = s.lastIndexOf( START_JAVADOC ); - if ( i != -1 ) - { - String tmp = s.substring( 0, i ); - if ( tmp.lastIndexOf( EOL ) != -1 ) - { - tmp = tmp.substring( 0, tmp.lastIndexOf( EOL ) ); - } - - old = stringWriter.getBuffer().substring( i ); - - stringWriter.getBuffer().delete( 0, stringWriter.getBuffer().length() ); - stringWriter.write( tmp ); - stringWriter.write( EOL ); - } - else - { - changeDetected = true; - } - - updateJavadocComment( stringWriter, originalContent, entity, indent ); - - if ( changeDetected ) - { - return true; // return now if we already know there's a change - } - - return !stringWriter.getBuffer().substring( i ).equals( old ); - } - - /** - * @param stringWriter not null - * @param originalContent not null - * @param entity not null - * @param indent not null - * @throws MojoExecutionException if any - * @throws IOException if any - */ - private void updateJavadocComment( final StringWriter stringWriter, final String originalContent, - final JavaAnnotatedElement entity, final String indent ) - throws MojoExecutionException, IOException - { - if ( entity.getComment() == null && ( entity.getTags() == null || entity.getTags().isEmpty() ) ) - { - return; - } - - boolean isJavaExecutable = entity instanceof JavaExecutable; - - StringBuilder sb = new StringBuilder(); - - // special case for inherited method - if ( isJavaExecutable ) - { - JavaExecutable javaMethod = (JavaExecutable) entity; - - if ( isInherited( javaMethod ) ) - { - // QDOX-154 could be empty - if ( StringUtils.isEmpty( javaMethod.getComment() ) ) - { - sb.append( indent ).append( INHERITED_JAVADOC ); - sb.append( EOL ); - stringWriter.write( sb.toString() ); - return; - } - - String javadoc = getJavadocComment( originalContent, javaMethod ); - - // case: /** {@inheritDoc} */ or no tags - if ( hasInheritedTag( javadoc ) && ( javaMethod.getTags() == null - || javaMethod.getTags().isEmpty() ) ) - { - sb.append( indent ).append( INHERITED_JAVADOC ); - sb.append( EOL ); - stringWriter.write( sb.toString() ); - return; - } - - if ( javadoc.contains( START_JAVADOC ) ) - { - javadoc = javadoc.substring( javadoc.indexOf( START_JAVADOC ) + START_JAVADOC.length() ); - } - if ( javadoc.contains( END_JAVADOC ) ) - { - javadoc = javadoc.substring( 0, javadoc.indexOf( END_JAVADOC ) ); - } - - sb.append( indent ).append( START_JAVADOC ); - sb.append( EOL ); - if ( !javadoc.contains( INHERITED_TAG ) ) - { - sb.append( indent ).append( SEPARATOR_JAVADOC ).append( INHERITED_TAG ); - sb.append( EOL ); - appendSeparator( sb, indent ); - } - javadoc = removeLastEmptyJavadocLines( javadoc ); - javadoc = alignIndentationJavadocLines( javadoc, indent ); - sb.append( javadoc ); - sb.append( EOL ); - if ( javaMethod.getTags() != null ) - { - for ( DocletTag docletTag : javaMethod.getTags() ) - { - // Voluntary ignore these tags - if ( JavadocUtil.equals( docletTag.getName(), PARAM_TAG, RETURN_TAG, THROWS_TAG ) ) - { - continue; - } - - String s = getJavadocComment( originalContent, entity, docletTag ); - s = removeLastEmptyJavadocLines( s ); - s = alignIndentationJavadocLines( s, indent ); - sb.append( s ); - sb.append( EOL ); - } - } - sb.append( indent ).append( " " ).append( END_JAVADOC ); - sb.append( EOL ); - - if ( hasInheritedTag( sb.toString().trim() ) ) - { - sb = new StringBuilder(); - sb.append( indent ).append( INHERITED_JAVADOC ); - sb.append( EOL ); - stringWriter.write( sb.toString() ); - return; - } - - stringWriter.write( sb.toString() ); - return; - } - } - - sb.append( indent ).append( START_JAVADOC ); - sb.append( EOL ); - - // comment - if ( StringUtils.isNotEmpty( entity.getComment() ) ) - { - updateJavadocComment( sb, originalContent, entity, indent ); - } - else - { - addDefaultJavadocComment( sb, entity, indent, isJavaExecutable ); - } - - // tags - updateJavadocTags( sb, originalContent, entity, indent, isJavaExecutable ); - - sb = new StringBuilder( removeLastEmptyJavadocLines( sb.toString() ) ).append( EOL ); - - sb.append( indent ).append( " " ).append( END_JAVADOC ); - sb.append( EOL ); - - stringWriter.write( sb.toString() ); - } - - /** - * @param sb not null - * @param originalContent not null - * @param entity not null - * @param indent not null - * @throws IOException if any - */ - private void updateJavadocComment( final StringBuilder sb, final String originalContent, - final JavaAnnotatedElement entity, final String indent ) - throws IOException - { - String comment = getJavadocComment( originalContent, entity ); - comment = removeLastEmptyJavadocLines( comment ); - comment = alignIndentationJavadocLines( comment, indent ); - - if ( comment.contains( START_JAVADOC ) ) - { - comment = comment.substring( comment.indexOf( START_JAVADOC ) + START_JAVADOC.length() ); - comment = indent + SEPARATOR_JAVADOC + comment.trim(); - } - if ( comment.contains( END_JAVADOC ) ) - { - comment = comment.substring( 0, comment.indexOf( END_JAVADOC ) ); - } - - if ( fixTag( LINK_TAG ) ) - { - comment = replaceLinkTags( comment, entity ); - } - - String[] lines = getLines( comment ); - for ( String line : lines ) - { - sb.append( indent ).append( " " ).append( line.trim() ); - sb.append( EOL ); - } - } - - private static final Pattern REPLACE_LINK_TAGS_PATTERN = Pattern.compile( "\\{@link\\s" ); - - static String replaceLinkTags( String comment, JavaAnnotatedElement entity ) - { - StringBuilder resolvedComment = new StringBuilder(); - // scan comment for {@link someClassName} and try to resolve this - Matcher linktagMatcher = REPLACE_LINK_TAGS_PATTERN.matcher( comment ); - int startIndex = 0; - while ( linktagMatcher.find() ) - { - int startName = linktagMatcher.end(); - resolvedComment.append( comment, startIndex, startName ); - int endName = comment.indexOf( "}", startName ); - if ( endName >= 0 ) - { - String name; - String link = comment.substring( startName, endName ); - int hashIndex = link.indexOf( '#' ); - if ( hashIndex >= 0 ) - { - name = link.substring( 0, hashIndex ); - } - else - { - name = link; - } - if ( StringUtils.isNotBlank( name ) ) - { - String typeName; - if ( entity instanceof JavaClass ) - { - JavaClass clazz = (JavaClass) entity; - typeName = - TypeResolver.byClassName( clazz.getBinaryName(), clazz.getJavaClassLibrary(), - clazz.getSource().getImports() ).resolveType( name.trim() ); - } - else if ( entity instanceof JavaMember ) - { - JavaClass clazz = ( (JavaMember) entity ).getDeclaringClass(); - typeName = - TypeResolver.byClassName( clazz.getBinaryName(), clazz.getJavaClassLibrary(), - clazz.getSource().getImports() ).resolveType( name.trim() ); - } - else - { - typeName = null; - } - - if ( typeName == null ) - { - typeName = name.trim(); - } - else - { - typeName = typeName.replaceAll( "\\$", "." ); - } - //adjust name for inner classes - resolvedComment.append( typeName ); - } - if ( hashIndex >= 0 ) - { - resolvedComment.append( link.substring( hashIndex ).trim() ); - } - startIndex = endName; - } - else - { - startIndex = startName; - } - - } - resolvedComment.append( comment.substring( startIndex ) ); - return resolvedComment.toString(); - - } - - /** - * @param sb not null - * @param entity not null - * @param indent not null - * @param isJavaExecutable - */ - private void addDefaultJavadocComment( final StringBuilder sb, final JavaAnnotatedElement entity, - final String indent, final boolean isJavaExecutable ) - { - sb.append( indent ).append( SEPARATOR_JAVADOC ); - if ( isJavaExecutable ) - { - sb.append( getDefaultMethodJavadocComment( (JavaExecutable) entity ) ); - } - else - { - sb.append( getDefaultClassJavadocComment( (JavaClass) entity ) ); - } - sb.append( EOL ); - } - - /** - * @param sb not null - * @param originalContent not null - * @param entity not null - * @param indent not null - * @param isJavaExecutable - * @throws IOException if any - * @throws MojoExecutionException if any - */ - private void updateJavadocTags( final StringBuilder sb, final String originalContent, - final JavaAnnotatedElement entity, final String indent, - final boolean isJavaExecutable ) - throws IOException, MojoExecutionException - { - appendSeparator( sb, indent ); - - // parse tags - JavaEntityTags javaEntityTags = parseJavadocTags( originalContent, entity, indent, isJavaExecutable ); - - // update and write tags - updateJavadocTags( sb, entity, isJavaExecutable, javaEntityTags ); - - // add missing tags... - addMissingJavadocTags( sb, entity, indent, isJavaExecutable, javaEntityTags ); - } - - /** - * Parse entity tags - * - * @param originalContent not null - * @param entity not null - * @param indent not null - * @param isJavaMethod - * @return an instance of {@link JavaEntityTags} - * @throws IOException if any - */ - JavaEntityTags parseJavadocTags( final String originalContent, final JavaAnnotatedElement entity, - final String indent, final boolean isJavaMethod ) - throws IOException - { - JavaEntityTags javaEntityTags = new JavaEntityTags( entity, isJavaMethod ); - for ( DocletTag docletTag : entity.getTags() ) - { - String originalJavadocTag = getJavadocComment( originalContent, entity, docletTag ); - originalJavadocTag = removeLastEmptyJavadocLines( originalJavadocTag ); - originalJavadocTag = alignIndentationJavadocLines( originalJavadocTag, indent ); - - javaEntityTags.getNamesTags().add( docletTag.getName() ); - - if ( isJavaMethod ) - { - List params = docletTag.getParameters(); - if ( params.size() < 1 ) - { - continue; - } - - String paramName = params.get( 0 ); - switch ( docletTag.getName() ) - { - case PARAM_TAG: - javaEntityTags.putJavadocParamTag( paramName, docletTag.getValue(), originalJavadocTag ); - break; - case RETURN_TAG: - javaEntityTags.setJavadocReturnTag( originalJavadocTag ); - break; - case THROWS_TAG: - javaEntityTags.putJavadocThrowsTag( paramName, originalJavadocTag ); - break; - default: - javaEntityTags.getUnknownTags().add( originalJavadocTag ); - break; - } - } - else - { - javaEntityTags.getUnknownTags().add( originalJavadocTag ); - } - } - - return javaEntityTags; - } - - /** - * Write tags according javaEntityTags. - * - * @param sb not null - * @param entity not null - * @param isJavaExecutable - * @param javaEntityTags not null - */ - private void updateJavadocTags( final StringBuilder sb, final JavaAnnotatedElement entity, - final boolean isJavaExecutable, final JavaEntityTags javaEntityTags ) - { - for ( DocletTag docletTag : entity.getTags() ) - { - if ( isJavaExecutable ) - { - JavaExecutable javaExecutable = (JavaExecutable) entity; - - List params = docletTag.getParameters(); - if ( params.size() < 1 ) - { - continue; - } - - if ( docletTag.getName().equals( PARAM_TAG ) ) - { - writeParamTag( sb, javaExecutable, javaEntityTags, params.get( 0 ), docletTag.getValue() ); - } - else if ( docletTag.getName().equals( RETURN_TAG ) && javaExecutable instanceof JavaMethod ) - { - writeReturnTag( sb, (JavaMethod) javaExecutable, javaEntityTags ); - } - else if ( docletTag.getName().equals( THROWS_TAG ) ) - { - writeThrowsTag( sb, javaExecutable, javaEntityTags, params ); - } - else - { - // write unknown tags - for ( Iterator it = javaEntityTags.getUnknownTags().iterator(); it.hasNext(); ) - { - String originalJavadocTag = it.next(); - String simplified = StringUtils.removeDuplicateWhitespace( originalJavadocTag ).trim(); - - if ( simplified.contains( "@" + docletTag.getName() ) ) - { - it.remove(); - sb.append( originalJavadocTag ); - sb.append( EOL ); - } - } - } - } - else - { - for ( Iterator it = javaEntityTags.getUnknownTags().iterator(); it.hasNext(); ) - { - String originalJavadocTag = it.next(); - String simplified = StringUtils.removeDuplicateWhitespace( originalJavadocTag ).trim(); - - if ( simplified.contains( "@" + docletTag.getName() ) ) - { - it.remove(); - sb.append( originalJavadocTag ); - sb.append( EOL ); - } - } - } - - if ( sb.toString().endsWith( EOL ) ) - { - sb.delete( sb.toString().lastIndexOf( EOL ), sb.toString().length() ); - } - - sb.append( EOL ); - } - } - - private void writeParamTag( final StringBuilder sb, final JavaExecutable javaExecutable, - final JavaEntityTags javaEntityTags, String paramName, String paramValue ) - { - if ( !fixTag( PARAM_TAG ) ) - { - // write original param tag if found - String originalJavadocTag = javaEntityTags.getJavadocParamTag( paramValue ); - if ( originalJavadocTag != null ) - { - sb.append( originalJavadocTag ); - } - return; - } - - boolean found = false; - JavaParameter javaParam = javaExecutable.getParameterByName( paramName ); - if ( javaParam == null ) - { - // is generic? - List> typeParams = javaExecutable.getTypeParameters(); - for ( JavaTypeVariable typeParam : typeParams ) - { - if ( ( "<" + typeParam.getName() + ">" ).equals( paramName ) ) - { - found = true; - } - } - } - else - { - found = true; - } - - if ( !found ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( - "Fixed unknown param '" + paramName + "' defined in " + getJavaMethodAsString( javaExecutable ) ); - } - - if ( sb.toString().endsWith( EOL ) ) - { - sb.delete( sb.toString().lastIndexOf( EOL ), sb.toString().length() ); - } - } - else - { - String originalJavadocTag = javaEntityTags.getJavadocParamTag( paramValue ); - if ( originalJavadocTag != null ) - { - sb.append( originalJavadocTag ); - String s = "@" + PARAM_TAG + " " + paramName; - if ( StringUtils.removeDuplicateWhitespace( originalJavadocTag ).trim().endsWith( s ) ) - { - sb.append( " " ); - sb.append( getDefaultJavadocForType( javaParam.getJavaClass() ) ); - } - } - } - } - - private void writeReturnTag( final StringBuilder sb, final JavaMethod javaMethod, - final JavaEntityTags javaEntityTags ) - { - String originalJavadocTag = javaEntityTags.getJavadocReturnTag(); - if ( originalJavadocTag == null ) - { - return; - } - - if ( !fixTag( RETURN_TAG ) ) - { - // write original param tag if found - sb.append( originalJavadocTag ); - return; - } - - if ( StringUtils.isNotEmpty( originalJavadocTag ) && javaMethod.getReturns() != null - && !javaMethod.getReturns().isVoid() ) - { - sb.append( originalJavadocTag ); - if ( originalJavadocTag.trim().endsWith( "@" + RETURN_TAG ) ) - { - sb.append( " " ); - sb.append( getDefaultJavadocForType( javaMethod.getReturns() ) ); - } - } - } - - void writeThrowsTag( final StringBuilder sb, final JavaExecutable javaExecutable, - final JavaEntityTags javaEntityTags, final List params ) - { - String exceptionClassName = params.get( 0 ); - - String originalJavadocTag = javaEntityTags.getJavadocThrowsTag( exceptionClassName ); - if ( originalJavadocTag == null ) - { - return; - } - - if ( !fixTag( THROWS_TAG ) ) - { - // write original param tag if found - sb.append( originalJavadocTag ); - return; - } - - if ( javaExecutable.getExceptions() != null ) - { - for ( JavaType exception : javaExecutable.getExceptions() ) - { - if ( exception.getFullyQualifiedName().endsWith( exceptionClassName ) ) - { - originalJavadocTag = StringUtils.replace( originalJavadocTag, exceptionClassName, - exception.getFullyQualifiedName() ); - if ( StringUtils.removeDuplicateWhitespace( originalJavadocTag ).trim().endsWith( - "@" + THROWS_TAG + " " + exception.getValue() ) ) - { - originalJavadocTag += " if any."; - } - - sb.append( originalJavadocTag ); - - // added qualified name - javaEntityTags.putJavadocThrowsTag( exception.getValue(), originalJavadocTag ); - - return; - } - } - } - - Class clazz = getClass( javaExecutable.getDeclaringClass(), exceptionClassName ); - - if ( clazz != null ) - { - if ( RuntimeException.class.isAssignableFrom( clazz ) ) - { - sb.append( StringUtils.replace( originalJavadocTag, exceptionClassName, clazz.getName() ) ); - - // added qualified name - javaEntityTags.putJavadocThrowsTag( clazz.getName(), originalJavadocTag ); - } - else if ( Throwable.class.isAssignableFrom( clazz ) ) - { - getLog().debug( "Removing '" + originalJavadocTag + "'; Throwable not specified by " - + getJavaMethodAsString( javaExecutable ) + " and it is not a RuntimeException." ); - } - else - { - getLog().debug( "Removing '" + originalJavadocTag + "'; It is not a Throwable" ); - } - } - else if ( removeUnknownThrows ) - { - getLog().warn( "Ignoring unknown throws '" + exceptionClassName + "' defined on " - + getJavaMethodAsString( javaExecutable ) ); - } - else - { - getLog().warn( "Found unknown throws '" + exceptionClassName + "' defined on " - + getJavaMethodAsString( javaExecutable ) ); - - sb.append( originalJavadocTag ); - - if ( params.size() == 1 ) - { - sb.append( " if any." ); - } - - javaEntityTags.putJavadocThrowsTag( exceptionClassName, originalJavadocTag ); - } - } - - /** - * Add missing tags not already written. - * - * @param sb not null - * @param entity not null - * @param indent not null - * @param isJavaExecutable - * @param javaEntityTags not null - * @throws MojoExecutionException if any - */ - private void addMissingJavadocTags( final StringBuilder sb, final JavaAnnotatedElement entity, - final String indent, final boolean isJavaExecutable, - final JavaEntityTags javaEntityTags ) - throws MojoExecutionException - { - if ( isJavaExecutable ) - { - JavaExecutable javaExecutable = (JavaExecutable) entity; - - if ( fixTag( PARAM_TAG ) ) - { - if ( javaExecutable.getParameters() != null ) - { - for ( JavaParameter javaParameter : javaExecutable.getParameters() ) - { - if ( !javaEntityTags.hasJavadocParamTag( javaParameter.getName() ) ) - { - appendDefaultParamTag( sb, indent, javaParameter ); - } - } - } - // is generic? - if ( javaExecutable.getTypeParameters() != null ) - { - for ( JavaTypeVariable typeParam : javaExecutable.getTypeParameters() ) - { - if ( !javaEntityTags.hasJavadocParamTag( "<" + typeParam.getName() + ">" ) ) - { - appendDefaultParamTag( sb, indent, typeParam ); - } - } - } - } - - if ( javaExecutable instanceof JavaMethod ) - { - JavaMethod javaMethod = (JavaMethod) javaExecutable; - if ( fixTag( RETURN_TAG ) && StringUtils.isEmpty( javaEntityTags.getJavadocReturnTag() ) - && javaMethod.getReturns() != null && !javaMethod.getReturns().isVoid() ) - { - appendDefaultReturnTag( sb, indent, javaMethod ); - } - } - - if ( fixTag( THROWS_TAG ) && javaExecutable.getExceptions() != null ) - { - for ( JavaType exception : javaExecutable.getExceptions() ) - { - if ( javaEntityTags.getJavadocThrowsTag( exception.getValue(), true ) == null ) - { - appendDefaultThrowsTag( sb, indent, exception ); - } - } - } - } - else - { - if ( !javaEntityTags.getNamesTags().contains( AUTHOR_TAG ) ) - { - appendDefaultAuthorTag( sb, indent ); - } - if ( !javaEntityTags.getNamesTags().contains( VERSION_TAG ) ) - { - appendDefaultVersionTag( sb, indent ); - } - } - - if ( fixTag( SINCE_TAG ) && !javaEntityTags.getNamesTags().contains( SINCE_TAG ) ) - { - if ( !isJavaExecutable ) - { - if ( !ignoreClirr ) - { - if ( isNewClassFromLastVersion( (JavaClass) entity ) ) - { - appendDefaultSinceTag( sb, indent ); - } - } - else - { - appendDefaultSinceTag( sb, indent ); - addSinceClasses( (JavaClass) entity ); - } - } - else - { - if ( !ignoreClirr ) - { - if ( isNewMethodFromLastRevision( (JavaExecutable) entity ) ) - { - appendDefaultSinceTag( sb, indent ); - } - } - else if ( sinceClasses != null ) - { - if ( entity instanceof JavaMember - && !sinceClassesContains( ( (JavaMember) entity ).getDeclaringClass() ) ) - { - appendDefaultSinceTag( sb, indent ); - } - else if ( entity instanceof JavaClass - && !sinceClassesContains( ( (JavaClass) entity ).getDeclaringClass() ) ) - { - appendDefaultSinceTag( sb, indent ); - } - } - } - } - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @return true if separator has been added. - */ - private boolean appendDefaultAuthorTag( final StringBuilder sb, final String indent, boolean separatorAdded ) - { - if ( !fixTag( AUTHOR_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultAuthorTag( sb, indent ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - */ - private void appendDefaultAuthorTag( final StringBuilder sb, final String indent ) - { - if ( !fixTag( AUTHOR_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( AUTHOR_TAG ).append( " " ); - sb.append( defaultAuthor ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @return true if separator has been added. - */ - private boolean appendDefaultSinceTag( final StringBuilder sb, final String indent, boolean separatorAdded ) - { - if ( !fixTag( SINCE_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultSinceTag( sb, indent ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - */ - private void appendDefaultSinceTag( final StringBuilder sb, final String indent ) - { - if ( !fixTag( SINCE_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( SINCE_TAG ).append( " " ); - sb.append( defaultSince ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @return true if separator has been added. - */ - private boolean appendDefaultVersionTag( final StringBuilder sb, final String indent, boolean separatorAdded ) - { - if ( !fixTag( VERSION_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultVersionTag( sb, indent ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - */ - private void appendDefaultVersionTag( final StringBuilder sb, final String indent ) - { - if ( !fixTag( VERSION_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( VERSION_TAG ).append( " " ); - sb.append( defaultVersion ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @param typeParam not null - * @return true if separator has been added. - */ - private boolean appendDefaultParamTag( final StringBuilder sb, final String indent, boolean separatorAdded, - final JavaParameter typeParam ) - { - if ( !fixTag( PARAM_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultParamTag( sb, indent, typeParam ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @param typeParameter not null - * @return true if separator has been added. - */ - private boolean appendDefaultParamTag( final StringBuilder sb, final String indent, boolean separatorAdded, - final JavaTypeVariable typeParameter ) - { - if ( !fixTag( PARAM_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultParamTag( sb, indent, typeParameter ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - * @param typeParam not null - */ - private void appendDefaultParamTag( final StringBuilder sb, final String indent, final JavaParameter typeParam ) - { - if ( !fixTag( PARAM_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( PARAM_TAG ).append( " " ); - sb.append( typeParam.getName() ); - sb.append( " " ); - sb.append( getDefaultJavadocForType( typeParam.getJavaClass() ) ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param typeParameter not null - */ - private void appendDefaultParamTag( final StringBuilder sb, final String indent, - final JavaTypeVariable typeParameter ) - { - if ( !fixTag( PARAM_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( PARAM_TAG ).append( " " ); - sb.append( "<" ).append( typeParameter.getName() ).append( ">" ); - sb.append( " " ); - sb.append( getDefaultJavadocForType( typeParameter ) ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @param javaMethod not null - * @return true if separator has been added. - */ - private boolean appendDefaultReturnTag( final StringBuilder sb, final String indent, boolean separatorAdded, - final JavaMethod javaMethod ) - { - if ( !fixTag( RETURN_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultReturnTag( sb, indent, javaMethod ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - * @param javaMethod not null - */ - private void appendDefaultReturnTag( final StringBuilder sb, final String indent, final JavaMethod javaMethod ) - { - if ( !fixTag( RETURN_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( RETURN_TAG ).append( " " ); - sb.append( getDefaultJavadocForType( javaMethod.getReturns() ) ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - * @param separatorAdded - * @param exception not null - * @return true if separator has been added. - */ - private boolean appendDefaultThrowsTag( final StringBuilder sb, final String indent, boolean separatorAdded, - final JavaType exception ) - { - if ( !fixTag( THROWS_TAG ) ) - { - return separatorAdded; - } - - if ( !separatorAdded ) - { - appendSeparator( sb, indent ); - separatorAdded = true; - } - - appendDefaultThrowsTag( sb, indent, exception ); - return separatorAdded; - } - - /** - * @param sb not null - * @param indent not null - * @param exception not null - */ - private void appendDefaultThrowsTag( final StringBuilder sb, final String indent, final JavaType exception ) - { - if ( !fixTag( THROWS_TAG ) ) - { - return; - } - - sb.append( indent ).append( " * @" ).append( THROWS_TAG ).append( " " ); - sb.append( exception.getFullyQualifiedName() ); - sb.append( " if any." ); - sb.append( EOL ); - } - - /** - * @param sb not null - * @param indent not null - */ - private void appendSeparator( final StringBuilder sb, final String indent ) - { - sb.append( indent ).append( " *" ); - sb.append( EOL ); - } - - /** - * Verify if a method has @java.lang.Override() annotation or if it is an inherited method - * from an interface or a super class. The goal is to handle {@inheritDoc} tag. - * - * @param javaMethod not null - * @return true if the method is inherited, false otherwise. - * @throws MojoExecutionException if any - */ - private boolean isInherited( JavaExecutable javaMethod ) - throws MojoExecutionException - { - if ( javaMethod.getAnnotations() != null ) - { - for ( JavaAnnotation annotation : javaMethod.getAnnotations() ) - { - if ( annotation.toString().equals( "@java.lang.Override()" ) ) - { - return true; - } - } - } - - Class clazz = getClass( javaMethod.getDeclaringClass().getFullyQualifiedName() ); - - List> interfaces = ClassUtils.getAllInterfaces( clazz ); - for ( Class intface : interfaces ) - { - if ( isInherited( intface, javaMethod ) ) - { - return true; - } - } - - List> classes = ClassUtils.getAllSuperclasses( clazz ); - for ( Class superClass : classes ) - { - if ( isInherited( superClass, javaMethod ) ) - { - return true; - } - } - - return false; - } - - /** - * @param clazz the Java class object, not null - * @param javaMethod the QDox JavaMethod object not null - * @return true if javaMethod exists in the given clazz, - * false otherwise. - * @see #isInherited(JavaExecutable) - */ - private boolean isInherited( Class clazz, JavaExecutable javaMethod ) - { - for ( Method method : clazz.getDeclaredMethods() ) - { - if ( !method.getName().equals( javaMethod.getName() ) ) - { - continue; - } - - if ( method.getParameterTypes().length != javaMethod.getParameters().size() ) - { - continue; - } - - boolean found = false; - int j = 0; - for ( Class paramType : method.getParameterTypes() ) - { - String name1 = paramType.getName(); - String name2 = javaMethod.getParameters().get( j++ ).getType().getFullyQualifiedName(); - found = name1.equals( name2 ); // TODO check algo, seems broken (only takes in account the last param) - } - - return found; - } - - return false; - } - - /** - * @param clazz - * @return - */ - private String getDefaultJavadocForType( JavaClass clazz ) - { - StringBuilder sb = new StringBuilder(); - - if ( !JavaTypeVariable.class.isAssignableFrom( clazz.getClass() ) && clazz.isPrimitive() ) - { - if ( clazz.isArray() ) - { - sb.append( "an array of " ).append( clazz.getComponentType().getCanonicalName() ); - } - else - { - sb.append( "a " ).append( clazz.getCanonicalName() ); - } - return sb.toString(); - } - - StringBuilder javadocLink = new StringBuilder(); - try - { - getClass( clazz.getCanonicalName() ); - - javadocLink.append( "{@link " ); - - if ( clazz.isArray() ) - { - javadocLink.append( clazz.getComponentType().getCanonicalName() ); - } - else - { - javadocLink.append( clazz.getCanonicalName() ); - } - javadocLink.append( "}" ); - } - catch ( Exception e ) - { - javadocLink.append( clazz.getValue() ); - } - - if ( clazz.isArray() ) - { - sb.append( "an array of " ).append( javadocLink ).append( " objects" ); - } - else - { - sb.append( "a " ).append( javadocLink ).append( " object" ); - } - - return sb.toString(); - } - - private String getDefaultJavadocForType( JavaTypeVariable typeParameter ) - { - return "a " + typeParameter.getName() + " class"; - } - - /** - * Check under Clirr if this given class is newer from the last version. - * - * @param javaClass a given class not null - * @return true if Clirr said that this class is added from the last version, - * false otherwise or if {@link #clirrNewClasses} is null. - */ - private boolean isNewClassFromLastVersion( JavaClass javaClass ) - { - return ( clirrNewClasses != null ) && clirrNewClasses.contains( javaClass.getFullyQualifiedName() ); - } - - /** - * Check under Clirr if this given method is newer from the last version. - * - * @param javaExecutable a given method not null - * @return true if Clirr said that this method is added from the last version, - * false otherwise or if {@link #clirrNewMethods} is null. - * @throws MojoExecutionException if any - */ - private boolean isNewMethodFromLastRevision( JavaExecutable javaExecutable ) - throws MojoExecutionException - { - if ( clirrNewMethods == null ) - { - return false; - } - - List clirrMethods = clirrNewMethods.get( javaExecutable.getDeclaringClass().getFullyQualifiedName() ); - if ( clirrMethods == null ) - { - return false; - } - - for ( String clirrMethod : clirrMethods ) - { - // see net.sf.clirr.core.internal.checks.MethodSetCheck#getMethodId(JavaType clazz, Method method) - String retrn = ""; - if ( javaExecutable instanceof JavaMethod && ( (JavaMethod) javaExecutable ).getReturns() != null ) - { - retrn = ( (JavaMethod) javaExecutable ).getReturns().getFullyQualifiedName(); - } - StringBuilder params = new StringBuilder(); - for ( JavaParameter parameter : javaExecutable.getParameters() ) - { - if ( params.length() > 0 ) - { - params.append( ", " ); - } - params.append( parameter.getResolvedFullyQualifiedName() ); - } - if ( clirrMethod.contains( retrn + " " ) && clirrMethod.contains( javaExecutable.getName() + "(" ) - && clirrMethod.contains( "(" + params.toString() + ")" ) ) - { - return true; - } - } - - return false; - } - - /** - * @param className not null - * @return the Class corresponding to the given class name using the project classloader. - * @throws MojoExecutionException if class not found - * @see ClassUtils#getClass(ClassLoader, String, boolean) - * @see #getProjectClassLoader() - */ - private Class getClass( String className ) - throws MojoExecutionException - { - try - { - return ClassUtils.getClass( getProjectClassLoader(), className, false ); - } - catch ( ClassNotFoundException e ) - { - throw new MojoExecutionException( "ClassNotFoundException: " + e.getMessage(), e ); - } - } - - /** - * Returns the Class object assignable for {@link RuntimeException} class and associated with the given - * exception class name. - * - * @param currentClass not null - * @param exceptionClassName not null, an exception class name defined as: - *
    - *
  • exception class fully qualified
  • - *
  • exception class in the same package
  • - *
  • exception inner class
  • - *
  • exception class in java.lang package
  • - *
- * @return the class if found, otherwise {@code null}. - * @see #getClass(String) - */ - private Class getClass( JavaClass currentClass, String exceptionClassName ) - { - String[] potentialClassNames = - new String[]{ exceptionClassName, currentClass.getPackage().getName() + "." + exceptionClassName, - currentClass.getPackage().getName() + "." + currentClass.getName() + "$" + exceptionClassName, - "java.lang." + exceptionClassName }; - - Class clazz = null; - for ( String potentialClassName : potentialClassNames ) - { - try - { - clazz = getClass( potentialClassName ); - } - catch ( MojoExecutionException e ) - { - // nop - } - if ( clazz != null ) - { - return clazz; - } - } - - return null; - } - - /** - * @param javaClass not null - */ - private void addSinceClasses( JavaClass javaClass ) - { - if ( sinceClasses == null ) - { - sinceClasses = new ArrayList<>(); - } - sinceClasses.add( javaClass.getFullyQualifiedName() ); - } - - private boolean sinceClassesContains( JavaClass javaClass ) - { - return sinceClasses.contains( javaClass.getFullyQualifiedName() ); - } - - // ---------------------------------------------------------------------- - // Static methods - // ---------------------------------------------------------------------- - - /** - * Write content into the given javaFile and using the given encoding. - * All line separators will be unified. - * - * @param javaFile not null - * @param encoding not null - * @param content not null - * @throws IOException if any - */ - private static void writeFile( final File javaFile, final String encoding, final String content ) - throws IOException - { - String unified = StringUtils.unifyLineSeparators( content ); - FileUtils.fileWrite( javaFile, encoding, unified ); - } - - /** - * @return the full clirr goal, i.e. groupId:artifactId:version:goal. The clirr-plugin version - * could be load from the pom.properties in the clirr-maven-plugin dependency. - */ - private static String getFullClirrGoal() - { - StringBuilder sb = new StringBuilder(); - - sb.append( CLIRR_MAVEN_PLUGIN_GROUPID ).append( ":" ).append( CLIRR_MAVEN_PLUGIN_ARTIFACTID ).append( ":" ); - - String clirrVersion = CLIRR_MAVEN_PLUGIN_VERSION; - - String resource = "META-INF/maven/" + CLIRR_MAVEN_PLUGIN_GROUPID + "/" + CLIRR_MAVEN_PLUGIN_ARTIFACTID - + "/pom.properties"; - - try ( InputStream resourceAsStream = - AbstractFixJavadocMojo.class.getClassLoader().getResourceAsStream( resource ) ) - { - - if ( resourceAsStream != null ) - { - Properties properties = new Properties(); - properties.load( resourceAsStream ); - if ( StringUtils.isNotEmpty( properties.getProperty( "version" ) ) ) - { - clirrVersion = properties.getProperty( "version" ); - } - } - } - catch ( IOException e ) - { - // nop - } - - sb.append( clirrVersion ).append( ":" ).append( CLIRR_MAVEN_PLUGIN_GOAL ); - - return sb.toString(); - } - - /** - * Default comment for class. - * - * @param javaClass not null - * @return a default comment for class. - */ - private static String getDefaultClassJavadocComment( final JavaClass javaClass ) - { - StringBuilder sb = new StringBuilder(); - - sb.append( "

" ); - if ( javaClass.isAbstract() ) - { - sb.append( "Abstract " ); - } - - sb.append( javaClass.getName() ); - - if ( !javaClass.isInterface() ) - { - sb.append( " class." ); - } - else - { - sb.append( " interface." ); - } - - sb.append( "

" ); - - return sb.toString(); - } - - /** - * Default comment for method with taking care of getter/setter in the javaMethod name. - * - * @param javaExecutable not null - * @return a default comment for method - */ - private static String getDefaultMethodJavadocComment( final JavaExecutable javaExecutable ) - { - if ( javaExecutable instanceof JavaConstructor ) - { - return "

Constructor for " + javaExecutable.getName() + ".

"; - } - - if ( javaExecutable.getName().length() > 3 && ( javaExecutable.getName().startsWith( "get" ) - || javaExecutable.getName().startsWith( "set" ) ) ) - { - String field = StringUtils.lowercaseFirstLetter( javaExecutable.getName().substring( 3 ) ); - - JavaClass clazz = javaExecutable.getDeclaringClass(); - - if ( clazz.getFieldByName( field ) == null ) - { - return "

" + javaExecutable.getName() + ".

"; - } - - StringBuilder sb = new StringBuilder(); - - sb.append( "

" ); - if ( javaExecutable.getName().startsWith( "get" ) ) - { - sb.append( "Getter " ); - } - else if ( javaExecutable.getName().startsWith( "set" ) ) - { - sb.append( "Setter " ); - } - sb.append( "for the field " ).append( field ).append( ".

" ); - - return sb.toString(); - } - - return "

" + javaExecutable.getName() + ".

"; - } - - /** - * Try to find if a Javadoc comment has an {@link #INHERITED_TAG} for instance: - *
-     * /** {@inheritDoc} */
-     * 
- * or - *
-     * /**
-     *  * {@inheritDoc}
-     *  */
-     * 
- * - * @param content not null - * @return true if the content has an inherited tag, false otherwise. - */ - private static boolean hasInheritedTag( final String content ) - { - final String inheritedTagPattern = - "^\\s*(\\/\\*\\*)?(\\s*(\\*)?)*(\\{)@inheritDoc\\s*(\\})(\\s*(\\*)?)*(\\*\\/)?$"; - return Pattern.matches( inheritedTagPattern, StringUtils.removeDuplicateWhitespace( content ) ); - } - - /** - * Workaround for QDOX-146 about whitespace. - * Ideally we want to use entity.getComment() - *
- * For instance, with the following snippet: - *
- *

- * - * 1 
- * 2      - * /**
- * 3       - * * Dummy Javadoc comment.
- * 4       - * @param  - * s a String
- * 5       - * */
- * 6      - * public void  - * dummyMethod - * String s ){}
- *
- *

- *
- * The return will be: - *
- *

- * - * 1       - * * Dummy Javadoc comment.
- *
- * - * @param javaClassContent original class content not null - * @param entity not null - * @return the javadoc comment for the entity without any tags. - * @throws IOException if any - */ - static String getJavadocComment( final String javaClassContent, final JavaAnnotatedElement entity ) - throws IOException - { - if ( entity.getComment() == null ) - { - return ""; - } - - String originalJavadoc = extractOriginalJavadocContent( javaClassContent, entity ); - - StringBuilder sb = new StringBuilder(); - BufferedReader lr = new BufferedReader( new StringReader( originalJavadoc ) ); - String line; - while ( ( line = lr.readLine() ) != null ) - { - String l = StringUtils.removeDuplicateWhitespace( line.trim() ); - if ( l.startsWith( "* @" ) || l.startsWith( "*@" ) ) - { - break; - } - sb.append( line ).append( EOL ); - } - - return trimRight( sb.toString() ); - } - - /** - * Work around for QDOX-146 about whitespace. - * Ideally we want to use docletTag.getValue() - *
- * For instance, with the following snippet: - *
- *

- * - * 1 
- * 2      - * /**
- * 3       - * * Dummy Javadoc comment.
- * 4       - * @param  - * s a String
- * 5       - * */
- * 6      - * public void  - * dummyMethod - * String s ){}
- *
- *

- *
- * The return will be: - *
- *

- * - * 1       - * @param  - * s a String
- *
- * - * @param javaClassContent original class content not null - * @param entity not null - * @param docletTag not null - * @return the javadoc comment for the entity without Javadoc tags. - * @throws IOException if any - */ - String getJavadocComment( final String javaClassContent, final JavaAnnotatedElement entity, - final DocletTag docletTag ) - throws IOException - { - if ( docletTag.getValue() == null || docletTag.getParameters().isEmpty() ) - { - return ""; - } - - String originalJavadoc = extractOriginalJavadocContent( javaClassContent, entity ); - - StringBuilder sb = new StringBuilder(); - BufferedReader lr = new BufferedReader( new StringReader( originalJavadoc ) ); - String line; - boolean found = false; - - // matching first line of doclettag - Pattern p = Pattern.compile( "(\\s*\\*\\s?@" + docletTag.getName() + ")\\s+" - + "(\\Q" + docletTag.getValue().split( "\r\n|\r|\n" )[0] + "\\E)" ); - - while ( ( line = lr.readLine() ) != null ) - { - Matcher m = p.matcher( line ); - if ( m.matches() ) - { - if ( fixTag( LINK_TAG ) ) - { - line = replaceLinkTags( line, entity ); - } - sb.append( line ).append( EOL ); - found = true; - } - else - { - if ( line.trim().startsWith( "* @" ) || line.trim().startsWith( "*@" ) ) - { - found = false; - } - if ( found ) - { - if ( fixTag( LINK_TAG ) ) - { - line = replaceLinkTags( line, entity ); - } - sb.append( line ).append( EOL ); - } - } - } - - return trimRight( sb.toString() ); - } - - /** - * Extract the original Javadoc and others comments up to {@link #START_JAVADOC} form the entity. This method - * takes care of the Javadoc indentation. All javadoc lines will be trimmed on right. - *
- * For instance, with the following snippet: - *
- *

- * - * 1 
- * 2      - * /**
- * 3       - * * Dummy Javadoc comment.
- * 4       - * @param  - * s a String
- * 5       - * */
- * 6      - * public void  - * dummyMethod - * String s ){}
- *
- *

- *
- * The return will be: - *
- *

- * - * 1      - * /**
- * 2       - * * Dummy Javadoc comment.
- * 3       - * @param  - * s a String
- * 4       - * */
- *
- * - * @param javaClassContent not null - * @param entity not null - * @return return the original javadoc as String for the current entity - * @throws IOException if any - */ - static String extractOriginalJavadoc( final String javaClassContent, final JavaAnnotatedElement entity ) - throws IOException - { - if ( entity.getComment() == null ) - { - return ""; - } - - String[] javaClassContentLines = getLines( javaClassContent ); - List list = new LinkedList<>(); - for ( int i = entity.getLineNumber() - 2; i >= 0; i-- ) - { - String line = javaClassContentLines[i]; - - list.add( trimRight( line ) ); - if ( line.trim().startsWith( START_JAVADOC ) ) - { - break; - } - } - - Collections.reverse( list ); - - return StringUtils.join( list.iterator(), EOL ); - } - - /** - * Extract the Javadoc comment between {@link #START_JAVADOC} and {@link #END_JAVADOC} form the entity. This method - * takes care of the Javadoc indentation. All javadoc lines will be trimmed on right. - *
- * For instance, with the following snippet: - *
- *

- * - * 1 
- * 2      - * /**
- * 3       - * * Dummy Javadoc comment.
- * 4       - * @param  - * s a String
- * 5       - * */
- * 6      - * public void  - * dummyMethod - * String s ){}
- *
- *

- *
- * The return will be: - *
- *

- * - * 1       - * * Dummy Javadoc comment.
- * 2       - * @param  - * s a String
- *
- * - * @param javaClassContent not null - * @param entity not null - * @return return the original javadoc as String for the current entity - * @throws IOException if any - */ - static String extractOriginalJavadocContent( final String javaClassContent, - final JavaAnnotatedElement entity ) - throws IOException - { - if ( entity.getComment() == null ) - { - return ""; - } - - String originalJavadoc = extractOriginalJavadoc( javaClassContent, entity ); - int index = originalJavadoc.indexOf( START_JAVADOC ); - if ( index != -1 ) - { - originalJavadoc = originalJavadoc.substring( index + START_JAVADOC.length() ); - } - index = originalJavadoc.indexOf( END_JAVADOC ); - if ( index != -1 ) - { - originalJavadoc = originalJavadoc.substring( 0, index ); - } - if ( originalJavadoc.startsWith( "\r\n" ) ) - { - originalJavadoc = originalJavadoc.substring( 2 ); - } - else if ( originalJavadoc.startsWith( "\n" ) || originalJavadoc.startsWith( "\r" ) ) - { - originalJavadoc = originalJavadoc.substring( 1 ); - } - - return trimRight( originalJavadoc ); - } - - /** - * @param content not null - * @return the content without last lines containing javadoc separator (ie * ) - * @throws IOException if any - * @see #getJavadocComment(String, JavaAnnotatedElement, DocletTag) - */ - private static String removeLastEmptyJavadocLines( final String content ) - throws IOException - { - if ( !content.contains( EOL ) ) - { - return content; - } - - String[] lines = getLines( content ); - if ( lines.length == 1 ) - { - return content; - } - - List linesList = new LinkedList<>( Arrays.asList( lines ) ); - - Collections.reverse( linesList ); - - for ( Iterator it = linesList.iterator(); it.hasNext(); ) - { - String line = it.next(); - - if ( line.trim().equals( "*" ) ) - { - it.remove(); - } - else - { - break; - } - } - - Collections.reverse( linesList ); - - return StringUtils.join( linesList.iterator(), EOL ); - } - - /** - * @param content not null - * @return the javadoc comment with the given indentation - * @throws IOException if any - * @see #getJavadocComment(String, JavaAnnotatedElement, DocletTag) - */ - private static String alignIndentationJavadocLines( final String content, final String indent ) - throws IOException - { - StringBuilder sb = new StringBuilder(); - for ( String line : getLines( content ) ) - { - if ( sb.length() > 0 ) - { - sb.append( EOL ); - } - if ( !line.trim().startsWith( "*" ) ) - { - line = "*" + line; - } - sb.append( indent ).append( " " ).append( trimLeft( line ) ); - } - - return sb.toString(); - } - - /** - * Autodetect the indentation of a given line: - *

-     * autodetectIndentation( null ) = "";
-     * autodetectIndentation( "a" ) = "";
-     * autodetectIndentation( "    a" ) = "    ";
-     * autodetectIndentation( "\ta" ) = "\t";
-     * 
- * - * @param line not null - * @return the indentation for the given line. - */ - private static String autodetectIndentation( final String line ) - { - if ( StringUtils.isEmpty( line ) ) - { - return ""; - } - - return line.substring( 0, line.indexOf( trimLeft( line ) ) ); - } - - /** - * @param content not null - * @return an array of all content lines - * @throws IOException if any - */ - private static String[] getLines( final String content ) - throws IOException - { - List lines = new LinkedList<>(); - - BufferedReader reader = new BufferedReader( new StringReader( content ) ); - String line = reader.readLine(); - while ( line != null ) - { - lines.add( line ); - line = reader.readLine(); - } - - return lines.toArray( new String[lines.size()] ); - } - - /** - * Trim a given line on the left: - *
-     * trimLeft( null ) = "";
-     * trimLeft( "  " ) = "";
-     * trimLeft( "a" ) = "a";
-     * trimLeft( "    a" ) = "a";
-     * trimLeft( "\ta" ) = "a";
-     * trimLeft( "    a    " ) = "a    ";
-     * 
- * - * @param text - * @return the text trimmed on left side or empty if text is null. - */ - private static String trimLeft( final String text ) - { - if ( StringUtils.isEmpty( text ) || StringUtils.isEmpty( text.trim() ) ) - { - return ""; - } - - String textTrimmed = text.trim(); - return text.substring( text.indexOf( textTrimmed ) ); - } - - /** - * Trim a given line on the right: - *
-     * trimRight( null ) = "";
-     * trimRight( "  " ) = "";
-     * trimRight( "a" ) = "a";
-     * trimRight( "a\t" ) = "a";
-     * trimRight( "    a    " ) = "    a";
-     * 
- * - * @param text - * @return the text trimmed on tight side or empty if text is null. - */ - private static String trimRight( final String text ) - { - if ( StringUtils.isEmpty( text ) || StringUtils.isEmpty( text.trim() ) ) - { - return ""; - } - - String textTrimmed = text.trim(); - return text.substring( 0, text.indexOf( textTrimmed ) + textTrimmed.length() ); - } - - - /** - * Wrapper class for the entity's tags. - */ - class JavaEntityTags - { - private final JavaAnnotatedElement entity; - - private final boolean isJavaMethod; - - /** - * List of tag names. - */ - private List namesTags; - - /** - * Map with java parameter as key and original Javadoc lines as values. - */ - private Map tagParams; - - private Set documentedParams = new HashSet<>(); - - /** - * Original javadoc lines. - */ - private String tagReturn; - - /** - * Map with java throw as key and original Javadoc lines as values. - */ - private Map tagThrows; - - /** - * Original javadoc lines for unknown tags. - */ - private List unknownsTags; - - JavaEntityTags( JavaAnnotatedElement entity, boolean isJavaMethod ) - { - this.entity = entity; - this.isJavaMethod = isJavaMethod; - this.namesTags = new LinkedList<>(); - this.tagParams = new LinkedHashMap<>(); - this.tagThrows = new LinkedHashMap<>(); - this.unknownsTags = new LinkedList<>(); - } - - public List getNamesTags() - { - return namesTags; - } - - public String getJavadocReturnTag() - { - return tagReturn; - } - - public void setJavadocReturnTag( String s ) - { - tagReturn = s; - } - - public List getUnknownTags() - { - return unknownsTags; - } - - public void putJavadocParamTag( String paramName, String paramValue, String originalJavadocTag ) - { - documentedParams.add( paramName ); - tagParams.put( paramValue, originalJavadocTag ); - } - - public String getJavadocParamTag( String paramValue ) - { - String originalJavadocTag = tagParams.get( paramValue ); - if ( originalJavadocTag == null && getLog().isWarnEnabled() ) - { - getLog().warn( getMessage( paramValue, "javaEntityTags.tagParams" ) ); - } - return originalJavadocTag; - } - - public boolean hasJavadocParamTag( String paramName ) - { - return documentedParams.contains( paramName ); - } - - public void putJavadocThrowsTag( String paramName, String originalJavadocTag ) - { - tagThrows.put( paramName, originalJavadocTag ); - } - - public String getJavadocThrowsTag( String paramName ) - { - return getJavadocThrowsTag( paramName, false ); - } - - public String getJavadocThrowsTag( String paramName, boolean nullable ) - { - String originalJavadocTag = tagThrows.get( paramName ); - if ( !nullable && originalJavadocTag == null && getLog().isWarnEnabled() ) - { - getLog().warn( getMessage( paramName, "javaEntityTags.tagThrows" ) ); - } - - return originalJavadocTag; - } - - private String getMessage( String paramName, String mapName ) - { - StringBuilder msg = new StringBuilder(); - msg.append( "No param '" ).append( paramName ).append( "' key found in " ).append( mapName ) - .append( " for the entity: " ); - if ( isJavaMethod ) - { - JavaMethod javaMethod = (JavaMethod) entity; - msg.append( getJavaMethodAsString( javaMethod ) ); - } - else - { - JavaClass javaClass = (JavaClass) entity; - msg.append( javaClass.getFullyQualifiedName() ); - } - - return msg.toString(); - } - - /** - * {@inheritDoc} - */ - @Override - public String toString() - { - StringBuilder sb = new StringBuilder(); - - sb.append( "namesTags=" ).append( namesTags ).append( "\n" ); - sb.append( "tagParams=" ).append( tagParams ).append( "\n" ); - sb.append( "tagReturn=" ).append( tagReturn ).append( "\n" ); - sb.append( "tagThrows=" ).append( tagThrows ).append( "\n" ); - sb.append( "unknownsTags=" ).append( unknownsTags ).append( "\n" ); - - return sb.toString(); - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.StringReader; +import java.io.StringWriter; +import java.lang.reflect.Method; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.library.ClassLibraryBuilder; +import com.thoughtworks.qdox.library.OrderedClassLibraryBuilder; +import com.thoughtworks.qdox.model.DocletTag; +import com.thoughtworks.qdox.model.JavaAnnotatedElement; +import com.thoughtworks.qdox.model.JavaAnnotation; +import com.thoughtworks.qdox.model.JavaClass; +import com.thoughtworks.qdox.model.JavaConstructor; +import com.thoughtworks.qdox.model.JavaExecutable; +import com.thoughtworks.qdox.model.JavaField; +import com.thoughtworks.qdox.model.JavaGenericDeclaration; +import com.thoughtworks.qdox.model.JavaMember; +import com.thoughtworks.qdox.model.JavaMethod; +import com.thoughtworks.qdox.model.JavaParameter; +import com.thoughtworks.qdox.model.JavaType; +import com.thoughtworks.qdox.model.JavaTypeVariable; +import com.thoughtworks.qdox.parser.ParseException; +import com.thoughtworks.qdox.type.TypeResolver; +import org.apache.commons.lang3.ClassUtils; +import org.apache.commons.text.StringEscapeUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.AbstractMojo; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Settings; +import org.apache.maven.shared.invoker.MavenInvocationException; +import org.codehaus.plexus.components.interactivity.InputHandler; +import org.codehaus.plexus.languages.java.version.JavaVersion; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.ReaderFactory; +import org.codehaus.plexus.util.StringUtils; + +/** + * Abstract class to fix Javadoc documentation and tags in source files. + * @see Where Tags + * Can Be Used. + * @author Vincent Siveton + * @since 2.6 + */ +public abstract class AbstractFixJavadocMojo extends AbstractMojo { + /** + * The vm line separator + */ + private static final String EOL = System.getProperty("line.separator"); + + /** + * Tag name for @author * + */ + private static final String AUTHOR_TAG = "author"; + + /** + * Tag name for @version * + */ + private static final String VERSION_TAG = "version"; + + /** + * Tag name for @since * + */ + private static final String SINCE_TAG = "since"; + + /** + * Tag name for @param * + */ + private static final String PARAM_TAG = "param"; + + /** + * Tag name for @return * + */ + private static final String RETURN_TAG = "return"; + + /** + * Tag name for @throws * + */ + private static final String THROWS_TAG = "throws"; + + /** + * Tag name for @link * + */ + private static final String LINK_TAG = "link"; + + /** + * Tag name for {@inheritDoc} * + */ + private static final String INHERITED_TAG = "{@inheritDoc}"; + + /** + * Start Javadoc String i.e. /** * + */ + private static final String START_JAVADOC = "/**"; + + /** + * End Javadoc String i.e. */ * + */ + private static final String END_JAVADOC = "*/"; + + /** + * Javadoc Separator i.e. * * + */ + private static final String SEPARATOR_JAVADOC = " * "; + + /** + * Inherited Javadoc i.e. /** {@inheritDoc} */ * + */ + private static final String INHERITED_JAVADOC = START_JAVADOC + " " + INHERITED_TAG + " " + END_JAVADOC; + + /** + * all parameter used by {@link #fixTags} * + */ + private static final String FIX_TAGS_ALL = "all"; + + /** + * public parameter used by {@link #level} * + */ + private static final String LEVEL_PUBLIC = "public"; + + /** + * protected parameter used by {@link #level} * + */ + private static final String LEVEL_PROTECTED = "protected"; + + /** + * package parameter used by {@link #level} * + */ + private static final String LEVEL_PACKAGE = "package"; + + /** + * private parameter used by {@link #level} * + */ + private static final String LEVEL_PRIVATE = "private"; + + /** + * The Clirr Maven plugin groupId org.codehaus.mojo * + */ + private static final String CLIRR_MAVEN_PLUGIN_GROUPID = "org.codehaus.mojo"; + + /** + * The Clirr Maven plugin artifactId clirr-maven-plugin * + */ + private static final String CLIRR_MAVEN_PLUGIN_ARTIFACTID = "clirr-maven-plugin"; + + /** + * The latest Clirr Maven plugin version 2.2.2 * + */ + private static final String CLIRR_MAVEN_PLUGIN_VERSION = "2.2.2"; + + /** + * The Clirr Maven plugin goal check * + */ + private static final String CLIRR_MAVEN_PLUGIN_GOAL = "check"; + + /** + * Java Files Pattern. + */ + public static final String JAVA_FILES = "**\\/*.java"; + + /** + * Default version value. + */ + public static final String DEFAULT_VERSION_VALUE = "\u0024Id: \u0024Id"; + + // ---------------------------------------------------------------------- + // Mojo components + // ---------------------------------------------------------------------- + + /** + * Input handler, needed for command line handling. + */ + @Component + private InputHandler inputHandler; + + // ---------------------------------------------------------------------- + // Mojo parameters + // ---------------------------------------------------------------------- + + /** + * Version to compare the current code against using the + * Clirr Maven Plugin. + *
+ * See defaultSince. + */ + @Parameter(property = "comparisonVersion", defaultValue = "(,${project.version})") + private String comparisonVersion; + + /** + * Default value for the Javadoc tag @author. + *
+ * If not specified, the user.name defined in the System properties will be used. + */ + @Parameter(property = "defaultAuthor") + private String defaultAuthor; + + /** + * Default value for the Javadoc tag @since. + */ + @Parameter(property = "defaultSince", defaultValue = "${project.version}") + private String defaultSince; + + /** + * Default value for the Javadoc tag @version. + *
+ * By default, it is $Id:$, corresponding to a + * SVN keyword. + * Refer to your SCM to use an other SCM keyword. + */ + @Parameter(property = "defaultVersion", defaultValue = DEFAULT_VERSION_VALUE) + private String defaultVersion = "\u0024Id: \u0024"; // can't use default-value="\u0024Id: \u0024" + + /** + * The file encoding to use when reading the source files. If the property + * project.build.sourceEncoding is not set, the platform default encoding is used. + */ + @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}") + private String encoding; + + /** + * Comma separated excludes Java files, i.e. **/*Test.java. + */ + @Parameter(property = "excludes") + private String excludes; + + /** + * Comma separated tags to fix in classes, interfaces or methods Javadoc comments. + * Possible values are: + *
    + *
  • all (fix all Javadoc tags)
  • + *
  • author (fix only @author tag)
  • + *
  • version (fix only @version tag)
  • + *
  • since (fix only @since tag)
  • + *
  • param (fix only @param tag)
  • + *
  • return (fix only @return tag)
  • + *
  • throws (fix only @throws tag)
  • + *
  • link (fix only @link tag)
  • + *
+ */ + @Parameter(property = "fixTags", defaultValue = "all") + private String fixTags; + + /** + * Flag to fix the classes or interfaces Javadoc comments according the level. + */ + @Parameter(property = "fixClassComment", defaultValue = "true") + private boolean fixClassComment; + + /** + * Flag to fix the fields Javadoc comments according the level. + */ + @Parameter(property = "fixFieldComment", defaultValue = "true") + private boolean fixFieldComment; + + /** + * Flag to fix the methods Javadoc comments according the level. + */ + @Parameter(property = "fixMethodComment", defaultValue = "true") + private boolean fixMethodComment; + + /** + *

Flag to remove throws tags from unknown classes.

+ *

NOTE:Since 3.1.0 the default value has been changed to {@code true}, + * due to JavaDoc 8 strictness. + */ + @Parameter(property = "removeUnknownThrows", defaultValue = "true") + private boolean removeUnknownThrows; + + /** + * Forcing the goal execution i.e. skip warranty messages (not recommended). + */ + @Parameter(property = "force") + private boolean force; + + /** + * Flag to ignore or not Clirr. + */ + @Parameter(property = "ignoreClirr", defaultValue = "false") + protected boolean ignoreClirr; + + /** + * Comma separated includes Java files, i.e. **/*Test.java. + *

+ * Note: default value is {@code **\/*.java}. + */ + @Parameter(property = "includes", defaultValue = JAVA_FILES) + private String includes; + + /** + * Specifies the access level for classes and members to show in the Javadocs. + * Possible values are: + *

    + *
  • public (shows only public classes and members)
  • + *
  • protected (shows only public and protected classes and members)
  • + *
  • package (shows all classes and members not marked private)
  • + *
  • private (shows all classes and members)
  • + *
+ * @see private, protected, public, package options for Javadoc + */ + @Parameter(property = "level", defaultValue = "protected") + private String level; + + /** + * The local repository where the artifacts are located, used by the tests. + */ + @Parameter(property = "localRepository") + private ArtifactRepository localRepository; + + /** + * Output directory where Java classes will be rewritten. + */ + @Parameter(property = "outputDirectory", defaultValue = "${project.build.sourceDirectory}") + private File outputDirectory; + + /** + * The Maven Project Object. + */ + @Parameter(defaultValue = "${project}", readonly = true, required = true) + private MavenProject project; + + @Parameter(defaultValue = "${session}", readonly = true, required = true) + private MavenSession session; + + /** + * The current user system settings for use in Maven. + */ + @Parameter(defaultValue = "${settings}", readonly = true, required = true) + private Settings settings; + + // ---------------------------------------------------------------------- + // Internal fields + // ---------------------------------------------------------------------- + + /** + * The current project class loader. + */ + private ClassLoader projectClassLoader; + + /** + * Split {@link #fixTags} by comma. + * + * @see #init() + */ + private String[] fixTagsSplitted; + + /** + * New classes found by Clirr. + */ + private List clirrNewClasses; + + /** + * New Methods in a Class (the key) found by Clirr. + */ + private Map> clirrNewMethods; + + /** + * List of classes where *since is added. Will be used to add or not this tag in the methods. + */ + private List sinceClasses; + + /** + * {@inheritDoc} + */ + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + if (!fixClassComment && !fixFieldComment && !fixMethodComment) { + getLog().info("Specified to NOT fix classes, fields and methods. Nothing to do."); + return; + } + + // verify goal params + init(); + + if (fixTagsSplitted.length == 0) { + getLog().info("No fix tag specified. Nothing to do."); + return; + } + + // add warranty msg + if (!preCheck()) { + return; + } + + // run clirr + try { + executeClirr(); + } catch (MavenInvocationException e) { + if (getLog().isDebugEnabled()) { + getLog().error("MavenInvocationException: " + e.getMessage(), e); + } else { + getLog().error("MavenInvocationException: " + e.getMessage()); + } + getLog().info("Clirr is ignored."); + } + + // run qdox and process + try { + Collection javaClasses = getQdoxClasses(); + + if (javaClasses != null) { + for (JavaClass javaClass : javaClasses) { + processFix(javaClass); + } + } + } catch (IOException e) { + throw new MojoExecutionException("IOException: " + e.getMessage(), e); + } + } + + // ---------------------------------------------------------------------- + // protected methods + // ---------------------------------------------------------------------- + + protected final MavenProject getProject() { + return project; + } + + /** + * @param p not null maven project. + * @return the artifact type. + */ + protected String getArtifactType(MavenProject p) { + return p.getArtifact().getType(); + } + + /** + * @param p not null maven project. + * @return the list of source paths for the given project. + */ + protected List getProjectSourceRoots(MavenProject p) { + return (p.getCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getCompileSourceRoots())); + } + + /** + * @param p not null + * @return the compile classpath elements + * @throws DependencyResolutionRequiredException + * if any + */ + protected List getCompileClasspathElements(MavenProject p) throws DependencyResolutionRequiredException { + return (p.getCompileClasspathElements() == null + ? Collections.emptyList() + : new LinkedList<>(p.getCompileClasspathElements())); + } + + /** + * @param javaExecutable not null + * @return the fully qualify name of javaMethod with signature + */ + protected static String getJavaMethodAsString(JavaExecutable javaExecutable) { + return javaExecutable.getDeclaringClass().getFullyQualifiedName() + "#" + javaExecutable.getCallSignature(); + } + + // ---------------------------------------------------------------------- + // private methods + // ---------------------------------------------------------------------- + + /** + * Init goal parameters. + */ + private void init() { + // defaultAuthor + if (StringUtils.isEmpty(defaultAuthor)) { + defaultAuthor = System.getProperty("user.name"); + } + + // defaultSince + int i = defaultSince.indexOf("-" + Artifact.SNAPSHOT_VERSION); + if (i != -1) { + defaultSince = defaultSince.substring(0, i); + } + + // fixTags + if (!FIX_TAGS_ALL.equalsIgnoreCase(fixTags.trim())) { + String[] split = StringUtils.split(fixTags, ","); + List filtered = new LinkedList<>(); + for (String aSplit : split) { + String s = aSplit.trim(); + if (JavadocUtil.equalsIgnoreCase( + s, + FIX_TAGS_ALL, + AUTHOR_TAG, + VERSION_TAG, + SINCE_TAG, + PARAM_TAG, + THROWS_TAG, + LINK_TAG, + RETURN_TAG)) { + filtered.add(s); + } else { + if (getLog().isWarnEnabled()) { + getLog().warn("Unrecognized '" + s + "' for fixTags parameter. Ignored it!"); + } + } + } + fixTags = StringUtils.join(filtered.iterator(), ","); + } + fixTagsSplitted = StringUtils.split(fixTags, ","); + + // encoding + if (StringUtils.isEmpty(encoding)) { + if (getLog().isWarnEnabled()) { + getLog().warn("File encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + + ", i.e. build is platform dependent!"); + } + encoding = ReaderFactory.FILE_ENCODING; + } + + // level + level = level.trim(); + if (!JavadocUtil.equalsIgnoreCase(level, LEVEL_PUBLIC, LEVEL_PROTECTED, LEVEL_PACKAGE, LEVEL_PRIVATE)) { + if (getLog().isWarnEnabled()) { + getLog().warn("Unrecognized '" + level + "' for level parameter, using 'protected' level."); + } + level = "protected"; + } + } + + /** + * @return true if the user wants to proceed, false otherwise. + * @throws MojoExecutionException if any + */ + private boolean preCheck() throws MojoExecutionException { + if (force) { + return true; + } + + if (outputDirectory != null + && !outputDirectory + .getAbsolutePath() + .equals(getProjectSourceDirectory().getAbsolutePath())) { + return true; + } + + if (!settings.isInteractiveMode()) { + getLog().error("Maven is not attempt to interact with the user for input. " + + "Verify the configuration in your settings."); + return false; + } + + getLog().warn(""); + getLog().warn(" WARRANTY DISCLAIMER"); + getLog().warn(""); + getLog().warn("All warranties with regard to this Maven goal are disclaimed!"); + getLog().warn("The changes will be done directly in the source code."); + getLog().warn("The Maven Team strongly recommends the use of a SCM software BEFORE executing this goal."); + getLog().warn(""); + + while (true) { + getLog().info("Are you sure to proceed? [Y]es [N]o"); + + try { + String userExpression = inputHandler.readLine(); + if (userExpression == null || JavadocUtil.equalsIgnoreCase(userExpression, "Y", "Yes")) { + getLog().info("OK, let's proceed..."); + break; + } + if (JavadocUtil.equalsIgnoreCase(userExpression, "N", "No")) { + getLog().info("No changes in your sources occur."); + return false; + } + } catch (IOException e) { + throw new MojoExecutionException("Unable to read from standard input.", e); + } + } + + return true; + } + + /** + * @return the source dir as File for the given project + */ + private File getProjectSourceDirectory() { + return new File(project.getBuild().getSourceDirectory()); + } + + /** + * Invoke Maven to run clirr-maven-plugin to find API differences. + * + * @throws MavenInvocationException if any + */ + private void executeClirr() throws MavenInvocationException { + if (ignoreClirr) { + getLog().info("Clirr is ignored."); + return; + } + + String clirrGoal = getFullClirrGoal(); + + // http://mojo.codehaus.org/clirr-maven-plugin/check-mojo.html + File clirrTextOutputFile = FileUtils.createTempFile( + "clirr", ".txt", new File(project.getBuild().getDirectory())); + Properties properties = new Properties(); + properties.put("textOutputFile", clirrTextOutputFile.getAbsolutePath()); + properties.put("comparisonVersion", comparisonVersion); + properties.put("failOnError", "false"); + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("8")) { + // ensure that Java7 picks up TLSv1.2 when connecting with Central + properties.put("https.protocols", "TLSv1.2"); + } + + File invokerDir = new File(project.getBuild().getDirectory(), "invoker"); + invokerDir.mkdirs(); + File invokerLogFile = FileUtils.createTempFile("clirr-maven-plugin", ".txt", invokerDir); + + JavadocUtil.invokeMaven( + getLog(), + new File(localRepository.getBasedir()), + project.getFile(), + Collections.singletonList(clirrGoal), + properties, + invokerLogFile, + session.getRequest().getGlobalSettingsFile()); + + try { + if (invokerLogFile.exists()) { + String invokerLogContent = StringUtils.unifyLineSeparators(FileUtils.fileRead(invokerLogFile, "UTF-8")); + // see org.codehaus.mojo.clirr.AbstractClirrMojo#getComparisonArtifact() + final String artifactNotFoundMsg = "Unable to find a previous version of the project in the repository"; + if (invokerLogContent.contains(artifactNotFoundMsg)) { + getLog().warn("No previous artifact has been deployed, Clirr is ignored."); + return; + } + } + } catch (IOException e) { + getLog().debug("IOException: " + e.getMessage()); + } + + try { + parseClirrTextOutputFile(clirrTextOutputFile); + } catch (IOException e) { + if (getLog().isDebugEnabled()) { + getLog().debug("IOException: " + e.getMessage(), e); + } + getLog().info("IOException when parsing Clirr output '" + clirrTextOutputFile.getAbsolutePath() + + "', Clirr is ignored."); + } + } + + /** + * @param clirrTextOutputFile not null + * @throws IOException if any + */ + private void parseClirrTextOutputFile(File clirrTextOutputFile) throws IOException { + if (!clirrTextOutputFile.exists()) { + if (getLog().isInfoEnabled()) { + getLog().info("No Clirr output file '" + clirrTextOutputFile.getAbsolutePath() + + "' exists, Clirr is ignored."); + } + return; + } + + if (getLog().isInfoEnabled()) { + getLog().info("Clirr output file was created: " + clirrTextOutputFile.getAbsolutePath()); + } + + clirrNewClasses = new LinkedList<>(); + clirrNewMethods = new LinkedHashMap<>(); + + try (BufferedReader reader = new BufferedReader(ReaderFactory.newReader(clirrTextOutputFile, "UTF-8"))) { + + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + String[] split = StringUtils.split(line, ":"); + if (split.length != 4) { + if (getLog().isDebugEnabled()) { + getLog().debug("Unable to parse the clirr line: " + line); + } + continue; + } + + int code; + try { + code = Integer.parseInt(split[1].trim()); + } catch (NumberFormatException e) { + if (getLog().isDebugEnabled()) { + getLog().debug("Unable to parse the clirr line: " + line); + } + continue; + } + + // http://clirr.sourceforge.net/clirr-core/exegesis.html + // 7011 - Method Added + // 7012 - Method Added to Interface + // 8000 - Class Added + + // CHECKSTYLE_OFF: MagicNumber + switch (code) { + case 7011: + methodAdded(split); + break; + case 7012: + methodAdded(split); + break; + case 8000: + clirrNewClasses.add(split[2].trim()); + break; + default: + break; + } + // CHECKSTYLE_ON: MagicNumber + } + } + if (clirrNewClasses.isEmpty() && clirrNewMethods.isEmpty()) { + getLog().info("Clirr NOT found API differences."); + } else { + getLog().info("Clirr found API differences, i.e. new classes/interfaces or methods."); + } + } + + private void methodAdded(String[] split) { + List list = clirrNewMethods.get(split[2].trim()); + if (list == null) { + list = new ArrayList<>(); + } + String[] splits2 = StringUtils.split(split[3].trim(), "'"); + if (splits2.length != 3) { + return; + } + list.add(splits2[1].trim()); + clirrNewMethods.put(split[2].trim(), list); + } + + /** + * @param tag not null + * @return true if tag is defined in {@link #fixTags}. + */ + private boolean fixTag(String tag) { + if (fixTagsSplitted.length == 1 && fixTagsSplitted[0].equals(FIX_TAGS_ALL)) { + return true; + } + + for (String aFixTagsSplitted : fixTagsSplitted) { + if (aFixTagsSplitted.trim().equals(tag)) { + return true; + } + } + + return false; + } + + /** + * Calling Qdox to find {@link JavaClass} objects from the Maven project sources. + * Ignore java class if Qdox has parsing errors. + * + * @return an array of {@link JavaClass} found by QDox + * @throws IOException if any + * @throws MojoExecutionException if any + */ + private Collection getQdoxClasses() throws IOException, MojoExecutionException { + if ("pom".equalsIgnoreCase(project.getPackaging())) { + getLog().warn("This project has 'pom' packaging, no Java sources is available."); + return null; + } + + List javaFiles = new LinkedList<>(); + for (String sourceRoot : getProjectSourceRoots(project)) { + File f = new File(sourceRoot); + if (f.isDirectory()) { + javaFiles.addAll(FileUtils.getFiles(f, includes, excludes, true)); + } else { + if (getLog().isWarnEnabled()) { + getLog().warn(f + " doesn't exist. Ignored it."); + } + } + } + + ClassLibraryBuilder classLibraryBuilder = new OrderedClassLibraryBuilder(); + classLibraryBuilder.appendClassLoader(getProjectClassLoader()); + + JavaProjectBuilder builder = new JavaProjectBuilder(classLibraryBuilder); + builder.setEncoding(encoding); + for (File f : javaFiles) { + if (!f.getAbsolutePath().toLowerCase(Locale.ENGLISH).endsWith(".java") && getLog().isWarnEnabled()) { + getLog().warn("'" + f + "' is not a Java file. Ignored it."); + continue; + } + + try { + builder.addSource(f); + } catch (ParseException e) { + if (getLog().isWarnEnabled()) { + getLog().warn("QDOX ParseException: " + e.getMessage() + ". Can't fix it."); + } + } + } + + return builder.getClasses(); + } + + /** + * @return the classLoader for the given project using lazy instantiation. + * @throws MojoExecutionException if any + */ + private ClassLoader getProjectClassLoader() throws MojoExecutionException { + if (projectClassLoader == null) { + List classPath; + try { + classPath = getCompileClasspathElements(project); + } catch (DependencyResolutionRequiredException e) { + throw new MojoExecutionException("DependencyResolutionRequiredException: " + e.getMessage(), e); + } + + List urls = new ArrayList<>(classPath.size()); + for (String filename : classPath) { + try { + urls.add(new File(filename).toURI().toURL()); + } catch (MalformedURLException e) { + throw new MojoExecutionException("MalformedURLException: " + e.getMessage(), e); + } + } + + projectClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null); + } + + return projectClassLoader; + } + + /** + * Process the given {@link JavaClass}, ie add missing javadoc tags depending user parameters. + * + * @param javaClass not null + * @throws IOException if any + * @throws MojoExecutionException if any + */ + private void processFix(JavaClass javaClass) throws IOException, MojoExecutionException { + // Skipping inner classes + if (javaClass.isInner()) { + return; + } + + File javaFile; + try { + javaFile = Paths.get(javaClass.getSource().getURL().toURI()).toFile(); + } catch (URISyntaxException e) { + throw new MojoExecutionException(e.getMessage()); + } + + // the original java content in memory + final String originalContent = StringUtils.unifyLineSeparators(FileUtils.fileRead(javaFile, encoding)); + + if (getLog().isDebugEnabled()) { + getLog().debug("Analyzing " + javaClass.getFullyQualifiedName()); + } + + final StringWriter stringWriter = new StringWriter(); + boolean changeDetected = false; + try (BufferedReader reader = new BufferedReader(new StringReader(originalContent))) { + + int lineNumber = 0; + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + lineNumber++; + final String indent = autodetectIndentation(line); + + // fixing classes + if (javaClass.getComment() == null + && javaClass.getAnnotations() != null + && !javaClass.getAnnotations().isEmpty()) { + if (lineNumber == javaClass.getAnnotations().get(0).getLineNumber()) { + changeDetected |= fixClassComment(stringWriter, originalContent, javaClass, indent); + + takeCareSingleComment(stringWriter, originalContent, javaClass); + } + } else if (lineNumber == javaClass.getLineNumber()) { + changeDetected |= fixClassComment(stringWriter, originalContent, javaClass, indent); + + takeCareSingleComment(stringWriter, originalContent, javaClass); + } + + // fixing fields + if (javaClass.getFields() != null) { + for (JavaField field : javaClass.getFields()) { + if (lineNumber == field.getLineNumber()) { + changeDetected |= fixFieldComment(stringWriter, javaClass, field, indent); + } + } + } + + // fixing methods + if (javaClass.getConstructors() != null) { + for (JavaConstructor method : javaClass.getConstructors()) { + if (lineNumber == method.getLineNumber()) { + final boolean commentUpdated = + fixMethodComment(stringWriter, originalContent, method, indent); + if (commentUpdated) { + takeCareSingleComment(stringWriter, originalContent, method); + } + changeDetected |= commentUpdated; + } + } + } + + // fixing methods + for (JavaMethod method : javaClass.getMethods()) { + int methodLineNumber; + if (method.getComment() == null && !method.getAnnotations().isEmpty()) { + methodLineNumber = method.getAnnotations().get(0).getLineNumber(); + } else { + methodLineNumber = method.getLineNumber(); + } + + if (lineNumber == methodLineNumber) { + final boolean commentUpdated = fixMethodComment(stringWriter, originalContent, method, indent); + if (commentUpdated) { + takeCareSingleComment(stringWriter, originalContent, method); + } + changeDetected |= commentUpdated; + } + } + + stringWriter.write(line); + stringWriter.write(EOL); + } + } + + if (changeDetected) { + if (getLog().isInfoEnabled()) { + getLog().info("Saving changes to " + javaClass.getFullyQualifiedName()); + } + + if (outputDirectory != null + && !outputDirectory + .getAbsolutePath() + .equals(getProjectSourceDirectory().getAbsolutePath())) { + String path = StringUtils.replace( + javaFile.getAbsolutePath().replaceAll("\\\\", "/"), + project.getBuild().getSourceDirectory().replaceAll("\\\\", "/"), + ""); + javaFile = new File(outputDirectory, path); + javaFile.getParentFile().mkdirs(); + } + writeFile(javaFile, encoding, stringWriter.toString()); + } else { + if (getLog().isDebugEnabled()) { + getLog().debug("No changes made to " + javaClass.getFullyQualifiedName()); + } + } + } + + /** + * Take care of block or single comments between Javadoc comment and entity declaration ie: + *
+ * + * 1   + * /**
+ * 2    + * * {Javadoc Comment}
+ * 3    + * */
+ * 4   + * /*
+ * 5    + * * {Block Comment}
+ * 6    + * */
+ * 7   + * // {Single comment}
+ * 8   + * public void  + * dummyMethod + * String s ){} + *
+ * + * @param stringWriter not null + * @param originalContent not null + * @param entity not null + * @throws IOException if any + * @see #extractOriginalJavadoc + */ + private void takeCareSingleComment( + final StringWriter stringWriter, final String originalContent, final JavaAnnotatedElement entity) + throws IOException { + if (entity.getComment() == null) { + return; + } + + String javadocComment = trimRight(extractOriginalJavadoc(originalContent, entity)); + String extraComment = javadocComment.substring(javadocComment.indexOf(END_JAVADOC) + END_JAVADOC.length()); + if (StringUtils.isNotEmpty(extraComment)) { + if (extraComment.contains(EOL)) { + stringWriter.write(extraComment.substring(extraComment.indexOf(EOL) + EOL.length())); + } else { + stringWriter.write(extraComment); + } + stringWriter.write(EOL); + } + } + + /** + * Add/update Javadoc class comment. + * + * @param stringWriter + * @param originalContent + * @param javaClass + * @param indent + * @return {@code true} if the comment is updated, otherwise {@code false} + * @throws MojoExecutionException + * @throws IOException + */ + private boolean fixClassComment( + final StringWriter stringWriter, + final String originalContent, + final JavaClass javaClass, + final String indent) + throws MojoExecutionException, IOException { + if (!fixClassComment) { + return false; + } + + if (!isInLevel(javaClass.getModifiers())) { + return false; + } + + // add + if (javaClass.getComment() == null) { + addDefaultClassComment(stringWriter, javaClass, indent); + return true; + } + + // update + return updateEntityComment(stringWriter, originalContent, javaClass, indent); + } + + /** + * @param modifiers list of modifiers (public, private, protected, package) + * @return true if modifier is align with level. + */ + private boolean isInLevel(List modifiers) { + if (LEVEL_PUBLIC.equalsIgnoreCase(level.trim())) { + return modifiers.contains(LEVEL_PUBLIC); + } + + if (LEVEL_PROTECTED.equalsIgnoreCase(level.trim())) { + return (modifiers.contains(LEVEL_PUBLIC) || modifiers.contains(LEVEL_PROTECTED)); + } + + if (LEVEL_PACKAGE.equalsIgnoreCase(level.trim())) { + return !modifiers.contains(LEVEL_PRIVATE); + } + + // should be private (shows all classes and members) + return true; + } + + /** + * Add a default Javadoc for the given class, i.e.: + *
+ * + * 1   + * /**
+ * 2    + * * {Comment based on the class name}
+ * 3    + * *
+ * 4    + * @author  + * X {added if addMissingAuthor}
+ * 5    + * @version  + * X {added if addMissingVersion}
+ * 6    + * @since  + * X {added if addMissingSince and new classes + * from previous version}
+ * 7    + * */
+ * 8 public class  + * DummyClass {}
+ * + * + * @param stringWriter not null + * @param javaClass not null + * @param indent not null + * @see #getDefaultClassJavadocComment(JavaClass) + * @see #appendDefaultAuthorTag(StringBuilder, String) + * @see #appendDefaultSinceTag(StringBuilder, String) + * @see #appendDefaultVersionTag(StringBuilder, String) + */ + private void addDefaultClassComment( + final StringWriter stringWriter, final JavaClass javaClass, final String indent) { + StringBuilder sb = new StringBuilder(); + + sb.append(indent).append(START_JAVADOC); + sb.append(EOL); + sb.append(indent).append(SEPARATOR_JAVADOC); + sb.append(getDefaultClassJavadocComment(javaClass)); + sb.append(EOL); + + appendSeparator(sb, indent); + + appendDefaultAuthorTag(sb, indent); + + appendDefaultVersionTag(sb, indent); + + if (fixTag(SINCE_TAG)) { + if (!ignoreClirr) { + if (isNewClassFromLastVersion(javaClass)) { + appendDefaultSinceTag(sb, indent); + } + } else { + appendDefaultSinceTag(sb, indent); + addSinceClasses(javaClass); + } + } + + sb.append(indent).append(" ").append(END_JAVADOC); + sb.append(EOL); + + stringWriter.write(sb.toString()); + } + + /** + * Add Javadoc field comment, only for static fields or interface fields. + * + * @param stringWriter not null + * @param javaClass not null + * @param field not null + * @param indent not null + * @return {@code true} if comment was updated, otherwise {@code false} + * @throws IOException if any + */ + private boolean fixFieldComment( + final StringWriter stringWriter, final JavaClass javaClass, final JavaField field, final String indent) + throws IOException { + if (!fixFieldComment) { + return false; + } + + if (!javaClass.isInterface() && (!isInLevel(field.getModifiers()) || !field.isStatic())) { + return false; + } + + // add + if (field.getComment() == null) { + addDefaultFieldComment(stringWriter, field, indent); + return true; + } + + // no update + return false; + } + + /** + * Add a default Javadoc for the given field, i.e.: + *
+ * + * 1      + * /** Constant <code> + * MY_STRING_CONSTANT="value" + * </code> */
+ * 2      + * public static final  + * String MY_STRING_CONSTANT =  + * "value"; + *
+ * + * @param stringWriter not null + * @param field not null + * @param indent not null + * @throws IOException if any + */ + private void addDefaultFieldComment(final StringWriter stringWriter, final JavaField field, final String indent) + throws IOException { + StringBuilder sb = new StringBuilder(); + + sb.append(indent).append(START_JAVADOC).append(" "); + sb.append("Constant ").append(field.getName()); + + if (StringUtils.isNotEmpty(field.getInitializationExpression())) { + String qualifiedName = field.getType().getFullyQualifiedName(); + + if (qualifiedName.equals(Byte.TYPE.toString()) + || qualifiedName.equals(Short.TYPE.toString()) + || qualifiedName.equals(Integer.TYPE.toString()) + || qualifiedName.equals(Long.TYPE.toString()) + || qualifiedName.equals(Float.TYPE.toString()) + || qualifiedName.equals(Double.TYPE.toString()) + || qualifiedName.equals(Boolean.TYPE.toString()) + || qualifiedName.equals(Character.TYPE.toString())) { + sb.append("="); + sb.append(StringEscapeUtils.escapeHtml4( + field.getInitializationExpression().trim())); + } + + if (qualifiedName.equals(String.class.getName())) { + StringBuilder value = new StringBuilder(); + String[] lines = getLines(field.getInitializationExpression()); + for (String line : lines) { + StringTokenizer token = new StringTokenizer(line.trim(), "\"\n\r"); + while (token.hasMoreTokens()) { + String s = token.nextToken(); + + if (s.trim().equals("+")) { + continue; + } + if (s.trim().endsWith("\\")) { + s += "\""; + } + value.append(s); + } + } + + sb.append("=\""); + String escapedValue = StringEscapeUtils.escapeHtml4(value.toString()); + // reduce the size + // CHECKSTYLE_OFF: MagicNumber + if (escapedValue.length() < 40) { + sb.append(escapedValue).append("\""); + } else { + sb.append(escapedValue, 0, 39).append("\"{trunked}"); + } + // CHECKSTYLE_ON: MagicNumber + } + } + + sb.append(" ").append(END_JAVADOC); + sb.append(EOL); + + stringWriter.write(sb.toString()); + } + + /** + * Add/update Javadoc method comment. + * + * @param stringWriter not null + * @param originalContent not null + * @param javaExecutable not null + * @param indent not null + * @return {@code true} if comment was updated, otherwise {@code false} + * @throws MojoExecutionException if any + * @throws IOException if any + */ + private boolean fixMethodComment( + final StringWriter stringWriter, + final String originalContent, + final JavaExecutable javaExecutable, + final String indent) + throws MojoExecutionException, IOException { + if (!fixMethodComment) { + return false; + } + + if (!javaExecutable.getDeclaringClass().isInterface() && !isInLevel(javaExecutable.getModifiers())) { + return false; + } + + // add + if (javaExecutable.getComment() == null) { + addDefaultMethodComment(stringWriter, javaExecutable, indent); + return true; + } + + // update + return updateEntityComment(stringWriter, originalContent, javaExecutable, indent); + } + + /** + * Add in the buffer a default Javadoc for the given class: + *
+ * + * 1   + * /**
+ * 2    + * * {Comment based on the method name}
+ * 3    + * *
+ * 4    + * @param  + * X {added if addMissingParam}
+ * 5    + * @return  + * X {added if addMissingReturn}
+ * 6    + * @throws  + * X {added if addMissingThrows}
+ * 7    + * @since  + * X {added if addMissingSince and new classes + * from previous version}
+ * 8    + * */
+ * 9 public  + * void dummyMethod + * String s  + * ){} + *
+ * + * @param stringWriter not null + * @param javaExecutable not null + * @param indent not null + * @throws MojoExecutionException if any + * @see #getDefaultMethodJavadocComment + * @see #appendDefaultSinceTag(StringBuilder, String) + */ + private void addDefaultMethodComment( + final StringWriter stringWriter, final JavaExecutable javaExecutable, final String indent) + throws MojoExecutionException { + StringBuilder sb = new StringBuilder(); + + // special case + if (isInherited(javaExecutable)) { + sb.append(indent).append(INHERITED_JAVADOC); + sb.append(EOL); + + stringWriter.write(sb.toString()); + return; + } + + sb.append(indent).append(START_JAVADOC); + sb.append(EOL); + sb.append(indent).append(SEPARATOR_JAVADOC); + sb.append(getDefaultMethodJavadocComment(javaExecutable)); + sb.append(EOL); + + boolean separatorAdded = false; + if (fixTag(PARAM_TAG)) { + if (javaExecutable.getParameters() != null) { + for (JavaParameter javaParameter : javaExecutable.getParameters()) { + separatorAdded = appendDefaultParamTag(sb, indent, separatorAdded, javaParameter); + } + } + // is generic? + if (javaExecutable.getTypeParameters() != null) { + for (JavaTypeVariable typeParam : javaExecutable.getTypeParameters()) { + separatorAdded = appendDefaultParamTag(sb, indent, separatorAdded, typeParam); + } + } + } + if (javaExecutable instanceof JavaMethod) { + JavaMethod javaMethod = (JavaMethod) javaExecutable; + if (fixTag(RETURN_TAG) + && javaMethod.getReturns() != null + && !javaMethod.getReturns().isVoid()) { + separatorAdded = appendDefaultReturnTag(sb, indent, separatorAdded, javaMethod); + } + } + if (fixTag(THROWS_TAG) && javaExecutable.getExceptions() != null) { + for (JavaType exception : javaExecutable.getExceptions()) { + separatorAdded = appendDefaultThrowsTag(sb, indent, separatorAdded, exception); + } + } + if (fixTag(SINCE_TAG) && isNewMethodFromLastRevision(javaExecutable)) { + separatorAdded = appendDefaultSinceTag(sb, indent, separatorAdded); + } + + sb.append(indent).append(" ").append(END_JAVADOC); + sb.append(EOL); + + stringWriter.write(sb.toString()); + } + + /** + * @param stringWriter not null + * @param originalContent not null + * @param entity not null + * @param indent not null + * @return the updated changeDetected flag + * @throws MojoExecutionException if any + * @throws IOException if any + */ + private boolean updateEntityComment( + final StringWriter stringWriter, + final String originalContent, + final JavaAnnotatedElement entity, + final String indent) + throws MojoExecutionException, IOException { + boolean changeDetected = false; + + String old = null; + String s = stringWriter.toString(); + int i = s.lastIndexOf(START_JAVADOC); + if (i != -1) { + String tmp = s.substring(0, i); + if (tmp.lastIndexOf(EOL) != -1) { + tmp = tmp.substring(0, tmp.lastIndexOf(EOL)); + } + + old = stringWriter.getBuffer().substring(i); + + stringWriter.getBuffer().delete(0, stringWriter.getBuffer().length()); + stringWriter.write(tmp); + stringWriter.write(EOL); + } else { + changeDetected = true; + } + + updateJavadocComment(stringWriter, originalContent, entity, indent); + + if (changeDetected) { + return true; // return now if we already know there's a change + } + + return !stringWriter.getBuffer().substring(i).equals(old); + } + + /** + * @param stringWriter not null + * @param originalContent not null + * @param entity not null + * @param indent not null + * @throws MojoExecutionException if any + * @throws IOException if any + */ + private void updateJavadocComment( + final StringWriter stringWriter, + final String originalContent, + final JavaAnnotatedElement entity, + final String indent) + throws MojoExecutionException, IOException { + if (entity.getComment() == null + && (entity.getTags() == null || entity.getTags().isEmpty())) { + return; + } + + boolean isJavaExecutable = entity instanceof JavaExecutable; + + StringBuilder sb = new StringBuilder(); + + // special case for inherited method + if (isJavaExecutable) { + JavaExecutable javaMethod = (JavaExecutable) entity; + + if (isInherited(javaMethod)) { + // QDOX-154 could be empty + if (StringUtils.isEmpty(javaMethod.getComment())) { + sb.append(indent).append(INHERITED_JAVADOC); + sb.append(EOL); + stringWriter.write(sb.toString()); + return; + } + + String javadoc = getJavadocComment(originalContent, javaMethod); + + // case: /** {@inheritDoc} */ or no tags + if (hasInheritedTag(javadoc) + && (javaMethod.getTags() == null || javaMethod.getTags().isEmpty())) { + sb.append(indent).append(INHERITED_JAVADOC); + sb.append(EOL); + stringWriter.write(sb.toString()); + return; + } + + if (javadoc.contains(START_JAVADOC)) { + javadoc = javadoc.substring(javadoc.indexOf(START_JAVADOC) + START_JAVADOC.length()); + } + if (javadoc.contains(END_JAVADOC)) { + javadoc = javadoc.substring(0, javadoc.indexOf(END_JAVADOC)); + } + + sb.append(indent).append(START_JAVADOC); + sb.append(EOL); + if (!javadoc.contains(INHERITED_TAG)) { + sb.append(indent).append(SEPARATOR_JAVADOC).append(INHERITED_TAG); + sb.append(EOL); + appendSeparator(sb, indent); + } + javadoc = removeLastEmptyJavadocLines(javadoc); + javadoc = alignIndentationJavadocLines(javadoc, indent); + sb.append(javadoc); + sb.append(EOL); + if (javaMethod.getTags() != null) { + for (DocletTag docletTag : javaMethod.getTags()) { + // Voluntary ignore these tags + if (JavadocUtil.equals(docletTag.getName(), PARAM_TAG, RETURN_TAG, THROWS_TAG)) { + continue; + } + + String s = getJavadocComment(originalContent, entity, docletTag); + s = removeLastEmptyJavadocLines(s); + s = alignIndentationJavadocLines(s, indent); + sb.append(s); + sb.append(EOL); + } + } + sb.append(indent).append(" ").append(END_JAVADOC); + sb.append(EOL); + + if (hasInheritedTag(sb.toString().trim())) { + sb = new StringBuilder(); + sb.append(indent).append(INHERITED_JAVADOC); + sb.append(EOL); + stringWriter.write(sb.toString()); + return; + } + + stringWriter.write(sb.toString()); + return; + } + } + + sb.append(indent).append(START_JAVADOC); + sb.append(EOL); + + // comment + if (StringUtils.isNotEmpty(entity.getComment())) { + updateJavadocComment(sb, originalContent, entity, indent); + } else { + addDefaultJavadocComment(sb, entity, indent, isJavaExecutable); + } + + // tags + updateJavadocTags(sb, originalContent, entity, indent, isJavaExecutable); + + sb = new StringBuilder(removeLastEmptyJavadocLines(sb.toString())).append(EOL); + + sb.append(indent).append(" ").append(END_JAVADOC); + sb.append(EOL); + + stringWriter.write(sb.toString()); + } + + /** + * @param sb not null + * @param originalContent not null + * @param entity not null + * @param indent not null + * @throws IOException if any + */ + private void updateJavadocComment( + final StringBuilder sb, + final String originalContent, + final JavaAnnotatedElement entity, + final String indent) + throws IOException { + String comment = getJavadocComment(originalContent, entity); + comment = removeLastEmptyJavadocLines(comment); + comment = alignIndentationJavadocLines(comment, indent); + + if (comment.contains(START_JAVADOC)) { + comment = comment.substring(comment.indexOf(START_JAVADOC) + START_JAVADOC.length()); + comment = indent + SEPARATOR_JAVADOC + comment.trim(); + } + if (comment.contains(END_JAVADOC)) { + comment = comment.substring(0, comment.indexOf(END_JAVADOC)); + } + + if (fixTag(LINK_TAG)) { + comment = replaceLinkTags(comment, entity); + } + + String[] lines = getLines(comment); + for (String line : lines) { + sb.append(indent).append(" ").append(line.trim()); + sb.append(EOL); + } + } + + private static final Pattern REPLACE_LINK_TAGS_PATTERN = Pattern.compile("\\{@link\\s"); + + static String replaceLinkTags(String comment, JavaAnnotatedElement entity) { + StringBuilder resolvedComment = new StringBuilder(); + // scan comment for {@link someClassName} and try to resolve this + Matcher linktagMatcher = REPLACE_LINK_TAGS_PATTERN.matcher(comment); + int startIndex = 0; + while (linktagMatcher.find()) { + int startName = linktagMatcher.end(); + resolvedComment.append(comment, startIndex, startName); + int endName = comment.indexOf("}", startName); + if (endName >= 0) { + String name; + String link = comment.substring(startName, endName); + int hashIndex = link.indexOf('#'); + if (hashIndex >= 0) { + name = link.substring(0, hashIndex); + } else { + name = link; + } + if (StringUtils.isNotBlank(name)) { + String typeName; + if (entity instanceof JavaClass) { + JavaClass clazz = (JavaClass) entity; + typeName = TypeResolver.byClassName( + clazz.getBinaryName(), + clazz.getJavaClassLibrary(), + clazz.getSource().getImports()) + .resolveType(name.trim()); + } else if (entity instanceof JavaMember) { + JavaClass clazz = ((JavaMember) entity).getDeclaringClass(); + typeName = TypeResolver.byClassName( + clazz.getBinaryName(), + clazz.getJavaClassLibrary(), + clazz.getSource().getImports()) + .resolveType(name.trim()); + } else { + typeName = null; + } + + if (typeName == null) { + typeName = name.trim(); + } else { + typeName = typeName.replaceAll("\\$", "."); + } + // adjust name for inner classes + resolvedComment.append(typeName); + } + if (hashIndex >= 0) { + resolvedComment.append(link.substring(hashIndex).trim()); + } + startIndex = endName; + } else { + startIndex = startName; + } + } + resolvedComment.append(comment.substring(startIndex)); + return resolvedComment.toString(); + } + + /** + * @param sb not null + * @param entity not null + * @param indent not null + * @param isJavaExecutable + */ + private void addDefaultJavadocComment( + final StringBuilder sb, + final JavaAnnotatedElement entity, + final String indent, + final boolean isJavaExecutable) { + sb.append(indent).append(SEPARATOR_JAVADOC); + if (isJavaExecutable) { + sb.append(getDefaultMethodJavadocComment((JavaExecutable) entity)); + } else { + sb.append(getDefaultClassJavadocComment((JavaClass) entity)); + } + sb.append(EOL); + } + + /** + * @param sb not null + * @param originalContent not null + * @param entity not null + * @param indent not null + * @param isJavaExecutable + * @throws IOException if any + * @throws MojoExecutionException if any + */ + private void updateJavadocTags( + final StringBuilder sb, + final String originalContent, + final JavaAnnotatedElement entity, + final String indent, + final boolean isJavaExecutable) + throws IOException, MojoExecutionException { + appendSeparator(sb, indent); + + // parse tags + JavaEntityTags javaEntityTags = parseJavadocTags(originalContent, entity, indent, isJavaExecutable); + + // update and write tags + updateJavadocTags(sb, entity, isJavaExecutable, javaEntityTags); + + // add missing tags... + addMissingJavadocTags(sb, entity, indent, isJavaExecutable, javaEntityTags); + } + + /** + * Parse entity tags + * + * @param originalContent not null + * @param entity not null + * @param indent not null + * @param isJavaMethod + * @return an instance of {@link JavaEntityTags} + * @throws IOException if any + */ + JavaEntityTags parseJavadocTags( + final String originalContent, + final JavaAnnotatedElement entity, + final String indent, + final boolean isJavaMethod) + throws IOException { + JavaEntityTags javaEntityTags = new JavaEntityTags(entity, isJavaMethod); + for (DocletTag docletTag : entity.getTags()) { + String originalJavadocTag = getJavadocComment(originalContent, entity, docletTag); + originalJavadocTag = removeLastEmptyJavadocLines(originalJavadocTag); + originalJavadocTag = alignIndentationJavadocLines(originalJavadocTag, indent); + + javaEntityTags.getNamesTags().add(docletTag.getName()); + + if (isJavaMethod) { + List params = docletTag.getParameters(); + if (params.size() < 1) { + continue; + } + + String paramName = params.get(0); + switch (docletTag.getName()) { + case PARAM_TAG: + javaEntityTags.putJavadocParamTag(paramName, docletTag.getValue(), originalJavadocTag); + break; + case RETURN_TAG: + javaEntityTags.setJavadocReturnTag(originalJavadocTag); + break; + case THROWS_TAG: + javaEntityTags.putJavadocThrowsTag(paramName, originalJavadocTag); + break; + default: + javaEntityTags.getUnknownTags().add(originalJavadocTag); + break; + } + } else { + javaEntityTags.getUnknownTags().add(originalJavadocTag); + } + } + + return javaEntityTags; + } + + /** + * Write tags according javaEntityTags. + * + * @param sb not null + * @param entity not null + * @param isJavaExecutable + * @param javaEntityTags not null + */ + private void updateJavadocTags( + final StringBuilder sb, + final JavaAnnotatedElement entity, + final boolean isJavaExecutable, + final JavaEntityTags javaEntityTags) { + for (DocletTag docletTag : entity.getTags()) { + if (isJavaExecutable) { + JavaExecutable javaExecutable = (JavaExecutable) entity; + + List params = docletTag.getParameters(); + if (params.size() < 1) { + continue; + } + + if (docletTag.getName().equals(PARAM_TAG)) { + writeParamTag(sb, javaExecutable, javaEntityTags, params.get(0), docletTag.getValue()); + } else if (docletTag.getName().equals(RETURN_TAG) && javaExecutable instanceof JavaMethod) { + writeReturnTag(sb, (JavaMethod) javaExecutable, javaEntityTags); + } else if (docletTag.getName().equals(THROWS_TAG)) { + writeThrowsTag(sb, javaExecutable, javaEntityTags, params); + } else { + // write unknown tags + for (Iterator it = javaEntityTags.getUnknownTags().iterator(); it.hasNext(); ) { + String originalJavadocTag = it.next(); + String simplified = StringUtils.removeDuplicateWhitespace(originalJavadocTag) + .trim(); + + if (simplified.contains("@" + docletTag.getName())) { + it.remove(); + sb.append(originalJavadocTag); + sb.append(EOL); + } + } + } + } else { + for (Iterator it = javaEntityTags.getUnknownTags().iterator(); it.hasNext(); ) { + String originalJavadocTag = it.next(); + String simplified = StringUtils.removeDuplicateWhitespace(originalJavadocTag) + .trim(); + + if (simplified.contains("@" + docletTag.getName())) { + it.remove(); + sb.append(originalJavadocTag); + sb.append(EOL); + } + } + } + + if (sb.toString().endsWith(EOL)) { + sb.delete(sb.toString().lastIndexOf(EOL), sb.toString().length()); + } + + sb.append(EOL); + } + } + + private void writeParamTag( + final StringBuilder sb, + final JavaExecutable javaExecutable, + final JavaEntityTags javaEntityTags, + String paramName, + String paramValue) { + if (!fixTag(PARAM_TAG)) { + // write original param tag if found + String originalJavadocTag = javaEntityTags.getJavadocParamTag(paramValue); + if (originalJavadocTag != null) { + sb.append(originalJavadocTag); + } + return; + } + + boolean found = false; + JavaParameter javaParam = javaExecutable.getParameterByName(paramName); + if (javaParam == null) { + // is generic? + List> typeParams = javaExecutable.getTypeParameters(); + for (JavaTypeVariable typeParam : typeParams) { + if (("<" + typeParam.getName() + ">").equals(paramName)) { + found = true; + } + } + } else { + found = true; + } + + if (!found) { + if (getLog().isWarnEnabled()) { + getLog().warn("Fixed unknown param '" + paramName + "' defined in " + + getJavaMethodAsString(javaExecutable)); + } + + if (sb.toString().endsWith(EOL)) { + sb.delete(sb.toString().lastIndexOf(EOL), sb.toString().length()); + } + } else { + String originalJavadocTag = javaEntityTags.getJavadocParamTag(paramValue); + if (originalJavadocTag != null) { + sb.append(originalJavadocTag); + String s = "@" + PARAM_TAG + " " + paramName; + if (StringUtils.removeDuplicateWhitespace(originalJavadocTag) + .trim() + .endsWith(s)) { + sb.append(" "); + sb.append(getDefaultJavadocForType(javaParam.getJavaClass())); + } + } + } + } + + private void writeReturnTag( + final StringBuilder sb, final JavaMethod javaMethod, final JavaEntityTags javaEntityTags) { + String originalJavadocTag = javaEntityTags.getJavadocReturnTag(); + if (originalJavadocTag == null) { + return; + } + + if (!fixTag(RETURN_TAG)) { + // write original param tag if found + sb.append(originalJavadocTag); + return; + } + + if (StringUtils.isNotEmpty(originalJavadocTag) + && javaMethod.getReturns() != null + && !javaMethod.getReturns().isVoid()) { + sb.append(originalJavadocTag); + if (originalJavadocTag.trim().endsWith("@" + RETURN_TAG)) { + sb.append(" "); + sb.append(getDefaultJavadocForType(javaMethod.getReturns())); + } + } + } + + void writeThrowsTag( + final StringBuilder sb, + final JavaExecutable javaExecutable, + final JavaEntityTags javaEntityTags, + final List params) { + String exceptionClassName = params.get(0); + + String originalJavadocTag = javaEntityTags.getJavadocThrowsTag(exceptionClassName); + if (originalJavadocTag == null) { + return; + } + + if (!fixTag(THROWS_TAG)) { + // write original param tag if found + sb.append(originalJavadocTag); + return; + } + + if (javaExecutable.getExceptions() != null) { + for (JavaType exception : javaExecutable.getExceptions()) { + if (exception.getFullyQualifiedName().endsWith(exceptionClassName)) { + originalJavadocTag = StringUtils.replace( + originalJavadocTag, exceptionClassName, exception.getFullyQualifiedName()); + if (StringUtils.removeDuplicateWhitespace(originalJavadocTag) + .trim() + .endsWith("@" + THROWS_TAG + " " + exception.getValue())) { + originalJavadocTag += " if any."; + } + + sb.append(originalJavadocTag); + + // added qualified name + javaEntityTags.putJavadocThrowsTag(exception.getValue(), originalJavadocTag); + + return; + } + } + } + + Class clazz = getClass(javaExecutable.getDeclaringClass(), exceptionClassName); + + if (clazz != null) { + if (RuntimeException.class.isAssignableFrom(clazz)) { + sb.append(StringUtils.replace(originalJavadocTag, exceptionClassName, clazz.getName())); + + // added qualified name + javaEntityTags.putJavadocThrowsTag(clazz.getName(), originalJavadocTag); + } else if (Throwable.class.isAssignableFrom(clazz)) { + getLog().debug("Removing '" + originalJavadocTag + "'; Throwable not specified by " + + getJavaMethodAsString(javaExecutable) + " and it is not a RuntimeException."); + } else { + getLog().debug("Removing '" + originalJavadocTag + "'; It is not a Throwable"); + } + } else if (removeUnknownThrows) { + getLog().warn("Ignoring unknown throws '" + exceptionClassName + "' defined on " + + getJavaMethodAsString(javaExecutable)); + } else { + getLog().warn("Found unknown throws '" + exceptionClassName + "' defined on " + + getJavaMethodAsString(javaExecutable)); + + sb.append(originalJavadocTag); + + if (params.size() == 1) { + sb.append(" if any."); + } + + javaEntityTags.putJavadocThrowsTag(exceptionClassName, originalJavadocTag); + } + } + + /** + * Add missing tags not already written. + * + * @param sb not null + * @param entity not null + * @param indent not null + * @param isJavaExecutable + * @param javaEntityTags not null + * @throws MojoExecutionException if any + */ + private void addMissingJavadocTags( + final StringBuilder sb, + final JavaAnnotatedElement entity, + final String indent, + final boolean isJavaExecutable, + final JavaEntityTags javaEntityTags) + throws MojoExecutionException { + if (isJavaExecutable) { + JavaExecutable javaExecutable = (JavaExecutable) entity; + + if (fixTag(PARAM_TAG)) { + if (javaExecutable.getParameters() != null) { + for (JavaParameter javaParameter : javaExecutable.getParameters()) { + if (!javaEntityTags.hasJavadocParamTag(javaParameter.getName())) { + appendDefaultParamTag(sb, indent, javaParameter); + } + } + } + // is generic? + if (javaExecutable.getTypeParameters() != null) { + for (JavaTypeVariable typeParam : javaExecutable.getTypeParameters()) { + if (!javaEntityTags.hasJavadocParamTag("<" + typeParam.getName() + ">")) { + appendDefaultParamTag(sb, indent, typeParam); + } + } + } + } + + if (javaExecutable instanceof JavaMethod) { + JavaMethod javaMethod = (JavaMethod) javaExecutable; + if (fixTag(RETURN_TAG) + && StringUtils.isEmpty(javaEntityTags.getJavadocReturnTag()) + && javaMethod.getReturns() != null + && !javaMethod.getReturns().isVoid()) { + appendDefaultReturnTag(sb, indent, javaMethod); + } + } + + if (fixTag(THROWS_TAG) && javaExecutable.getExceptions() != null) { + for (JavaType exception : javaExecutable.getExceptions()) { + if (javaEntityTags.getJavadocThrowsTag(exception.getValue(), true) == null) { + appendDefaultThrowsTag(sb, indent, exception); + } + } + } + } else { + if (!javaEntityTags.getNamesTags().contains(AUTHOR_TAG)) { + appendDefaultAuthorTag(sb, indent); + } + if (!javaEntityTags.getNamesTags().contains(VERSION_TAG)) { + appendDefaultVersionTag(sb, indent); + } + } + + if (fixTag(SINCE_TAG) && !javaEntityTags.getNamesTags().contains(SINCE_TAG)) { + if (!isJavaExecutable) { + if (!ignoreClirr) { + if (isNewClassFromLastVersion((JavaClass) entity)) { + appendDefaultSinceTag(sb, indent); + } + } else { + appendDefaultSinceTag(sb, indent); + addSinceClasses((JavaClass) entity); + } + } else { + if (!ignoreClirr) { + if (isNewMethodFromLastRevision((JavaExecutable) entity)) { + appendDefaultSinceTag(sb, indent); + } + } else if (sinceClasses != null) { + if (entity instanceof JavaMember + && !sinceClassesContains(((JavaMember) entity).getDeclaringClass())) { + appendDefaultSinceTag(sb, indent); + } else if (entity instanceof JavaClass + && !sinceClassesContains(((JavaClass) entity).getDeclaringClass())) { + appendDefaultSinceTag(sb, indent); + } + } + } + } + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @return true if separator has been added. + */ + private boolean appendDefaultAuthorTag(final StringBuilder sb, final String indent, boolean separatorAdded) { + if (!fixTag(AUTHOR_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultAuthorTag(sb, indent); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + */ + private void appendDefaultAuthorTag(final StringBuilder sb, final String indent) { + if (!fixTag(AUTHOR_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(AUTHOR_TAG).append(" "); + sb.append(defaultAuthor); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @return true if separator has been added. + */ + private boolean appendDefaultSinceTag(final StringBuilder sb, final String indent, boolean separatorAdded) { + if (!fixTag(SINCE_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultSinceTag(sb, indent); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + */ + private void appendDefaultSinceTag(final StringBuilder sb, final String indent) { + if (!fixTag(SINCE_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(SINCE_TAG).append(" "); + sb.append(defaultSince); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @return true if separator has been added. + */ + private boolean appendDefaultVersionTag(final StringBuilder sb, final String indent, boolean separatorAdded) { + if (!fixTag(VERSION_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultVersionTag(sb, indent); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + */ + private void appendDefaultVersionTag(final StringBuilder sb, final String indent) { + if (!fixTag(VERSION_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(VERSION_TAG).append(" "); + sb.append(defaultVersion); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @param typeParam not null + * @return true if separator has been added. + */ + private boolean appendDefaultParamTag( + final StringBuilder sb, final String indent, boolean separatorAdded, final JavaParameter typeParam) { + if (!fixTag(PARAM_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultParamTag(sb, indent, typeParam); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @param typeParameter not null + * @return true if separator has been added. + */ + private boolean appendDefaultParamTag( + final StringBuilder sb, + final String indent, + boolean separatorAdded, + final JavaTypeVariable typeParameter) { + if (!fixTag(PARAM_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultParamTag(sb, indent, typeParameter); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + * @param typeParam not null + */ + private void appendDefaultParamTag(final StringBuilder sb, final String indent, final JavaParameter typeParam) { + if (!fixTag(PARAM_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(PARAM_TAG).append(" "); + sb.append(typeParam.getName()); + sb.append(" "); + sb.append(getDefaultJavadocForType(typeParam.getJavaClass())); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param typeParameter not null + */ + private void appendDefaultParamTag( + final StringBuilder sb, final String indent, final JavaTypeVariable typeParameter) { + if (!fixTag(PARAM_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(PARAM_TAG).append(" "); + sb.append("<").append(typeParameter.getName()).append(">"); + sb.append(" "); + sb.append(getDefaultJavadocForType(typeParameter)); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @param javaMethod not null + * @return true if separator has been added. + */ + private boolean appendDefaultReturnTag( + final StringBuilder sb, final String indent, boolean separatorAdded, final JavaMethod javaMethod) { + if (!fixTag(RETURN_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultReturnTag(sb, indent, javaMethod); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + * @param javaMethod not null + */ + private void appendDefaultReturnTag(final StringBuilder sb, final String indent, final JavaMethod javaMethod) { + if (!fixTag(RETURN_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(RETURN_TAG).append(" "); + sb.append(getDefaultJavadocForType(javaMethod.getReturns())); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + * @param separatorAdded + * @param exception not null + * @return true if separator has been added. + */ + private boolean appendDefaultThrowsTag( + final StringBuilder sb, final String indent, boolean separatorAdded, final JavaType exception) { + if (!fixTag(THROWS_TAG)) { + return separatorAdded; + } + + if (!separatorAdded) { + appendSeparator(sb, indent); + separatorAdded = true; + } + + appendDefaultThrowsTag(sb, indent, exception); + return separatorAdded; + } + + /** + * @param sb not null + * @param indent not null + * @param exception not null + */ + private void appendDefaultThrowsTag(final StringBuilder sb, final String indent, final JavaType exception) { + if (!fixTag(THROWS_TAG)) { + return; + } + + sb.append(indent).append(" * @").append(THROWS_TAG).append(" "); + sb.append(exception.getFullyQualifiedName()); + sb.append(" if any."); + sb.append(EOL); + } + + /** + * @param sb not null + * @param indent not null + */ + private void appendSeparator(final StringBuilder sb, final String indent) { + sb.append(indent).append(" *"); + sb.append(EOL); + } + + /** + * Verify if a method has @java.lang.Override() annotation or if it is an inherited method + * from an interface or a super class. The goal is to handle {@inheritDoc} tag. + * + * @param javaMethod not null + * @return true if the method is inherited, false otherwise. + * @throws MojoExecutionException if any + */ + private boolean isInherited(JavaExecutable javaMethod) throws MojoExecutionException { + if (javaMethod.getAnnotations() != null) { + for (JavaAnnotation annotation : javaMethod.getAnnotations()) { + if (annotation.toString().equals("@java.lang.Override()")) { + return true; + } + } + } + + Class clazz = getClass(javaMethod.getDeclaringClass().getFullyQualifiedName()); + + List> interfaces = ClassUtils.getAllInterfaces(clazz); + for (Class intface : interfaces) { + if (isInherited(intface, javaMethod)) { + return true; + } + } + + List> classes = ClassUtils.getAllSuperclasses(clazz); + for (Class superClass : classes) { + if (isInherited(superClass, javaMethod)) { + return true; + } + } + + return false; + } + + /** + * @param clazz the Java class object, not null + * @param javaMethod the QDox JavaMethod object not null + * @return true if javaMethod exists in the given clazz, + * false otherwise. + * @see #isInherited(JavaExecutable) + */ + private boolean isInherited(Class clazz, JavaExecutable javaMethod) { + for (Method method : clazz.getDeclaredMethods()) { + if (!method.getName().equals(javaMethod.getName())) { + continue; + } + + if (method.getParameterTypes().length != javaMethod.getParameters().size()) { + continue; + } + + boolean found = false; + int j = 0; + for (Class paramType : method.getParameterTypes()) { + String name1 = paramType.getName(); + String name2 = javaMethod.getParameters().get(j++).getType().getFullyQualifiedName(); + found = name1.equals(name2); // TODO check algo, seems broken (only takes in account the last param) + } + + return found; + } + + return false; + } + + /** + * @param clazz + * @return + */ + private String getDefaultJavadocForType(JavaClass clazz) { + StringBuilder sb = new StringBuilder(); + + if (!JavaTypeVariable.class.isAssignableFrom(clazz.getClass()) && clazz.isPrimitive()) { + if (clazz.isArray()) { + sb.append("an array of ").append(clazz.getComponentType().getCanonicalName()); + } else { + sb.append("a ").append(clazz.getCanonicalName()); + } + return sb.toString(); + } + + StringBuilder javadocLink = new StringBuilder(); + try { + getClass(clazz.getCanonicalName()); + + javadocLink.append("{@link "); + + if (clazz.isArray()) { + javadocLink.append(clazz.getComponentType().getCanonicalName()); + } else { + javadocLink.append(clazz.getCanonicalName()); + } + javadocLink.append("}"); + } catch (Exception e) { + javadocLink.append(clazz.getValue()); + } + + if (clazz.isArray()) { + sb.append("an array of ").append(javadocLink).append(" objects"); + } else { + sb.append("a ").append(javadocLink).append(" object"); + } + + return sb.toString(); + } + + private String getDefaultJavadocForType(JavaTypeVariable typeParameter) { + return "a " + typeParameter.getName() + " class"; + } + + /** + * Check under Clirr if this given class is newer from the last version. + * + * @param javaClass a given class not null + * @return true if Clirr said that this class is added from the last version, + * false otherwise or if {@link #clirrNewClasses} is null. + */ + private boolean isNewClassFromLastVersion(JavaClass javaClass) { + return (clirrNewClasses != null) && clirrNewClasses.contains(javaClass.getFullyQualifiedName()); + } + + /** + * Check under Clirr if this given method is newer from the last version. + * + * @param javaExecutable a given method not null + * @return true if Clirr said that this method is added from the last version, + * false otherwise or if {@link #clirrNewMethods} is null. + * @throws MojoExecutionException if any + */ + private boolean isNewMethodFromLastRevision(JavaExecutable javaExecutable) throws MojoExecutionException { + if (clirrNewMethods == null) { + return false; + } + + List clirrMethods = + clirrNewMethods.get(javaExecutable.getDeclaringClass().getFullyQualifiedName()); + if (clirrMethods == null) { + return false; + } + + for (String clirrMethod : clirrMethods) { + // see net.sf.clirr.core.internal.checks.MethodSetCheck#getMethodId(JavaType clazz, Method method) + String retrn = ""; + if (javaExecutable instanceof JavaMethod && ((JavaMethod) javaExecutable).getReturns() != null) { + retrn = ((JavaMethod) javaExecutable).getReturns().getFullyQualifiedName(); + } + StringBuilder params = new StringBuilder(); + for (JavaParameter parameter : javaExecutable.getParameters()) { + if (params.length() > 0) { + params.append(", "); + } + params.append(parameter.getResolvedFullyQualifiedName()); + } + if (clirrMethod.contains(retrn + " ") + && clirrMethod.contains(javaExecutable.getName() + "(") + && clirrMethod.contains("(" + params.toString() + ")")) { + return true; + } + } + + return false; + } + + /** + * @param className not null + * @return the Class corresponding to the given class name using the project classloader. + * @throws MojoExecutionException if class not found + * @see ClassUtils#getClass(ClassLoader, String, boolean) + * @see #getProjectClassLoader() + */ + private Class getClass(String className) throws MojoExecutionException { + try { + return ClassUtils.getClass(getProjectClassLoader(), className, false); + } catch (ClassNotFoundException e) { + throw new MojoExecutionException("ClassNotFoundException: " + e.getMessage(), e); + } + } + + /** + * Returns the Class object assignable for {@link RuntimeException} class and associated with the given + * exception class name. + * + * @param currentClass not null + * @param exceptionClassName not null, an exception class name defined as: + *
    + *
  • exception class fully qualified
  • + *
  • exception class in the same package
  • + *
  • exception inner class
  • + *
  • exception class in java.lang package
  • + *
+ * @return the class if found, otherwise {@code null}. + * @see #getClass(String) + */ + private Class getClass(JavaClass currentClass, String exceptionClassName) { + String[] potentialClassNames = new String[] { + exceptionClassName, + currentClass.getPackage().getName() + "." + exceptionClassName, + currentClass.getPackage().getName() + "." + currentClass.getName() + "$" + exceptionClassName, + "java.lang." + exceptionClassName + }; + + Class clazz = null; + for (String potentialClassName : potentialClassNames) { + try { + clazz = getClass(potentialClassName); + } catch (MojoExecutionException e) { + // nop + } + if (clazz != null) { + return clazz; + } + } + + return null; + } + + /** + * @param javaClass not null + */ + private void addSinceClasses(JavaClass javaClass) { + if (sinceClasses == null) { + sinceClasses = new ArrayList<>(); + } + sinceClasses.add(javaClass.getFullyQualifiedName()); + } + + private boolean sinceClassesContains(JavaClass javaClass) { + return sinceClasses.contains(javaClass.getFullyQualifiedName()); + } + + // ---------------------------------------------------------------------- + // Static methods + // ---------------------------------------------------------------------- + + /** + * Write content into the given javaFile and using the given encoding. + * All line separators will be unified. + * + * @param javaFile not null + * @param encoding not null + * @param content not null + * @throws IOException if any + */ + private static void writeFile(final File javaFile, final String encoding, final String content) throws IOException { + String unified = StringUtils.unifyLineSeparators(content); + FileUtils.fileWrite(javaFile, encoding, unified); + } + + /** + * @return the full clirr goal, i.e. groupId:artifactId:version:goal. The clirr-plugin version + * could be load from the pom.properties in the clirr-maven-plugin dependency. + */ + private static String getFullClirrGoal() { + StringBuilder sb = new StringBuilder(); + + sb.append(CLIRR_MAVEN_PLUGIN_GROUPID) + .append(":") + .append(CLIRR_MAVEN_PLUGIN_ARTIFACTID) + .append(":"); + + String clirrVersion = CLIRR_MAVEN_PLUGIN_VERSION; + + String resource = "META-INF/maven/" + CLIRR_MAVEN_PLUGIN_GROUPID + "/" + CLIRR_MAVEN_PLUGIN_ARTIFACTID + + "/pom.properties"; + + try (InputStream resourceAsStream = + AbstractFixJavadocMojo.class.getClassLoader().getResourceAsStream(resource)) { + + if (resourceAsStream != null) { + Properties properties = new Properties(); + properties.load(resourceAsStream); + if (StringUtils.isNotEmpty(properties.getProperty("version"))) { + clirrVersion = properties.getProperty("version"); + } + } + } catch (IOException e) { + // nop + } + + sb.append(clirrVersion).append(":").append(CLIRR_MAVEN_PLUGIN_GOAL); + + return sb.toString(); + } + + /** + * Default comment for class. + * + * @param javaClass not null + * @return a default comment for class. + */ + private static String getDefaultClassJavadocComment(final JavaClass javaClass) { + StringBuilder sb = new StringBuilder(); + + sb.append("

"); + if (javaClass.isAbstract()) { + sb.append("Abstract "); + } + + sb.append(javaClass.getName()); + + if (!javaClass.isInterface()) { + sb.append(" class."); + } else { + sb.append(" interface."); + } + + sb.append("

"); + + return sb.toString(); + } + + /** + * Default comment for method with taking care of getter/setter in the javaMethod name. + * + * @param javaExecutable not null + * @return a default comment for method + */ + private static String getDefaultMethodJavadocComment(final JavaExecutable javaExecutable) { + if (javaExecutable instanceof JavaConstructor) { + return "

Constructor for " + javaExecutable.getName() + ".

"; + } + + if (javaExecutable.getName().length() > 3 + && (javaExecutable.getName().startsWith("get") + || javaExecutable.getName().startsWith("set"))) { + String field = + StringUtils.lowercaseFirstLetter(javaExecutable.getName().substring(3)); + + JavaClass clazz = javaExecutable.getDeclaringClass(); + + if (clazz.getFieldByName(field) == null) { + return "

" + javaExecutable.getName() + ".

"; + } + + StringBuilder sb = new StringBuilder(); + + sb.append("

"); + if (javaExecutable.getName().startsWith("get")) { + sb.append("Getter "); + } else if (javaExecutable.getName().startsWith("set")) { + sb.append("Setter "); + } + sb.append("for the field ").append(field).append(".

"); + + return sb.toString(); + } + + return "

" + javaExecutable.getName() + ".

"; + } + + /** + * Try to find if a Javadoc comment has an {@link #INHERITED_TAG} for instance: + *
+     * /** {@inheritDoc} */
+     * 
+ * or + *
+     * /**
+     *  * {@inheritDoc}
+     *  */
+     * 
+ * + * @param content not null + * @return true if the content has an inherited tag, false otherwise. + */ + private static boolean hasInheritedTag(final String content) { + final String inheritedTagPattern = + "^\\s*(\\/\\*\\*)?(\\s*(\\*)?)*(\\{)@inheritDoc\\s*(\\})(\\s*(\\*)?)*(\\*\\/)?$"; + return Pattern.matches(inheritedTagPattern, StringUtils.removeDuplicateWhitespace(content)); + } + + /** + * Workaround for QDOX-146 about whitespace. + * Ideally we want to use entity.getComment() + *
+ * For instance, with the following snippet: + *
+ *

+ * + * 1 
+ * 2      + * /**
+ * 3       + * * Dummy Javadoc comment.
+ * 4       + * @param  + * s a String
+ * 5       + * */
+ * 6      + * public void  + * dummyMethod + * String s ){}
+ *
+ *

+ *
+ * The return will be: + *
+ *

+ * + * 1       + * * Dummy Javadoc comment.
+ *
+ * + * @param javaClassContent original class content not null + * @param entity not null + * @return the javadoc comment for the entity without any tags. + * @throws IOException if any + */ + static String getJavadocComment(final String javaClassContent, final JavaAnnotatedElement entity) + throws IOException { + if (entity.getComment() == null) { + return ""; + } + + String originalJavadoc = extractOriginalJavadocContent(javaClassContent, entity); + + StringBuilder sb = new StringBuilder(); + BufferedReader lr = new BufferedReader(new StringReader(originalJavadoc)); + String line; + while ((line = lr.readLine()) != null) { + String l = StringUtils.removeDuplicateWhitespace(line.trim()); + if (l.startsWith("* @") || l.startsWith("*@")) { + break; + } + sb.append(line).append(EOL); + } + + return trimRight(sb.toString()); + } + + /** + * Work around for QDOX-146 about whitespace. + * Ideally we want to use docletTag.getValue() + *
+ * For instance, with the following snippet: + *
+ *

+ * + * 1 
+ * 2      + * /**
+ * 3       + * * Dummy Javadoc comment.
+ * 4       + * @param  + * s a String
+ * 5       + * */
+ * 6      + * public void  + * dummyMethod + * String s ){}
+ *
+ *

+ *
+ * The return will be: + *
+ *

+ * + * 1       + * @param  + * s a String
+ *
+ * + * @param javaClassContent original class content not null + * @param entity not null + * @param docletTag not null + * @return the javadoc comment for the entity without Javadoc tags. + * @throws IOException if any + */ + String getJavadocComment( + final String javaClassContent, final JavaAnnotatedElement entity, final DocletTag docletTag) + throws IOException { + if (docletTag.getValue() == null || docletTag.getParameters().isEmpty()) { + return ""; + } + + String originalJavadoc = extractOriginalJavadocContent(javaClassContent, entity); + + StringBuilder sb = new StringBuilder(); + BufferedReader lr = new BufferedReader(new StringReader(originalJavadoc)); + String line; + boolean found = false; + + // matching first line of doclettag + Pattern p = Pattern.compile("(\\s*\\*\\s?@" + docletTag.getName() + ")\\s+" + "(\\Q" + + docletTag.getValue().split("\r\n|\r|\n")[0] + "\\E)"); + + while ((line = lr.readLine()) != null) { + Matcher m = p.matcher(line); + if (m.matches()) { + if (fixTag(LINK_TAG)) { + line = replaceLinkTags(line, entity); + } + sb.append(line).append(EOL); + found = true; + } else { + if (line.trim().startsWith("* @") || line.trim().startsWith("*@")) { + found = false; + } + if (found) { + if (fixTag(LINK_TAG)) { + line = replaceLinkTags(line, entity); + } + sb.append(line).append(EOL); + } + } + } + + return trimRight(sb.toString()); + } + + /** + * Extract the original Javadoc and others comments up to {@link #START_JAVADOC} form the entity. This method + * takes care of the Javadoc indentation. All javadoc lines will be trimmed on right. + *
+ * For instance, with the following snippet: + *
+ *

+ * + * 1 
+ * 2      + * /**
+ * 3       + * * Dummy Javadoc comment.
+ * 4       + * @param  + * s a String
+ * 5       + * */
+ * 6      + * public void  + * dummyMethod + * String s ){}
+ *
+ *

+ *
+ * The return will be: + *
+ *

+ * + * 1      + * /**
+ * 2       + * * Dummy Javadoc comment.
+ * 3       + * @param  + * s a String
+ * 4       + * */
+ *
+ * + * @param javaClassContent not null + * @param entity not null + * @return return the original javadoc as String for the current entity + * @throws IOException if any + */ + static String extractOriginalJavadoc(final String javaClassContent, final JavaAnnotatedElement entity) + throws IOException { + if (entity.getComment() == null) { + return ""; + } + + String[] javaClassContentLines = getLines(javaClassContent); + List list = new LinkedList<>(); + for (int i = entity.getLineNumber() - 2; i >= 0; i--) { + String line = javaClassContentLines[i]; + + list.add(trimRight(line)); + if (line.trim().startsWith(START_JAVADOC)) { + break; + } + } + + Collections.reverse(list); + + return StringUtils.join(list.iterator(), EOL); + } + + /** + * Extract the Javadoc comment between {@link #START_JAVADOC} and {@link #END_JAVADOC} form the entity. This method + * takes care of the Javadoc indentation. All javadoc lines will be trimmed on right. + *
+ * For instance, with the following snippet: + *
+ *

+ * + * 1 
+ * 2      + * /**
+ * 3       + * * Dummy Javadoc comment.
+ * 4       + * @param  + * s a String
+ * 5       + * */
+ * 6      + * public void  + * dummyMethod + * String s ){}
+ *
+ *

+ *
+ * The return will be: + *
+ *

+ * + * 1       + * * Dummy Javadoc comment.
+ * 2       + * @param  + * s a String
+ *
+ * + * @param javaClassContent not null + * @param entity not null + * @return return the original javadoc as String for the current entity + * @throws IOException if any + */ + static String extractOriginalJavadocContent(final String javaClassContent, final JavaAnnotatedElement entity) + throws IOException { + if (entity.getComment() == null) { + return ""; + } + + String originalJavadoc = extractOriginalJavadoc(javaClassContent, entity); + int index = originalJavadoc.indexOf(START_JAVADOC); + if (index != -1) { + originalJavadoc = originalJavadoc.substring(index + START_JAVADOC.length()); + } + index = originalJavadoc.indexOf(END_JAVADOC); + if (index != -1) { + originalJavadoc = originalJavadoc.substring(0, index); + } + if (originalJavadoc.startsWith("\r\n")) { + originalJavadoc = originalJavadoc.substring(2); + } else if (originalJavadoc.startsWith("\n") || originalJavadoc.startsWith("\r")) { + originalJavadoc = originalJavadoc.substring(1); + } + + return trimRight(originalJavadoc); + } + + /** + * @param content not null + * @return the content without last lines containing javadoc separator (ie * ) + * @throws IOException if any + * @see #getJavadocComment(String, JavaAnnotatedElement, DocletTag) + */ + private static String removeLastEmptyJavadocLines(final String content) throws IOException { + if (!content.contains(EOL)) { + return content; + } + + String[] lines = getLines(content); + if (lines.length == 1) { + return content; + } + + List linesList = new LinkedList<>(Arrays.asList(lines)); + + Collections.reverse(linesList); + + for (Iterator it = linesList.iterator(); it.hasNext(); ) { + String line = it.next(); + + if (line.trim().equals("*")) { + it.remove(); + } else { + break; + } + } + + Collections.reverse(linesList); + + return StringUtils.join(linesList.iterator(), EOL); + } + + /** + * @param content not null + * @return the javadoc comment with the given indentation + * @throws IOException if any + * @see #getJavadocComment(String, JavaAnnotatedElement, DocletTag) + */ + private static String alignIndentationJavadocLines(final String content, final String indent) throws IOException { + StringBuilder sb = new StringBuilder(); + for (String line : getLines(content)) { + if (sb.length() > 0) { + sb.append(EOL); + } + if (!line.trim().startsWith("*")) { + line = "*" + line; + } + sb.append(indent).append(" ").append(trimLeft(line)); + } + + return sb.toString(); + } + + /** + * Autodetect the indentation of a given line: + *

+     * autodetectIndentation( null ) = "";
+     * autodetectIndentation( "a" ) = "";
+     * autodetectIndentation( "    a" ) = "    ";
+     * autodetectIndentation( "\ta" ) = "\t";
+     * 
+ * + * @param line not null + * @return the indentation for the given line. + */ + private static String autodetectIndentation(final String line) { + if (StringUtils.isEmpty(line)) { + return ""; + } + + return line.substring(0, line.indexOf(trimLeft(line))); + } + + /** + * @param content not null + * @return an array of all content lines + * @throws IOException if any + */ + private static String[] getLines(final String content) throws IOException { + List lines = new LinkedList<>(); + + BufferedReader reader = new BufferedReader(new StringReader(content)); + String line = reader.readLine(); + while (line != null) { + lines.add(line); + line = reader.readLine(); + } + + return lines.toArray(new String[lines.size()]); + } + + /** + * Trim a given line on the left: + *
+     * trimLeft( null ) = "";
+     * trimLeft( "  " ) = "";
+     * trimLeft( "a" ) = "a";
+     * trimLeft( "    a" ) = "a";
+     * trimLeft( "\ta" ) = "a";
+     * trimLeft( "    a    " ) = "a    ";
+     * 
+ * + * @param text + * @return the text trimmed on left side or empty if text is null. + */ + private static String trimLeft(final String text) { + if (StringUtils.isEmpty(text) || StringUtils.isEmpty(text.trim())) { + return ""; + } + + String textTrimmed = text.trim(); + return text.substring(text.indexOf(textTrimmed)); + } + + /** + * Trim a given line on the right: + *
+     * trimRight( null ) = "";
+     * trimRight( "  " ) = "";
+     * trimRight( "a" ) = "a";
+     * trimRight( "a\t" ) = "a";
+     * trimRight( "    a    " ) = "    a";
+     * 
+ * + * @param text + * @return the text trimmed on tight side or empty if text is null. + */ + private static String trimRight(final String text) { + if (StringUtils.isEmpty(text) || StringUtils.isEmpty(text.trim())) { + return ""; + } + + String textTrimmed = text.trim(); + return text.substring(0, text.indexOf(textTrimmed) + textTrimmed.length()); + } + + /** + * Wrapper class for the entity's tags. + */ + class JavaEntityTags { + private final JavaAnnotatedElement entity; + + private final boolean isJavaMethod; + + /** + * List of tag names. + */ + private List namesTags; + + /** + * Map with java parameter as key and original Javadoc lines as values. + */ + private Map tagParams; + + private Set documentedParams = new HashSet<>(); + + /** + * Original javadoc lines. + */ + private String tagReturn; + + /** + * Map with java throw as key and original Javadoc lines as values. + */ + private Map tagThrows; + + /** + * Original javadoc lines for unknown tags. + */ + private List unknownsTags; + + JavaEntityTags(JavaAnnotatedElement entity, boolean isJavaMethod) { + this.entity = entity; + this.isJavaMethod = isJavaMethod; + this.namesTags = new LinkedList<>(); + this.tagParams = new LinkedHashMap<>(); + this.tagThrows = new LinkedHashMap<>(); + this.unknownsTags = new LinkedList<>(); + } + + public List getNamesTags() { + return namesTags; + } + + public String getJavadocReturnTag() { + return tagReturn; + } + + public void setJavadocReturnTag(String s) { + tagReturn = s; + } + + public List getUnknownTags() { + return unknownsTags; + } + + public void putJavadocParamTag(String paramName, String paramValue, String originalJavadocTag) { + documentedParams.add(paramName); + tagParams.put(paramValue, originalJavadocTag); + } + + public String getJavadocParamTag(String paramValue) { + String originalJavadocTag = tagParams.get(paramValue); + if (originalJavadocTag == null && getLog().isWarnEnabled()) { + getLog().warn(getMessage(paramValue, "javaEntityTags.tagParams")); + } + return originalJavadocTag; + } + + public boolean hasJavadocParamTag(String paramName) { + return documentedParams.contains(paramName); + } + + public void putJavadocThrowsTag(String paramName, String originalJavadocTag) { + tagThrows.put(paramName, originalJavadocTag); + } + + public String getJavadocThrowsTag(String paramName) { + return getJavadocThrowsTag(paramName, false); + } + + public String getJavadocThrowsTag(String paramName, boolean nullable) { + String originalJavadocTag = tagThrows.get(paramName); + if (!nullable && originalJavadocTag == null && getLog().isWarnEnabled()) { + getLog().warn(getMessage(paramName, "javaEntityTags.tagThrows")); + } + + return originalJavadocTag; + } + + private String getMessage(String paramName, String mapName) { + StringBuilder msg = new StringBuilder(); + msg.append("No param '") + .append(paramName) + .append("' key found in ") + .append(mapName) + .append(" for the entity: "); + if (isJavaMethod) { + JavaMethod javaMethod = (JavaMethod) entity; + msg.append(getJavaMethodAsString(javaMethod)); + } else { + JavaClass javaClass = (JavaClass) entity; + msg.append(javaClass.getFullyQualifiedName()); + } + + return msg.toString(); + } + + /** + * {@inheritDoc} + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + + sb.append("namesTags=").append(namesTags).append("\n"); + sb.append("tagParams=").append(tagParams).append("\n"); + sb.append("tagReturn=").append(tagReturn).append("\n"); + sb.append("tagThrows=").append(tagThrows).append("\n"); + sb.append("unknownsTags=").append(unknownsTags).append("\n"); + + return sb.toString(); + } + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java index 546f2b752..e9f38d544 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import java.io.File; import java.io.FileNotFoundException; @@ -159,9 +158,7 @@ * @see The javadoc Command * @since 2.0 */ -public abstract class AbstractJavadocMojo - extends AbstractMojo -{ +public abstract class AbstractJavadocMojo extends AbstractMojo { /** * Classifier used in the name of the javadoc-options XML file, and in the resources bundle * artifact that gets attached to the project. This one is used for non-test javadocs. @@ -183,7 +180,7 @@ public abstract class AbstractJavadocMojo /** * The Javadoc script file name when debug parameter is on, i.e. javadoc.bat or javadoc.sh */ - protected static final String DEBUG_JAVADOC_SCRIPT_NAME = "javadoc." + ( SystemUtils.IS_OS_WINDOWS ? "bat" : "sh" ); + protected static final String DEBUG_JAVADOC_SCRIPT_NAME = "javadoc." + (SystemUtils.IS_OS_WINDOWS ? "bat" : "sh"); /** * The options file name in the output directory when calling: @@ -218,7 +215,6 @@ public abstract class AbstractJavadocMojo private static final String PACKAGE_LIST = "package-list"; private static final String ELEMENT_LIST = "element-list"; - /** * For Javadoc options appears since Java 1.4. * See @@ -226,7 +222,7 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - private static final JavaVersion SINCE_JAVADOC_1_4 = JavaVersion.parse( "1.4" ); + private static final JavaVersion SINCE_JAVADOC_1_4 = JavaVersion.parse("1.4"); /** * For Javadoc options appears since Java 1.4.2. @@ -236,7 +232,7 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - private static final JavaVersion SINCE_JAVADOC_1_4_2 = JavaVersion.parse( "1.4.2" ); + private static final JavaVersion SINCE_JAVADOC_1_4_2 = JavaVersion.parse("1.4.2"); /** * For Javadoc options appears since Java 5.0. @@ -246,7 +242,7 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - private static final JavaVersion SINCE_JAVADOC_1_5 = JavaVersion.parse( "1.5" ); + private static final JavaVersion SINCE_JAVADOC_1_5 = JavaVersion.parse("1.5"); /** * For Javadoc options appears since Java 6.0. @@ -255,7 +251,7 @@ public abstract class AbstractJavadocMojo * * @since 2.4 */ - private static final JavaVersion SINCE_JAVADOC_1_6 = JavaVersion.parse( "1.6" ); + private static final JavaVersion SINCE_JAVADOC_1_6 = JavaVersion.parse("1.6"); /** * For Javadoc options appears since Java 8.0. @@ -264,7 +260,7 @@ public abstract class AbstractJavadocMojo * * @since 3.0.0 */ - private static final JavaVersion SINCE_JAVADOC_1_8 = JavaVersion.parse( "1.8" ); + private static final JavaVersion SINCE_JAVADOC_1_8 = JavaVersion.parse("1.8"); /** * @@ -289,7 +285,7 @@ public abstract class AbstractJavadocMojo @Component private RepositorySystem repoSystem; - @Parameter( defaultValue = "${repositorySystemSession}", readonly = true, required = true ) + @Parameter(defaultValue = "${repositorySystemSession}", readonly = true, required = true) private RepositorySystemSession repoSession; @Component @@ -317,7 +313,7 @@ public abstract class AbstractJavadocMojo * The current build session instance. This is used for * toolchain manager API calls. */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession session; /** @@ -325,22 +321,22 @@ public abstract class AbstractJavadocMojo * * @since 2.3 */ - @Parameter( defaultValue = "${settings}", readonly = true, required = true ) + @Parameter(defaultValue = "${settings}", readonly = true, required = true) private Settings settings; /** * The Maven Project Object */ - @Parameter( defaultValue = "${project}", readonly = true, required = true ) + @Parameter(defaultValue = "${project}", readonly = true, required = true) protected MavenProject project; - @Parameter( defaultValue = "${mojoExecution}", readonly = true ) + @Parameter(defaultValue = "${mojoExecution}", readonly = true) private MojoExecution mojo; /** * Specify if the Javadoc should operate in offline mode. */ - @Parameter( defaultValue = "${settings.offline}", required = true, readonly = true ) + @Parameter(defaultValue = "${settings.offline}", required = true, readonly = true) private boolean isOffline; /** @@ -353,7 +349,7 @@ public abstract class AbstractJavadocMojo * @see #docfilessubdirs * @since 2.1 */ - @Parameter( defaultValue = "${basedir}/src/main/javadoc" ) + @Parameter(defaultValue = "${basedir}/src/main/javadoc") private File javadocDirectory; /** @@ -380,7 +376,7 @@ public abstract class AbstractJavadocMojo * * @since 2.3 */ - @Parameter( property = "additionalJOption" ) + @Parameter(property = "additionalJOption") private String additionalJOption; /** @@ -417,19 +413,19 @@ public abstract class AbstractJavadocMojo * * @since 2.5 */ - @Parameter( property = "resourcesArtifacts" ) + @Parameter(property = "resourcesArtifacts") private ResourcesArtifact[] resourcesArtifacts; /** * The local repository where the artifacts are located. */ - @Parameter( property = "localRepository" ) + @Parameter(property = "localRepository") private ArtifactRepository localRepository; /** * The projects in the reactor for aggregation report. */ - @Parameter( property = "reactorProjects", readonly = true ) + @Parameter(property = "reactorProjects", readonly = true) private List reactorProjects; /** @@ -439,7 +435,7 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - @Parameter( property = "debug", defaultValue = "false" ) + @Parameter(property = "debug", defaultValue = "false") private boolean debug; /** @@ -448,7 +444,7 @@ public abstract class AbstractJavadocMojo * * @since 2.3 */ - @Parameter( property = "javadocExecutable" ) + @Parameter(property = "javadocExecutable") private String javadocExecutable; /** @@ -456,7 +452,7 @@ public abstract class AbstractJavadocMojo * * @since 2.3 */ - @Parameter( property = "javadocVersion" ) + @Parameter(property = "javadocVersion") private String javadocVersion; /** @@ -469,7 +465,7 @@ public abstract class AbstractJavadocMojo * * @since 2.5 */ - @Parameter( property = "maven.javadoc.skip", defaultValue = "false" ) + @Parameter(property = "maven.javadoc.skip", defaultValue = "false") protected boolean skip; /** @@ -477,16 +473,15 @@ public abstract class AbstractJavadocMojo * * @since 2.5 */ - @Parameter( property = "maven.javadoc.failOnError", defaultValue = "true" ) + @Parameter(property = "maven.javadoc.failOnError", defaultValue = "true") protected boolean failOnError; - /** * Specifies if the build will fail if there are warning during javadoc execution or not. * * @since 3.0.1 */ - @Parameter( property = "maven.javadoc.failOnWarnings", defaultValue = "false" ) + @Parameter(property = "maven.javadoc.failOnWarnings", defaultValue = "false") protected boolean failOnWarnings; /** @@ -508,7 +503,7 @@ public abstract class AbstractJavadocMojo * * @since 2.5 */ - @Parameter( property = "useStandardDocletOptions", defaultValue = "true" ) + @Parameter(property = "useStandardDocletOptions", defaultValue = "true") protected boolean useStandardDocletOptions; /** @@ -529,7 +524,7 @@ public abstract class AbstractJavadocMojo * @see #dependencyLinks * @since 2.6 */ - @Parameter( property = "detectLinks", defaultValue = "false" ) + @Parameter(property = "detectLinks", defaultValue = "false") private boolean detectLinks; /** @@ -548,7 +543,7 @@ public abstract class AbstractJavadocMojo * @see #offlineLinks * @since 2.6 */ - @Parameter( property = "detectOfflineLinks", defaultValue = "true" ) + @Parameter(property = "detectOfflineLinks", defaultValue = "true") private boolean detectOfflineLinks; /** @@ -564,7 +559,7 @@ public abstract class AbstractJavadocMojo * @see #javaApiLinks * @since 2.6 */ - @Parameter( property = "detectJavaApiLink", defaultValue = "true" ) + @Parameter(property = "detectJavaApiLink", defaultValue = "true") private boolean detectJavaApiLink; /** @@ -583,7 +578,7 @@ public abstract class AbstractJavadocMojo * * @since 2.6 */ - @Parameter( property = "javaApiLinks" ) + @Parameter(property = "javaApiLinks") private Properties javaApiLinks; /** @@ -592,7 +587,7 @@ public abstract class AbstractJavadocMojo * * @since 2.8 */ - @Parameter( property = "validateLinks", defaultValue = "false" ) + @Parameter(property = "validateLinks", defaultValue = "false") private boolean validateLinks; // ---------------------------------------------------------------------- @@ -607,7 +602,7 @@ public abstract class AbstractJavadocMojo * Javadoc option bootclasspath. * @since 2.5 */ - @Parameter( property = "bootclasspath" ) + @Parameter(property = "bootclasspath") private String bootclasspath; /** @@ -631,7 +626,7 @@ public abstract class AbstractJavadocMojo * Javadoc option bootclasspath * @since 2.5 */ - @Parameter( property = "bootclasspathArtifacts" ) + @Parameter(property = "bootclasspathArtifacts") private BootclasspathArtifact[] bootclasspathArtifacts; /** @@ -640,14 +635,14 @@ public abstract class AbstractJavadocMojo * "https://docs.oracle.com/en/java/javase/17/docs/specs/man/javadoc.html#options-for-javadoc"> * Javadoc option breakiterator. */ - @Parameter( property = "breakiterator", defaultValue = "false" ) + @Parameter(property = "breakiterator", defaultValue = "false") private boolean breakiterator; /** * Specifies the class file that starts the doclet used in generating the documentation. * @see Javadoc option doclet. */ - @Parameter( property = "doclet" ) + @Parameter(property = "doclet") private String doclet; /** @@ -667,7 +662,7 @@ public abstract class AbstractJavadocMojo *
* @see Javadoc option docletpath. */ - @Parameter( property = "docletArtifact" ) + @Parameter(property = "docletArtifact") private DocletArtifact docletArtifact; /** @@ -690,7 +685,7 @@ public abstract class AbstractJavadocMojo * @see Javadoc option docletpath. * @since 2.1 */ - @Parameter( property = "docletArtifacts" ) + @Parameter(property = "docletArtifacts") private DocletArtifact[] docletArtifacts; /** @@ -699,7 +694,7 @@ public abstract class AbstractJavadocMojo * a colon (:) or a semicolon (;). * @see Javadoc option docletpath. */ - @Parameter( property = "docletPath" ) + @Parameter(property = "docletPath") private String docletPath; /** @@ -710,7 +705,7 @@ public abstract class AbstractJavadocMojo * this was reverted in 2.5. * @see Javadoc option encoding. */ - @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}") private String encoding; /** @@ -730,7 +725,7 @@ public abstract class AbstractJavadocMojo * * @see Javadoc option exclude. */ - @Parameter( property = "excludePackageNames" ) + @Parameter(property = "excludePackageNames") private String excludePackageNames; /** @@ -738,14 +733,14 @@ public abstract class AbstractJavadocMojo * colon (:) or a semicolon (;). * @see Javadoc option extdirs. */ - @Parameter( property = "extdirs" ) + @Parameter(property = "extdirs") private String extdirs; /** * Specifies the locale that javadoc uses when generating documentation. * @see Javadoc option locale. */ - @Parameter( property = "locale" ) + @Parameter(property = "locale") private String locale; /** @@ -755,7 +750,7 @@ public abstract class AbstractJavadocMojo * m, mb, g, gb, t, tb. * If no unit specified, the default unit is m. */ - @Parameter( property = "maxmemory" ) + @Parameter(property = "maxmemory") private String maxmemory; /** @@ -765,7 +760,7 @@ public abstract class AbstractJavadocMojo * m, mb, g, gb, t, tb. * If no unit specified, the default unit is m. */ - @Parameter( property = "minmemory" ) + @Parameter(property = "minmemory") private String minmemory; /** @@ -773,7 +768,7 @@ public abstract class AbstractJavadocMojo * Javadoc 1.1. This is no longer supported since Javadoc 1.4 (shipped with JDK 1.4) * @see Javadoc option 1.1. */ - @Parameter( property = "old", defaultValue = "false" ) + @Parameter(property = "old", defaultValue = "false") private boolean old; /** @@ -784,7 +779,7 @@ public abstract class AbstractJavadocMojo * @see Javadoc option overview. *
*/ - @Parameter( property = "overview", defaultValue = "${basedir}/src/main/javadoc/overview.html" ) + @Parameter(property = "overview", defaultValue = "${basedir}/src/main/javadoc/overview.html") private File overview; /** @@ -797,7 +792,7 @@ public abstract class AbstractJavadocMojo * Since Java 5.0. * @see Javadoc option quiet. */ - @Parameter( property = "quiet", defaultValue = "false" ) + @Parameter(property = "quiet", defaultValue = "false") private boolean quiet; /** @@ -811,14 +806,14 @@ public abstract class AbstractJavadocMojo * * @see Javadoc options private, protected, public and package */ - @Parameter( property = "show", defaultValue = "protected" ) + @Parameter(property = "show", defaultValue = "protected") private String show; /** * Provide source compatibility with specified release. Since JDK 9 rather use {@link #release}. * @see Javadoc option source. */ - @Parameter( property = "source", defaultValue = "${maven.compiler.source}" ) + @Parameter(property = "source", defaultValue = "${maven.compiler.source}") private String source; /** @@ -827,7 +822,7 @@ public abstract class AbstractJavadocMojo * @since JDK 9 * @since 3.1.0 */ - @Parameter( defaultValue = "${maven.compiler.release}" ) + @Parameter(defaultValue = "${maven.compiler.release}") private String release; /** @@ -835,7 +830,7 @@ public abstract class AbstractJavadocMojo * multiple paths by separating them with a colon (:) or a semicolon (;). * @see Javadoc option sourcepath. */ - @Parameter( property = "sourcepath" ) + @Parameter(property = "sourcepath") private String sourcepath; /** @@ -843,14 +838,14 @@ public abstract class AbstractJavadocMojo * colons (:). * @see Javadoc option subpackages. */ - @Parameter( property = "subpackages" ) + @Parameter(property = "subpackages") private String subpackages; /** * Provides more detailed messages while javadoc is running. * @see Javadoc option verbose. */ - @Parameter( property = "verbose", defaultValue = "false" ) + @Parameter(property = "verbose", defaultValue = "false") private boolean verbose; // ---------------------------------------------------------------------- @@ -861,7 +856,7 @@ public abstract class AbstractJavadocMojo * Specifies whether or not the author text is included in the generated Javadocs. * @see Doclet option author. */ - @Parameter( property = "author", defaultValue = "true" ) + @Parameter(property = "author", defaultValue = "true") private boolean author; /** @@ -873,9 +868,10 @@ public abstract class AbstractJavadocMojo * be used as {currentYear}. This way it is possible to generate reproducible javadoc jars. * @see Doclet option bottom. */ - @Parameter( property = "bottom", - defaultValue = "Copyright © {inceptionYear}–{currentYear} {organizationName}. " - + "All rights reserved." ) + @Parameter( + property = "bottom", + defaultValue = "Copyright © {inceptionYear}–{currentYear} {organizationName}. " + + "All rights reserved.") private String bottom; /** @@ -883,7 +879,7 @@ public abstract class AbstractJavadocMojo * the {@link #docencoding} parameter. * @see Doclet option charset. */ - @Parameter( property = "charset" ) + @Parameter(property = "charset") private String charset; /** @@ -891,7 +887,7 @@ public abstract class AbstractJavadocMojo * UTF-8. * @see Doclet option docencoding. */ - @Parameter( property = "docencoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "docencoding", defaultValue = "${project.reporting.outputEncoding}") private String docencoding; /** @@ -902,7 +898,7 @@ public abstract class AbstractJavadocMojo * @see #excludedocfilessubdir * @see #javadocDirectory */ - @Parameter( property = "docfilessubdirs", defaultValue = "false" ) + @Parameter(property = "docfilessubdirs", defaultValue = "false") private boolean docfilessubdirs; /** @@ -911,14 +907,14 @@ public abstract class AbstractJavadocMojo * * @since 3.0.0 */ - @Parameter( property = "doclint" ) + @Parameter(property = "doclint") private String doclint; /** * Specifies the title to be placed near the top of the overview summary file. * @see Doclet option doctitle. */ - @Parameter( property = "doctitle", defaultValue = "${project.name} ${project.version} API" ) + @Parameter(property = "doctitle", defaultValue = "${project.name} ${project.version} API") private String doctitle; /** @@ -927,14 +923,14 @@ public abstract class AbstractJavadocMojo * @see Doclet option excludedocfilessubdir. * @see #docfilessubdirs */ - @Parameter( property = "excludedocfilessubdir" ) + @Parameter(property = "excludedocfilessubdir") private String excludedocfilessubdir; /** * Specifies the footer text to be placed at the bottom of each output file. * @see Doclet option footer. */ - @Parameter( property = "footer" ) + @Parameter(property = "footer") private String footer; /** @@ -973,7 +969,7 @@ public abstract class AbstractJavadocMojo * Specifies the header text to be placed at the top of each output file. * @see Doclet option header. */ - @Parameter( property = "header" ) + @Parameter(property = "header") private String header; /** @@ -1017,7 +1013,7 @@ public abstract class AbstractJavadocMojo * groupId:artifactId:version javadoc plugin dependency. * @see Doclet option helpfile. */ - @Parameter( property = "helpfile" ) + @Parameter(property = "helpfile") private String helpfile; /** @@ -1026,7 +1022,7 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - @Parameter( property = "keywords", defaultValue = "false" ) + @Parameter(property = "keywords", defaultValue = "false") private boolean keywords; /** @@ -1035,7 +1031,7 @@ public abstract class AbstractJavadocMojo * Notes: *
    *
  1. only used if {@code isOffline} is set to false.
  2. - *
  3. all given links should have a fetchable /package-list or /element-list + *
  4. all given links should have a fetchable /package-list or /element-list * (since Java 10). For instance: *
          * <links>
    @@ -1050,10 +1046,9 @@ public abstract class AbstractJavadocMojo
          * 
* @see Doclet option link. */ - @Parameter( property = "links" ) + @Parameter(property = "links") protected ArrayList links; - /** * Redefine the apidoc URL for specific dependencies when using {@link #detectLinks}. * Useful if the dependency wasn't build with Maven or when the apidocs have been moved. @@ -1080,14 +1075,14 @@ public abstract class AbstractJavadocMojo * @see Doclet option linksource/a>. *
*/ - @Parameter( property = "linksource", defaultValue = "false" ) + @Parameter(property = "linksource", defaultValue = "false") private boolean linksource; /** * Suppress the entire comment body, including the main description and all tags, generating only declarations. * @see
Doclet option nocomment. */ - @Parameter( property = "nocomment", defaultValue = "false" ) + @Parameter(property = "nocomment", defaultValue = "false") private boolean nocomment; /** @@ -1095,7 +1090,7 @@ public abstract class AbstractJavadocMojo * @see Doclet option nodeprecated. *
*/ - @Parameter( property = "nodeprecated", defaultValue = "false" ) + @Parameter(property = "nodeprecated", defaultValue = "false") private boolean nodeprecated; /** @@ -1104,7 +1099,7 @@ public abstract class AbstractJavadocMojo * @see * Doclet option nodeprecatedlist. */ - @Parameter( property = "nodeprecatedlist", defaultValue = "false" ) + @Parameter(property = "nodeprecatedlist", defaultValue = "false") private boolean nodeprecatedlist; /** @@ -1113,7 +1108,7 @@ public abstract class AbstractJavadocMojo * Note: could be in conflict with {@link #helpfile}. * @see Doclet option nohelp. */ - @Parameter( property = "nohelp", defaultValue = "false" ) + @Parameter(property = "nohelp", defaultValue = "false") private boolean nohelp; /** @@ -1122,14 +1117,14 @@ public abstract class AbstractJavadocMojo * Note: could be in conflict with {@link #splitindex} * @see Doclet option noindex. */ - @Parameter( property = "noindex", defaultValue = "false" ) + @Parameter(property = "noindex", defaultValue = "false") private boolean noindex; /** * Omits the navigation bar from the generated docs. * @see Doclet option nonavbar. */ - @Parameter( property = "nonavbar", defaultValue = "false" ) + @Parameter(property = "nonavbar", defaultValue = "false") private boolean nonavbar; /** @@ -1142,7 +1137,7 @@ public abstract class AbstractJavadocMojo * * @since 2.4 */ - @Parameter( property = "nooverview", defaultValue = "false" ) + @Parameter(property = "nooverview", defaultValue = "false") private boolean nooverview; /** @@ -1155,14 +1150,14 @@ public abstract class AbstractJavadocMojo * * @see Doclet option noqualifier. */ - @Parameter( property = "noqualifier" ) + @Parameter(property = "noqualifier") private String noqualifier; /** * Omits from the generated docs the "Since" sections associated with the since tags. * @see Doclet option nosince. */ - @Parameter( property = "nosince", defaultValue = "false" ) + @Parameter(property = "nosince", defaultValue = "false") private boolean nosince; /** @@ -1174,14 +1169,14 @@ public abstract class AbstractJavadocMojo * * @since 2.1 */ - @Parameter( property = "notimestamp", defaultValue = "false" ) + @Parameter(property = "notimestamp", defaultValue = "false") private boolean notimestamp; /** * Omits the class/interface hierarchy pages from the generated docs. * @see Doclet option notree */ - @Parameter( property = "notree", defaultValue = "false" ) + @Parameter(property = "notree", defaultValue = "false") private boolean notree; /** @@ -1203,15 +1198,18 @@ public abstract class AbstractJavadocMojo * @see OfflineLink. * @see Doclet option linkoffline */ - @Parameter( property = "offlineLinks" ) + @Parameter(property = "offlineLinks") private OfflineLink[] offlineLinks; /** * Specifies the destination directory where javadoc saves the generated HTML files. * @see Doclet option d */ - @Parameter( property = "destDir", alias = "destDir", defaultValue = "${project.build.directory}/apidocs", - required = true ) + @Parameter( + property = "destDir", + alias = "destDir", + defaultValue = "${project.build.directory}/apidocs", + required = true) protected File outputDirectory; /** @@ -1219,14 +1217,14 @@ public abstract class AbstractJavadocMojo * @see Bug Report about missing documentation * @since 2.1 */ - @Parameter( property = "packagesheader" ) + @Parameter(property = "packagesheader") private String packagesheader; /** * Generates compile-time warnings for missing serial tags. * @see Doclet option serialwarn */ - @Parameter( property = "serialwarn", defaultValue = "false" ) + @Parameter(property = "serialwarn", defaultValue = "false") private boolean serialwarn; /** @@ -1236,7 +1234,7 @@ public abstract class AbstractJavadocMojo * @see Doclet option sourcetab * @since 2.1 */ - @Parameter( property = "sourcetab", alias = "linksourcetab" ) + @Parameter(property = "sourcetab", alias = "linksourcetab") private int sourcetab; /** @@ -1246,7 +1244,7 @@ public abstract class AbstractJavadocMojo * Note: could be in conflict with {@link #noindex}. * @see Doclet option splitindex. */ - @Parameter( property = "splitindex", defaultValue = "false" ) + @Parameter(property = "splitindex", defaultValue = "false") private boolean splitindex; /** @@ -1256,7 +1254,7 @@ public abstract class AbstractJavadocMojo * Possible values: maven or java. * @deprecated This is no longer evaluated, instead use {@link #addStylesheets} to customize the CSS. */ - @Parameter( property = "stylesheet", defaultValue = "java" ) + @Parameter(property = "stylesheet", defaultValue = "java") @Deprecated private String stylesheet; @@ -1296,10 +1294,10 @@ public abstract class AbstractJavadocMojo * * Where path/to/your/resource/yourstylesheet.css is defined in the * groupId:artifactId:version javadoc plugin dependency. - * @see Doclet option + * @see Doclet option * stylesheetfile. */ - @Parameter( property = "stylesheetfile" ) + @Parameter(property = "stylesheetfile") private String stylesheetfile; /** @@ -1319,7 +1317,7 @@ public abstract class AbstractJavadocMojo * Specifies the class file that starts the taglet used in generating the documentation for that tag. * @see Doclet option taglet. */ - @Parameter( property = "taglet" ) + @Parameter(property = "taglet") private String taglet; /** @@ -1347,7 +1345,7 @@ public abstract class AbstractJavadocMojo * @see Doclet option tagletpath. * @since 2.1 */ - @Parameter( property = "tagletArtifact" ) + @Parameter(property = "tagletArtifact") private TagletArtifact tagletArtifact; /** @@ -1370,7 +1368,7 @@ public abstract class AbstractJavadocMojo * @see Doclet options taglet and tagletpath * @since 2.5 */ - @Parameter( property = "tagletArtifacts" ) + @Parameter(property = "tagletArtifacts") private TagletArtifact[] tagletArtifacts; /** @@ -1378,7 +1376,7 @@ public abstract class AbstractJavadocMojo * multiple paths by separating them with a colon (:) or a semicolon (;). * @see Doclet option tagletpath. */ - @Parameter( property = "tagletpath" ) + @Parameter(property = "tagletpath") private String tagletpath; /** @@ -1404,7 +1402,7 @@ public abstract class AbstractJavadocMojo * @see Doclet options taglet and tagletpath * @since 2.1 */ - @Parameter( property = "taglets" ) + @Parameter(property = "taglets") private Taglet[] taglets; /** @@ -1434,7 +1432,7 @@ public abstract class AbstractJavadocMojo * See Javadoc. * @see Doclet option tag. */ - @Parameter( property = "tags" ) + @Parameter(property = "tags") private Tag[] tags; /** @@ -1443,28 +1441,28 @@ public abstract class AbstractJavadocMojo * @see Doclet option top. * @since 2.4 */ - @Parameter( property = "top" ) + @Parameter(property = "top") private String top; /** * Includes one "Use" page for each documented class and package. * @see Doclet option use. */ - @Parameter( property = "use", defaultValue = "true" ) + @Parameter(property = "use", defaultValue = "true") private boolean use; /** * Includes the given version text in the generated docs. * @see Doclet option version. */ - @Parameter( property = "version", defaultValue = "true" ) + @Parameter(property = "version", defaultValue = "true") private boolean version; /** * Specifies the title to be placed in the HTML title tag. * @see Doclet option windowtitle. */ - @Parameter( property = "windowtitle", defaultValue = "${project.name} ${project.version} API" ) + @Parameter(property = "windowtitle", defaultValue = "${project.name} ${project.version} API") private String windowtitle; /** @@ -1473,7 +1471,7 @@ public abstract class AbstractJavadocMojo * * @since 2.7 */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") private boolean includeDependencySources; /** @@ -1482,7 +1480,7 @@ public abstract class AbstractJavadocMojo * @see #includeDependencySources * @since 2.7 */ - @Parameter( defaultValue = "${project.build.directory}/distro-javadoc-sources" ) + @Parameter(defaultValue = "${project.build.directory}/distro-javadoc-sources") private File sourceDependencyCacheDir; /** @@ -1494,7 +1492,7 @@ public abstract class AbstractJavadocMojo * @deprecated if these sources depend on transitive dependencies, those dependencies should be added to the pom as * direct dependencies */ - @Parameter( defaultValue = "false" ) + @Parameter(defaultValue = "false") @Deprecated private boolean includeTransitiveDependencySources; @@ -1522,7 +1520,7 @@ public abstract class AbstractJavadocMojo * * @since 2.7 */ - @Parameter( defaultValue = "${project.build.directory}/javadoc-bundle-options", readonly = true ) + @Parameter(defaultValue = "${project.build.directory}/javadoc-bundle-options", readonly = true) private File javadocOptionsDir; /** @@ -1570,11 +1568,11 @@ public abstract class AbstractJavadocMojo private List sourceFileExcludes; /** - * To apply a security fix on generated javadoc, see + * To apply a security fix on generated javadoc, see * * Comma separated list of modules (artifactId) to not add in aggregated javadoc @@ -1633,7 +1631,7 @@ public abstract class AbstractJavadocMojo * * @since 3.2.0 */ - @Parameter( property = "maven.javadoc.skippedModules" ) + @Parameter(property = "maven.javadoc.skippedModules") private String skippedModules; /** @@ -1643,7 +1641,7 @@ public abstract class AbstractJavadocMojo * * @since 3.2.0 */ - @Parameter( defaultValue = "${project.build.outputTimestamp}" ) + @Parameter(defaultValue = "${project.build.outputTimestamp}") protected String outputTimestamp; // ---------------------------------------------------------------------- @@ -1657,8 +1655,7 @@ public abstract class AbstractJavadocMojo * @see AggregatorJavadocReport * @see AggregatorTestJavadocReport */ - protected boolean isAggregator() - { + protected boolean isAggregator() { return false; } @@ -1667,21 +1664,18 @@ protected boolean isAggregator() * * @return true if the goal generates Test Javadocs, false otherwise. */ - protected boolean isTest() - { + protected boolean isTest() { return false; } /** * @return the output directory */ - protected String getOutputDirectory() - { + protected String getOutputDirectory() { return outputDirectory.getAbsoluteFile().toString(); } - protected MavenProject getProject() - { + protected MavenProject getProject() { return project; } @@ -1690,14 +1684,12 @@ protected MavenProject getProject() * @return the list of directories where compiled classes are placed for the given project. These dirs are * added in the javadoc classpath. */ - protected List getProjectBuildOutputDirs( MavenProject p ) - { - if ( StringUtils.isEmpty( p.getBuild().getOutputDirectory() ) ) - { + protected List getProjectBuildOutputDirs(MavenProject p) { + if (StringUtils.isEmpty(p.getBuild().getOutputDirectory())) { return Collections.emptyList(); } - return Collections.singletonList( new File( p.getBuild().getOutputDirectory() ) ); + return Collections.singletonList(new File(p.getBuild().getOutputDirectory())); } /** @@ -1706,38 +1698,28 @@ protected List getProjectBuildOutputDirs( MavenProject p ) * @param project * @return */ - protected File getClassesFile( MavenProject project ) - { - if ( !isAggregator() && isTest() ) - { + protected File getClassesFile(MavenProject project) { + if (!isAggregator() && isTest()) { return null; } - if ( project.getArtifact() != null && project.getArtifact().getFile() != null ) - { + if (project.getArtifact() != null && project.getArtifact().getFile() != null) { File artifactFile = project.getArtifact().getFile(); - if ( artifactFile.isDirectory() || artifactFile.getName().endsWith( ".jar" ) ) - { + if (artifactFile.isDirectory() || artifactFile.getName().endsWith(".jar")) { return artifactFile; } - } - else if ( project.getExecutionProject() != null - && project.getExecutionProject().getArtifact() != null - && project.getExecutionProject().getArtifact().getFile() != null ) - { + } else if (project.getExecutionProject() != null + && project.getExecutionProject().getArtifact() != null + && project.getExecutionProject().getArtifact().getFile() != null) { File artifactFile = project.getExecutionProject().getArtifact().getFile(); - if ( artifactFile.isDirectory() || artifactFile.getName().endsWith( ".jar" ) ) - { + if (artifactFile.isDirectory() || artifactFile.getName().endsWith(".jar")) { return artifactFile; } } - if ( project.getBuild().getOutputDirectory() != null ) - { - return new File( project.getBuild().getOutputDirectory() ); - } - else - { + if (project.getBuild().getOutputDirectory() != null) { + return new File(project.getBuild().getOutputDirectory()); + } else { return null; } } @@ -1746,134 +1728,114 @@ else if ( project.getExecutionProject() != null * @param p not null maven project * @return the list of source paths for the given project */ - protected List getProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getPackaging().toLowerCase() ) ) - { + protected List getProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getPackaging().toLowerCase())) { return Collections.emptyList(); } - return ( p.getCompileSourceRoots() == null - ? Collections.emptyList() - : new LinkedList<>( p.getCompileSourceRoots() ) ); + return (p.getCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getCompileSourceRoots())); } /** * @param p not null maven project * @return the list of source paths for the execution project of the given project */ - protected List getExecutionProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getExecutionProject().getPackaging().toLowerCase() ) ) - { + protected List getExecutionProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getExecutionProject().getPackaging().toLowerCase())) { return Collections.emptyList(); } - return ( p.getExecutionProject().getCompileSourceRoots() == null - ? Collections.emptyList() - : new LinkedList<>( p.getExecutionProject().getCompileSourceRoots() ) ); + return (p.getExecutionProject().getCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getExecutionProject().getCompileSourceRoots())); } /** * @return the current javadoc directory */ - protected File getJavadocDirectory() - { + protected File getJavadocDirectory() { return javadocDirectory; } /** * @return the doclint specific checks configuration */ - protected String getDoclint() - { + protected String getDoclint() { return doclint; } /** * @return the title to be placed near the top of the overview summary file */ - protected String getDoctitle() - { + protected String getDoctitle() { return doctitle; } /** * @return the overview documentation file from the user parameter or from the javadocdirectory */ - protected File getOverview() - { + protected File getOverview() { return overview; } /** * @return the title to be placed in the HTML title tag */ - protected String getWindowtitle() - { + protected String getWindowtitle() { return windowtitle; } /** * @return the charset attribute or the value of {@link #getDocencoding()} if null. */ - private String getCharset() - { - return ( StringUtils.isEmpty( charset ) ) ? getDocencoding() : charset; + private String getCharset() { + return (StringUtils.isEmpty(charset)) ? getDocencoding() : charset; } /** * @return the docencoding attribute or UTF-8 if null. */ - private String getDocencoding() - { - return ( StringUtils.isEmpty( docencoding ) ) ? ReaderFactory.UTF_8 : docencoding; + private String getDocencoding() { + return (StringUtils.isEmpty(docencoding)) ? ReaderFactory.UTF_8 : docencoding; } /** * @return the encoding attribute or the value of file.encoding system property if null. */ - private String getEncoding() - { - return ( StringUtils.isEmpty( encoding ) ) ? ReaderFactory.FILE_ENCODING : encoding; + private String getEncoding() { + return (StringUtils.isEmpty(encoding)) ? ReaderFactory.FILE_ENCODING : encoding; } @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - verifyRemovedParameter( "aggregator" ); - verifyRemovedParameter( "proxyHost" ); - verifyRemovedParameter( "proxyPort" ); - verifyReplacedParameter( "additionalparam", "additionalOptions" ); + public void execute() throws MojoExecutionException, MojoFailureException { + verifyRemovedParameter("aggregator"); + verifyRemovedParameter("proxyHost"); + verifyRemovedParameter("proxyPort"); + verifyReplacedParameter("additionalparam", "additionalOptions"); doExecute(); } abstract void doExecute() throws MojoExecutionException, MojoFailureException; - protected final void verifyRemovedParameter( String paramName ) - { + protected final void verifyRemovedParameter(String paramName) { Xpp3Dom configDom = mojo.getConfiguration(); - if ( configDom != null ) - { - if ( configDom.getChild( paramName ) != null ) - { - throw new IllegalArgumentException( "parameter '" + paramName - + "' has been removed from the plugin, please verify documentation." ); + if (configDom != null) { + if (configDom.getChild(paramName) != null) { + throw new IllegalArgumentException( + "parameter '" + paramName + "' has been removed from the plugin, please verify documentation."); } } } - private void verifyReplacedParameter( String oldParamName, String newParamNew ) - { + private void verifyReplacedParameter(String oldParamName, String newParamNew) { Xpp3Dom configDom = mojo.getConfiguration(); - if ( configDom != null ) - { - if ( configDom.getChild( oldParamName ) != null ) - { - throw new IllegalArgumentException( "parameter '" + oldParamName - + "' has been replaced with " + newParamNew + ", please verify documentation." ); + if (configDom != null) { + if (configDom.getChild(oldParamName) != null) { + throw new IllegalArgumentException("parameter '" + oldParamName + "' has been replaced with " + + newParamNew + ", please verify documentation."); } } } @@ -1885,40 +1847,31 @@ private void verifyReplacedParameter( String oldParamName, String newParamNew ) * @param unusedLocale the wanted locale (actually unused). * @throws MavenReportException if any */ - protected void executeReport( Locale unusedLocale ) - throws MavenReportException - { - if ( skip ) - { - getLog().info( "Skipping javadoc generation" ); + protected void executeReport(Locale unusedLocale) throws MavenReportException { + if (skip) { + getLog().info("Skipping javadoc generation"); return; } - if ( getLog().isDebugEnabled() ) - { + if (getLog().isDebugEnabled()) { this.debug = true; } // NOTE: Always generate this file, to allow javadocs from modules to be aggregated via // useDependencySources in a distro module build. - try - { + try { buildJavadocOptions(); - } - catch ( IOException e ) - { - throw new MavenReportException( "Failed to generate javadoc options file: " + e.getMessage(), e ); + } catch (IOException e) { + throw new MavenReportException("Failed to generate javadoc options file: " + e.getMessage(), e); } Collection sourcePaths = getSourcePaths(); - Collection collectedSourcePaths = sourcePaths.stream() - .flatMap( e -> e.getSourcePaths().stream() ) - .collect( Collectors.toList() ); + Collection collectedSourcePaths = + sourcePaths.stream().flatMap(e -> e.getSourcePaths().stream()).collect(Collectors.toList()); - Map> files = getFiles( collectedSourcePaths ); - if ( !canGenerateReport( files ) ) - { + Map> files = getFiles(collectedSourcePaths); + if (!canGenerateReport(files)) { return; } @@ -1927,38 +1880,30 @@ protected void executeReport( Locale unusedLocale ) // ---------------------------------------------------------------------- String jExecutable; - try - { + try { jExecutable = getJavadocExecutable(); + } catch (IOException e) { + throw new MavenReportException("Unable to find javadoc command: " + e.getMessage(), e); } - catch ( IOException e ) - { - throw new MavenReportException( "Unable to find javadoc command: " + e.getMessage(), e ); - } - setFJavadocVersion( new File( jExecutable ) ); + setFJavadocVersion(new File(jExecutable)); Collection packageNames; - if ( javadocRuntimeVersion.isAtLeast( "9" ) ) - { - packageNames = getPackageNamesRespectingJavaModules( sourcePaths ); - } - else - { - packageNames = getPackageNames( files ); + if (javadocRuntimeVersion.isAtLeast("9")) { + packageNames = getPackageNamesRespectingJavaModules(sourcePaths); + } else { + packageNames = getPackageNames(files); } // ---------------------------------------------------------------------- // Javadoc output directory as File // ---------------------------------------------------------------------- - File javadocOutputDirectory = new File( getOutputDirectory() ); - if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.isDirectory() ) - { - throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not a directory." ); + File javadocOutputDirectory = new File(getOutputDirectory()); + if (javadocOutputDirectory.exists() && !javadocOutputDirectory.isDirectory()) { + throw new MavenReportException("IOException: " + getOutputDirectory() + " is not a directory."); } - if ( javadocOutputDirectory.exists() && !javadocOutputDirectory.canWrite() ) - { - throw new MavenReportException( "IOException: " + getOutputDirectory() + " is not writable." ); + if (javadocOutputDirectory.exists() && !javadocOutputDirectory.canWrite()) { + throw new MavenReportException("IOException: " + getOutputDirectory() + " is not writable."); } javadocOutputDirectory.mkdirs(); @@ -1966,35 +1911,32 @@ protected void executeReport( Locale unusedLocale ) // Copy all resources // ---------------------------------------------------------------------- - copyAllResources( javadocOutputDirectory ); + copyAllResources(javadocOutputDirectory); // ---------------------------------------------------------------------- // Create command line for Javadoc // ---------------------------------------------------------------------- Commandline cmd = new Commandline(); - cmd.getShell().setQuotedArgumentsEnabled( false ); // for Javadoc JVM args - cmd.setWorkingDirectory( javadocOutputDirectory.getAbsolutePath() ); - cmd.setExecutable( jExecutable ); + cmd.getShell().setQuotedArgumentsEnabled(false); // for Javadoc JVM args + cmd.setWorkingDirectory(javadocOutputDirectory.getAbsolutePath()); + cmd.setExecutable(jExecutable); // ---------------------------------------------------------------------- // Wrap Javadoc JVM args // ---------------------------------------------------------------------- - addMemoryArg( cmd, "-Xmx", this.maxmemory ); - addMemoryArg( cmd, "-Xms", this.minmemory ); - addProxyArg( cmd ); + addMemoryArg(cmd, "-Xmx", this.maxmemory); + addMemoryArg(cmd, "-Xms", this.minmemory); + addProxyArg(cmd); - if ( StringUtils.isNotEmpty( additionalJOption ) ) - { - cmd.createArg().setValue( additionalJOption ); + if (StringUtils.isNotEmpty(additionalJOption)) { + cmd.createArg().setValue(additionalJOption); } - if ( additionalJOptions != null && additionalJOptions.length != 0 ) - { - for ( String jo : additionalJOptions ) - { - cmd.createArg().setValue( jo ); + if (additionalJOptions != null && additionalJOptions.length != 0) { + for (String jo : additionalJOptions) { + cmd.createArg().setValue(jo); } } @@ -2004,13 +1946,10 @@ protected void executeReport( Locale unusedLocale ) List standardDocletArguments = new ArrayList<>(); Set offlineLinks; - if ( StringUtils.isEmpty( doclet ) || useStandardDocletOptions ) - { + if (StringUtils.isEmpty(doclet) || useStandardDocletOptions) { offlineLinks = getLinkofflines(); - addStandardDocletOptions( javadocOutputDirectory, standardDocletArguments, offlineLinks ); - } - else - { + addStandardDocletOptions(javadocOutputDirectory, standardDocletArguments, offlineLinks); + } else { offlineLinks = Collections.emptySet(); } @@ -2019,19 +1958,18 @@ protected void executeReport( Locale unusedLocale ) // ---------------------------------------------------------------------- List javadocArguments = new ArrayList<>(); - addJavadocOptions( javadocOutputDirectory, javadocArguments, sourcePaths, offlineLinks ); + addJavadocOptions(javadocOutputDirectory, javadocArguments, sourcePaths, offlineLinks); // ---------------------------------------------------------------------- // Write options file and include it in the command line // ---------------------------------------------------------------------- - List arguments = new ArrayList<>( javadocArguments.size() + standardDocletArguments.size() ); - arguments.addAll( javadocArguments ); - arguments.addAll( standardDocletArguments ); + List arguments = new ArrayList<>(javadocArguments.size() + standardDocletArguments.size()); + arguments.addAll(javadocArguments); + arguments.addAll(standardDocletArguments); - if ( arguments.size() > 0 ) - { - addCommandLineOptions( cmd, arguments, javadocOutputDirectory ); + if (arguments.size() > 0) { + addCommandLineOptions(cmd, arguments, javadocOutputDirectory); } // ---------------------------------------------------------------------- @@ -2042,47 +1980,38 @@ protected void executeReport( Locale unusedLocale ) // package-based mode and force javadoc into file-based mode unless subpackages are // specified. Subpackages take precedence over file-based include/excludes. Why? Because // getFiles(...) returns an empty list when subpackages are specified. - boolean includesExcludesActive = - ( sourceFileIncludes != null && !sourceFileIncludes.isEmpty() ) - || ( sourceFileExcludes != null && !sourceFileExcludes.isEmpty() ); - if ( includesExcludesActive && !StringUtils.isEmpty( subpackages ) ) - { - getLog().warn( "sourceFileIncludes and sourceFileExcludes have no effect when subpackages are specified!" ); + boolean includesExcludesActive = (sourceFileIncludes != null && !sourceFileIncludes.isEmpty()) + || (sourceFileExcludes != null && !sourceFileExcludes.isEmpty()); + if (includesExcludesActive && !StringUtils.isEmpty(subpackages)) { + getLog().warn("sourceFileIncludes and sourceFileExcludes have no effect when subpackages are specified!"); includesExcludesActive = false; } - if ( !packageNames.isEmpty() && !includesExcludesActive ) - { - addCommandLinePackages( cmd, javadocOutputDirectory, packageNames ); + if (!packageNames.isEmpty() && !includesExcludesActive) { + addCommandLinePackages(cmd, javadocOutputDirectory, packageNames); // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- - List specialFiles = getSpecialFiles( files ); + List specialFiles = getSpecialFiles(files); - if ( !specialFiles.isEmpty() ) - { - addCommandLineArgFile( cmd, javadocOutputDirectory, specialFiles ); + if (!specialFiles.isEmpty()) { + addCommandLineArgFile(cmd, javadocOutputDirectory, specialFiles); } - } - else - { + } else { // ---------------------------------------------------------------------- // Write argfile file and include it in the command line // ---------------------------------------------------------------------- List allFiles = new ArrayList<>(); - for ( Map.Entry> filesEntry : files.entrySet() ) - { - for ( String file : filesEntry.getValue() ) - { - allFiles.add( filesEntry.getKey().resolve( file ).toString() ); + for (Map.Entry> filesEntry : files.entrySet()) { + for (String file : filesEntry.getValue()) { + allFiles.add(filesEntry.getKey().resolve(file).toString()); } } - if ( !files.isEmpty() ) - { - addCommandLineArgFile( cmd, javadocOutputDirectory, allFiles ); + if (!files.isEmpty()) { + addCommandLineArgFile(cmd, javadocOutputDirectory, allFiles); } } @@ -2090,56 +2019,43 @@ protected void executeReport( Locale unusedLocale ) // Execute command line // ---------------------------------------------------------------------- - executeJavadocCommandLine( cmd, javadocOutputDirectory ); + executeJavadocCommandLine(cmd, javadocOutputDirectory); // delete generated javadoc files only if no error and no debug mode // [MJAVADOC-336] Use File.delete() instead of File.deleteOnExit() to // prevent these files from making their way into archives. - if ( !debug ) - { - for ( int i = 0; i < cmd.getArguments().length; i++ ) - { + if (!debug) { + for (int i = 0; i < cmd.getArguments().length; i++) { String arg = cmd.getArguments()[i].trim(); - if ( !arg.startsWith( "@" ) ) - { + if (!arg.startsWith("@")) { continue; } - File argFile = new File( javadocOutputDirectory, arg.substring( 1 ) ); - if ( argFile.exists() ) - { + File argFile = new File(javadocOutputDirectory, arg.substring(1)); + if (argFile.exists()) { argFile.delete(); } } - File scriptFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); - if ( scriptFile.exists() ) - { + File scriptFile = new File(javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME); + if (scriptFile.exists()) { scriptFile.delete(); } } - if ( applyJavadocSecurityFix ) - { + if (applyJavadocSecurityFix) { // finally, patch the Javadoc vulnerability in older Javadoc tools (CVE-2013-1571): - try - { - final int patched = fixFrameInjectionBug( javadocOutputDirectory, getDocencoding() ); - if ( patched > 0 ) - { - getLog().info( - String.format( "Fixed Javadoc frame injection vulnerability (CVE-2013-1571) in %d files.", - patched ) ); + try { + final int patched = fixFrameInjectionBug(javadocOutputDirectory, getDocencoding()); + if (patched > 0) { + getLog().info(String.format( + "Fixed Javadoc frame injection vulnerability (CVE-2013-1571) in %d files.", patched)); } + } catch (IOException e) { + throw new MavenReportException("Failed to patch javadocs vulnerability: " + e.getMessage(), e); } - catch ( IOException e ) - { - throw new MavenReportException( "Failed to patch javadocs vulnerability: " + e.getMessage(), e ); - } - } - else - { - getLog().info( "applying javadoc security fix has been disabled" ); + } else { + getLog().info("applying javadoc security fix has been disabled"); } } @@ -2150,40 +2066,29 @@ protected void executeReport( Locale unusedLocale ) * @return a List that contains the specific path for every source file * @throws MavenReportException {@link MavenReportException} issue while generating report */ - protected Map> getFiles( Collection sourcePaths ) - throws MavenReportException - { - Map> mappedFiles = new LinkedHashMap<>( sourcePaths.size() ); - if ( StringUtils.isEmpty( subpackages ) ) - { + protected Map> getFiles(Collection sourcePaths) throws MavenReportException { + Map> mappedFiles = new LinkedHashMap<>(sourcePaths.size()); + if (StringUtils.isEmpty(subpackages)) { Collection excludedPackages = getExcludedPackages(); final boolean autoExclude; - if ( release != null ) - { - autoExclude = JavaVersion.parse( release ).isBefore( "9" ); - } - else if ( source != null ) - { - autoExclude = JavaVersion.parse( source ).isBefore( "9" ); - } - else - { + if (release != null) { + autoExclude = JavaVersion.parse(release).isBefore("9"); + } else if (source != null) { + autoExclude = JavaVersion.parse(source).isBefore("9"); + } else { autoExclude = false; } - for ( Path sourcePath : sourcePaths ) - { + for (Path sourcePath : sourcePaths) { File sourceDirectory = sourcePath.toFile(); - List files = new ArrayList<>( JavadocUtil.getFilesFromSource( sourceDirectory, - sourceFileIncludes, sourceFileExcludes, - excludedPackages ) ); + List files = new ArrayList<>(JavadocUtil.getFilesFromSource( + sourceDirectory, sourceFileIncludes, sourceFileExcludes, excludedPackages)); - if ( autoExclude && files.remove( "module-info.java" ) ) - { - getLog().debug( "Auto exclude module-info.java due to source value" ); + if (autoExclude && files.remove("module-info.java")) { + getLog().debug("Auto exclude module-info.java due to source value"); } - mappedFiles.put( sourcePath, files ); + mappedFiles.put(sourcePath, files); } } @@ -2198,21 +2103,16 @@ else if ( source != null ) * @throws MavenReportException {@link MavenReportException} issue while generating report * @see JavadocUtil#pruneDirs(MavenProject, Collection) */ - protected Collection getSourcePaths() - throws MavenReportException - { + protected Collection getSourcePaths() throws MavenReportException { Collection mappedSourcePaths = new ArrayList<>(); - if ( StringUtils.isEmpty( sourcepath ) ) - { - if ( !"pom".equals( project.getPackaging() ) ) - { + if (StringUtils.isEmpty(sourcepath)) { + if (!"pom".equals(project.getPackaging())) { Set sourcePaths = - new LinkedHashSet<>( JavadocUtil.pruneDirs( project, getProjectSourceRoots( project ) ) ); + new LinkedHashSet<>(JavadocUtil.pruneDirs(project, getProjectSourceRoots(project))); - if ( project.getExecutionProject() != null ) - { - sourcePaths.addAll( JavadocUtil.pruneDirs( project, getExecutionProjectSourceRoots( project ) ) ); + if (project.getExecutionProject() != null) { + sourcePaths.addAll(JavadocUtil.pruneDirs(project, getExecutionProjectSourceRoots(project))); } /* @@ -2220,112 +2120,93 @@ protected Collection getSourcePaths() * the opposite. If not, the javadoc tool always copies doc files, even if -docfilessubdirs is not * setted. */ - if ( getJavadocDirectory() != null ) - { + if (getJavadocDirectory() != null) { File javadocDir = getJavadocDirectory(); - if ( javadocDir.exists() && javadocDir.isDirectory() ) - { - Collection l = - JavadocUtil.pruneDirs( project, - Collections.singletonList( getJavadocDirectory().getAbsolutePath() ) ); - sourcePaths.addAll( l ); + if (javadocDir.exists() && javadocDir.isDirectory()) { + Collection l = JavadocUtil.pruneDirs( + project, + Collections.singletonList(getJavadocDirectory().getAbsolutePath())); + sourcePaths.addAll(l); } } - if ( !sourcePaths.isEmpty() ) - { - mappedSourcePaths.add( buildJavadocModule( project, sourcePaths ) ); + if (!sourcePaths.isEmpty()) { + mappedSourcePaths.add(buildJavadocModule(project, sourcePaths)); } } - if ( isAggregator() ) - { - for ( MavenProject subProject : getAggregatedProjects() ) - { - if ( subProject != project ) - { + if (isAggregator()) { + for (MavenProject subProject : getAggregatedProjects()) { + if (subProject != project) { Collection additionalSourcePaths = new ArrayList<>(); - List sourceRoots = getProjectSourceRoots( subProject ); + List sourceRoots = getProjectSourceRoots(subProject); - if ( subProject.getExecutionProject() != null ) - { - sourceRoots.addAll( getExecutionProjectSourceRoots( subProject ) ); + if (subProject.getExecutionProject() != null) { + sourceRoots.addAll(getExecutionProjectSourceRoots(subProject)); } - ArtifactHandler artifactHandler = subProject.getArtifact().getArtifactHandler(); - if ( "java".equals( artifactHandler.getLanguage() ) ) - { - additionalSourcePaths.addAll( JavadocUtil.pruneDirs( subProject, sourceRoots ) ); + ArtifactHandler artifactHandler = + subProject.getArtifact().getArtifactHandler(); + if ("java".equals(artifactHandler.getLanguage())) { + additionalSourcePaths.addAll(JavadocUtil.pruneDirs(subProject, sourceRoots)); } - if ( getJavadocDirectory() != null ) - { - String javadocDirRelative = - PathUtils.toRelative( project.getBasedir(), - getJavadocDirectory().getAbsolutePath() ); - File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); - if ( javadocDir.exists() && javadocDir.isDirectory() ) - { - Collection l = JavadocUtil.pruneDirs( subProject, Collections.singletonList( - javadocDir.getAbsolutePath() ) ); - additionalSourcePaths.addAll( l ); + if (getJavadocDirectory() != null) { + String javadocDirRelative = PathUtils.toRelative( + project.getBasedir(), getJavadocDirectory().getAbsolutePath()); + File javadocDir = new File(subProject.getBasedir(), javadocDirRelative); + if (javadocDir.exists() && javadocDir.isDirectory()) { + Collection l = JavadocUtil.pruneDirs( + subProject, Collections.singletonList(javadocDir.getAbsolutePath())); + additionalSourcePaths.addAll(l); } } - if ( !additionalSourcePaths.isEmpty() ) - { - mappedSourcePaths.add( buildJavadocModule( subProject , additionalSourcePaths ) ); + if (!additionalSourcePaths.isEmpty()) { + mappedSourcePaths.add(buildJavadocModule(subProject, additionalSourcePaths)); } } } } - if ( includeDependencySources ) - { - mappedSourcePaths.addAll( getDependencySourcePaths() ); + if (includeDependencySources) { + mappedSourcePaths.addAll(getDependencySourcePaths()); } - } - else - { + } else { Collection sourcePaths = - JavadocUtil.pruneDirs( project, - new ArrayList<>( Arrays.asList( JavadocUtil.splitPath( sourcepath ) ) ) ); - if ( getJavadocDirectory() != null ) - { - Collection l = JavadocUtil.pruneDirs( project, Collections.singletonList( - getJavadocDirectory().getAbsolutePath() ) ); - sourcePaths.addAll( l ); + JavadocUtil.pruneDirs(project, new ArrayList<>(Arrays.asList(JavadocUtil.splitPath(sourcepath)))); + if (getJavadocDirectory() != null) { + Collection l = JavadocUtil.pruneDirs( + project, Collections.singletonList(getJavadocDirectory().getAbsolutePath())); + sourcePaths.addAll(l); } - if ( !sourcePaths.isEmpty() ) - { - mappedSourcePaths.add( new JavadocModule( ArtifactUtils.versionlessKey( project.getGroupId(), - project.getArtifactId() ), - getClassesFile( project ), - sourcePaths ) ); + if (!sourcePaths.isEmpty()) { + mappedSourcePaths.add(new JavadocModule( + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()), + getClassesFile(project), + sourcePaths)); } } return mappedSourcePaths; } - private JavadocModule buildJavadocModule( MavenProject project, Collection sourcePaths ) - { - File classessFile = getClassesFile( project ); - ResolvePathResult resolvePathResult = getResolvePathResult( classessFile ); - if ( resolvePathResult == null ) - { - return new JavadocModule( ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ), - classessFile, - sourcePaths ); - } - else - { - return new JavadocModule( ArtifactUtils.versionlessKey( project.getGroupId(), project.getArtifactId() ), - classessFile, - sourcePaths, - resolvePathResult.getModuleDescriptor(), - resolvePathResult.getModuleNameSource() ); + private JavadocModule buildJavadocModule(MavenProject project, Collection sourcePaths) { + File classessFile = getClassesFile(project); + ResolvePathResult resolvePathResult = getResolvePathResult(classessFile); + if (resolvePathResult == null) { + return new JavadocModule( + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()), + classessFile, + sourcePaths); + } else { + return new JavadocModule( + ArtifactUtils.versionlessKey(project.getGroupId(), project.getArtifactId()), + classessFile, + sourcePaths, + resolvePathResult.getModuleDescriptor(), + resolvePathResult.getModuleNameSource()); } } @@ -2335,34 +2216,29 @@ private JavadocModule buildJavadocModule( MavenProject project, Collection * @param aggregatedProject the project being aggregated * @param reactorProjectsMap map of (still) available reactor projects */ - private Set modulesForAggregatedProject( MavenProject aggregatedProject, - Map reactorProjectsMap ) - { + private Set modulesForAggregatedProject( + MavenProject aggregatedProject, Map reactorProjectsMap) { // Maven does not supply an easy way to get the projects representing // the modules of a project. So we will get the paths to the base // directories of the modules from the project and compare with the // base directories of the projects in the reactor. - if ( aggregatedProject.getModules().isEmpty() ) - { - return Collections.singleton( aggregatedProject ); + if (aggregatedProject.getModules().isEmpty()) { + return Collections.singleton(aggregatedProject); } Path basePath = aggregatedProject.getBasedir().toPath(); List modulePaths = new LinkedList<>(); - for ( String module : aggregatedProject.getModules() ) - { - modulePaths.add( basePath.resolve( module ).normalize() ); + for (String module : aggregatedProject.getModules()) { + modulePaths.add(basePath.resolve(module).normalize()); } Set aggregatedModules = new LinkedHashSet<>(); - for ( Path modulePath : modulePaths ) - { - MavenProject module = reactorProjectsMap.remove( modulePath ); - if ( module != null ) - { - aggregatedModules.addAll( modulesForAggregatedProject( module, reactorProjectsMap ) ); + for (Path modulePath : modulePaths) { + MavenProject module = reactorProjectsMap.remove(modulePath); + if (module != null) { + aggregatedModules.addAll(modulesForAggregatedProject(module, reactorProjectsMap)); } } @@ -2375,8 +2251,7 @@ private Set modulesForAggregatedProject( MavenProject aggregatedPr * @param config {@link SourceResolverConfig} * @return {@link SourceResolverConfig} */ - protected SourceResolverConfig configureDependencySourceResolution( final SourceResolverConfig config ) - { + protected SourceResolverConfig configureDependencySourceResolution(final SourceResolverConfig config) { return config.withCompileSources(); } @@ -2386,34 +2261,25 @@ protected SourceResolverConfig configureDependencySourceResolution( final Source * @return List of source paths. * @throws MavenReportException {@link MavenReportException} */ - protected final Collection getDependencySourcePaths() - throws MavenReportException - { - try - { - if ( sourceDependencyCacheDir.exists() ) - { - FileUtils.forceDelete( sourceDependencyCacheDir ); + protected final Collection getDependencySourcePaths() throws MavenReportException { + try { + if (sourceDependencyCacheDir.exists()) { + FileUtils.forceDelete(sourceDependencyCacheDir); sourceDependencyCacheDir.mkdirs(); } - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to delete cache directory: " + sourceDependencyCacheDir + "\nReason: " + e.getMessage(), e ); + "Failed to delete cache directory: " + sourceDependencyCacheDir + "\nReason: " + e.getMessage(), e); } final SourceResolverConfig config = getDependencySourceResolverConfig(); - try - { - return resourceResolver.resolveDependencySourcePaths( config ); - } - catch ( org.apache.maven.artifact.resolver.ArtifactResolutionException - | org.apache.maven.artifact.resolver.ArtifactNotFoundException e ) - { + try { + return resourceResolver.resolveDependencySourcePaths(config); + } catch (org.apache.maven.artifact.resolver.ArtifactResolutionException + | org.apache.maven.artifact.resolver.ArtifactNotFoundException e) { throw new MavenReportException( - "Failed to resolve one or more javadoc source/resource artifacts:\n\n" + e.getMessage(), e ); + "Failed to resolve one or more javadoc source/resource artifacts:\n\n" + e.getMessage(), e); } } @@ -2423,17 +2289,15 @@ protected final Collection getDependencySourcePaths() * * @return */ - private TransformableFilter createDependencyArtifactFilter() - { + private TransformableFilter createDependencyArtifactFilter() { Set dependencyArtifacts = project.getDependencyArtifacts(); - List artifactPatterns = new ArrayList<>( dependencyArtifacts.size() ); - for ( Artifact artifact : dependencyArtifacts ) - { - artifactPatterns.add( artifact.getGroupId() + ":" + artifact.getArtifactId() ); + List artifactPatterns = new ArrayList<>(dependencyArtifacts.size()); + for (Artifact artifact : dependencyArtifacts) { + artifactPatterns.add(artifact.getGroupId() + ":" + artifact.getArtifactId()); } - return new PatternInclusionsFilter( artifactPatterns ); + return new PatternInclusionsFilter(artifactPatterns); } /** @@ -2442,44 +2306,35 @@ private TransformableFilter createDependencyArtifactFilter() * * @since 2.7 */ - private SourceResolverConfig getDependencySourceResolverConfig() - { + private SourceResolverConfig getDependencySourceResolverConfig() { final List andFilters = new ArrayList<>(); final List dependencyIncludes = dependencySourceIncludes; final List dependencyExcludes = dependencySourceExcludes; - if ( !includeTransitiveDependencySources || isNotEmpty( dependencyIncludes ) || isNotEmpty( - dependencyExcludes ) ) - { - if ( !includeTransitiveDependencySources ) - { - andFilters.add( createDependencyArtifactFilter() ); + if (!includeTransitiveDependencySources || isNotEmpty(dependencyIncludes) || isNotEmpty(dependencyExcludes)) { + if (!includeTransitiveDependencySources) { + andFilters.add(createDependencyArtifactFilter()); } - if ( isNotEmpty( dependencyIncludes ) ) - { - andFilters.add( new PatternInclusionsFilter( dependencyIncludes ) ); + if (isNotEmpty(dependencyIncludes)) { + andFilters.add(new PatternInclusionsFilter(dependencyIncludes)); } - if ( isNotEmpty( dependencyExcludes ) ) - { - andFilters.add( new PatternExclusionsFilter( dependencyExcludes ) ); + if (isNotEmpty(dependencyExcludes)) { + andFilters.add(new PatternExclusionsFilter(dependencyExcludes)); } } - return configureDependencySourceResolution( new SourceResolverConfig( project, - getProjectBuildingRequest( project ), - sourceDependencyCacheDir ) - .withReactorProjects( this.reactorProjects ) ) - .withFilter( new AndFilter( andFilters ) ); - + return configureDependencySourceResolution( + new SourceResolverConfig(project, getProjectBuildingRequest(project), sourceDependencyCacheDir) + .withReactorProjects(this.reactorProjects)) + .withFilter(new AndFilter(andFilters)); } - private ProjectBuildingRequest getProjectBuildingRequest( MavenProject currentProject ) - { - return new DefaultProjectBuildingRequest( session.getProjectBuildingRequest() ) - .setRemoteRepositories( currentProject.getRemoteArtifactRepositories() ); + private ProjectBuildingRequest getProjectBuildingRequest(MavenProject currentProject) { + return new DefaultProjectBuildingRequest(session.getProjectBuildingRequest()) + .setRemoteRepositories(currentProject.getRemoteArtifactRepositories()); } /** @@ -2489,17 +2344,14 @@ private ProjectBuildingRequest getProjectBuildingRequest( MavenProject currentPr * @param files the project files * @return a boolean that indicates whether javadoc report can be generated or not */ - protected boolean canGenerateReport( Map> files ) - { - for ( Collection filesValues : files.values() ) - { - if ( !filesValues.isEmpty() ) - { + protected boolean canGenerateReport(Map> files) { + for (Collection filesValues : files.values()) { + if (!filesValues.isEmpty()) { return true; } } - return !StringUtils.isEmpty( subpackages ); + return !StringUtils.isEmpty(subpackages); } // ---------------------------------------------------------------------- @@ -2514,23 +2366,19 @@ protected boolean canGenerateReport( Map> files ) * @return a String that contains the exclude argument that will be used by javadoc * @throws MavenReportException */ - private String getExcludedPackages( Collection sourcePaths ) - throws MavenReportException - { + private String getExcludedPackages(Collection sourcePaths) throws MavenReportException { List excludedNames = null; - if ( StringUtils.isNotEmpty( sourcepath ) && StringUtils.isNotEmpty( subpackages ) ) - { + if (StringUtils.isNotEmpty(sourcepath) && StringUtils.isNotEmpty(subpackages)) { Collection excludedPackages = getExcludedPackages(); - excludedNames = JavadocUtil.getExcludedPackages( sourcePaths, excludedPackages ); + excludedNames = JavadocUtil.getExcludedPackages(sourcePaths, excludedPackages); } String excludeArg = ""; - if ( StringUtils.isNotEmpty( subpackages ) && excludedNames != null ) - { + if (StringUtils.isNotEmpty(subpackages) && excludedNames != null) { // add the excludedpackage names - excludeArg = StringUtils.join( excludedNames.iterator(), ":" ); + excludeArg = StringUtils.join(excludedNames.iterator(), ":"); } return excludeArg; @@ -2544,13 +2392,11 @@ private String getExcludedPackages( Collection sourcePaths ) * string (colon (:) on Solaris or semicolon (;) on Windows). * @see File#pathSeparator */ - private String getSourcePath( Collection sourcePaths ) - { + private String getSourcePath(Collection sourcePaths) { String sourcePath = null; - if ( StringUtils.isEmpty( subpackages ) || StringUtils.isNotEmpty( sourcepath ) ) - { - sourcePath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); + if (StringUtils.isEmpty(subpackages) || StringUtils.isNotEmpty(sourcepath)) { + sourcePath = StringUtils.join(sourcePaths.iterator(), File.pathSeparator); } return sourcePath; @@ -2563,71 +2409,56 @@ private String getSourcePath( Collection sourcePaths ) * @return an array of String objects that contain the package names * @throws MavenReportException */ - private Collection getExcludedPackages() - throws MavenReportException - { + private Collection getExcludedPackages() throws MavenReportException { Set excluded = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getExcludePackageNames() ) ) - { - excluded.addAll( options.getExcludePackageNames() ); + if (options != null && isNotEmpty(options.getExcludePackageNames())) { + excluded.addAll(options.getExcludePackageNames()); } } } } // for the specified excludePackageNames - if ( StringUtils.isNotEmpty( excludePackageNames ) ) - { - List packageNames = Arrays.asList( excludePackageNames.split( "[,:;]" ) ); - excluded.addAll( trimValues( packageNames ) ); + if (StringUtils.isNotEmpty(excludePackageNames)) { + List packageNames = Arrays.asList(excludePackageNames.split("[,:;]")); + excluded.addAll(trimValues(packageNames)); } return excluded; } - private static List trimValues( List items ) - { - List result = new ArrayList<>( items.size() ); - for ( String item : items ) - { + private static List trimValues(List items) { + List result = new ArrayList<>(items.size()); + for (String item : items) { String trimmed = item.trim(); - if ( StringUtils.isEmpty( trimmed ) ) - { + if (StringUtils.isEmpty(trimmed)) { continue; } - result.add( trimmed ); + result.add(trimmed); } return result; } - private List toResolverDependencies( List dependencies ) - { - if ( dependencies == null ) - { + private List toResolverDependencies(List dependencies) { + if (dependencies == null) { return null; } - ArtifactTypeRegistry registry = RepositoryUtils.newArtifactTypeRegistry( artifactHandlerManager ); + ArtifactTypeRegistry registry = RepositoryUtils.newArtifactTypeRegistry(artifactHandlerManager); return dependencies.stream() - .map( d -> RepositoryUtils.toDependency( d, registry ) ) - .collect( Collectors.toList() ); + .map(d -> RepositoryUtils.toDependency(d, registry)) + .collect(Collectors.toList()); } /** @@ -2640,114 +2471,94 @@ private List toResolverDependencies( List getPathElements() - throws MavenReportException - { + private Collection getPathElements() throws MavenReportException { Set classpathElements = new LinkedHashSet<>(); Map compileArtifactMap = new LinkedHashMap<>(); - if ( isTest() ) - { - classpathElements.addAll( getProjectBuildOutputDirs( project ) ); + if (isTest()) { + classpathElements.addAll(getProjectBuildOutputDirs(project)); } - populateCompileArtifactMap( compileArtifactMap, project.getArtifacts() ); + populateCompileArtifactMap(compileArtifactMap, project.getArtifacts()); - if ( isAggregator() ) - { + if (isAggregator()) { Collection aggregatorProjects = getAggregatedProjects(); List reactorArtifacts = new ArrayList<>(); - for ( MavenProject p : aggregatorProjects ) - { - reactorArtifacts.add( p.getGroupId() + ':' + p.getArtifactId() ); - } - - DependencyFilter dependencyFilter = new AndDependencyFilter( - new PatternExclusionsDependencyFilter( reactorArtifacts ), - getDependencyScopeFilter() ); - - for ( MavenProject subProject : aggregatorProjects ) - { - if ( subProject != project ) - { - File projectArtifactFile = getClassesFile( subProject ); - if ( projectArtifactFile != null ) - { - classpathElements.add( projectArtifactFile ); - } - else - { - classpathElements.addAll( getProjectBuildOutputDirs( subProject ) ); + for (MavenProject p : aggregatorProjects) { + reactorArtifacts.add(p.getGroupId() + ':' + p.getArtifactId()); + } + + DependencyFilter dependencyFilter = new AndDependencyFilter( + new PatternExclusionsDependencyFilter(reactorArtifacts), getDependencyScopeFilter()); + + for (MavenProject subProject : aggregatorProjects) { + if (subProject != project) { + File projectArtifactFile = getClassesFile(subProject); + if (projectArtifactFile != null) { + classpathElements.add(projectArtifactFile); + } else { + classpathElements.addAll(getProjectBuildOutputDirs(subProject)); } - try - { + try { StringBuilder sb = new StringBuilder(); - sb.append( "Compiled artifacts for " ); - sb.append( subProject.getGroupId() ).append( ":" ); - sb.append( subProject.getArtifactId() ).append( ":" ); - sb.append( subProject.getVersion() ).append( '\n' ); + sb.append("Compiled artifacts for "); + sb.append(subProject.getGroupId()).append(":"); + sb.append(subProject.getArtifactId()).append(":"); + sb.append(subProject.getVersion()).append('\n'); List managedDependencies = null; - if ( subProject.getDependencyManagement() != null ) - { - managedDependencies = subProject.getDependencyManagement().getDependencies(); + if (subProject.getDependencyManagement() != null) { + managedDependencies = + subProject.getDependencyManagement().getDependencies(); } - CollectRequest collRequest = new CollectRequest( - toResolverDependencies( subProject.getDependencies() ), - toResolverDependencies( managedDependencies ), - subProject.getRemoteProjectRepositories() ); - DependencyRequest depRequest = new DependencyRequest( collRequest, dependencyFilter ); - for ( ArtifactResult artifactResult - : repoSystem.resolveDependencies( repoSession, depRequest ).getArtifactResults() ) - { - List artifacts = Collections.singletonList( - RepositoryUtils.toArtifact( artifactResult.getArtifact() ) ); - populateCompileArtifactMap( compileArtifactMap, artifacts ); - - sb.append( artifactResult.getArtifact().getFile() ).append( '\n' ); + CollectRequest collRequest = new CollectRequest( + toResolverDependencies(subProject.getDependencies()), + toResolverDependencies(managedDependencies), + subProject.getRemoteProjectRepositories()); + DependencyRequest depRequest = new DependencyRequest(collRequest, dependencyFilter); + for (ArtifactResult artifactResult : repoSystem + .resolveDependencies(repoSession, depRequest) + .getArtifactResults()) { + List artifacts = + Collections.singletonList(RepositoryUtils.toArtifact(artifactResult.getArtifact())); + populateCompileArtifactMap(compileArtifactMap, artifacts); + + sb.append(artifactResult.getArtifact().getFile()).append('\n'); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( sb.toString() ); + if (getLog().isDebugEnabled()) { + getLog().debug(sb.toString()); } - } - catch ( DependencyResolutionException e ) - { - throw new MavenReportException( e.getMessage(), e ); + } catch (DependencyResolutionException e) { + throw new MavenReportException(e.getMessage(), e); } } } } - for ( Artifact a : compileArtifactMap.values() ) - { - classpathElements.add( a.getFile() ); + for (Artifact a : compileArtifactMap.values()) { + classpathElements.add(a.getFile()); } - if ( additionalDependencies != null ) - { - for ( Dependency dependency : additionalDependencies ) - { - Artifact artifact = resolveDependency( dependency ); - getLog().debug( "add additional artifact with path " + artifact.getFile() ); - classpathElements.add( artifact.getFile() ); + if (additionalDependencies != null) { + for (Dependency dependency : additionalDependencies) { + Artifact artifact = resolveDependency(dependency); + getLog().debug("add additional artifact with path " + artifact.getFile()); + classpathElements.add(artifact.getFile()); } } return classpathElements; } - protected ScopeDependencyFilter getDependencyScopeFilter() - { - return new ScopeDependencyFilter( Arrays.asList( Artifact.SCOPE_COMPILE, - Artifact.SCOPE_PROVIDED, - Artifact.SCOPE_SYSTEM ), null ); + protected ScopeDependencyFilter getDependencyScopeFilter() { + return new ScopeDependencyFilter( + Arrays.asList(Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM), null); } /** @@ -2755,58 +2566,46 @@ protected ScopeDependencyFilter getDependencyScopeFilter() * @return {@link Artifact} * @throws MavenReportException when artifact could not be resolved */ - public Artifact resolveDependency( Dependency dependency ) - throws MavenReportException - { - ArtifactTypeRegistry registry = RepositoryUtils.newArtifactTypeRegistry( artifactHandlerManager ); - ArtifactRequest req = new ArtifactRequest( RepositoryUtils.toDependency( dependency, registry ).getArtifact(), - project.getRemoteProjectRepositories(), null ); - try - { - ArtifactResult resolutionResult = repoSystem.resolveArtifact( repoSession, req ); - return RepositoryUtils.toArtifact( resolutionResult.getArtifact( ) ); - } - catch ( ArtifactResolutionException e ) - { - throw new MavenReportException( "artifact resolver problem - " + e.getMessage(), e ); + public Artifact resolveDependency(Dependency dependency) throws MavenReportException { + ArtifactTypeRegistry registry = RepositoryUtils.newArtifactTypeRegistry(artifactHandlerManager); + ArtifactRequest req = new ArtifactRequest( + RepositoryUtils.toDependency(dependency, registry).getArtifact(), + project.getRemoteProjectRepositories(), + null); + try { + ArtifactResult resolutionResult = repoSystem.resolveArtifact(repoSession, req); + return RepositoryUtils.toArtifact(resolutionResult.getArtifact()); + } catch (ArtifactResolutionException e) { + throw new MavenReportException("artifact resolver problem - " + e.getMessage(), e); } } - - //TODO remove the part with ToolchainManager lookup once we depend on - //3.0.9 (have it as prerequisite). Define as regular component field then. - protected final Toolchain getToolchain() - { + // TODO remove the part with ToolchainManager lookup once we depend on + // 3.0.9 (have it as prerequisite). Define as regular component field then. + protected final Toolchain getToolchain() { Toolchain tc = null; - if ( jdkToolchain != null ) - { + if (jdkToolchain != null) { // Maven 3.3.1 has plugin execution scoped Toolchain Support - try - { - Method getToolchainsMethod = - toolchainManager.getClass().getMethod( "getToolchains", MavenSession.class, String.class, - Map.class ); + try { + Method getToolchainsMethod = toolchainManager + .getClass() + .getMethod("getToolchains", MavenSession.class, String.class, Map.class); - @SuppressWarnings( "unchecked" ) + @SuppressWarnings("unchecked") List tcs = - (List) getToolchainsMethod.invoke( toolchainManager, session, "jdk", - jdkToolchain ); + (List) getToolchainsMethod.invoke(toolchainManager, session, "jdk", jdkToolchain); - if ( tcs != null && tcs.size() > 0 ) - { - tc = tcs.get( 0 ); + if (tcs != null && tcs.size() > 0) { + tc = tcs.get(0); } - } - catch ( SecurityException | ReflectiveOperationException e ) - { + } catch (SecurityException | ReflectiveOperationException e) { // ignore } } - if ( tc == null ) - { - tc = toolchainManager.getToolchainFromBuildContext( "jdk", session ); + if (tc == null) { + tc = toolchainManager.getToolchainFromBuildContext("jdk", session); } return tc; @@ -2819,41 +2618,32 @@ protected final Toolchain getToolchain() * @param artifactList the list of artifacts that will be put in the map * @throws MavenReportException if any */ - private void populateCompileArtifactMap( Map compileArtifactMap, - Collection artifactList ) - throws MavenReportException - { - if ( artifactList == null ) - { + private void populateCompileArtifactMap(Map compileArtifactMap, Collection artifactList) + throws MavenReportException { + if (artifactList == null) { return; } - for ( Artifact newArtifact : artifactList ) - { + for (Artifact newArtifact : artifactList) { File file = newArtifact.getFile(); - if ( file == null ) - { + if (file == null) { throw new MavenReportException( - "Error in plugin descriptor - " + "dependency was not resolved for artifact: " - + newArtifact.getGroupId() + ":" + newArtifact.getArtifactId() + ":" - + newArtifact.getVersion() ); + "Error in plugin descriptor - " + "dependency was not resolved for artifact: " + + newArtifact.getGroupId() + ":" + newArtifact.getArtifactId() + ":" + + newArtifact.getVersion()); } - if ( compileArtifactMap.get( newArtifact.getDependencyConflictId() ) != null ) - { - Artifact oldArtifact = compileArtifactMap.get( newArtifact.getDependencyConflictId() ); + if (compileArtifactMap.get(newArtifact.getDependencyConflictId()) != null) { + Artifact oldArtifact = compileArtifactMap.get(newArtifact.getDependencyConflictId()); - ArtifactVersion oldVersion = new DefaultArtifactVersion( oldArtifact.getVersion() ); - ArtifactVersion newVersion = new DefaultArtifactVersion( newArtifact.getVersion() ); - if ( newVersion.compareTo( oldVersion ) > 0 ) - { - compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); + ArtifactVersion oldVersion = new DefaultArtifactVersion(oldArtifact.getVersion()); + ArtifactVersion newVersion = new DefaultArtifactVersion(newArtifact.getVersion()); + if (newVersion.compareTo(oldVersion) > 0) { + compileArtifactMap.put(newArtifact.getDependencyConflictId(), newArtifact); } - } - else - { - compileArtifactMap.put( newArtifact.getDependencyConflictId(), newArtifact ); + } else { + compileArtifactMap.put(newArtifact.getDependencyConflictId(), newArtifact); } } } @@ -2864,51 +2654,42 @@ private void populateCompileArtifactMap( Map compileArtifactMa * * @return a String that contains the text that will be displayed at the bottom of the javadoc */ - private String getBottomText() - { + private String getBottomText() { final String inceptionYear = project.getInceptionYear(); // get Reproducible Builds outputTimestamp date value or the current local date. - final LocalDate localDate = MavenArchiver.parseBuildOutputTimestamp( outputTimestamp ) - .map( instant -> instant.atZone( ZoneOffset.UTC ).toLocalDate() ) - .orElseGet( LocalDate::now ); - - final String currentYear = Integer.toString( localDate.getYear() ); - - String theBottom = StringUtils.replace( this.bottom, "{currentYear}", currentYear ); - - if ( ( inceptionYear == null ) || inceptionYear.equals( currentYear ) ) - { - theBottom = StringUtils.replace( theBottom, "{inceptionYear}–", "" ); - } - else - { - theBottom = StringUtils.replace( theBottom, "{inceptionYear}", inceptionYear ); - } - - if ( project.getOrganization() == null ) - { - theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); - } - else - { - if ( StringUtils.isNotEmpty( project.getOrganization().getName() ) ) - { - if ( StringUtils.isNotEmpty( project.getOrganization().getUrl() ) ) - { - theBottom = StringUtils.replace( theBottom, "{organizationName}", - "" - + project.getOrganization().getName() + "" ); + final LocalDate localDate = MavenArchiver.parseBuildOutputTimestamp(outputTimestamp) + .map(instant -> instant.atZone(ZoneOffset.UTC).toLocalDate()) + .orElseGet(LocalDate::now); + + final String currentYear = Integer.toString(localDate.getYear()); + + String theBottom = StringUtils.replace(this.bottom, "{currentYear}", currentYear); + + if ((inceptionYear == null) || inceptionYear.equals(currentYear)) { + theBottom = StringUtils.replace(theBottom, "{inceptionYear}–", ""); + } else { + theBottom = StringUtils.replace(theBottom, "{inceptionYear}", inceptionYear); + } + + if (project.getOrganization() == null) { + theBottom = StringUtils.replace(theBottom, " {organizationName}", ""); + } else { + if (StringUtils.isNotEmpty(project.getOrganization().getName())) { + if (StringUtils.isNotEmpty(project.getOrganization().getUrl())) { + theBottom = StringUtils.replace( + theBottom, + "{organizationName}", + "" + + project.getOrganization().getName() + ""); + } else { + theBottom = StringUtils.replace( + theBottom, + "{organizationName}", + project.getOrganization().getName()); } - else - { - theBottom = - StringUtils.replace( theBottom, "{organizationName}", project.getOrganization().getName() ); - } - } - else - { - theBottom = StringUtils.replace( theBottom, " {organizationName}", "" ); + } else { + theBottom = StringUtils.replace(theBottom, " {organizationName}", ""); } } @@ -2930,76 +2711,64 @@ private String getBottomText() * @return the stylesheet file absolute path as String. * @see #getResource(List, String) */ - private Optional getStylesheetFile( final File javadocOutputDirectory ) - { - if ( StringUtils.isEmpty( stylesheetfile ) ) - { - if ( "java".equalsIgnoreCase( stylesheet ) ) - { + private Optional getStylesheetFile(final File javadocOutputDirectory) { + if (StringUtils.isEmpty(stylesheetfile)) { + if ("java".equalsIgnoreCase(stylesheet)) { // use the default Javadoc tool stylesheet return Optional.empty(); } - getLog().warn( "Parameter 'stylesheet' is no longer evaluated, rather use 'addStylesheets'" - + " to customize the CSS!" ); + getLog().warn("Parameter 'stylesheet' is no longer evaluated, rather use 'addStylesheets'" + + " to customize the CSS!"); return Optional.empty(); } - if ( new File( stylesheetfile ).exists() ) - { - return Optional.of( new File( stylesheetfile ) ); + if (new File(stylesheetfile).exists()) { + return Optional.of(new File(stylesheetfile)); } - return getResource( new File( javadocOutputDirectory, DEFAULT_CSS_NAME ), stylesheetfile ); + return getResource(new File(javadocOutputDirectory, DEFAULT_CSS_NAME), stylesheetfile); } - private void addAddStyleSheets( List arguments ) throws MavenReportException - { - if ( addStylesheets == null ) - { + private void addAddStyleSheets(List arguments) throws MavenReportException { + if (addStylesheets == null) { return; } - for ( String addStylesheet : addStylesheets ) - { - Optional styleSheet = getAddStylesheet( getJavadocDirectory(), addStylesheet ); + for (String addStylesheet : addStylesheets) { + Optional styleSheet = getAddStylesheet(getJavadocDirectory(), addStylesheet); - if ( styleSheet.isPresent() ) - { - addArgIfNotEmpty( arguments, "--add-stylesheet", - JavadocUtil.quotedPathArgument( styleSheet.get().getAbsolutePath() ), - JavaVersion.parse( "10" ) ); + if (styleSheet.isPresent()) { + addArgIfNotEmpty( + arguments, + "--add-stylesheet", + JavadocUtil.quotedPathArgument(styleSheet.get().getAbsolutePath()), + JavaVersion.parse("10")); } } } - - private Optional getAddStylesheet( final File javadocOutputDirectory, final String stylesheet ) - throws MavenReportException - { - if ( StringUtils.isEmpty( stylesheet ) ) - { + private Optional getAddStylesheet(final File javadocOutputDirectory, final String stylesheet) + throws MavenReportException { + if (StringUtils.isEmpty(stylesheet)) { return Optional.empty(); } - File addstylesheetfile = new File( getJavadocDirectory(), stylesheet ); - if ( addstylesheetfile.exists() ) - { - Optional stylesheetfile = getStylesheetFile( javadocOutputDirectory ); - if ( stylesheetfile.isPresent() ) - { - if ( stylesheetfile.get().getName().equals( addstylesheetfile.getName() ) ) - { - throw new MavenReportException( "additional stylesheet must have a different name " - + "than stylesheetfile: " + stylesheetfile.get().getName() ); + File addstylesheetfile = new File(getJavadocDirectory(), stylesheet); + if (addstylesheetfile.exists()) { + Optional stylesheetfile = getStylesheetFile(javadocOutputDirectory); + if (stylesheetfile.isPresent()) { + if (stylesheetfile.get().getName().equals(addstylesheetfile.getName())) { + throw new MavenReportException("additional stylesheet must have a different name " + + "than stylesheetfile: " + stylesheetfile.get().getName()); } } - return Optional.of( addstylesheetfile ); + return Optional.of(addstylesheetfile); } - throw new MavenReportException( "additional stylesheet file does not exist: " - + addstylesheetfile.getAbsolutePath() ); + throw new MavenReportException( + "additional stylesheet file does not exist: " + addstylesheetfile.getAbsolutePath()); } /** @@ -3014,19 +2783,16 @@ private Optional getAddStylesheet( final File javadocOutputDirectory, fina * @see #getResource(File, String) * @since 2.6 */ - private Optional getHelpFile( final File javadocOutputDirectory ) - { - if ( StringUtils.isEmpty( helpfile ) ) - { + private Optional getHelpFile(final File javadocOutputDirectory) { + if (StringUtils.isEmpty(helpfile)) { return Optional.empty(); } - if ( new File( helpfile ).exists() ) - { - return Optional.of( new File( helpfile ) ); + if (new File(helpfile).exists()) { + return Optional.of(new File(helpfile)); } - return getResource( new File( javadocOutputDirectory, "help-doc.html" ), helpfile ); + return getResource(new File(javadocOutputDirectory, "help-doc.html"), helpfile); } /** @@ -3036,19 +2802,16 @@ private Optional getHelpFile( final File javadocOutputDirectory ) * * @return the access level */ - private String getAccessLevel() - { + private String getAccessLevel() { String accessLevel; - if ( "public".equalsIgnoreCase( show ) || "protected".equalsIgnoreCase( show ) || "package".equalsIgnoreCase( - show ) || "private".equalsIgnoreCase( show ) ) - { + if ("public".equalsIgnoreCase(show) + || "protected".equalsIgnoreCase(show) + || "package".equalsIgnoreCase(show) + || "private".equalsIgnoreCase(show)) { accessLevel = "-" + show; - } - else - { - if ( getLog().isErrorEnabled() ) - { - getLog().error( "Unrecognized access level to show '" + show + "'. Defaulting to protected." ); + } else { + if (getLog().isErrorEnabled()) { + getLog().error("Unrecognized access level to show '" + show + "'. Defaulting to protected."); } accessLevel = "-protected"; } @@ -3064,30 +2827,25 @@ private String getAccessLevel() * @throws MavenReportException if any * @see File#pathSeparator */ - private String getBootclassPath() - throws MavenReportException - { + private String getBootclassPath() throws MavenReportException { Set bootclasspathArtifacts = collectBootClasspathArtifacts(); List bootclassPath = new ArrayList<>(); - for ( BootclasspathArtifact aBootclasspathArtifact : bootclasspathArtifacts ) - { - if ( ( StringUtils.isNotEmpty( aBootclasspathArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( - aBootclasspathArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( - aBootclasspathArtifact.getVersion() ) ) ) - { - bootclassPath.addAll( getArtifactsAbsolutePath( aBootclasspathArtifact ) ); + for (BootclasspathArtifact aBootclasspathArtifact : bootclasspathArtifacts) { + if ((StringUtils.isNotEmpty(aBootclasspathArtifact.getGroupId())) + && (StringUtils.isNotEmpty(aBootclasspathArtifact.getArtifactId())) + && (StringUtils.isNotEmpty(aBootclasspathArtifact.getVersion()))) { + bootclassPath.addAll(getArtifactsAbsolutePath(aBootclasspathArtifact)); } } - bootclassPath = JavadocUtil.pruneFiles( bootclassPath ); + bootclassPath = JavadocUtil.pruneFiles(bootclassPath); StringBuilder path = new StringBuilder(); - path.append( StringUtils.join( bootclassPath.iterator(), File.pathSeparator ) ); + path.append(StringUtils.join(bootclassPath.iterator(), File.pathSeparator)); - if ( StringUtils.isNotEmpty( bootclasspath ) ) - { - path.append( JavadocUtil.unifyPathSeparator( bootclasspath ) ); + if (StringUtils.isNotEmpty(bootclasspath)) { + path.append(JavadocUtil.unifyPathSeparator(bootclasspath)); } return path.toString(); @@ -3105,31 +2863,25 @@ private String getBootclassPath() * @throws MavenReportException if any * @see File#pathSeparator */ - private String getDocletPath() - throws MavenReportException - { + private String getDocletPath() throws MavenReportException { Set docletArtifacts = collectDocletArtifacts(); List pathParts = new ArrayList<>(); - for ( DocletArtifact docletArtifact : docletArtifacts ) - { - if ( !isDocletArtifactEmpty( docletArtifact ) ) - { - pathParts.addAll( getArtifactsAbsolutePath( docletArtifact ) ); + for (DocletArtifact docletArtifact : docletArtifacts) { + if (!isDocletArtifactEmpty(docletArtifact)) { + pathParts.addAll(getArtifactsAbsolutePath(docletArtifact)); } } - if ( !StringUtils.isEmpty( docletPath ) ) - { - pathParts.add( JavadocUtil.unifyPathSeparator( docletPath ) ); + if (!StringUtils.isEmpty(docletPath)) { + pathParts.add(JavadocUtil.unifyPathSeparator(docletPath)); } - String path = StringUtils.join( pathParts.iterator(), File.pathSeparator ); + String path = StringUtils.join(pathParts.iterator(), File.pathSeparator); - if ( StringUtils.isEmpty( path ) && getLog().isWarnEnabled() ) - { - getLog().warn( "No docletpath option was found. Please review or " - + " or ." ); + if (StringUtils.isEmpty(path) && getLog().isWarnEnabled()) { + getLog().warn("No docletpath option was found. Please review or " + + " or ."); } return path; @@ -3142,15 +2894,14 @@ private String getDocletPath() * @return true if aDocletArtifact or the groupId/artifactId/version of the doclet artifact is null, * false otherwise. */ - private boolean isDocletArtifactEmpty( DocletArtifact aDocletArtifact ) - { - if ( aDocletArtifact == null ) - { + private boolean isDocletArtifactEmpty(DocletArtifact aDocletArtifact) { + if (aDocletArtifact == null) { return true; } - return StringUtils.isEmpty( aDocletArtifact.getGroupId() ) && StringUtils.isEmpty( - aDocletArtifact.getArtifactId() ) && StringUtils.isEmpty( aDocletArtifact.getVersion() ); + return StringUtils.isEmpty(aDocletArtifact.getGroupId()) + && StringUtils.isEmpty(aDocletArtifact.getArtifactId()) + && StringUtils.isEmpty(aDocletArtifact.getVersion()); } /** @@ -3161,412 +2912,309 @@ private boolean isDocletArtifactEmpty( DocletArtifact aDocletArtifact ) * @throws MavenReportException if any * @see File#pathSeparator */ - private String getTagletPath() - throws MavenReportException - { + private String getTagletPath() throws MavenReportException { Set tArtifacts = collectTagletArtifacts(); Collection pathParts = new ArrayList<>(); - for ( TagletArtifact tagletArtifact : tArtifacts ) - { - if ( ( tagletArtifact != null ) && ( StringUtils.isNotEmpty( tagletArtifact.getGroupId() ) ) - && ( StringUtils.isNotEmpty( tagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( - tagletArtifact.getVersion() ) ) ) - { - pathParts.addAll( getArtifactsAbsolutePath( tagletArtifact ) ); + for (TagletArtifact tagletArtifact : tArtifacts) { + if ((tagletArtifact != null) + && (StringUtils.isNotEmpty(tagletArtifact.getGroupId())) + && (StringUtils.isNotEmpty(tagletArtifact.getArtifactId())) + && (StringUtils.isNotEmpty(tagletArtifact.getVersion()))) { + pathParts.addAll(getArtifactsAbsolutePath(tagletArtifact)); } } Set taglets = collectTaglets(); - for ( Taglet taglet : taglets ) - { - if ( taglet == null ) - { + for (Taglet taglet : taglets) { + if (taglet == null) { continue; } - if ( ( taglet.getTagletArtifact() != null ) && ( StringUtils.isNotEmpty( - taglet.getTagletArtifact().getGroupId() ) ) && ( StringUtils.isNotEmpty( - taglet.getTagletArtifact().getArtifactId() ) ) && ( StringUtils.isNotEmpty( - taglet.getTagletArtifact().getVersion() ) ) ) - { - pathParts.addAll( JavadocUtil.pruneFiles( getArtifactsAbsolutePath( taglet.getTagletArtifact() ) ) ); - } - else if ( StringUtils.isNotEmpty( taglet.getTagletpath() ) ) - { - for ( Path dir : JavadocUtil.pruneDirs( project, Collections.singletonList( taglet.getTagletpath() ) ) ) - { - pathParts.add( dir.toString() ); + if ((taglet.getTagletArtifact() != null) + && (StringUtils.isNotEmpty(taglet.getTagletArtifact().getGroupId())) + && (StringUtils.isNotEmpty(taglet.getTagletArtifact().getArtifactId())) + && (StringUtils.isNotEmpty(taglet.getTagletArtifact().getVersion()))) { + pathParts.addAll(JavadocUtil.pruneFiles(getArtifactsAbsolutePath(taglet.getTagletArtifact()))); + } else if (StringUtils.isNotEmpty(taglet.getTagletpath())) { + for (Path dir : JavadocUtil.pruneDirs(project, Collections.singletonList(taglet.getTagletpath()))) { + pathParts.add(dir.toString()); } } } StringBuilder path = new StringBuilder(); - path.append( StringUtils.join( pathParts.iterator(), File.pathSeparator ) ); + path.append(StringUtils.join(pathParts.iterator(), File.pathSeparator)); - if ( StringUtils.isNotEmpty( tagletpath ) ) - { - path.append( JavadocUtil.unifyPathSeparator( tagletpath ) ); + if (StringUtils.isNotEmpty(tagletpath)) { + path.append(JavadocUtil.unifyPathSeparator(tagletpath)); } return path.toString(); } - private Set collectLinks() - throws MavenReportException - { + private Set collectLinks() throws MavenReportException { Set links = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getLinks() ) ) - { - links.addAll( options.getLinks() ); + if (options != null && isNotEmpty(options.getLinks())) { + links.addAll(options.getLinks()); } } } } - if ( isNotEmpty( this.links ) ) - { - links.addAll( this.links ); + if (isNotEmpty(this.links)) { + links.addAll(this.links); } - links.addAll( getDependenciesLinks() ); + links.addAll(getDependenciesLinks()); - return followLinks( links ); + return followLinks(links); } - private Set collectGroups() - throws MavenReportException - { + private Set collectGroups() throws MavenReportException { Set groups = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getGroups() ) ) - { - groups.addAll( options.getGroups() ); + if (options != null && isNotEmpty(options.getGroups())) { + groups.addAll(options.getGroups()); } } } } - if ( this.groups != null && this.groups.length > 0 ) - { - groups.addAll( Arrays.asList( this.groups ) ); + if (this.groups != null && this.groups.length > 0) { + groups.addAll(Arrays.asList(this.groups)); } return groups; } - private Set collectResourcesArtifacts() - throws MavenReportException - { + private Set collectResourcesArtifacts() throws MavenReportException { Set result = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getResourcesArtifacts() ) ) - { - result.addAll( options.getResourcesArtifacts() ); + if (options != null && isNotEmpty(options.getResourcesArtifacts())) { + result.addAll(options.getResourcesArtifacts()); } } } } - if ( this.resourcesArtifacts != null && this.resourcesArtifacts.length > 0 ) - { - result.addAll( Arrays.asList( this.resourcesArtifacts ) ); + if (this.resourcesArtifacts != null && this.resourcesArtifacts.length > 0) { + result.addAll(Arrays.asList(this.resourcesArtifacts)); } return result; } - private Set collectBootClasspathArtifacts() - throws MavenReportException - { + private Set collectBootClasspathArtifacts() throws MavenReportException { Set result = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getBootclasspathArtifacts() ) ) - { - result.addAll( options.getBootclasspathArtifacts() ); + if (options != null && isNotEmpty(options.getBootclasspathArtifacts())) { + result.addAll(options.getBootclasspathArtifacts()); } } } } - if ( this.bootclasspathArtifacts != null && this.bootclasspathArtifacts.length > 0 ) - { - result.addAll( Arrays.asList( this.bootclasspathArtifacts ) ); + if (this.bootclasspathArtifacts != null && this.bootclasspathArtifacts.length > 0) { + result.addAll(Arrays.asList(this.bootclasspathArtifacts)); } return result; } - private Set collectOfflineLinks() - throws MavenReportException - { + private Set collectOfflineLinks() throws MavenReportException { Set result = new LinkedHashSet<>(); OfflineLink javaApiLink = getDefaultJavadocApiLink(); - if ( javaApiLink != null ) - { - result.add( javaApiLink ); + if (javaApiLink != null) { + result.add(javaApiLink); } - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getOfflineLinks() ) ) - { - result.addAll( options.getOfflineLinks() ); + if (options != null && isNotEmpty(options.getOfflineLinks())) { + result.addAll(options.getOfflineLinks()); } } } } - if ( this.offlineLinks != null && this.offlineLinks.length > 0 ) - { - result.addAll( Arrays.asList( this.offlineLinks ) ); + if (this.offlineLinks != null && this.offlineLinks.length > 0) { + result.addAll(Arrays.asList(this.offlineLinks)); } return result; } - private Set collectTags() - throws MavenReportException - { + private Set collectTags() throws MavenReportException { Set tags = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getTags() ) ) - { - tags.addAll( options.getTags() ); + if (options != null && isNotEmpty(options.getTags())) { + tags.addAll(options.getTags()); } } } } - if ( this.tags != null && this.tags.length > 0 ) - { - tags.addAll( Arrays.asList( this.tags ) ); + if (this.tags != null && this.tags.length > 0) { + tags.addAll(Arrays.asList(this.tags)); } return tags; } - private Set collectTagletArtifacts() - throws MavenReportException - { + private Set collectTagletArtifacts() throws MavenReportException { Set tArtifacts = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getTagletArtifacts() ) ) - { - tArtifacts.addAll( options.getTagletArtifacts() ); + if (options != null && isNotEmpty(options.getTagletArtifacts())) { + tArtifacts.addAll(options.getTagletArtifacts()); } } } } - if ( tagletArtifact != null ) - { - tArtifacts.add( tagletArtifact ); + if (tagletArtifact != null) { + tArtifacts.add(tagletArtifact); } - if ( tagletArtifacts != null && tagletArtifacts.length > 0 ) - { - tArtifacts.addAll( Arrays.asList( tagletArtifacts ) ); + if (tagletArtifacts != null && tagletArtifacts.length > 0) { + tArtifacts.addAll(Arrays.asList(tagletArtifacts)); } return tArtifacts; } - private Set collectDocletArtifacts() - throws MavenReportException - { + private Set collectDocletArtifacts() throws MavenReportException { Set dArtifacts = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getDocletArtifacts() ) ) - { - dArtifacts.addAll( options.getDocletArtifacts() ); + if (options != null && isNotEmpty(options.getDocletArtifacts())) { + dArtifacts.addAll(options.getDocletArtifacts()); } } } } - if ( docletArtifact != null ) - { - dArtifacts.add( docletArtifact ); + if (docletArtifact != null) { + dArtifacts.add(docletArtifact); } - if ( docletArtifacts != null && docletArtifacts.length > 0 ) - { - dArtifacts.addAll( Arrays.asList( docletArtifacts ) ); + if (docletArtifacts != null && docletArtifacts.length > 0) { + dArtifacts.addAll(Arrays.asList(docletArtifacts)); } return dArtifacts; } - private Set collectTaglets() - throws MavenReportException - { + private Set collectTaglets() throws MavenReportException { Set result = new LinkedHashSet<>(); - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getTaglets() ) ) - { - result.addAll( options.getTaglets() ); + if (options != null && isNotEmpty(options.getTaglets())) { + result.addAll(options.getTaglets()); } } } } - if ( taglets != null && taglets.length > 0 ) - { - result.addAll( Arrays.asList( taglets ) ); + if (taglets != null && taglets.length > 0) { + result.addAll(Arrays.asList(taglets)); } return result; @@ -3579,43 +3227,34 @@ private Set collectTaglets() * @return a list of locale artifacts absolute path * @throws MavenReportException if any */ - private List getArtifactsAbsolutePath( JavadocPathArtifact javadocArtifact ) - throws MavenReportException - { - if ( ( StringUtils.isEmpty( javadocArtifact.getGroupId() ) ) && ( StringUtils.isEmpty( - javadocArtifact.getArtifactId() ) ) && ( StringUtils.isEmpty( javadocArtifact.getVersion() ) ) ) - { + private List getArtifactsAbsolutePath(JavadocPathArtifact javadocArtifact) throws MavenReportException { + if ((StringUtils.isEmpty(javadocArtifact.getGroupId())) + && (StringUtils.isEmpty(javadocArtifact.getArtifactId())) + && (StringUtils.isEmpty(javadocArtifact.getVersion()))) { return Collections.emptyList(); } List path = new ArrayList<>(); - try - { - Artifact artifact = createAndResolveArtifact( javadocArtifact ); - path.add( artifact.getFile().getAbsolutePath() ); + try { + Artifact artifact = createAndResolveArtifact(javadocArtifact); + path.add(artifact.getFile().getAbsolutePath()); DependencyFilter filter = new ScopeDependencyFilter( - Arrays.asList( Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED ), - Collections.emptySet() ); - DependencyRequest req = new DependencyRequest( - new DefaultDependencyNode( RepositoryUtils.toArtifact( artifact ) ), filter ); + Arrays.asList(Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED), Collections.emptySet()); + DependencyRequest req = + new DependencyRequest(new DefaultDependencyNode(RepositoryUtils.toArtifact(artifact)), filter); Iterable deps = - repoSystem.resolveDependencies( repoSession, req ).getArtifactResults(); - for ( ArtifactResult a : deps ) - { - path.add( a.getArtifact().getFile().getAbsolutePath() ); + repoSystem.resolveDependencies(repoSession, req).getArtifactResults(); + for (ArtifactResult a : deps) { + path.add(a.getArtifact().getFile().getAbsolutePath()); } return path; - } - catch ( ArtifactResolutionException e ) - { - throw new MavenReportException( "Unable to resolve artifact:" + javadocArtifact, e ); - } - catch ( DependencyResolutionException e ) - { - throw new MavenReportException( "Unable to resolve dependencies for:" + javadocArtifact, e ); + } catch (ArtifactResolutionException e) { + throw new MavenReportException("Unable to resolve artifact:" + javadocArtifact, e); + } catch (DependencyResolutionException e) { + throw new MavenReportException("Unable to resolve dependencies for:" + javadocArtifact, e); } } @@ -3624,20 +3263,20 @@ private List getArtifactsAbsolutePath( JavadocPathArtifact javadocArtifa * * @param javadocArtifact the {@link JavadocPathArtifact} to resolve * @return a resolved {@link Artifact} - * @throws org.eclipse.aether.resolution.ArtifactResolutionException + * @throws org.eclipse.aether.resolution.ArtifactResolutionException * @throws ArtifactResolverException issue while resolving artifact */ - private Artifact createAndResolveArtifact( JavadocPathArtifact javadocArtifact ) - throws org.eclipse.aether.resolution.ArtifactResolutionException - { - org.eclipse.aether.artifact.Artifact artifact = - new DefaultArtifact( javadocArtifact.getGroupId(), - javadocArtifact.getArtifactId(), - javadocArtifact.getClassifier(), - "jar", - javadocArtifact.getVersion() ); - ArtifactRequest req = new ArtifactRequest( artifact, project.getRemoteProjectRepositories(), null ); - return RepositoryUtils.toArtifact( repoSystem.resolveArtifact( repoSession, req ).getArtifact() ); + private Artifact createAndResolveArtifact(JavadocPathArtifact javadocArtifact) + throws org.eclipse.aether.resolution.ArtifactResolutionException { + org.eclipse.aether.artifact.Artifact artifact = new DefaultArtifact( + javadocArtifact.getGroupId(), + javadocArtifact.getArtifactId(), + javadocArtifact.getClassifier(), + "jar", + javadocArtifact.getVersion()); + ArtifactRequest req = new ArtifactRequest(artifact, project.getRemoteProjectRepositories(), null); + return RepositoryUtils.toArtifact( + repoSystem.resolveArtifact(repoSession, req).getArtifact()); } /** @@ -3648,19 +3287,13 @@ private Artifact createAndResolveArtifact( JavadocPathArtifact javadocArtifact ) * @param memory the JVM memory value to be set * @see JavadocUtil#parseJavadocMemory(String) */ - private void addMemoryArg( Commandline cmd, String arg, String memory ) - { - if ( StringUtils.isNotEmpty( memory ) ) - { - try - { - cmd.createArg().setValue( "-J" + arg + JavadocUtil.parseJavadocMemory( memory ) ); - } - catch ( IllegalArgumentException e ) - { - if ( getLog().isErrorEnabled() ) - { - getLog().error( "Malformed memory pattern for '" + arg + memory + "'. Ignore this option." ); + private void addMemoryArg(Commandline cmd, String arg, String memory) { + if (StringUtils.isNotEmpty(memory)) { + try { + cmd.createArg().setValue("-J" + arg + JavadocUtil.parseJavadocMemory(memory)); + } catch (IllegalArgumentException e) { + if (getLog().isErrorEnabled()) { + getLog().error("Malformed memory pattern for '" + arg + memory + "'. Ignore this option."); } } } @@ -3671,64 +3304,54 @@ private void addMemoryArg( Commandline cmd, String arg, String memory ) * * @param cmd the command line execution object where the argument will be added */ - private void addProxyArg( Commandline cmd ) - { - if ( settings == null || settings.getProxies().isEmpty() ) - { + private void addProxyArg(Commandline cmd) { + if (settings == null || settings.getProxies().isEmpty()) { return; } Map activeProxies = new HashMap<>(); - for ( Proxy proxy : settings.getProxies() ) - { - if ( proxy.isActive() ) - { + for (Proxy proxy : settings.getProxies()) { + if (proxy.isActive()) { String protocol = proxy.getProtocol(); - if ( !activeProxies.containsKey( protocol ) ) - { - activeProxies.put( protocol, proxy ); + if (!activeProxies.containsKey(protocol)) { + activeProxies.put(protocol, proxy); } } - } + } - if ( activeProxies.containsKey( "https" ) ) - { - Proxy httpsProxy = activeProxies.get( "https" ); - if ( StringUtils.isNotEmpty( httpsProxy.getHost() ) ) - { - cmd.createArg().setValue( "-J-Dhttps.proxyHost=" + httpsProxy.getHost() ); - cmd.createArg().setValue( "-J-Dhttps.proxyPort=" + httpsProxy.getPort() ); - - if ( StringUtils.isNotEmpty( httpsProxy.getNonProxyHosts() ) - && ( !activeProxies.containsKey( "http" ) - || StringUtils.isEmpty( activeProxies.get( "http" ).getNonProxyHosts() ) ) ) - { - cmd.createArg().setValue( "-J-Dhttp.nonProxyHosts=\"" - + httpsProxy.getNonProxyHosts().replace( "|", "^|" ) + "\"" ); + if (activeProxies.containsKey("https")) { + Proxy httpsProxy = activeProxies.get("https"); + if (StringUtils.isNotEmpty(httpsProxy.getHost())) { + cmd.createArg().setValue("-J-Dhttps.proxyHost=" + httpsProxy.getHost()); + cmd.createArg().setValue("-J-Dhttps.proxyPort=" + httpsProxy.getPort()); + + if (StringUtils.isNotEmpty(httpsProxy.getNonProxyHosts()) + && (!activeProxies.containsKey("http") + || StringUtils.isEmpty(activeProxies.get("http").getNonProxyHosts()))) { + cmd.createArg() + .setValue("-J-Dhttp.nonProxyHosts=\"" + + httpsProxy.getNonProxyHosts().replace("|", "^|") + "\""); } } } - if ( activeProxies.containsKey( "http" ) ) - { - Proxy httpProxy = activeProxies.get( "http" ); - if ( StringUtils.isNotEmpty( httpProxy.getHost() ) ) - { - cmd.createArg().setValue( "-J-Dhttp.proxyHost=" + httpProxy.getHost() ); - cmd.createArg().setValue( "-J-Dhttp.proxyPort=" + httpProxy.getPort() ); - - if ( !activeProxies.containsKey( "https" ) ) - { - cmd.createArg().setValue( "-J-Dhttps.proxyHost=" + httpProxy.getHost() ); - cmd.createArg().setValue( "-J-Dhttps.proxyPort=" + httpProxy.getPort() ); + if (activeProxies.containsKey("http")) { + Proxy httpProxy = activeProxies.get("http"); + if (StringUtils.isNotEmpty(httpProxy.getHost())) { + cmd.createArg().setValue("-J-Dhttp.proxyHost=" + httpProxy.getHost()); + cmd.createArg().setValue("-J-Dhttp.proxyPort=" + httpProxy.getPort()); + + if (!activeProxies.containsKey("https")) { + cmd.createArg().setValue("-J-Dhttps.proxyHost=" + httpProxy.getHost()); + cmd.createArg().setValue("-J-Dhttps.proxyPort=" + httpProxy.getPort()); } - if ( StringUtils.isNotEmpty( httpProxy.getNonProxyHosts() ) ) - { - cmd.createArg().setValue( "-J-Dhttp.nonProxyHosts=\"" - + httpProxy.getNonProxyHosts().replace( "|", "^|" ) + "\"" ); + if (StringUtils.isNotEmpty(httpProxy.getNonProxyHosts())) { + cmd.createArg() + .setValue("-J-Dhttp.nonProxyHosts=\"" + + httpProxy.getNonProxyHosts().replace("|", "^|") + "\""); } } } @@ -3743,49 +3366,39 @@ private void addProxyArg( Commandline cmd ) * @return the path of the Javadoc tool * @throws IOException if not found */ - private String getJavadocExecutable() - throws IOException - { + private String getJavadocExecutable() throws IOException { Toolchain tc = getToolchain(); - if ( tc != null ) - { - getLog().info( "Toolchain in maven-javadoc-plugin: " + tc ); - if ( javadocExecutable != null ) - { - getLog().warn( "Toolchains are ignored, 'javadocExecutable' parameter is set to " + javadocExecutable ); - } - else - { - javadocExecutable = tc.findTool( "javadoc" ); + if (tc != null) { + getLog().info("Toolchain in maven-javadoc-plugin: " + tc); + if (javadocExecutable != null) { + getLog().warn("Toolchains are ignored, 'javadocExecutable' parameter is set to " + javadocExecutable); + } else { + javadocExecutable = tc.findTool("javadoc"); } } - String javadocCommand = "javadoc" + ( SystemUtils.IS_OS_WINDOWS ? ".exe" : "" ); + String javadocCommand = "javadoc" + (SystemUtils.IS_OS_WINDOWS ? ".exe" : ""); File javadocExe; // ---------------------------------------------------------------------- // The javadoc executable is defined by the user // ---------------------------------------------------------------------- - if ( StringUtils.isNotEmpty( javadocExecutable ) ) - { - javadocExe = new File( javadocExecutable ); + if (StringUtils.isNotEmpty(javadocExecutable)) { + javadocExe = new File(javadocExecutable); - if ( javadocExe.isDirectory() ) - { - javadocExe = new File( javadocExe, javadocCommand ); + if (javadocExe.isDirectory()) { + javadocExe = new File(javadocExe, javadocCommand); } - if ( SystemUtils.IS_OS_WINDOWS && javadocExe.getName().indexOf( '.' ) < 0 ) - { - javadocExe = new File( javadocExe.getPath() + ".exe" ); + if (SystemUtils.IS_OS_WINDOWS && javadocExe.getName().indexOf('.') < 0) { + javadocExe = new File(javadocExe.getPath() + ".exe"); } - if ( !javadocExe.isFile() ) - { - throw new IOException( "The javadoc executable '" + javadocExe - + "' doesn't exist or is not a file. Verify the parameter." ); + if (!javadocExe.isFile()) { + throw new IOException("The javadoc executable '" + javadocExe + + "' doesn't exist or is not a file. Verify the parameter."); } return javadocExe.getAbsolutePath(); @@ -3825,55 +3438,46 @@ private String getJavadocExecutable() // ---------------------------------------------------------------------- // For IBM's JDK 1.2 // CHECKSTYLE_ON: LineLength - if ( SystemUtils.IS_OS_AIX ) - { + if (SystemUtils.IS_OS_AIX) { javadocExe = - new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "sh", javadocCommand ); + new File(SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "sh", javadocCommand); } // For Apple's JDK 1.6.x (and older?) on Mac OSX // CHECKSTYLE_OFF: MagicNumber - else if ( SystemUtils.IS_OS_MAC_OSX && !JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "1.7" ) ) + else if (SystemUtils.IS_OS_MAC_OSX && !JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("1.7")) // CHECKSTYLE_ON: MagicNumber { - javadocExe = new File( SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand ); - } - else if ( isJavaVersionAtLeast( org.apache.commons.lang3.JavaVersion.JAVA_9 ) ) - { - javadocExe = - new File( SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand ); - } - else - { + javadocExe = new File(SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand); + } else if (isJavaVersionAtLeast(org.apache.commons.lang3.JavaVersion.JAVA_9)) { + javadocExe = new File(SystemUtils.getJavaHome() + File.separator + "bin", javadocCommand); + } else { // Java <= 8 - javadocExe = - new File( SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "bin", javadocCommand ); + javadocExe = new File( + SystemUtils.getJavaHome() + File.separator + ".." + File.separator + "bin", javadocCommand); } // ---------------------------------------------------------------------- // Try to find javadocExe from JAVA_HOME environment variable // ---------------------------------------------------------------------- - if ( !javadocExe.exists() || !javadocExe.isFile() ) - { + if (!javadocExe.exists() || !javadocExe.isFile()) { Properties env = CommandLineUtils.getSystemEnvVars(); - String javaHome = env.getProperty( "JAVA_HOME" ); - if ( StringUtils.isEmpty( javaHome ) ) - { - throw new IOException( "The environment variable JAVA_HOME is not correctly set." ); + String javaHome = env.getProperty("JAVA_HOME"); + if (StringUtils.isEmpty(javaHome)) { + throw new IOException("The environment variable JAVA_HOME is not correctly set."); } - if ( ( !new File( javaHome ).getCanonicalFile().exists() ) - || ( new File( javaHome ).getCanonicalFile().isFile() ) ) - { - throw new IOException( "The environment variable JAVA_HOME=" + javaHome - + " doesn't exist or is not a valid directory." ); + if ((!new File(javaHome).getCanonicalFile().exists()) + || (new File(javaHome).getCanonicalFile().isFile())) { + throw new IOException("The environment variable JAVA_HOME=" + javaHome + + " doesn't exist or is not a valid directory."); } - javadocExe = new File( javaHome + File.separator + "bin", javadocCommand ); + javadocExe = new File(javaHome + File.separator + "bin", javadocCommand); } - if ( !javadocExe.getCanonicalFile().exists() || !javadocExe.getCanonicalFile().isFile() ) - { - throw new IOException( "The javadoc executable '" + javadocExe - + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable." ); + if (!javadocExe.getCanonicalFile().exists() + || !javadocExe.getCanonicalFile().isFile()) { + throw new IOException("The javadoc executable '" + javadocExe + + "' doesn't exist or is not a file. Verify the JAVA_HOME environment variable."); } return javadocExe.getAbsolutePath(); @@ -3886,42 +3490,29 @@ else if ( isJavaVersionAtLeast( org.apache.commons.lang3.JavaVersion.JAVA_9 ) ) * @throws MavenReportException if not found * @see JavadocUtil#getJavadocVersion(File) */ - private void setFJavadocVersion( File jExecutable ) - throws MavenReportException - { + private void setFJavadocVersion(File jExecutable) throws MavenReportException { JavaVersion jVersion; - try - { - jVersion = JavadocUtil.getJavadocVersion( jExecutable ); - } - catch ( IOException | CommandLineException | IllegalArgumentException e ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unable to find the javadoc version: " + e.getMessage() ); - getLog().warn( "Using the Java version instead of, i.e. " + JAVA_VERSION ); + try { + jVersion = JavadocUtil.getJavadocVersion(jExecutable); + } catch (IOException | CommandLineException | IllegalArgumentException e) { + if (getLog().isWarnEnabled()) { + getLog().warn("Unable to find the javadoc version: " + e.getMessage()); + getLog().warn("Using the Java version instead of, i.e. " + JAVA_VERSION); } jVersion = JAVA_VERSION; } - if ( StringUtils.isNotEmpty( javadocVersion ) ) - { - try - { - javadocRuntimeVersion = JavaVersion.parse( javadocVersion ); - } - catch ( NumberFormatException e ) - { - throw new MavenReportException( "Unable to parse javadoc version: " + e.getMessage(), e ); + if (StringUtils.isNotEmpty(javadocVersion)) { + try { + javadocRuntimeVersion = JavaVersion.parse(javadocVersion); + } catch (NumberFormatException e) { + throw new MavenReportException("Unable to parse javadoc version: " + e.getMessage(), e); } - if ( javadocRuntimeVersion.compareTo( jVersion ) != 0 && getLog().isWarnEnabled() ) - { - getLog().warn( "Are you sure about the parameter? It seems to be " + jVersion ); + if (javadocRuntimeVersion.compareTo(jVersion) != 0 && getLog().isWarnEnabled()) { + getLog().warn("Are you sure about the parameter? It seems to be " + jVersion); } - } - else - { + } else { javadocRuntimeVersion = jVersion; } } @@ -3933,9 +3524,8 @@ private void setFJavadocVersion( File jExecutable ) * @return true if the javadoc version is equal or greater than the * required version */ - private boolean isJavaDocVersionAtLeast( JavaVersion requiredVersion ) - { - return JAVA_VERSION.compareTo( requiredVersion ) >= 0; + private boolean isJavaDocVersionAtLeast(JavaVersion requiredVersion) { + return JAVA_VERSION.compareTo(requiredVersion) >= 0; } /** @@ -3946,11 +3536,9 @@ private boolean isJavaDocVersionAtLeast( JavaVersion requiredVersion ) * @param b the flag which controls if the argument is added or not. * @param value the argument value to be added. */ - private void addArgIf( List arguments, boolean b, String value ) - { - if ( b ) - { - arguments.add( value ); + private void addArgIf(List arguments, boolean b, String value) { + if (b) { + arguments.add(value); } } @@ -3965,20 +3553,14 @@ private void addArgIf( List arguments, boolean b, String value ) * @see #addArgIf(List, boolean, String) * @see #isJavaDocVersionAtLeast(JavaVersion) */ - private void addArgIf( List arguments, boolean b, String value, JavaVersion requiredJavaVersion ) - { - if ( b ) - { - if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) - { - addArgIf( arguments, true, value ); - } - else - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( value + " option is not supported on Java version < " + requiredJavaVersion - + ". Ignore this option." ); + private void addArgIf(List arguments, boolean b, String value, JavaVersion requiredJavaVersion) { + if (b) { + if (isJavaDocVersionAtLeast(requiredJavaVersion)) { + addArgIf(arguments, true, value); + } else { + if (getLog().isWarnEnabled()) { + getLog().warn(value + " option is not supported on Java version < " + requiredJavaVersion + + ". Ignore this option."); } } } @@ -3995,9 +3577,8 @@ private void addArgIf( List arguments, boolean b, String value, JavaVers * @param value the argument value to be added. * @see #addArgIfNotEmpty(List, String, String, boolean) */ - private void addArgIfNotEmpty( List arguments, String key, String value ) - { - addArgIfNotEmpty( arguments, key, value, false ); + private void addArgIfNotEmpty(List arguments, String key, String value) { + addArgIfNotEmpty(arguments, key, value, false); } /** @@ -4015,21 +3596,20 @@ private void addArgIfNotEmpty( List arguments, String key, String value * @see #addArgIfNotEmpty(List, String, String, boolean, boolean) * @see #isJavaDocVersionAtLeast(JavaVersion) */ - private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, - boolean splitValue, JavaVersion requiredJavaVersion ) - { - if ( StringUtils.isNotEmpty( value ) ) - { - if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) - { - addArgIfNotEmpty( arguments, key, value, repeatKey, splitValue ); - } - else - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion - + ". Ignore this option." ); + private void addArgIfNotEmpty( + List arguments, + String key, + String value, + boolean repeatKey, + boolean splitValue, + JavaVersion requiredJavaVersion) { + if (StringUtils.isNotEmpty(value)) { + if (isJavaDocVersionAtLeast(requiredJavaVersion)) { + addArgIfNotEmpty(arguments, key, value, repeatKey, splitValue); + } else { + if (getLog().isWarnEnabled()) { + getLog().warn(key + " option is not supported on Java version < " + requiredJavaVersion + + ". Ignore this option."); } } } @@ -4047,37 +3627,28 @@ private void addArgIfNotEmpty( List arguments, String key, String value, * @param repeatKey repeat or not the key in the command line * @param splitValue if true given value will be tokenized by comma */ - private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey, - boolean splitValue ) - { - if ( StringUtils.isNotEmpty( value ) ) - { - if ( StringUtils.isNotEmpty( key ) ) - { - arguments.add( key ); + private void addArgIfNotEmpty( + List arguments, String key, String value, boolean repeatKey, boolean splitValue) { + if (StringUtils.isNotEmpty(value)) { + if (StringUtils.isNotEmpty(key)) { + arguments.add(key); } - if ( splitValue ) - { - StringTokenizer token = new StringTokenizer( value, "," ); - while ( token.hasMoreTokens() ) - { + if (splitValue) { + StringTokenizer token = new StringTokenizer(value, ","); + while (token.hasMoreTokens()) { String current = token.nextToken().trim(); - if ( StringUtils.isNotEmpty( current ) ) - { - arguments.add( current ); + if (StringUtils.isNotEmpty(current)) { + arguments.add(current); - if ( token.hasMoreTokens() && repeatKey ) - { - arguments.add( key ); + if (token.hasMoreTokens() && repeatKey) { + arguments.add(key); } } } - } - else - { - arguments.add( value ); + } else { + arguments.add(value); } } } @@ -4093,9 +3664,8 @@ private void addArgIfNotEmpty( List arguments, String key, String value, * @param value the argument value to be added. * @param repeatKey repeat or not the key in the command line */ - private void addArgIfNotEmpty( List arguments, String key, String value, boolean repeatKey ) - { - addArgIfNotEmpty( arguments, key, value, repeatKey, true ); + private void addArgIfNotEmpty(List arguments, String key, String value, boolean repeatKey) { + addArgIfNotEmpty(arguments, key, value, repeatKey, true); } /** @@ -4108,10 +3678,8 @@ private void addArgIfNotEmpty( List arguments, String key, String value, * @param requiredJavaVersion the required Java version, for example 1.31f or 1.4f * @see #addArgIfNotEmpty(List, String, String, JavaVersion, boolean) */ - private void addArgIfNotEmpty( List arguments, String key, String value, - JavaVersion requiredJavaVersion ) - { - addArgIfNotEmpty( arguments, key, value, requiredJavaVersion, false ); + private void addArgIfNotEmpty(List arguments, String key, String value, JavaVersion requiredJavaVersion) { + addArgIfNotEmpty(arguments, key, value, requiredJavaVersion, false); } /** @@ -4126,20 +3694,14 @@ private void addArgIfNotEmpty( List arguments, String key, String value, * @see #addArgIfNotEmpty(List, String, String) * @see #isJavaDocVersionAtLeast */ - private void addArgIfNotEmpty( List arguments, String key, String value, JavaVersion requiredJavaVersion, - boolean repeatKey ) - { - if ( StringUtils.isNotEmpty( value ) ) - { - if ( isJavaDocVersionAtLeast( requiredJavaVersion ) ) - { - addArgIfNotEmpty( arguments, key, value, repeatKey ); - } - else - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( key + " option is not supported on Java version < " + requiredJavaVersion ); + private void addArgIfNotEmpty( + List arguments, String key, String value, JavaVersion requiredJavaVersion, boolean repeatKey) { + if (StringUtils.isNotEmpty(value)) { + if (isJavaDocVersionAtLeast(requiredJavaVersion)) { + addArgIfNotEmpty(arguments, key, value, repeatKey); + } else { + if (getLog().isWarnEnabled()) { + getLog().warn(key + " option is not supported on Java version < " + requiredJavaVersion); } } } @@ -4158,37 +3720,33 @@ private void addArgIfNotEmpty( List arguments, String key, String value, * @see #getModulesLinks() * @see package-list spec */ - private void addLinkofflineArguments( List arguments, Set offlineLinksList ) - throws MavenReportException - { - for ( OfflineLink offlineLink : offlineLinksList ) - { + private void addLinkofflineArguments(List arguments, Set offlineLinksList) + throws MavenReportException { + for (OfflineLink offlineLink : offlineLinksList) { String url = offlineLink.getUrl(); - if ( StringUtils.isEmpty( url ) ) - { + if (StringUtils.isEmpty(url)) { continue; } - url = cleanUrl( url ); + url = cleanUrl(url); String location = offlineLink.getLocation(); - if ( StringUtils.isEmpty( location ) ) - { + if (StringUtils.isEmpty(location)) { continue; } - if ( isValidJavadocLink( location, false ) ) - { - addArgIfNotEmpty( arguments, "-linkoffline", - JavadocUtil.quotedPathArgument( url ) + " " + JavadocUtil.quotedPathArgument( - location ), true ); + if (isValidJavadocLink(location, false)) { + addArgIfNotEmpty( + arguments, + "-linkoffline", + JavadocUtil.quotedPathArgument(url) + " " + JavadocUtil.quotedPathArgument(location), + true); } } } - private Set getLinkofflines() throws MavenReportException - { + private Set getLinkofflines() throws MavenReportException { Set offlineLinksList = collectOfflineLinks(); - offlineLinksList.addAll( getModulesLinks() ); + offlineLinksList.addAll(getModulesLinks()); return offlineLinksList; } @@ -4212,29 +3770,23 @@ private Set getLinkofflines() throws MavenReportException * @see #getDependenciesLinks() * @see link option */ - private void addLinkArguments( List arguments ) - throws MavenReportException - { + private void addLinkArguments(List arguments) throws MavenReportException { Set links = collectLinks(); - for ( String link : links ) - { - if ( StringUtils.isEmpty( link ) ) - { + for (String link : links) { + if (StringUtils.isEmpty(link)) { continue; } - if ( isOffline && !link.startsWith( "file:" ) ) - { + if (isOffline && !link.startsWith("file:")) { continue; } - while ( link.endsWith( "/" ) ) - { - link = link.substring( 0, link.lastIndexOf( "/" ) ); + while (link.endsWith("/")) { + link = link.substring(0, link.lastIndexOf("/")); } - addArgIfNotEmpty( arguments, "-link", JavadocUtil.quotedPathArgument( link ), true, false ); + addArgIfNotEmpty(arguments, "-link", JavadocUtil.quotedPathArgument(link), true, false); } } @@ -4247,27 +3799,21 @@ private void addLinkArguments( List arguments ) * @see #copyJavadocResources(File) * @see #copyAdditionalJavadocResources(File) */ - private void copyAllResources( File javadocOutputDirectory ) - throws MavenReportException - { + private void copyAllResources(File javadocOutputDirectory) throws MavenReportException { // ---------------------------------------------------------------------- // Copy javadoc resources // ---------------------------------------------------------------------- - if ( docfilessubdirs ) - { + if (docfilessubdirs) { /* * Workaround since -docfilessubdirs doesn't seem to be used correctly by the javadoc tool * (see other note about -sourcepath). Take care of the -excludedocfilessubdir option. */ - try - { - copyJavadocResources( javadocOutputDirectory ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Unable to copy javadoc resources: " + e.getMessage(), e ); + try { + copyJavadocResources(javadocOutputDirectory); + } catch (IOException e) { + throw new MavenReportException("Unable to copy javadoc resources: " + e.getMessage(), e); } } @@ -4275,7 +3821,7 @@ private void copyAllResources( File javadocOutputDirectory ) // Copy additional javadoc resources in artifacts // ---------------------------------------------------------------------- - copyAdditionalJavadocResources( javadocOutputDirectory ); + copyAdditionalJavadocResources(javadocOutputDirectory); } /** @@ -4288,62 +3834,46 @@ private void copyAllResources( File javadocOutputDirectory ) * Guide, Copies new "doc-files" directory for holding images and examples * @see #docfilessubdirs */ - private void copyJavadocResources( File anOutputDirectory ) - throws IOException - { - if ( anOutputDirectory == null || !anOutputDirectory.exists() ) - { - throw new IOException( "The outputDirectory " + anOutputDirectory + " doesn't exists." ); + private void copyJavadocResources(File anOutputDirectory) throws IOException { + if (anOutputDirectory == null || !anOutputDirectory.exists()) { + throw new IOException("The outputDirectory " + anOutputDirectory + " doesn't exists."); } - if ( includeDependencySources ) - { + if (includeDependencySources) { resolveDependencyBundles(); - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { File dir = bundle.getResourcesDirectory(); JavadocOptions options = bundle.getOptions(); - if ( dir != null && dir.isDirectory() ) - { - JavadocUtil.copyJavadocResources( anOutputDirectory, dir, options == null - ? null - : options.getExcludedDocfilesSubdirs() ); + if (dir != null && dir.isDirectory()) { + JavadocUtil.copyJavadocResources( + anOutputDirectory, dir, options == null ? null : options.getExcludedDocfilesSubdirs()); } } } } - if ( getJavadocDirectory() != null ) - { - JavadocUtil.copyJavadocResources( anOutputDirectory, getJavadocDirectory(), excludedocfilessubdir ); + if (getJavadocDirectory() != null) { + JavadocUtil.copyJavadocResources(anOutputDirectory, getJavadocDirectory(), excludedocfilessubdir); } - if ( isAggregator() ) - { - for ( MavenProject subProject : getAggregatedProjects() ) - { - if ( subProject != project && getJavadocDirectory() != null ) - { - String javadocDirRelative = - PathUtils.toRelative( project.getBasedir(), getJavadocDirectory().getAbsolutePath() ); - File javadocDir = new File( subProject.getBasedir(), javadocDirRelative ); - JavadocUtil.copyJavadocResources( anOutputDirectory, javadocDir, excludedocfilessubdir ); + if (isAggregator()) { + for (MavenProject subProject : getAggregatedProjects()) { + if (subProject != project && getJavadocDirectory() != null) { + String javadocDirRelative = PathUtils.toRelative( + project.getBasedir(), getJavadocDirectory().getAbsolutePath()); + File javadocDir = new File(subProject.getBasedir(), javadocDirRelative); + JavadocUtil.copyJavadocResources(anOutputDirectory, javadocDir, excludedocfilessubdir); } } } } - private synchronized void resolveDependencyBundles() - throws IOException - { - if ( dependencyJavadocBundles == null ) - { + private synchronized void resolveDependencyBundles() throws IOException { + if (dependencyJavadocBundles == null) { dependencyJavadocBundles = - resourceResolver.resolveDependencyJavadocBundles( getDependencySourceResolverConfig() ); - if ( dependencyJavadocBundles == null ) - { + resourceResolver.resolveDependencyJavadocBundles(getDependencySourceResolverConfig()); + if (dependencyJavadocBundles == null) { dependencyJavadocBundles = new ArrayList<>(); } } @@ -4356,55 +3886,42 @@ private synchronized void resolveDependencyBundles() * @throws MavenReportException if any * @see #resourcesArtifacts */ - private void copyAdditionalJavadocResources( File anOutputDirectory ) - throws MavenReportException - { + private void copyAdditionalJavadocResources(File anOutputDirectory) throws MavenReportException { Set resourcesArtifacts = collectResourcesArtifacts(); - if ( isEmpty( resourcesArtifacts ) ) - { + if (isEmpty(resourcesArtifacts)) { return; } UnArchiver unArchiver; - try - { - unArchiver = archiverManager.getUnArchiver( "jar" ); - } - catch ( NoSuchArchiverException e ) - { + try { + unArchiver = archiverManager.getUnArchiver("jar"); + } catch (NoSuchArchiverException e) { throw new MavenReportException( - "Unable to extract resources artifact. " + "No archiver for 'jar' available.", e ); + "Unable to extract resources artifact. " + "No archiver for 'jar' available.", e); } - for ( ResourcesArtifact item : resourcesArtifacts ) - { + for (ResourcesArtifact item : resourcesArtifacts) { Artifact artifact; - try - { - artifact = createAndResolveArtifact( item ); - } - catch ( ArtifactResolutionException e ) - { - throw new MavenReportException( "Unable to resolve artifact:" + item, e ); + try { + artifact = createAndResolveArtifact(item); + } catch (ArtifactResolutionException e) { + throw new MavenReportException("Unable to resolve artifact:" + item, e); } - unArchiver.setSourceFile( artifact.getFile() ); - unArchiver.setDestDirectory( anOutputDirectory ); + unArchiver.setSourceFile(artifact.getFile()); + unArchiver.setDestDirectory(anOutputDirectory); // remove the META-INF directory from resource artifact IncludeExcludeFileSelector[] selectors = - new IncludeExcludeFileSelector[]{ new IncludeExcludeFileSelector() }; - selectors[0].setExcludes( new String[]{ "META-INF/**" } ); - unArchiver.setFileSelectors( selectors ); + new IncludeExcludeFileSelector[] {new IncludeExcludeFileSelector()}; + selectors[0].setExcludes(new String[] {"META-INF/**"}); + unArchiver.setFileSelectors(selectors); - getLog().info( "Extracting contents of resources artifact: " + artifact.getArtifactId() ); - try - { + getLog().info("Extracting contents of resources artifact: " + artifact.getArtifactId()); + try { unArchiver.extract(); - } - catch ( ArchiverException e ) - { + } catch (ArchiverException e) { throw new MavenReportException( - "Extraction of resources failed. Artifact that failed was: " + artifact.getArtifactId(), e ); + "Extraction of resources failed. Artifact that failed was: " + artifact.getArtifactId(), e); } } } @@ -4413,36 +3930,30 @@ private void copyAdditionalJavadocResources( File anOutputDirectory ) * @param sourcePaths could be null * @return the list of package names for files in the sourcePaths */ - private List getPackageNames( Map> sourcePaths ) - { + private List getPackageNames(Map> sourcePaths) { List returnList = new ArrayList<>(); - if ( !StringUtils.isEmpty( sourcepath ) ) - { + if (!StringUtils.isEmpty(sourcepath)) { return returnList; } - for ( Entry> currentPathEntry : sourcePaths.entrySet() ) - { - for ( String currentFile : currentPathEntry.getValue() ) - { + for (Entry> currentPathEntry : sourcePaths.entrySet()) { + for (String currentFile : currentPathEntry.getValue()) { /* * Remove the miscellaneous files * https://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ - if ( currentFile.contains( "doc-files" ) ) - { + if (currentFile.contains("doc-files")) { continue; } - int lastIndexOfSeparator = currentFile.lastIndexOf( "/" ); - if ( lastIndexOfSeparator != -1 ) - { - String packagename = currentFile.substring( 0, lastIndexOfSeparator ).replace( '/', '.' ); + int lastIndexOfSeparator = currentFile.lastIndexOf("/"); + if (lastIndexOfSeparator != -1) { + String packagename = + currentFile.substring(0, lastIndexOfSeparator).replace('/', '.'); - if ( !returnList.contains( packagename ) ) - { - returnList.add( packagename ); + if (!returnList.contains(packagename)) { + returnList.add(packagename); } } } @@ -4458,61 +3969,50 @@ private List getPackageNames( Map> sourcePaths * @see #getFiles * @see #getSourcePaths() */ - private Collection getPackageNamesRespectingJavaModules( Collection javadocModules ) - throws MavenReportException - { - if ( !StringUtils.isEmpty( sourcepath ) ) - { + private Collection getPackageNamesRespectingJavaModules(Collection javadocModules) + throws MavenReportException { + if (!StringUtils.isEmpty(sourcepath)) { return Collections.emptyList(); } Set returnList = new LinkedHashSet<>(); - for ( JavadocModule javadocModule : javadocModules ) - { + for (JavadocModule javadocModule : javadocModules) { Collection artifactSourcePaths = javadocModule.getSourcePaths(); Set exportedPackages = new HashSet<>(); boolean exportAllPackages; - ResolvePathResult resolvedPath = getResolvePathResult( javadocModule.getArtifactFile() ); - if ( resolvedPath != null && resolvedPath.getModuleNameSource() == ModuleNameSource.MODULEDESCRIPTOR ) - { - Set exports = resolvedPath.getModuleDescriptor().exports(); - if ( exports.isEmpty() ) - { + ResolvePathResult resolvedPath = getResolvePathResult(javadocModule.getArtifactFile()); + if (resolvedPath != null && resolvedPath.getModuleNameSource() == ModuleNameSource.MODULEDESCRIPTOR) { + Set exports = + resolvedPath.getModuleDescriptor().exports(); + if (exports.isEmpty()) { continue; } - for ( JavaModuleDescriptor.JavaExports export : exports ) - { - exportedPackages.add( export.source() ); + for (JavaModuleDescriptor.JavaExports export : exports) { + exportedPackages.add(export.source()); } exportAllPackages = false; - } - else - { + } else { exportAllPackages = true; } - for ( Map.Entry> currentPathEntry : getFiles( artifactSourcePaths ).entrySet() ) - { - for ( String currentFile : currentPathEntry.getValue() ) - { + for (Map.Entry> currentPathEntry : + getFiles(artifactSourcePaths).entrySet()) { + for (String currentFile : currentPathEntry.getValue()) { /* * Remove the miscellaneous files * https://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ - if ( currentFile.contains( "doc-files" ) ) - { + if (currentFile.contains("doc-files")) { continue; } - int lastIndexOfSeparator = currentFile.lastIndexOf( '/' ); - if ( lastIndexOfSeparator != -1 ) - { + int lastIndexOfSeparator = currentFile.lastIndexOf('/'); + if (lastIndexOfSeparator != -1) { String packagename = - currentFile.substring( 0, lastIndexOfSeparator ).replace( '/', '.' ); + currentFile.substring(0, lastIndexOfSeparator).replace('/', '.'); - if ( exportAllPackages || exportedPackages.contains( packagename ) ) - { - returnList.add( packagename ); + if (exportAllPackages || exportedPackages.contains(packagename)) { + returnList.add(packagename); } } } @@ -4526,33 +4026,30 @@ private Collection getPackageNamesRespectingJavaModules( Collection getFilesWithUnnamedPackages( Map> sourcePaths ) - { + private List getFilesWithUnnamedPackages(Map> sourcePaths) { List returnList = new ArrayList<>(); - if ( !StringUtils.isEmpty( sourcepath ) ) - { + if (!StringUtils.isEmpty(sourcepath)) { return returnList; } - for ( Entry> currentPathEntry : sourcePaths.entrySet() ) - { + for (Entry> currentPathEntry : sourcePaths.entrySet()) { Path currentSourcePath = currentPathEntry.getKey(); - for ( String currentFile : currentPathEntry.getValue() ) - { + for (String currentFile : currentPathEntry.getValue()) { /* * Remove the miscellaneous files * https://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ - if ( currentFile.contains( "doc-files" ) ) - { + if (currentFile.contains("doc-files")) { continue; } - if ( currentFile.indexOf( '/' ) == -1 ) - { - returnList.add( currentSourcePath.resolve( currentFile ).toAbsolutePath().toString() ); + if (currentFile.indexOf('/') == -1) { + returnList.add(currentSourcePath + .resolve(currentFile) + .toAbsolutePath() + .toString()); } } } @@ -4565,58 +4062,50 @@ private List getFilesWithUnnamedPackages( Map> * @param sourcePaths could be null * @return a list of files */ - private List getSpecialFiles( Map> sourcePaths ) - { - if ( !StringUtils.isEmpty( sourcepath ) ) - { + private List getSpecialFiles(Map> sourcePaths) { + if (!StringUtils.isEmpty(sourcepath)) { return new ArrayList<>(); } boolean containsModuleDescriptor = false; - for ( Collection sourcepathFiles : sourcePaths.values() ) - { - containsModuleDescriptor = sourcepathFiles.contains( "module-info.java" ); - if ( containsModuleDescriptor ) - { + for (Collection sourcepathFiles : sourcePaths.values()) { + containsModuleDescriptor = sourcepathFiles.contains("module-info.java"); + if (containsModuleDescriptor) { break; } } - if ( containsModuleDescriptor ) - { - return getModuleSourcePathFiles( sourcePaths ); - } - else - { - return getFilesWithUnnamedPackages( sourcePaths ); + if (containsModuleDescriptor) { + return getModuleSourcePathFiles(sourcePaths); + } else { + return getFilesWithUnnamedPackages(sourcePaths); } } - private List getModuleSourcePathFiles( Map> sourcePaths ) - { + private List getModuleSourcePathFiles(Map> sourcePaths) { List returnList = new ArrayList<>(); - for ( Entry> currentPathEntry : sourcePaths.entrySet() ) - { + for (Entry> currentPathEntry : sourcePaths.entrySet()) { Path currentSourcePath = currentPathEntry.getKey(); - if ( currentPathEntry.getValue().contains( "module-info.java" ) ) - { - returnList.add( currentSourcePath.resolve( "module-info.java" ).toAbsolutePath().toString() ); - } - else - { - for ( String currentFile : currentPathEntry.getValue() ) - { + if (currentPathEntry.getValue().contains("module-info.java")) { + returnList.add(currentSourcePath + .resolve("module-info.java") + .toAbsolutePath() + .toString()); + } else { + for (String currentFile : currentPathEntry.getValue()) { /* * Remove the miscellaneous files * https://docs.oracle.com/javase/1.4.2/docs/tooldocs/solaris/javadoc.html#unprocessed */ - if ( currentFile.contains( "doc-files" ) ) - { + if (currentFile.contains("doc-files")) { continue; } - returnList.add( currentSourcePath.resolve( currentFile ).toAbsolutePath().toString() ); + returnList.add(currentSourcePath + .resolve(currentFile) + .toAbsolutePath() + .toString()); } } } @@ -4635,35 +4124,27 @@ private List getModuleSourcePathFiles( Map> sou * Reference Guide, Command line argument files * @see #OPTIONS_FILE_NAME */ - private void addCommandLineOptions( Commandline cmd, List arguments, File javadocOutputDirectory ) - throws MavenReportException - { - File optionsFile = new File( javadocOutputDirectory, OPTIONS_FILE_NAME ); + private void addCommandLineOptions(Commandline cmd, List arguments, File javadocOutputDirectory) + throws MavenReportException { + File optionsFile = new File(javadocOutputDirectory, OPTIONS_FILE_NAME); StringBuilder options = new StringBuilder(); - options.append( StringUtils.join( arguments.iterator(), - SystemUtils.LINE_SEPARATOR ) ); + options.append(StringUtils.join(arguments.iterator(), SystemUtils.LINE_SEPARATOR)); Charset outputFileEncoding; - if ( JAVA_VERSION.isAtLeast( "9" ) && JAVA_VERSION.isBefore( "12" ) ) - { + if (JAVA_VERSION.isAtLeast("9") && JAVA_VERSION.isBefore("12")) { outputFileEncoding = StandardCharsets.UTF_8; - } - else - { + } else { outputFileEncoding = Charset.defaultCharset(); } - try - { - Files.write( optionsFile.toPath(), Collections.singleton( options ), outputFileEncoding ); - } - catch ( IOException e ) - { + try { + Files.write(optionsFile.toPath(), Collections.singleton(options), outputFileEncoding); + } catch (IOException e) { throw new MavenReportException( - "Unable to write '" + optionsFile.getName() + "' temporary file for command execution", e ); + "Unable to write '" + optionsFile.getName() + "' temporary file for command execution", e); } - cmd.createArg().setValue( "@" + OPTIONS_FILE_NAME ); + cmd.createArg().setValue("@" + OPTIONS_FILE_NAME); } /** @@ -4684,46 +4165,35 @@ private void addCommandLineOptions( Commandline cmd, List arguments, Fil * @see #ARGFILE_FILE_NAME * @see #FILES_FILE_NAME */ - private void addCommandLineArgFile( Commandline cmd, File javadocOutputDirectory, List files ) - throws MavenReportException - { + private void addCommandLineArgFile(Commandline cmd, File javadocOutputDirectory, List files) + throws MavenReportException { File argfileFile; - if ( JAVA_VERSION.compareTo( SINCE_JAVADOC_1_4 ) >= 0 ) - { - argfileFile = new File( javadocOutputDirectory, ARGFILE_FILE_NAME ); - cmd.createArg().setValue( "@" + ARGFILE_FILE_NAME ); - } - else - { - argfileFile = new File( javadocOutputDirectory, FILES_FILE_NAME ); - cmd.createArg().setValue( "@" + FILES_FILE_NAME ); + if (JAVA_VERSION.compareTo(SINCE_JAVADOC_1_4) >= 0) { + argfileFile = new File(javadocOutputDirectory, ARGFILE_FILE_NAME); + cmd.createArg().setValue("@" + ARGFILE_FILE_NAME); + } else { + argfileFile = new File(javadocOutputDirectory, FILES_FILE_NAME); + cmd.createArg().setValue("@" + FILES_FILE_NAME); } - List quotedFiles = new ArrayList<>( files.size() ); - for ( String file : files ) - { - quotedFiles.add( JavadocUtil.quotedPathArgument( file ) ); + List quotedFiles = new ArrayList<>(files.size()); + for (String file : files) { + quotedFiles.add(JavadocUtil.quotedPathArgument(file)); } Charset cs; - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "9" ) - && JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "12" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9") + && JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("12")) { cs = StandardCharsets.UTF_8; - } - else - { + } else { cs = Charset.defaultCharset(); } - try - { - Files.write( argfileFile.toPath(), quotedFiles, cs ); - } - catch ( IOException e ) - { + try { + Files.write(argfileFile.toPath(), quotedFiles, cs); + } catch (IOException e) { throw new MavenReportException( - "Unable to write '" + argfileFile.getName() + "' temporary file for command execution", e ); + "Unable to write '" + argfileFile.getName() + "' temporary file for command execution", e); } } @@ -4739,23 +4209,21 @@ private void addCommandLineArgFile( Commandline cmd, File javadocOutputDirectory * Reference Guide, Command line argument files * @see #PACKAGES_FILE_NAME */ - private void addCommandLinePackages( Commandline cmd, File javadocOutputDirectory, Collection packageNames ) - throws MavenReportException - { - File packagesFile = new File( javadocOutputDirectory, PACKAGES_FILE_NAME ); + private void addCommandLinePackages(Commandline cmd, File javadocOutputDirectory, Collection packageNames) + throws MavenReportException { + File packagesFile = new File(javadocOutputDirectory, PACKAGES_FILE_NAME); - try - { - FileUtils.fileWrite( packagesFile.getAbsolutePath(), null /* platform encoding */, - StringUtils.join( packageNames.iterator(), SystemUtils.LINE_SEPARATOR ) ); - } - catch ( IOException e ) - { + try { + FileUtils.fileWrite( + packagesFile.getAbsolutePath(), + null /* platform encoding */, + StringUtils.join(packageNames.iterator(), SystemUtils.LINE_SEPARATOR)); + } catch (IOException e) { throw new MavenReportException( - "Unable to write '" + packagesFile.getName() + "' temporary file for command execution", e ); + "Unable to write '" + packagesFile.getName() + "' temporary file for command execution", e); } - cmd.createArg().setValue( "@" + PACKAGES_FILE_NAME ); + cmd.createArg().setValue("@" + PACKAGES_FILE_NAME); } /** @@ -4763,82 +4231,70 @@ private void addCommandLinePackages( Commandline cmd, File javadocOutputDirector * * @throws MavenReportException if error */ - private void validateJavadocOptions() - throws MavenReportException - { + private void validateJavadocOptions() throws MavenReportException { // encoding - if ( StringUtils.isNotEmpty( getEncoding() ) && !JavadocUtil.validateEncoding( getEncoding() ) ) - { - throw new MavenReportException( "Unsupported option '" + getEncoding() + "'" ); + if (StringUtils.isNotEmpty(getEncoding()) && !JavadocUtil.validateEncoding(getEncoding())) { + throw new MavenReportException("Unsupported option '" + getEncoding() + "'"); } // locale - if ( StringUtils.isNotEmpty( this.locale ) ) - { - StringTokenizer tokenizer = new StringTokenizer( this.locale, "_" ); + if (StringUtils.isNotEmpty(this.locale)) { + StringTokenizer tokenizer = new StringTokenizer(this.locale, "_"); final int maxTokens = 3; - if ( tokenizer.countTokens() > maxTokens ) - { + if (tokenizer.countTokens() > maxTokens) { throw new MavenReportException( - "Unsupported option '" + this.locale + "', should be language_country_variant." ); + "Unsupported option '" + this.locale + "', should be language_country_variant."); } Locale localeObject = null; - if ( tokenizer.hasMoreTokens() ) - { - String language = tokenizer.nextToken().toLowerCase( Locale.ENGLISH ); - if ( !Arrays.asList( Locale.getISOLanguages() ).contains( language ) ) - { + if (tokenizer.hasMoreTokens()) { + String language = tokenizer.nextToken().toLowerCase(Locale.ENGLISH); + if (!Arrays.asList(Locale.getISOLanguages()).contains(language)) { throw new MavenReportException( - "Unsupported language '" + language + "' in option '" + this.locale + "'" ); + "Unsupported language '" + language + "' in option '" + this.locale + "'"); } - localeObject = new Locale( language ); + localeObject = new Locale(language); - if ( tokenizer.hasMoreTokens() ) - { - String country = tokenizer.nextToken().toUpperCase( Locale.ENGLISH ); - if ( !Arrays.asList( Locale.getISOCountries() ).contains( country ) ) - { + if (tokenizer.hasMoreTokens()) { + String country = tokenizer.nextToken().toUpperCase(Locale.ENGLISH); + if (!Arrays.asList(Locale.getISOCountries()).contains(country)) { throw new MavenReportException( - "Unsupported country '" + country + "' in option '" + this.locale + "'" ); + "Unsupported country '" + country + "' in option '" + this.locale + "'"); } - localeObject = new Locale( language, country ); + localeObject = new Locale(language, country); - if ( tokenizer.hasMoreTokens() ) - { + if (tokenizer.hasMoreTokens()) { String variant = tokenizer.nextToken(); - localeObject = new Locale( language, country, variant ); + localeObject = new Locale(language, country, variant); } } } - if ( localeObject == null ) - { + if (localeObject == null) { throw new MavenReportException( - "Unsupported option '" + this.locale + "', should be language_country_variant." ); + "Unsupported option '" + this.locale + "', should be language_country_variant."); } this.locale = localeObject.toString(); - final List availableLocalesList = Arrays.asList( Locale.getAvailableLocales() ); - if ( StringUtils.isNotEmpty( localeObject.getVariant() ) && !availableLocalesList.contains( localeObject ) ) - { + final List availableLocalesList = Arrays.asList(Locale.getAvailableLocales()); + if (StringUtils.isNotEmpty(localeObject.getVariant()) && !availableLocalesList.contains(localeObject)) { StringBuilder sb = new StringBuilder(); - sb.append( "Unsupported option with variant '" ).append( this.locale ); - sb.append( "'" ); + sb.append("Unsupported option with variant '").append(this.locale); + sb.append("'"); - localeObject = new Locale( localeObject.getLanguage(), localeObject.getCountry() ); + localeObject = new Locale(localeObject.getLanguage(), localeObject.getCountry()); this.locale = localeObject.toString(); - sb.append( ", trying to use without variant, i.e. '" ).append( this.locale ).append( "'" ); - if ( getLog().isWarnEnabled() ) - { - getLog().warn( sb.toString() ); + sb.append(", trying to use without variant, i.e. '") + .append(this.locale) + .append("'"); + if (getLog().isWarnEnabled()) { + getLog().warn(sb.toString()); } } - if ( !availableLocalesList.contains( localeObject ) ) - { - throw new MavenReportException( "Unsupported option '" + this.locale + "'" ); + if (!availableLocalesList.contains(localeObject)) { + throw new MavenReportException("Unsupported option '" + this.locale + "'"); } } } @@ -4850,44 +4306,36 @@ private void validateJavadocOptions() * * @throws MavenReportException if error or conflict found */ - private void validateStandardDocletOptions() - throws MavenReportException - { + private void validateStandardDocletOptions() throws MavenReportException { // docencoding - if ( StringUtils.isNotEmpty( getDocencoding() ) && !JavadocUtil.validateEncoding( getDocencoding() ) ) - { - throw new MavenReportException( "Unsupported option '" + getDocencoding() + "'" ); + if (StringUtils.isNotEmpty(getDocencoding()) && !JavadocUtil.validateEncoding(getDocencoding())) { + throw new MavenReportException("Unsupported option '" + getDocencoding() + "'"); } // charset - if ( StringUtils.isNotEmpty( getCharset() ) && !JavadocUtil.validateEncoding( getCharset() ) ) - { - throw new MavenReportException( "Unsupported option '" + getCharset() + "'" ); + if (StringUtils.isNotEmpty(getCharset()) && !JavadocUtil.validateEncoding(getCharset())) { + throw new MavenReportException("Unsupported option '" + getCharset() + "'"); } // helpfile - if ( StringUtils.isNotEmpty( helpfile ) && nohelp ) - { - throw new MavenReportException( "Option conflicts with " ); + if (StringUtils.isNotEmpty(helpfile) && nohelp) { + throw new MavenReportException("Option conflicts with "); } // overview - if ( getOverview() != null && getOverview().exists() && nooverview ) - { - throw new MavenReportException( "Option conflicts with " ); + if (getOverview() != null && getOverview().exists() && nooverview) { + throw new MavenReportException("Option conflicts with "); } // index - if ( splitindex && noindex ) - { - throw new MavenReportException( "Option conflicts with " ); + if (splitindex && noindex) { + throw new MavenReportException("Option conflicts with "); } // stylesheet - if ( StringUtils.isNotEmpty( stylesheet ) && !( stylesheet.equalsIgnoreCase( "maven" ) - || stylesheet.equalsIgnoreCase( "java" ) ) ) - { - throw new MavenReportException( "Option supports only \"maven\" or \"java\" value." ); + if (StringUtils.isNotEmpty(stylesheet) + && !(stylesheet.equalsIgnoreCase("maven") || stylesheet.equalsIgnoreCase("java"))) { + throw new MavenReportException("Option supports only \"maven\" or \"java\" value."); } } @@ -4903,86 +4351,72 @@ private void validateStandardDocletOptions() * @throws MavenReportException if any * @see https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#javadocoptions */ - private void addJavadocOptions( File javadocOutputDirectory, - List arguments, - Collection allSourcePaths, - Set offlineLinks ) - throws MavenReportException - { + private void addJavadocOptions( + File javadocOutputDirectory, + List arguments, + Collection allSourcePaths, + Set offlineLinks) + throws MavenReportException { Collection sourcePaths = allSourcePaths.stream() - .flatMap( e -> e.getSourcePaths().stream() ) - .collect( Collectors.toList() ); + .flatMap(e -> e.getSourcePaths().stream()) + .collect(Collectors.toList()); validateJavadocOptions(); // see com.sun.tools.javadoc.Start#parseAndExecute(String argv[]) - addArgIfNotEmpty( arguments, "-locale", JavadocUtil.quotedArgument( this.locale ) ); + addArgIfNotEmpty(arguments, "-locale", JavadocUtil.quotedArgument(this.locale)); // all options in alphabetical order - if ( old && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_4 ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Javadoc 1.4+ doesn't support the -1.1 switch anymore. Ignore this option." ); + if (old && isJavaDocVersionAtLeast(SINCE_JAVADOC_1_4)) { + if (getLog().isWarnEnabled()) { + getLog().warn("Javadoc 1.4+ doesn't support the -1.1 switch anymore. Ignore this option."); } - } - else - { - addArgIf( arguments, old, "-1.1" ); + } else { + addArgIf(arguments, old, "-1.1"); } - addArgIfNotEmpty( arguments, "-bootclasspath", JavadocUtil.quotedPathArgument( getBootclassPath() ) ); + addArgIfNotEmpty(arguments, "-bootclasspath", JavadocUtil.quotedPathArgument(getBootclassPath())); - if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) - { - addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_5 ); + if (isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) { + addArgIf(arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_5); } List aggregatedProjects = reactorProjects; // getAggregatedProjects(); - Map reactorKeys = new HashMap<>( aggregatedProjects.size() ); - for ( MavenProject reactorProject : aggregatedProjects ) - { - reactorKeys.put( ArtifactUtils.versionlessKey( reactorProject.getGroupId(), - reactorProject.getArtifactId() ), reactorProject ); + Map reactorKeys = new HashMap<>(aggregatedProjects.size()); + for (MavenProject reactorProject : aggregatedProjects) { + reactorKeys.put( + ArtifactUtils.versionlessKey(reactorProject.getGroupId(), reactorProject.getArtifactId()), + reactorProject); } Map allModuleDescriptors = new HashMap<>(); - boolean supportModulePath = javadocRuntimeVersion.isAtLeast( "9" ); - if ( release != null ) - { - supportModulePath &= JavaVersion.parse( release ).isAtLeast( "9" ); - } - else if ( source != null ) - { - supportModulePath &= JavaVersion.parse( source ).isAtLeast( "9" ); - } - - if ( supportModulePath ) - { - for ( JavadocModule entry : allSourcePaths ) - { - if ( entry.getModuleNameSource() == null || entry.getModuleNameSource() == ModuleNameSource.FILENAME ) - { - Path moduleDescriptor = findMainDescriptor( entry.getSourcePaths() ); - - if ( moduleDescriptor != null ) - { - try - { - allModuleDescriptors.put( entry.getGa(), - locationManager.parseModuleDescriptor( moduleDescriptor ).getModuleDescriptor() ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + boolean supportModulePath = javadocRuntimeVersion.isAtLeast("9"); + if (release != null) { + supportModulePath &= JavaVersion.parse(release).isAtLeast("9"); + } else if (source != null) { + supportModulePath &= JavaVersion.parse(source).isAtLeast("9"); + } + + if (supportModulePath) { + for (JavadocModule entry : allSourcePaths) { + if (entry.getModuleNameSource() == null || entry.getModuleNameSource() == ModuleNameSource.FILENAME) { + Path moduleDescriptor = findMainDescriptor(entry.getSourcePaths()); + + if (moduleDescriptor != null) { + try { + allModuleDescriptors.put( + entry.getGa(), + locationManager + .parseModuleDescriptor(moduleDescriptor) + .getModuleDescriptor()); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } } - } - else - { - allModuleDescriptors.put( entry.getGa(), entry.getModuleDescriptor() ); + } else { + allModuleDescriptors.put(entry.getGa(), entry.getModuleDescriptor()); } } } @@ -4994,358 +4428,283 @@ else if ( source != null ) Map> patchModules = new HashMap<>(); Path moduleSourceDir = null; - if ( supportModulePath && !allModuleDescriptors.isEmpty() ) - { + if (supportModulePath && !allModuleDescriptors.isEmpty()) { Collection unnamedProjects = new ArrayList<>(); - for ( JavadocModule javadocModule : allSourcePaths ) - { - MavenProject aggregatedProject = reactorKeys.get( javadocModule.getGa() ); - if ( aggregatedProject != null && !"pom".equals( aggregatedProject.getPackaging() ) ) - { + for (JavadocModule javadocModule : allSourcePaths) { + MavenProject aggregatedProject = reactorKeys.get(javadocModule.getGa()); + if (aggregatedProject != null && !"pom".equals(aggregatedProject.getPackaging())) { ResolvePathResult result = null; // Prefer jar over outputDirectory, since it may may contain an automatic module name - File artifactFile = getClassesFile( aggregatedProject ); - if ( artifactFile != null ) - { - ResolvePathRequest request = ResolvePathRequest.ofFile( artifactFile ); - try - { - result = locationManager.resolvePath( request ); - } - catch ( RuntimeException e ) - { + File artifactFile = getClassesFile(aggregatedProject); + if (artifactFile != null) { + ResolvePathRequest request = ResolvePathRequest.ofFile(artifactFile); + try { + result = locationManager.resolvePath(request); + } catch (RuntimeException e) { // most likely an invalid module name based on filename - if ( !"java.lang.module.FindException".equals( e.getClass().getName() ) ) - { + if (!"java.lang.module.FindException" + .equals(e.getClass().getName())) { throw e; } + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - } - else - { - Path moduleDescriptor = findMainDescriptor( javadocModule.getSourcePaths() ); - - if ( moduleDescriptor != null ) - { - try - { - result = locationManager.parseModuleDescriptor( moduleDescriptor ); - } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); + } else { + Path moduleDescriptor = findMainDescriptor(javadocModule.getSourcePaths()); + + if (moduleDescriptor != null) { + try { + result = locationManager.parseModuleDescriptor(moduleDescriptor); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } } } - if ( result != null && result.getModuleDescriptor() != null ) - { - moduleSourceDir = javadocOutputDirectory.toPath().resolve( "src" ); - try - { - moduleSourceDir = Files.createDirectories( moduleSourceDir ); + if (result != null && result.getModuleDescriptor() != null) { + moduleSourceDir = javadocOutputDirectory.toPath().resolve("src"); + try { + moduleSourceDir = Files.createDirectories(moduleSourceDir); - additionalModules.add( result.getModuleDescriptor().name() ); + additionalModules.add(result.getModuleDescriptor().name()); - patchModules.put( result.getModuleDescriptor().name(), javadocModule.getSourcePaths() ); + patchModules.put(result.getModuleDescriptor().name(), javadocModule.getSourcePaths()); - Path modulePath = moduleSourceDir.resolve( result.getModuleDescriptor().name() ); - if ( !Files.isDirectory( modulePath ) ) - { - Files.createDirectory( modulePath ); + Path modulePath = moduleSourceDir.resolve( + result.getModuleDescriptor().name()); + if (!Files.isDirectory(modulePath)) { + Files.createDirectory(modulePath); } + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - } - else - { - unnamedProjects.add( javadocModule.getGa() ); + } else { + unnamedProjects.add(javadocModule.getGa()); } - if ( aggregatedProject.equals( getProject() ) ) - { + if (aggregatedProject.equals(getProject())) { mainResolvePathResult = result; } - } - else - { + } else { // todo - getLog().error( "no reactor project: " + javadocModule.getGa() ); + getLog().error("no reactor project: " + javadocModule.getGa()); } } - if ( !unnamedProjects.isEmpty() ) - { - getLog().error( "Creating an aggregated report for both named and unnamed modules is not possible." ); - getLog().error( "Ensure that every module has a module descriptor or is a jar with a MANIFEST.MF " - + "containing an Automatic-Module-Name." ); - getLog().error( "Fix the following projects:" ); - for ( String unnamedProject : unnamedProjects ) - { - getLog().error( " - " + unnamedProject ); + if (!unnamedProjects.isEmpty()) { + getLog().error("Creating an aggregated report for both named and unnamed modules is not possible."); + getLog().error("Ensure that every module has a module descriptor or is a jar with a MANIFEST.MF " + + "containing an Automatic-Module-Name."); + getLog().error("Fix the following projects:"); + for (String unnamedProject : unnamedProjects) { + getLog().error(" - " + unnamedProject); } - throw new MavenReportException( "Aggregator report contains named and unnamed modules" ); + throw new MavenReportException("Aggregator report contains named and unnamed modules"); } - if ( mainResolvePathResult != null - && ModuleNameSource.MANIFEST.equals( mainResolvePathResult.getModuleNameSource() ) ) - { - arguments.add( "--add-modules" ); - arguments.add( "ALL-MODULE-PATH" ); + if (mainResolvePathResult != null + && ModuleNameSource.MANIFEST.equals(mainResolvePathResult.getModuleNameSource())) { + arguments.add("--add-modules"); + arguments.add("ALL-MODULE-PATH"); } } // MJAVADOC-506 boolean moduleDescriptorSource = false; - for ( Path sourcepath : sourcePaths ) - { - if ( Files.isRegularFile( sourcepath.resolve( "module-info.java" ) ) ) - { + for (Path sourcepath : sourcePaths) { + if (Files.isRegularFile(sourcepath.resolve("module-info.java"))) { moduleDescriptorSource = true; break; } } final ModuleNameSource mainModuleNameSource; - if ( mainResolvePathResult != null ) - { + if (mainResolvePathResult != null) { mainModuleNameSource = mainResolvePathResult.getModuleNameSource(); - } - else - { + } else { mainModuleNameSource = null; } - if ( supportModulePath - && ( isAggregator() - || ModuleNameSource.MODULEDESCRIPTOR.equals( mainModuleNameSource ) - || ModuleNameSource.MANIFEST.equals( mainModuleNameSource ) ) ) - { - List pathElements = new ArrayList<>( getPathElements() ); - File artifactFile = getClassesFile( project ); - if ( artifactFile != null ) - { - pathElements.add( 0, artifactFile ); + if (supportModulePath + && (isAggregator() + || ModuleNameSource.MODULEDESCRIPTOR.equals(mainModuleNameSource) + || ModuleNameSource.MANIFEST.equals(mainModuleNameSource))) { + List pathElements = new ArrayList<>(getPathElements()); + File artifactFile = getClassesFile(project); + if (artifactFile != null) { + pathElements.add(0, artifactFile); } - ResolvePathsRequest request = - ResolvePathsRequest.ofFiles( pathElements ); + ResolvePathsRequest request = ResolvePathsRequest.ofFiles(pathElements); String mainModuleName = null; - if ( mainResolvePathResult != null ) - { - request.setModuleDescriptor( mainResolvePathResult.getModuleDescriptor() ); + if (mainResolvePathResult != null) { + request.setModuleDescriptor(mainResolvePathResult.getModuleDescriptor()); mainModuleName = mainResolvePathResult.getModuleDescriptor().name(); } - request.setAdditionalModules( additionalModules ); - request.setIncludeStatic( isAggregator() ); + request.setAdditionalModules(additionalModules); + request.setIncludeStatic(isAggregator()); - try - { - ResolvePathsResult result = locationManager.resolvePaths( request ); + try { + ResolvePathsResult result = locationManager.resolvePaths(request); - Set modulePathElements = new HashSet<>( result.getModulepathElements().keySet() ) ; + Set modulePathElements = + new HashSet<>(result.getModulepathElements().keySet()); - Collection classPathElements = new ArrayList<>( result.getClasspathElements().size() ); + Collection classPathElements = + new ArrayList<>(result.getClasspathElements().size()); - for ( File file : result.getClasspathElements() ) - { - if ( file.isDirectory() && new File( file, "module-info.class" ).exists() ) - { - modulePathElements.add( file ); - } - else if ( ModuleNameSource.MANIFEST.equals( mainModuleNameSource ) ) - { - ModuleNameSource depModuleNameSource = - locationManager.resolvePath( ResolvePathRequest.ofFile( file ) ).getModuleNameSource(); - if ( ModuleNameSource.MODULEDESCRIPTOR.equals( depModuleNameSource ) - || ModuleNameSource.MANIFEST.equals( depModuleNameSource ) ) - { - modulePathElements.add( file ); - } - else - { - patchModules.get( mainModuleName ).add( file.toPath() ); + for (File file : result.getClasspathElements()) { + if (file.isDirectory() && new File(file, "module-info.class").exists()) { + modulePathElements.add(file); + } else if (ModuleNameSource.MANIFEST.equals(mainModuleNameSource)) { + ModuleNameSource depModuleNameSource = locationManager + .resolvePath(ResolvePathRequest.ofFile(file)) + .getModuleNameSource(); + if (ModuleNameSource.MODULEDESCRIPTOR.equals(depModuleNameSource) + || ModuleNameSource.MANIFEST.equals(depModuleNameSource)) { + modulePathElements.add(file); + } else { + patchModules.get(mainModuleName).add(file.toPath()); } - } - else - { - classPathElements.add( file ); + } else { + classPathElements.add(file); } } /* MJAVADOC-620: also add all JARs where module-name-guessing leads to a FindException: */ - for ( Entry pathExceptionEntry : result.getPathExceptions().entrySet() ) - { + for (Entry pathExceptionEntry : + result.getPathExceptions().entrySet()) { Exception exception = pathExceptionEntry.getValue(); // For Java < 9 compatibility, reference FindException by name: - if ( "java.lang.module.FindException".equals( exception.getClass().getName() ) ) - { + if ("java.lang.module.FindException" + .equals(exception.getClass().getName())) { File jarPath = pathExceptionEntry.getKey(); - classPathElements.add( jarPath ); + classPathElements.add(jarPath); } } - String classpath = StringUtils.join( classPathElements.iterator(), File.pathSeparator ); - addArgIfNotEmpty( arguments, "--class-path", JavadocUtil.quotedPathArgument( classpath ), false, - false ); + String classpath = StringUtils.join(classPathElements.iterator(), File.pathSeparator); + addArgIfNotEmpty(arguments, "--class-path", JavadocUtil.quotedPathArgument(classpath), false, false); - String modulepath = - StringUtils.join( modulePathElements.iterator(), File.pathSeparator ); - addArgIfNotEmpty( arguments, "--module-path", JavadocUtil.quotedPathArgument( modulepath ), false, - false ); + String modulepath = StringUtils.join(modulePathElements.iterator(), File.pathSeparator); + addArgIfNotEmpty(arguments, "--module-path", JavadocUtil.quotedPathArgument(modulepath), false, false); + } catch (IOException e) { + throw new MavenReportException(e.getMessage(), e); } - catch ( IOException e ) - { - throw new MavenReportException( e.getMessage(), e ); - } - } - else if ( supportModulePath && moduleDescriptorSource && !isTest() ) - { - String modulepath = StringUtils.join( getPathElements().iterator(), File.pathSeparator ); - addArgIfNotEmpty( arguments, "--module-path", JavadocUtil.quotedPathArgument( modulepath ) , false, false ); - } - else - { - String classpath = StringUtils.join( getPathElements().iterator(), File.pathSeparator ); - addArgIfNotEmpty( arguments, "-classpath", JavadocUtil.quotedPathArgument( classpath ) , false, false ); + } else if (supportModulePath && moduleDescriptorSource && !isTest()) { + String modulepath = StringUtils.join(getPathElements().iterator(), File.pathSeparator); + addArgIfNotEmpty(arguments, "--module-path", JavadocUtil.quotedPathArgument(modulepath), false, false); + } else { + String classpath = StringUtils.join(getPathElements().iterator(), File.pathSeparator); + addArgIfNotEmpty(arguments, "-classpath", JavadocUtil.quotedPathArgument(classpath), false, false); } - for ( Entry> entry : patchModules.entrySet() ) - { - addArgIfNotEmpty( arguments, "--patch-module", entry.getKey() + '=' - + JavadocUtil.quotedPathArgument( getSourcePath( entry.getValue() ) ), - false, false ); + for (Entry> entry : patchModules.entrySet()) { + addArgIfNotEmpty( + arguments, + "--patch-module", + entry.getKey() + '=' + JavadocUtil.quotedPathArgument(getSourcePath(entry.getValue())), + false, + false); } - if ( StringUtils.isNotEmpty( doclet ) ) - { - addArgIfNotEmpty( arguments, "-doclet", JavadocUtil.quotedArgument( doclet ) ); - addArgIfNotEmpty( arguments, "-docletpath", JavadocUtil.quotedPathArgument( getDocletPath() ) ); + if (StringUtils.isNotEmpty(doclet)) { + addArgIfNotEmpty(arguments, "-doclet", JavadocUtil.quotedArgument(doclet)); + addArgIfNotEmpty(arguments, "-docletpath", JavadocUtil.quotedPathArgument(getDocletPath())); } - if ( StringUtils.isEmpty( encoding ) ) - { - getLog().warn( - "Source files encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING - + ", i.e. build is platform dependent!" ); + if (StringUtils.isEmpty(encoding)) { + getLog().warn("Source files encoding has not been set, using platform encoding " + + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!"); } - addArgIfNotEmpty( arguments, "-encoding", JavadocUtil.quotedArgument( getEncoding() ) ); + addArgIfNotEmpty(arguments, "-encoding", JavadocUtil.quotedArgument(getEncoding())); - addArgIfNotEmpty( arguments, "-extdirs", - JavadocUtil.quotedPathArgument( JavadocUtil.unifyPathSeparator( extdirs ) ) ); + addArgIfNotEmpty( + arguments, "-extdirs", JavadocUtil.quotedPathArgument(JavadocUtil.unifyPathSeparator(extdirs))); - if ( ( getOverview() != null ) && ( getOverview().exists() ) ) - { - addArgIfNotEmpty( arguments, "-overview", - JavadocUtil.quotedPathArgument( getOverview().getAbsolutePath() ) ); + if ((getOverview() != null) && (getOverview().exists())) { + addArgIfNotEmpty( + arguments, + "-overview", + JavadocUtil.quotedPathArgument(getOverview().getAbsolutePath())); } - arguments.add( getAccessLevel() ); + arguments.add(getAccessLevel()); - if ( isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) - { - addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_5 ); + if (isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) { + addArgIf(arguments, quiet, "-quiet", SINCE_JAVADOC_1_5); } - if ( release != null ) - { - arguments.add( "--release" ); - arguments.add( release ); - } - else - { - addArgIfNotEmpty( arguments, "-source", JavadocUtil.quotedArgument( source ), SINCE_JAVADOC_1_4 ); + if (release != null) { + arguments.add("--release"); + arguments.add(release); + } else { + addArgIfNotEmpty(arguments, "-source", JavadocUtil.quotedArgument(source), SINCE_JAVADOC_1_4); } - if ( ( StringUtils.isEmpty( sourcepath ) ) && ( StringUtils.isNotEmpty( subpackages ) ) ) - { - sourcepath = StringUtils.join( sourcePaths.iterator(), File.pathSeparator ); + if ((StringUtils.isEmpty(sourcepath)) && (StringUtils.isNotEmpty(subpackages))) { + sourcepath = StringUtils.join(sourcePaths.iterator(), File.pathSeparator); } - if ( moduleSourceDir == null ) - { - addArgIfNotEmpty( arguments, "-sourcepath", - JavadocUtil.quotedPathArgument( getSourcePath( sourcePaths ) ), false, false ); - } - else if ( mainResolvePathResult == null - || ModuleNameSource.MODULEDESCRIPTOR.equals( mainResolvePathResult.getModuleNameSource() ) ) - { - addArgIfNotEmpty( arguments, "--module-source-path", - JavadocUtil.quotedPathArgument( moduleSourceDir.toString() ) ); + if (moduleSourceDir == null) { + addArgIfNotEmpty( + arguments, "-sourcepath", JavadocUtil.quotedPathArgument(getSourcePath(sourcePaths)), false, false); + } else if (mainResolvePathResult == null + || ModuleNameSource.MODULEDESCRIPTOR.equals(mainResolvePathResult.getModuleNameSource())) { + addArgIfNotEmpty( + arguments, "--module-source-path", JavadocUtil.quotedPathArgument(moduleSourceDir.toString())); } - - if ( StringUtils.isNotEmpty( sourcepath ) && isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) - { - addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_5 ); + if (StringUtils.isNotEmpty(sourcepath) && isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) { + addArgIfNotEmpty(arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_5); } // [MJAVADOC-497] must be after sourcepath is recalculated, since getExcludedPackages() depends on it - addArgIfNotEmpty( arguments, "-exclude", getExcludedPackages( sourcePaths ), SINCE_JAVADOC_1_4 ); + addArgIfNotEmpty(arguments, "-exclude", getExcludedPackages(sourcePaths), SINCE_JAVADOC_1_4); - addArgIf( arguments, verbose, "-verbose" ); + addArgIf(arguments, verbose, "-verbose"); - if ( additionalOptions != null && additionalOptions.length > 0 ) - { - for ( String additionalOption : additionalOptions ) - { - arguments.add( additionalOption.replaceAll( "(? 0) { + for (String additionalOption : additionalOptions) { + arguments.add(additionalOption.replaceAll("(? resolvePathRequest = ResolvePathRequest.ofFile( artifactFile ); - try - { - resolvePathResult = locationManager.resolvePath( resolvePathRequest ); + ResolvePathRequest resolvePathRequest = ResolvePathRequest.ofFile(artifactFile); + try { + resolvePathResult = locationManager.resolvePath(resolvePathRequest); // happens when artifactFile is a directory without module descriptor - if ( resolvePathResult.getModuleDescriptor() == null ) - { + if (resolvePathResult.getModuleDescriptor() == null) { return null; } - } - catch ( IOException | RuntimeException /* e.g java.lang.module.FindException */ e ) - { - if ( getLog().isDebugEnabled() ) - { + } catch (IOException | RuntimeException /* e.g java.lang.module.FindException */ e) { + if (getLog().isDebugEnabled()) { Throwable cause = e; - while ( cause.getCause() != null ) - { + while (cause.getCause() != null) { cause = cause.getCause(); } - getLog().debug( "resolve path for: " + artifactFile + " cause error: " + cause ); + getLog().debug("resolve path for: " + artifactFile + " cause error: " + cause); } } return resolvePathResult; } - private Path findMainDescriptor( Collection roots ) throws MavenReportException - { - for ( Map.Entry> entry : getFiles( roots ).entrySet() ) - { - if ( entry.getValue().contains( "module-info.java" ) ) - { - return entry.getKey().resolve( "module-info.java" ); + private Path findMainDescriptor(Collection roots) throws MavenReportException { + for (Map.Entry> entry : getFiles(roots).entrySet()) { + if (entry.getValue().contains("module-info.java")) { + return entry.getKey().resolve("module-info.java"); } } return null; @@ -5363,142 +4722,138 @@ private Path findMainDescriptor( Collection roots ) throws MavenReportExce * @see * https://docs.oracle.com/javase/7/docs/technotes/tools/windows/javadoc.html#standard */ - private void addStandardDocletOptions( File javadocOutputDirectory, - List arguments, - Set offlineLinks ) - throws MavenReportException - { + private void addStandardDocletOptions( + File javadocOutputDirectory, List arguments, Set offlineLinks) + throws MavenReportException { validateStandardDocletOptions(); // all options in alphabetical order - addArgIf( arguments, author, "-author" ); + addArgIf(arguments, author, "-author"); - addArgIfNotEmpty( arguments, "-bottom", JavadocUtil.quotedArgument( getBottomText() ), false, false ); + addArgIfNotEmpty(arguments, "-bottom", JavadocUtil.quotedArgument(getBottomText()), false, false); - if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) - { - addArgIf( arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_4 ); + if (!isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) { + addArgIf(arguments, breakiterator, "-breakiterator", SINCE_JAVADOC_1_4); } - addArgIfNotEmpty( arguments, "-charset", JavadocUtil.quotedArgument( getCharset() ) ); + addArgIfNotEmpty(arguments, "-charset", JavadocUtil.quotedArgument(getCharset())); - addArgIfNotEmpty( arguments, "-d", JavadocUtil.quotedPathArgument( javadocOutputDirectory.toString() ) ); + addArgIfNotEmpty(arguments, "-d", JavadocUtil.quotedPathArgument(javadocOutputDirectory.toString())); - addArgIfNotEmpty( arguments, "-docencoding", JavadocUtil.quotedArgument( getDocencoding() ) ); + addArgIfNotEmpty(arguments, "-docencoding", JavadocUtil.quotedArgument(getDocencoding())); - addArgIf( arguments, docfilessubdirs, "-docfilessubdirs", SINCE_JAVADOC_1_4 ); + addArgIf(arguments, docfilessubdirs, "-docfilessubdirs", SINCE_JAVADOC_1_4); - addArgIf( arguments, StringUtils.isNotEmpty( doclint ), "-Xdoclint:" + getDoclint(), SINCE_JAVADOC_1_8 ); + addArgIf(arguments, StringUtils.isNotEmpty(doclint), "-Xdoclint:" + getDoclint(), SINCE_JAVADOC_1_8); - addArgIfNotEmpty( arguments, "-doctitle", JavadocUtil.quotedArgument( getDoctitle() ), false, false ); + addArgIfNotEmpty(arguments, "-doctitle", JavadocUtil.quotedArgument(getDoctitle()), false, false); - if ( docfilessubdirs ) - { - addArgIfNotEmpty( arguments, "-excludedocfilessubdir", - JavadocUtil.quotedPathArgument( excludedocfilessubdir ), SINCE_JAVADOC_1_4 ); + if (docfilessubdirs) { + addArgIfNotEmpty( + arguments, + "-excludedocfilessubdir", + JavadocUtil.quotedPathArgument(excludedocfilessubdir), + SINCE_JAVADOC_1_4); } - addArgIfNotEmpty( arguments, "-footer", JavadocUtil.quotedArgument( footer ), false, false ); + addArgIfNotEmpty(arguments, "-footer", JavadocUtil.quotedArgument(footer), false, false); - addGroups( arguments ); + addGroups(arguments); - addArgIfNotEmpty( arguments, "-header", JavadocUtil.quotedArgument( header ), false, false ); + addArgIfNotEmpty(arguments, "-header", JavadocUtil.quotedArgument(header), false, false); - Optional helpFile = getHelpFile( javadocOutputDirectory ); - if ( helpFile.isPresent() ) - { - addArgIfNotEmpty( arguments, "-helpfile", - JavadocUtil.quotedPathArgument( helpFile.get().getAbsolutePath() ) ); + Optional helpFile = getHelpFile(javadocOutputDirectory); + if (helpFile.isPresent()) { + addArgIfNotEmpty( + arguments, + "-helpfile", + JavadocUtil.quotedPathArgument(helpFile.get().getAbsolutePath())); } - addArgIf( arguments, keywords, "-keywords", SINCE_JAVADOC_1_4_2 ); + addArgIf(arguments, keywords, "-keywords", SINCE_JAVADOC_1_4_2); - addLinkArguments( arguments ); + addLinkArguments(arguments); - addLinkofflineArguments( arguments, offlineLinks ); + addLinkofflineArguments(arguments, offlineLinks); - addArgIf( arguments, linksource, "-linksource", SINCE_JAVADOC_1_4 ); + addArgIf(arguments, linksource, "-linksource", SINCE_JAVADOC_1_4); - if ( sourcetab > 0 ) - { - if ( javadocRuntimeVersion == SINCE_JAVADOC_1_4_2 ) - { - addArgIfNotEmpty( arguments, "-linksourcetab", String.valueOf( sourcetab ) ); + if (sourcetab > 0) { + if (javadocRuntimeVersion == SINCE_JAVADOC_1_4_2) { + addArgIfNotEmpty(arguments, "-linksourcetab", String.valueOf(sourcetab)); } - addArgIfNotEmpty( arguments, "-sourcetab", String.valueOf( sourcetab ), SINCE_JAVADOC_1_5 ); + addArgIfNotEmpty(arguments, "-sourcetab", String.valueOf(sourcetab), SINCE_JAVADOC_1_5); } - addArgIf( arguments, nocomment, "-nocomment", SINCE_JAVADOC_1_4 ); + addArgIf(arguments, nocomment, "-nocomment", SINCE_JAVADOC_1_4); - addArgIf( arguments, nodeprecated, "-nodeprecated" ); + addArgIf(arguments, nodeprecated, "-nodeprecated"); - addArgIf( arguments, nodeprecatedlist, "-nodeprecatedlist" ); + addArgIf(arguments, nodeprecatedlist, "-nodeprecatedlist"); - addArgIf( arguments, nohelp, "-nohelp" ); + addArgIf(arguments, nohelp, "-nohelp"); - addArgIf( arguments, noindex, "-noindex" ); + addArgIf(arguments, noindex, "-noindex"); - addArgIf( arguments, nonavbar, "-nonavbar" ); + addArgIf(arguments, nonavbar, "-nonavbar"); - addArgIf( arguments, nooverview, "-nooverview" ); + addArgIf(arguments, nooverview, "-nooverview"); - addArgIfNotEmpty( arguments, "-noqualifier", JavadocUtil.quotedArgument( noqualifier ), SINCE_JAVADOC_1_4 ); + addArgIfNotEmpty(arguments, "-noqualifier", JavadocUtil.quotedArgument(noqualifier), SINCE_JAVADOC_1_4); - addArgIf( arguments, nosince, "-nosince" ); + addArgIf(arguments, nosince, "-nosince"); - if ( !notimestamp && MavenArchiver.parseBuildOutputTimestamp( outputTimestamp ).isPresent() ) - { + if (!notimestamp + && MavenArchiver.parseBuildOutputTimestamp(outputTimestamp).isPresent()) { // Override the notimestamp option if a Reproducible Build is requested. notimestamp = true; } - addArgIf( arguments, notimestamp, "-notimestamp", SINCE_JAVADOC_1_5 ); + addArgIf(arguments, notimestamp, "-notimestamp", SINCE_JAVADOC_1_5); - addArgIf( arguments, notree, "-notree" ); + addArgIf(arguments, notree, "-notree"); - addArgIfNotEmpty( arguments, "-packagesheader", JavadocUtil.quotedArgument( packagesheader ), - SINCE_JAVADOC_1_4_2 ); + addArgIfNotEmpty(arguments, "-packagesheader", JavadocUtil.quotedArgument(packagesheader), SINCE_JAVADOC_1_4_2); - if ( !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) // Sun bug: 4714350 + if (!isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) // Sun bug: 4714350 { - addArgIf( arguments, quiet, "-quiet", SINCE_JAVADOC_1_4 ); + addArgIf(arguments, quiet, "-quiet", SINCE_JAVADOC_1_4); } - addArgIf( arguments, serialwarn, "-serialwarn" ); + addArgIf(arguments, serialwarn, "-serialwarn"); - addArgIf( arguments, splitindex, "-splitindex" ); + addArgIf(arguments, splitindex, "-splitindex"); - Optional stylesheetfile = getStylesheetFile( javadocOutputDirectory ); + Optional stylesheetfile = getStylesheetFile(javadocOutputDirectory); - if ( stylesheetfile.isPresent() ) - { - addArgIfNotEmpty( arguments, "-stylesheetfile", - JavadocUtil.quotedPathArgument( stylesheetfile.get().getAbsolutePath() ) ); + if (stylesheetfile.isPresent()) { + addArgIfNotEmpty( + arguments, + "-stylesheetfile", + JavadocUtil.quotedPathArgument(stylesheetfile.get().getAbsolutePath())); } - addAddStyleSheets( arguments ); + addAddStyleSheets(arguments); - if ( StringUtils.isNotEmpty( sourcepath ) && !isJavaDocVersionAtLeast( SINCE_JAVADOC_1_5 ) ) - { - addArgIfNotEmpty( arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_4 ); + if (StringUtils.isNotEmpty(sourcepath) && !isJavaDocVersionAtLeast(SINCE_JAVADOC_1_5)) { + addArgIfNotEmpty(arguments, "-subpackages", subpackages, SINCE_JAVADOC_1_4); } - addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglet ), SINCE_JAVADOC_1_4 ); - addTaglets( arguments ); - addTagletsFromTagletArtifacts( arguments ); - addArgIfNotEmpty( arguments, "-tagletpath", JavadocUtil.quotedPathArgument( getTagletPath() ), - SINCE_JAVADOC_1_4 ); + addArgIfNotEmpty(arguments, "-taglet", JavadocUtil.quotedArgument(taglet), SINCE_JAVADOC_1_4); + addTaglets(arguments); + addTagletsFromTagletArtifacts(arguments); + addArgIfNotEmpty(arguments, "-tagletpath", JavadocUtil.quotedPathArgument(getTagletPath()), SINCE_JAVADOC_1_4); - addTags( arguments ); + addTags(arguments); - addArgIfNotEmpty( arguments, "-top", JavadocUtil.quotedArgument( top ), false, false, SINCE_JAVADOC_1_6 ); + addArgIfNotEmpty(arguments, "-top", JavadocUtil.quotedArgument(top), false, false, SINCE_JAVADOC_1_6); - addArgIf( arguments, use, "-use" ); + addArgIf(arguments, use, "-use"); - addArgIf( arguments, version, "-version" ); + addArgIf(arguments, version, "-version"); - addArgIfNotEmpty( arguments, "-windowtitle", JavadocUtil.quotedArgument( getWindowtitle() ), false, false ); + addArgIfNotEmpty(arguments, "-windowtitle", JavadocUtil.quotedArgument(getWindowtitle()), false, false); } /** @@ -5507,31 +4862,24 @@ private void addStandardDocletOptions( File javadocOutputDirectory, * @param arguments not null * @throws MavenReportException */ - private void addGroups( List arguments ) - throws MavenReportException - { + private void addGroups(List arguments) throws MavenReportException { Set groups = collectGroups(); - if ( isEmpty( groups ) ) - { + if (isEmpty(groups)) { return; } - for ( Group group : groups ) - { - if ( group == null || StringUtils.isEmpty( group.getTitle() ) || StringUtils.isEmpty( - group.getPackages() ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "A group option is empty. Ignore this option." ); + for (Group group : groups) { + if (group == null || StringUtils.isEmpty(group.getTitle()) || StringUtils.isEmpty(group.getPackages())) { + if (getLog().isWarnEnabled()) { + getLog().warn("A group option is empty. Ignore this option."); } - } - else - { - String groupTitle = StringUtils.replace( group.getTitle(), ",", "," ); - addArgIfNotEmpty( arguments, "-group", - JavadocUtil.quotedArgument( groupTitle ) + " " + JavadocUtil.quotedArgument( - group.getPackages() ), true ); + } else { + String groupTitle = StringUtils.replace(group.getTitle(), ",", ","); + addArgIfNotEmpty( + arguments, + "-group", + JavadocUtil.quotedArgument(groupTitle) + " " + JavadocUtil.quotedArgument(group.getPackages()), + true); } } } @@ -5542,41 +4890,29 @@ private void addGroups( List arguments ) * @param arguments not null * @throws MavenReportException */ - private void addTags( List arguments ) - throws MavenReportException - { + private void addTags(List arguments) throws MavenReportException { final String lineSeparator; - if ( javadocRuntimeVersion.isBefore( "9" ) ) - { + if (javadocRuntimeVersion.isBefore("9")) { lineSeparator = " "; - } - else - { + } else { lineSeparator = " \\\\" + SystemUtils.LINE_SEPARATOR; } - for ( Tag tag : collectTags() ) - { - if ( StringUtils.isEmpty( tag.getName() ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "A tag name is empty. Ignore this option." ); + for (Tag tag : collectTags()) { + if (StringUtils.isEmpty(tag.getName())) { + if (getLog().isWarnEnabled()) { + getLog().warn("A tag name is empty. Ignore this option."); } - } - else - { + } else { String value = "\"" + tag.getName(); - if ( StringUtils.isNotEmpty( tag.getPlacement() ) ) - { - value += ":" + tag.getPlacement().replaceAll( "\\R", lineSeparator ); - if ( StringUtils.isNotEmpty( tag.getHead() ) ) - { - value += ":" + tag.getHead().replaceAll( "\\R", lineSeparator ); + if (StringUtils.isNotEmpty(tag.getPlacement())) { + value += ":" + tag.getPlacement().replaceAll("\\R", lineSeparator); + if (StringUtils.isNotEmpty(tag.getHead())) { + value += ":" + tag.getHead().replaceAll("\\R", lineSeparator); } } value += "\""; - addArgIfNotEmpty( arguments, "-tag", value, SINCE_JAVADOC_1_4 ); + addArgIfNotEmpty(arguments, "-tag", value, SINCE_JAVADOC_1_4); } } } @@ -5586,26 +4922,19 @@ private void addTags( List arguments ) * * @param arguments not null */ - private void addTaglets( List arguments ) - { - if ( taglets == null ) - { + private void addTaglets(List arguments) { + if (taglets == null) { return; } - for ( Taglet taglet1 : taglets ) - { - if ( ( taglet1 == null ) || ( StringUtils.isEmpty( taglet1.getTagletClass() ) ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "A taglet option is empty. Ignore this option." ); + for (Taglet taglet1 : taglets) { + if ((taglet1 == null) || (StringUtils.isEmpty(taglet1.getTagletClass()))) { + if (getLog().isWarnEnabled()) { + getLog().warn("A taglet option is empty. Ignore this option."); } - } - else - { - addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( taglet1.getTagletClass() ), - SINCE_JAVADOC_1_4 ); + } else { + addArgIfNotEmpty( + arguments, "-taglet", JavadocUtil.quotedArgument(taglet1.getTagletClass()), SINCE_JAVADOC_1_4); } } } @@ -5617,126 +4946,93 @@ private void addTaglets( List arguments ) * @throws MavenReportException if any * @see JavadocUtil#getTagletClassNames(File) */ - private void addTagletsFromTagletArtifacts( List arguments ) - throws MavenReportException - { + private void addTagletsFromTagletArtifacts(List arguments) throws MavenReportException { Set tArtifacts = new LinkedHashSet<>(); - if ( tagletArtifacts != null && tagletArtifacts.length > 0 ) - { - tArtifacts.addAll( Arrays.asList( tagletArtifacts ) ); + if (tagletArtifacts != null && tagletArtifacts.length > 0) { + tArtifacts.addAll(Arrays.asList(tagletArtifacts)); } - if ( includeDependencySources ) - { - try - { + if (includeDependencySources) { + try { resolveDependencyBundles(); - } - catch ( IOException e ) - { + } catch (IOException e) { throw new MavenReportException( - "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e ); + "Failed to resolve javadoc bundles from dependencies: " + e.getMessage(), e); } - if ( isNotEmpty( dependencyJavadocBundles ) ) - { - for ( JavadocBundle bundle : dependencyJavadocBundles ) - { + if (isNotEmpty(dependencyJavadocBundles)) { + for (JavadocBundle bundle : dependencyJavadocBundles) { JavadocOptions options = bundle.getOptions(); - if ( options != null && isNotEmpty( options.getTagletArtifacts() ) ) - { - tArtifacts.addAll( options.getTagletArtifacts() ); + if (options != null && isNotEmpty(options.getTagletArtifacts())) { + tArtifacts.addAll(options.getTagletArtifacts()); } } } } - if ( isEmpty( tArtifacts ) ) - { + if (isEmpty(tArtifacts)) { return; } List tagletsPath = new ArrayList<>(); - for ( TagletArtifact aTagletArtifact : tArtifacts ) - { - if ( ( StringUtils.isNotEmpty( aTagletArtifact.getGroupId() ) ) && ( StringUtils.isNotEmpty( - aTagletArtifact.getArtifactId() ) ) && ( StringUtils.isNotEmpty( aTagletArtifact.getVersion() ) ) ) - { + for (TagletArtifact aTagletArtifact : tArtifacts) { + if ((StringUtils.isNotEmpty(aTagletArtifact.getGroupId())) + && (StringUtils.isNotEmpty(aTagletArtifact.getArtifactId())) + && (StringUtils.isNotEmpty(aTagletArtifact.getVersion()))) { Artifact artifact; - try - { - artifact = createAndResolveArtifact( aTagletArtifact ); - } - catch ( ArtifactResolutionException e ) - { - throw new MavenReportException( "Unable to resolve artifact:" + aTagletArtifact, e ); + try { + artifact = createAndResolveArtifact(aTagletArtifact); + } catch (ArtifactResolutionException e) { + throw new MavenReportException("Unable to resolve artifact:" + aTagletArtifact, e); } - tagletsPath.add( artifact.getFile().getAbsolutePath() ); + tagletsPath.add(artifact.getFile().getAbsolutePath()); } } - tagletsPath = JavadocUtil.pruneFiles( tagletsPath ); + tagletsPath = JavadocUtil.pruneFiles(tagletsPath); - for ( String tagletJar : tagletsPath ) - { - if ( !tagletJar.toLowerCase( Locale.ENGLISH ).endsWith( ".jar" ) ) - { + for (String tagletJar : tagletsPath) { + if (!tagletJar.toLowerCase(Locale.ENGLISH).endsWith(".jar")) { continue; } List tagletClasses; - try - { - tagletClasses = JavadocUtil.getTagletClassNames( new File( tagletJar ) ); - } - catch ( IOException e ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar - + "'. Try to specify them with ." ); + try { + tagletClasses = JavadocUtil.getTagletClassNames(new File(tagletJar)); + } catch (IOException e) { + if (getLog().isWarnEnabled()) { + getLog().warn("Unable to auto-detect Taglet class names from '" + tagletJar + + "'. Try to specify them with ."); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "IOException: " + e.getMessage(), e ); + if (getLog().isDebugEnabled()) { + getLog().debug("IOException: " + e.getMessage(), e); } continue; - } - catch ( ClassNotFoundException e ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar - + "'. Try to specify them with ." ); + } catch (ClassNotFoundException e) { + if (getLog().isWarnEnabled()) { + getLog().warn("Unable to auto-detect Taglet class names from '" + tagletJar + + "'. Try to specify them with ."); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "ClassNotFoundException: " + e.getMessage(), e ); + if (getLog().isDebugEnabled()) { + getLog().debug("ClassNotFoundException: " + e.getMessage(), e); } continue; - } - catch ( NoClassDefFoundError e ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Unable to auto-detect Taglet class names from '" + tagletJar - + "'. Try to specify them with ." ); + } catch (NoClassDefFoundError e) { + if (getLog().isWarnEnabled()) { + getLog().warn("Unable to auto-detect Taglet class names from '" + tagletJar + + "'. Try to specify them with ."); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "NoClassDefFoundError: " + e.getMessage(), e ); + if (getLog().isDebugEnabled()) { + getLog().debug("NoClassDefFoundError: " + e.getMessage(), e); } continue; } - if ( tagletClasses != null && !tagletClasses.isEmpty() ) - { - for ( String tagletClass : tagletClasses ) - { - addArgIfNotEmpty( arguments, "-taglet", JavadocUtil.quotedArgument( tagletClass ), - SINCE_JAVADOC_1_4 ); + if (tagletClasses != null && !tagletClasses.isEmpty()) { + for (String tagletClass : tagletClasses) { + addArgIfNotEmpty(arguments, "-taglet", JavadocUtil.quotedArgument(tagletClass), SINCE_JAVADOC_1_4); } } } @@ -5749,20 +5045,14 @@ private void addTagletsFromTagletArtifacts( List arguments ) * @param javadocOutputDirectory not null * @throws MavenReportException if any errors occur */ - private void executeJavadocCommandLine( Commandline cmd, File javadocOutputDirectory ) - throws MavenReportException - { - if ( staleDataPath != null ) - { - if ( !isUpToDate( cmd ) ) - { - doExecuteJavadocCommandLine( cmd, javadocOutputDirectory ); - StaleHelper.writeStaleData( cmd, staleDataPath.toPath() ); + private void executeJavadocCommandLine(Commandline cmd, File javadocOutputDirectory) throws MavenReportException { + if (staleDataPath != null) { + if (!isUpToDate(cmd)) { + doExecuteJavadocCommandLine(cmd, javadocOutputDirectory); + StaleHelper.writeStaleData(cmd, staleDataPath.toPath()); } - } - else - { - doExecuteJavadocCommandLine( cmd, javadocOutputDirectory ); + } else { + doExecuteJavadocCommandLine(cmd, javadocOutputDirectory); } } @@ -5773,42 +5063,28 @@ private void executeJavadocCommandLine( Commandline cmd, File javadocOutputDirec * @return true is the javadoc is uptodate, false otherwise * @throws MavenReportException if any error occur */ - private boolean isUpToDate( Commandline cmd ) - throws MavenReportException - { - try - { - String curdata = StaleHelper.getStaleData( cmd ); + private boolean isUpToDate(Commandline cmd) throws MavenReportException { + try { + String curdata = StaleHelper.getStaleData(cmd); Path cacheData = staleDataPath.toPath(); String prvdata; - if ( Files.isRegularFile( cacheData ) ) - { - prvdata = new String( Files.readAllBytes( cacheData ), StandardCharsets.UTF_8 ); - } - else - { + if (Files.isRegularFile(cacheData)) { + prvdata = new String(Files.readAllBytes(cacheData), StandardCharsets.UTF_8); + } else { prvdata = null; } - if ( curdata.equals( prvdata ) ) - { - getLog().info( "Skipping javadoc generation, everything is up to date." ); + if (curdata.equals(prvdata)) { + getLog().info("Skipping javadoc generation, everything is up to date."); return true; - } - else - { - if ( prvdata == null ) - { - getLog().info( "No previous run data found, generating javadoc." ); - } - else - { - getLog().info( "Configuration changed, re-generating javadoc." ); + } else { + if (prvdata == null) { + getLog().info("No previous run data found, generating javadoc."); + } else { + getLog().info("Configuration changed, re-generating javadoc."); } } - } - catch ( IOException e ) - { - throw new MavenReportException( "Error checking uptodate status", e ); + } catch (IOException e) { + throw new MavenReportException("Error checking uptodate status", e); } return false; } @@ -5820,145 +5096,119 @@ private boolean isUpToDate( Commandline cmd ) * @param javadocOutputDirectory not null * @throws MavenReportException if any errors occur */ - private void doExecuteJavadocCommandLine( Commandline cmd, File javadocOutputDirectory ) - throws MavenReportException - { - if ( getLog().isDebugEnabled() ) - { + private void doExecuteJavadocCommandLine(Commandline cmd, File javadocOutputDirectory) throws MavenReportException { + if (getLog().isDebugEnabled()) { // no quoted arguments - getLog().debug( CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ) ); + getLog().debug(CommandLineUtils.toString(cmd.getCommandline()).replaceAll("'", "")); } String cmdLine = null; - if ( debug ) - { - cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); + if (debug) { + cmdLine = CommandLineUtils.toString(cmd.getCommandline()).replaceAll("'", ""); - writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); + writeDebugJavadocScript(cmdLine, javadocOutputDirectory); } CommandLineUtils.StringStreamConsumer err = new JavadocUtil.JavadocOutputStreamConsumer(); CommandLineUtils.StringStreamConsumer out = new JavadocUtil.JavadocOutputStreamConsumer(); - try - { - int exitCode = CommandLineUtils.executeCommandLine( cmd, out, err ); + try { + int exitCode = CommandLineUtils.executeCommandLine(cmd, out, err); - String output = ( StringUtils.isEmpty( out.getOutput() ) ? null : '\n' + out.getOutput().trim() ); + String output = (StringUtils.isEmpty(out.getOutput()) + ? null + : '\n' + out.getOutput().trim()); - if ( exitCode != 0 ) - { - if ( cmdLine == null ) - { - cmdLine = CommandLineUtils.toString( cmd.getCommandline() ).replaceAll( "'", "" ); + if (exitCode != 0) { + if (cmdLine == null) { + cmdLine = CommandLineUtils.toString(cmd.getCommandline()).replaceAll("'", ""); } - writeDebugJavadocScript( cmdLine, javadocOutputDirectory ); - - if ( StringUtils.isNotEmpty( output ) && StringUtils.isEmpty( err.getOutput() ) - && isJavadocVMInitError( output ) ) - { - throw new MavenReportException( output + '\n' + '\n' + JavadocUtil.ERROR_INIT_VM + '\n' - + "Or, try to reduce the Java heap size for the Javadoc goal using " - + "-Dminmemory= and -Dmaxmemory=." + '\n' + '\n' + "Command line was: " + cmdLine - + '\n' + '\n' + "Refer to the generated Javadoc files in '" + javadocOutputDirectory - + "' dir.\n" ); + writeDebugJavadocScript(cmdLine, javadocOutputDirectory); + + if (StringUtils.isNotEmpty(output) + && StringUtils.isEmpty(err.getOutput()) + && isJavadocVMInitError(output)) { + throw new MavenReportException(output + '\n' + '\n' + JavadocUtil.ERROR_INIT_VM + '\n' + + "Or, try to reduce the Java heap size for the Javadoc goal using " + + "-Dminmemory= and -Dmaxmemory=." + '\n' + '\n' + "Command line was: " + + cmdLine + + '\n' + '\n' + "Refer to the generated Javadoc files in '" + javadocOutputDirectory + + "' dir.\n"); } - if ( StringUtils.isNotEmpty( output ) ) - { - getLog().info( output ); + if (StringUtils.isNotEmpty(output)) { + getLog().info(output); } - StringBuilder msg = new StringBuilder( "\nExit code: " ); - msg.append( exitCode ); - if ( StringUtils.isNotEmpty( err.getOutput() ) ) - { + StringBuilder msg = new StringBuilder("\nExit code: "); + msg.append(exitCode); + if (StringUtils.isNotEmpty(err.getOutput())) { // parse stderr, log informational output, add all other to exception message List nonInfoLines = new ArrayList<>(); - for ( String str : err.getOutput().split( "\\R" ) ) - { - if ( isInformationalOutput( str ) ) - { - getLog().debug( str ); - } - else - { - nonInfoLines.add( str ); + for (String str : err.getOutput().split("\\R")) { + if (isInformationalOutput(str)) { + getLog().debug(str); + } else { + nonInfoLines.add(str); } } - if ( !nonInfoLines.isEmpty() ) - { - msg.append( '\n' ); // new line between exit code and warnings/errors - msg.append( String.join( "\n" , nonInfoLines ) ); + if (!nonInfoLines.isEmpty()) { + msg.append('\n'); // new line between exit code and warnings/errors + msg.append(String.join("\n", nonInfoLines)); } - } - msg.append( '\n' ); - msg.append( "Command line was: " ).append( cmdLine ).append( '\n' ).append( '\n' ); + msg.append('\n'); + msg.append("Command line was: ").append(cmdLine).append('\n').append('\n'); - msg.append( "Refer to the generated Javadoc files in '" ).append( javadocOutputDirectory ) - .append( "' dir.\n" ); + msg.append("Refer to the generated Javadoc files in '") + .append(javadocOutputDirectory) + .append("' dir.\n"); - throw new MavenReportException( msg.toString() ); + throw new MavenReportException(msg.toString()); } - if ( StringUtils.isNotEmpty( output ) ) - { - getLog().info( output ); + if (StringUtils.isNotEmpty(output)) { + getLog().info(output); } - } - catch ( CommandLineException e ) - { - throw new MavenReportException( "Unable to execute javadoc command: " + e.getMessage(), e ); + } catch (CommandLineException e) { + throw new MavenReportException("Unable to execute javadoc command: " + e.getMessage(), e); } // ---------------------------------------------------------------------- // Handle Javadoc warnings // ---------------------------------------------------------------------- - if ( containsWarnings( err.getOutput() ) ) - { - if ( getLog().isWarnEnabled() ) - { - getLog().warn( "Javadoc Warnings" ); + if (containsWarnings(err.getOutput())) { + if (getLog().isWarnEnabled()) { + getLog().warn("Javadoc Warnings"); - StringTokenizer token = new StringTokenizer( err.getOutput(), "\n" ); - while ( token.hasMoreTokens() ) - { + StringTokenizer token = new StringTokenizer(err.getOutput(), "\n"); + while (token.hasMoreTokens()) { String current = token.nextToken().trim(); // log informational output at debug level only - if ( isInformationalOutput( current ) ) - { - getLog().debug( current ); + if (isInformationalOutput(current)) { + getLog().debug(current); + } else { + getLog().warn(current); } - else - { - getLog().warn( current ); - } - } } - if ( failOnWarnings ) - { - throw new MavenReportException( "Project contains Javadoc Warnings" ); + if (failOnWarnings) { + throw new MavenReportException("Project contains Javadoc Warnings"); } } } - private boolean containsWarnings( String output ) - { + private boolean containsWarnings(String output) { // JDK-8268774 / JDK-8270831 - if ( this.javadocRuntimeVersion.isBefore( "17" ) ) - { - return StringUtils.isNotEmpty( output ); - } - else - { - return Arrays.stream( output.split( "\\R" ) ) - .reduce( ( first, second ) -> second ) // last line - .filter( line -> line.matches( "\\d+ warnings?" ) ) - .isPresent(); + if (this.javadocRuntimeVersion.isBefore("17")) { + return StringUtils.isNotEmpty(output); + } else { + return Arrays.stream(output.split("\\R")) + .reduce((first, second) -> second) // last line + .filter(line -> line.matches("\\d+ warnings?")) + .isPresent(); } } @@ -5974,17 +5224,16 @@ private boolean containsWarnings( String output ) * @param str string to check * @return true if informational output, false if not or cannot be determined */ - private boolean isInformationalOutput( String str ) - { + private boolean isInformationalOutput(String str) { return str == null || str.trim().isEmpty() - || str.startsWith( "Loading source files for package " ) // main.Loading_source_files_for_package - || str.startsWith( "Loading source file " ) // main.Loading_source_file - || str.startsWith( "Generating " ) - || str.startsWith( "Constructing Javadoc information" ) // main.Building_tree - || str.startsWith( "Building index for " ) - || str.startsWith( "Building tree for " ) - || str.startsWith( "Standard Doclet version " ); + || str.startsWith("Loading source files for package ") // main.Loading_source_files_for_package + || str.startsWith("Loading source file ") // main.Loading_source_file + || str.startsWith("Generating ") + || str.startsWith("Constructing Javadoc information") // main.Building_tree + || str.startsWith("Building index for ") + || str.startsWith("Building tree for ") + || str.startsWith("Standard Doclet version "); } /** @@ -5996,43 +5245,36 @@ private boolean isInformationalOutput( String str ) * If {@code null}, the platform's default encoding is used (like javadoc does). * @return the number of patched files */ - private int fixFrameInjectionBug( File javadocOutputDirectory, String outputEncoding ) - throws IOException - { + private int fixFrameInjectionBug(File javadocOutputDirectory, String outputEncoding) throws IOException { final String fixData; - try ( InputStream in = this.getClass().getResourceAsStream( "frame-injection-fix.txt" ) ) - { - if ( in == null ) - { - throw new FileNotFoundException( "Missing resource 'frame-injection-fix.txt' in classpath." ); + try (InputStream in = this.getClass().getResourceAsStream("frame-injection-fix.txt")) { + if (in == null) { + throw new FileNotFoundException("Missing resource 'frame-injection-fix.txt' in classpath."); } - fixData = org.codehaus.plexus.util.StringUtils - .unifyLineSeparators( IOUtil.toString( in, "US-ASCII" ) ).trim(); + fixData = org.codehaus.plexus.util.StringUtils.unifyLineSeparators(IOUtil.toString(in, "US-ASCII")) + .trim(); } final DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( javadocOutputDirectory ); - ds.setCaseSensitive( false ); - ds.setIncludes( new String[]{ "**/index.html", "**/index.htm", "**/toc.html", "**/toc.htm" } ); + ds.setBasedir(javadocOutputDirectory); + ds.setCaseSensitive(false); + ds.setIncludes(new String[] {"**/index.html", "**/index.htm", "**/toc.html", "**/toc.htm"}); ds.addDefaultExcludes(); ds.scan(); int patched = 0; - for ( String f : ds.getIncludedFiles() ) - { - final File file = new File( javadocOutputDirectory, f ); + for (String f : ds.getIncludedFiles()) { + final File file = new File(javadocOutputDirectory, f); // we load the whole file as one String (toc/index files are // generally small, because they only contain frameset declaration): - final String fileContents = FileUtils.fileRead( file, outputEncoding ); + final String fileContents = FileUtils.fileRead(file, outputEncoding); // check if file may be vulnerable because it was not patched with "validURL(url)": - if ( !StringUtils.contains( fileContents, "function validURL(url) {" ) ) - { + if (!StringUtils.contains(fileContents, "function validURL(url) {")) { // we need to patch the file! final String patchedFileContents = - StringUtils.replaceOnce( fileContents, "function loadFrames() {", fixData ); - if ( !patchedFileContents.equals( fileContents ) ) - { - FileUtils.fileWrite( file, outputEncoding, patchedFileContents ); + StringUtils.replaceOnce(fileContents, "function loadFrames() {", fixData); + if (!patchedFileContents.equals(fileContents)) { + FileUtils.fileWrite(file, outputEncoding, patchedFileContents); patched++; } } @@ -6047,94 +5289,77 @@ private int fixFrameInjectionBug( File javadocOutputDirectory, String outputEnco * @return the resource file absolute path as String * @since 2.6 */ - private Optional getResource( File outputFile, String inputResourceName ) - { - if ( inputResourceName.startsWith( "/" ) ) - { - inputResourceName = inputResourceName.replaceFirst( "//*", "" ); + private Optional getResource(File outputFile, String inputResourceName) { + if (inputResourceName.startsWith("/")) { + inputResourceName = inputResourceName.replaceFirst("//*", ""); } List classPath = new ArrayList<>(); - classPath.add( project.getBuild().getSourceDirectory() ); + classPath.add(project.getBuild().getSourceDirectory()); - URL resourceURL = getResource( classPath, inputResourceName ); - if ( resourceURL != null ) - { - getLog().debug( inputResourceName + " found in the main src directory of the project." ); - return Optional.of( FileUtils.toFile( resourceURL ) ); + URL resourceURL = getResource(classPath, inputResourceName); + if (resourceURL != null) { + getLog().debug(inputResourceName + " found in the main src directory of the project."); + return Optional.of(FileUtils.toFile(resourceURL)); } classPath.clear(); List resources = project.getBuild().getResources(); - for ( Resource resource : resources ) - { - classPath.add( resource.getDirectory() ); + for (Resource resource : resources) { + classPath.add(resource.getDirectory()); } - resourceURL = getResource( classPath, inputResourceName ); - if ( resourceURL != null ) - { - getLog().debug( inputResourceName + " found in the main resources directories of the project." ); - return Optional.of( FileUtils.toFile( resourceURL ) ); + resourceURL = getResource(classPath, inputResourceName); + if (resourceURL != null) { + getLog().debug(inputResourceName + " found in the main resources directories of the project."); + return Optional.of(FileUtils.toFile(resourceURL)); } - if ( javadocDirectory.exists() ) - { + if (javadocDirectory.exists()) { classPath.clear(); - classPath.add( javadocDirectory.getAbsolutePath() ); - resourceURL = getResource( classPath, inputResourceName ); - if ( resourceURL != null ) - { - getLog().debug( inputResourceName + " found in the main javadoc directory of the project." ); - return Optional.of( FileUtils.toFile( resourceURL ) ); + classPath.add(javadocDirectory.getAbsolutePath()); + resourceURL = getResource(classPath, inputResourceName); + if (resourceURL != null) { + getLog().debug(inputResourceName + " found in the main javadoc directory of the project."); + return Optional.of(FileUtils.toFile(resourceURL)); } } classPath.clear(); final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; - Plugin javadocPlugin = getPlugin( project, pluginId ); - if ( javadocPlugin != null && javadocPlugin.getDependencies() != null ) - { + Plugin javadocPlugin = getPlugin(project, pluginId); + if (javadocPlugin != null && javadocPlugin.getDependencies() != null) { List dependencies = javadocPlugin.getDependencies(); - for ( Dependency dependency : dependencies ) - { + for (Dependency dependency : dependencies) { ResourcesArtifact resourceArtifact = new ResourcesArtifact(); - resourceArtifact.setGroupId( dependency.getGroupId() ); - resourceArtifact.setArtifactId( dependency.getArtifactId() ); - resourceArtifact.setVersion( dependency.getVersion() ); - resourceArtifact.setClassifier( dependency.getClassifier() ); + resourceArtifact.setGroupId(dependency.getGroupId()); + resourceArtifact.setArtifactId(dependency.getArtifactId()); + resourceArtifact.setVersion(dependency.getVersion()); + resourceArtifact.setClassifier(dependency.getClassifier()); Artifact artifact = null; - try - { - artifact = createAndResolveArtifact( resourceArtifact ); - } - catch ( Exception e ) - { - logError( "Unable to retrieve the dependency: " + dependency + ". Ignored.", e ); + try { + artifact = createAndResolveArtifact(resourceArtifact); + } catch (Exception e) { + logError("Unable to retrieve the dependency: " + dependency + ". Ignored.", e); } - if ( artifact != null && artifact.getFile().exists() ) - { - classPath.add( artifact.getFile().getAbsolutePath() ); + if (artifact != null && artifact.getFile().exists()) { + classPath.add(artifact.getFile().getAbsolutePath()); } } - resourceURL = getResource( classPath, inputResourceName ); - if ( resourceURL != null ) - { - getLog().debug( inputResourceName + " found in javadoc plugin dependencies." ); - try - { - JavadocUtil.copyResource( resourceURL, outputFile ); + resourceURL = getResource(classPath, inputResourceName); + if (resourceURL != null) { + getLog().debug(inputResourceName + " found in javadoc plugin dependencies."); + try { + JavadocUtil.copyResource(resourceURL, outputFile); - return Optional.of( outputFile ); - } - catch ( IOException e ) - { - logError( "IOException: " + e.getMessage(), e ); + return Optional.of(outputFile); + } catch (IOException e) { + logError("IOException: " + e.getMessage(), e); } } } - getLog().warn( "Unable to find the resource '" + inputResourceName + "'. Using default Javadoc resources." ); + getLog().warn("Unable to find the resource '" + inputResourceName + "'. Using default Javadoc resources."); return Optional.empty(); } @@ -6146,34 +5371,23 @@ private Optional getResource( File outputFile, String inputResourceName ) * @see ClassLoader#getResource(String) * @since 2.6 */ - private URL getResource( final List classPath, final String resource ) - { - List urls = new ArrayList<>( classPath.size() ); - for ( String filename : classPath ) - { - try - { - urls.add( new File( filename ).toURI().toURL() ); - } - catch ( MalformedURLException e ) - { - getLog().error( "MalformedURLException: " + e.getMessage() ); + private URL getResource(final List classPath, final String resource) { + List urls = new ArrayList<>(classPath.size()); + for (String filename : classPath) { + try { + urls.add(new File(filename).toURI().toURL()); + } catch (MalformedURLException e) { + getLog().error("MalformedURLException: " + e.getMessage()); } } - URLClassLoader javadocClassLoader = new URLClassLoader( urls.toArray( new URL[urls.size()] ), null ); - try - { - return javadocClassLoader.getResource( resource ); - } - finally - { - try - { + URLClassLoader javadocClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]), null); + try { + return javadocClassLoader.getResource(resource); + } finally { + try { javadocClassLoader.close(); - } - catch ( IOException ex ) - { + } catch (IOException ex) { // ignore } } @@ -6184,43 +5398,33 @@ private URL getResource( final List classPath, final String resource ) * * @return org.apache.maven.plugins:maven-javadoc-plugin:CURRENT_VERSION:[test-]javadoc */ - private String getFullJavadocGoal() - { + private String getFullJavadocGoal() { String javadocPluginVersion = null; String resource = "META-INF/maven/org.apache.maven.plugins/maven-javadoc-plugin/pom.properties"; - try ( InputStream resourceAsStream - = AbstractJavadocMojo.class.getClassLoader().getResourceAsStream( resource ) ) - { - if ( resourceAsStream != null ) - { + try (InputStream resourceAsStream = + AbstractJavadocMojo.class.getClassLoader().getResourceAsStream(resource)) { + if (resourceAsStream != null) { Properties properties = new Properties(); - properties.load( resourceAsStream ); - if ( StringUtils.isNotEmpty( properties.getProperty( "version" ) ) ) - { - javadocPluginVersion = properties.getProperty( "version" ); + properties.load(resourceAsStream); + if (StringUtils.isNotEmpty(properties.getProperty("version"))) { + javadocPluginVersion = properties.getProperty("version"); } } - } - catch ( IOException e ) - { + } catch (IOException e) { // nop } StringBuilder sb = new StringBuilder(); - sb.append( "org.apache.maven.plugins:maven-javadoc-plugin:" ); - if ( StringUtils.isNotEmpty( javadocPluginVersion ) ) - { - sb.append( javadocPluginVersion ).append( ":" ); + sb.append("org.apache.maven.plugins:maven-javadoc-plugin:"); + if (StringUtils.isNotEmpty(javadocPluginVersion)) { + sb.append(javadocPluginVersion).append(":"); } - if ( this instanceof TestJavadocReport ) - { - sb.append( "test-javadoc" ); - } - else - { - sb.append( "javadoc" ); + if (this instanceof TestJavadocReport) { + sb.append("test-javadoc"); + } else { + sb.append("javadoc"); } return sb.toString(); @@ -6236,95 +5440,82 @@ private String getFullJavadocGoal() * @see #reactorProjects * @since 2.6 */ - private List getModulesLinks() - throws MavenReportException - { + private List getModulesLinks() throws MavenReportException { List aggregatedProjects = reactorProjects; - if ( !detectOfflineLinks || isAggregator() || aggregatedProjects.isEmpty() ) - { + if (!detectOfflineLinks || isAggregator() || aggregatedProjects.isEmpty()) { return Collections.emptyList(); } - getLog().debug( "Trying to add links for modules..." ); + getLog().debug("Trying to add links for modules..."); Set dependencyArtifactIds = new HashSet<>(); final Set dependencyArtifacts = project.getDependencyArtifacts(); - for ( Artifact artifact : dependencyArtifacts ) - { - dependencyArtifactIds.add( artifact.getId() ); + for (Artifact artifact : dependencyArtifacts) { + dependencyArtifactIds.add(artifact.getId()); } List modulesLinks = new ArrayList<>(); - String javadocDirRelative = PathUtils.toRelative( project.getBasedir(), getOutputDirectory() ); - for ( MavenProject p : aggregatedProjects ) - { - if ( !dependencyArtifactIds.contains( p.getArtifact().getId() ) || ( p.getUrl() == null ) ) - { + String javadocDirRelative = PathUtils.toRelative(project.getBasedir(), getOutputDirectory()); + for (MavenProject p : aggregatedProjects) { + if (!dependencyArtifactIds.contains(p.getArtifact().getId()) || (p.getUrl() == null)) { continue; } - File location = new File( p.getBasedir(), javadocDirRelative ); + File location = new File(p.getBasedir(), javadocDirRelative); - if ( !location.exists() ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Javadoc directory not found: " + location ); + if (!location.exists()) { + if (getLog().isDebugEnabled()) { + getLog().debug("Javadoc directory not found: " + location); } String javadocGoal = getFullJavadocGoal(); - getLog().info( - "The goal '" + javadocGoal + "' has not been previously called for the module: '" + p.getId() - + "'. Trying to invoke it..." ); + getLog().info("The goal '" + javadocGoal + "' has not been previously called for the module: '" + + p.getId() + "'. Trying to invoke it..."); - File invokerDir = new File( project.getBuild().getDirectory(), "invoker" ); + File invokerDir = new File(project.getBuild().getDirectory(), "invoker"); invokerDir.mkdirs(); - File invokerLogFile = FileUtils.createTempFile( "maven-javadoc-plugin", ".txt", invokerDir ); - try - { - JavadocUtil.invokeMaven( getLog(), new File( localRepository.getBasedir() ), p.getFile(), - Collections.singletonList( javadocGoal ), null, invokerLogFile, - session.getRequest().getGlobalSettingsFile() ); - } - catch ( MavenInvocationException e ) - { - logError( "MavenInvocationException: " + e.getMessage(), e ); - - String invokerLogContent = JavadocUtil.readFile( invokerLogFile, null /* platform encoding */ ); + File invokerLogFile = FileUtils.createTempFile("maven-javadoc-plugin", ".txt", invokerDir); + try { + JavadocUtil.invokeMaven( + getLog(), + new File(localRepository.getBasedir()), + p.getFile(), + Collections.singletonList(javadocGoal), + null, + invokerLogFile, + session.getRequest().getGlobalSettingsFile()); + } catch (MavenInvocationException e) { + logError("MavenInvocationException: " + e.getMessage(), e); + + String invokerLogContent = JavadocUtil.readFile(invokerLogFile, null /* platform encoding */); // TODO: Why are we only interested in cases where the JVM won't start? // [MJAVADOC-275][jdcasey] I changed the logic here to only throw an error WHEN // the JVM won't start (opposite of what it was). - if ( invokerLogContent != null && invokerLogContent.contains( JavadocUtil.ERROR_INIT_VM ) ) - { - throw new MavenReportException( e.getMessage(), e ); + if (invokerLogContent != null && invokerLogContent.contains(JavadocUtil.ERROR_INIT_VM)) { + throw new MavenReportException(e.getMessage(), e); } - } - finally - { + } finally { // just create the directory to prevent repeated invocations.. - if ( !location.exists() ) - { - getLog().warn( "Creating fake javadoc directory to prevent repeated invocations: " + location ); + if (!location.exists()) { + getLog().warn("Creating fake javadoc directory to prevent repeated invocations: " + location); location.mkdirs(); } } } - if ( location.exists() ) - { - String url = getJavadocLink( p ); + if (location.exists()) { + String url = getJavadocLink(p); OfflineLink ol = new OfflineLink(); - ol.setUrl( url ); - ol.setLocation( location.getAbsolutePath() ); + ol.setUrl(url); + ol.setLocation(location.getAbsolutePath()); - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Added Javadoc offline link: " + url + " for the module: " + p.getId() ); + if (getLog().isDebugEnabled()) { + getLog().debug("Added Javadoc offline link: " + url + " for the module: " + p.getId()); } - modulesLinks.add( ol ); + modulesLinks.add(ol); } } @@ -6340,75 +5531,62 @@ private List getModulesLinks() * @see #isValidJavadocLink(String, boolean) * @since 2.6 */ - private List getDependenciesLinks() - { - if ( !detectLinks ) - { + private List getDependenciesLinks() { + if (!detectLinks) { return Collections.emptyList(); } - getLog().debug( "Trying to add links for dependencies..." ); + getLog().debug("Trying to add links for dependencies..."); List dependenciesLinks = new ArrayList<>(); final Set dependencies = project.getDependencyArtifacts(); - for ( Artifact artifact : dependencies ) - { - if ( artifact.getFile() == null || !artifact.getFile().exists() ) - { + for (Artifact artifact : dependencies) { + if (artifact.getFile() == null || !artifact.getFile().exists()) { continue; } - Optional depLink = - this.dependencyLinks.stream().filter( d -> matches( d, artifact ) ).findAny(); + Optional depLink = this.dependencyLinks.stream() + .filter(d -> matches(d, artifact)) + .findAny(); final String url; final boolean detected; - if ( depLink.isPresent() ) - { + if (depLink.isPresent()) { url = depLink.get().getUrl(); detected = false; - } - else - { - try - { - MavenProject artifactProject = - mavenProjectBuilder.build( artifact, getProjectBuildingRequest( project ) ).getProject(); + } else { + try { + MavenProject artifactProject = mavenProjectBuilder + .build(artifact, getProjectBuildingRequest(project)) + .getProject(); - url = getJavadocLink( artifactProject ); + url = getJavadocLink(artifactProject); detected = true; - } - catch ( ProjectBuildingException e ) - { - logError( "ProjectBuildingException for " + artifact.toString() + ": " + e.getMessage(), e ); + } catch (ProjectBuildingException e) { + logError("ProjectBuildingException for " + artifact.toString() + ": " + e.getMessage(), e); continue; } } - if ( url != null && isValidJavadocLink( url, detected ) ) - { - getLog().debug( "Added Javadoc link: " + url + " for " + artifact.getId() ); + if (url != null && isValidJavadocLink(url, detected)) { + getLog().debug("Added Javadoc link: " + url + " for " + artifact.getId()); - dependenciesLinks.add( url ); + dependenciesLinks.add(url); } } return dependenciesLinks; } - private boolean matches( DependencyLink d, Artifact artifact ) - { - if ( d.getGroupId() != null && !d.getGroupId().equals( artifact.getGroupId() ) ) - { + private boolean matches(DependencyLink d, Artifact artifact) { + if (d.getGroupId() != null && !d.getGroupId().equals(artifact.getGroupId())) { return false; } - if ( d.getArtifactId() != null && !d.getArtifactId().equals( artifact.getArtifactId() ) ) - { + if (d.getArtifactId() != null && !d.getArtifactId().equals(artifact.getArtifactId())) { return false; } - if ( d.getClassifier() != null && !d.getClassifier().equals( artifact.getClassifier() ) ) - { + if (d.getClassifier() != null && !d.getClassifier().equals(artifact.getClassifier())) { return false; } return true; @@ -6423,129 +5601,93 @@ private boolean matches( DependencyLink d, Artifact artifact ) * @see source parameter * @since 2.6 */ - protected final OfflineLink getDefaultJavadocApiLink() - { - if ( !detectJavaApiLink ) - { + protected final OfflineLink getDefaultJavadocApiLink() { + if (!detectJavaApiLink) { return null; } final JavaVersion javaApiversion; - if ( release != null ) - { - javaApiversion = JavaVersion.parse( release ); - } - else if ( source != null && !source.isEmpty() ) - { - javaApiversion = JavaVersion.parse( source ); - } - else - { + if (release != null) { + javaApiversion = JavaVersion.parse(release); + } else if (source != null && !source.isEmpty()) { + javaApiversion = JavaVersion.parse(source); + } else { final String pluginId = "org.apache.maven.plugins:maven-compiler-plugin"; - String sourceConfigured = getPluginParameter( project, pluginId, "source" ); - if ( sourceConfigured != null ) - { - javaApiversion = JavaVersion.parse( sourceConfigured ); - } - else - { - getLog().debug( "No maven-compiler-plugin defined in ${build.plugins} or in " - + "${project.build.pluginManagement} for the " + project.getId() - + ". Added Javadoc API link according the javadoc executable version i.e.: " - + javadocRuntimeVersion ); + String sourceConfigured = getPluginParameter(project, pluginId, "source"); + if (sourceConfigured != null) { + javaApiversion = JavaVersion.parse(sourceConfigured); + } else { + getLog().debug("No maven-compiler-plugin defined in ${build.plugins} or in " + + "${project.build.pluginManagement} for the " + project.getId() + + ". Added Javadoc API link according the javadoc executable version i.e.: " + + javadocRuntimeVersion); javaApiversion = javadocRuntimeVersion; } } final String javaApiKey; - if ( javaApiversion.asMajor().isAtLeast( "9" ) ) - { + if (javaApiversion.asMajor().isAtLeast("9")) { javaApiKey = "api_" + javaApiversion.asMajor(); - } - else - { - javaApiKey = "api_1." + javaApiversion.asMajor().toString().charAt( 0 ); + } else { + javaApiKey = "api_1." + javaApiversion.asMajor().toString().charAt(0); } final String javaApiLink; - if ( javaApiLinks != null && javaApiLinks.containsKey( javaApiKey ) ) - { - javaApiLink = javaApiLinks.getProperty( javaApiKey ); - } - else if ( javaApiversion.isAtLeast( "16" ) ) - { + if (javaApiLinks != null && javaApiLinks.containsKey(javaApiKey)) { + javaApiLink = javaApiLinks.getProperty(javaApiKey); + } else if (javaApiversion.isAtLeast("16")) { javaApiLink = null; // JDK-8216497 - } - else if ( javaApiversion.isAtLeast( "11" ) ) - { - javaApiLink = - String.format( "https://docs.oracle.com/en/java/javase/%s/docs/api/", javaApiversion.getValue( 1 ) ); - } - else if ( javaApiversion.asMajor().isAtLeast( "6" ) ) - { + } else if (javaApiversion.isAtLeast("11")) { javaApiLink = - String.format( "https://docs.oracle.com/javase/%s/docs/api/", javaApiversion.asMajor().getValue( 1 ) ); - } - else if ( javaApiversion.isAtLeast( "1.5" ) ) - { + String.format("https://docs.oracle.com/en/java/javase/%s/docs/api/", javaApiversion.getValue(1)); + } else if (javaApiversion.asMajor().isAtLeast("6")) { + javaApiLink = String.format( + "https://docs.oracle.com/javase/%s/docs/api/", + javaApiversion.asMajor().getValue(1)); + } else if (javaApiversion.isAtLeast("1.5")) { javaApiLink = "https://docs.oracle.com/javase/1.5.0/docs/api/"; - } - else - { + } else { javaApiLink = null; } - if ( getLog().isDebugEnabled() ) - { - if ( javaApiLink != null ) - { - getLog().debug( "Found Java API link: " + javaApiLink ); - } - else - { - getLog().debug( "No Java API link found." ); + if (getLog().isDebugEnabled()) { + if (javaApiLink != null) { + getLog().debug("Found Java API link: " + javaApiLink); + } else { + getLog().debug("No Java API link found."); } } - if ( javaApiLink == null ) - { + if (javaApiLink == null) { return null; } final Path javaApiListFile; final String resourceName; - if ( javaApiversion.isAtLeast( "10" ) ) - { - javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve( "element-list" ); - resourceName = "java-api-element-list-" + javaApiversion.toString().substring( 0, 2 ); - } - else if ( javaApiversion.asMajor().isAtLeast( "9" ) ) - { - javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve( "package-list" ); + if (javaApiversion.isAtLeast("10")) { + javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve("element-list"); + resourceName = "java-api-element-list-" + javaApiversion.toString().substring(0, 2); + } else if (javaApiversion.asMajor().isAtLeast("9")) { + javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve("package-list"); resourceName = "java-api-package-list-9"; - } - else - { - javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve( "package-list" ); - resourceName = "java-api-package-list-1." + javaApiversion.asMajor().toString().charAt( 0 ); + } else { + javaApiListFile = getJavadocOptionsFile().getParentFile().toPath().resolve("package-list"); + resourceName = "java-api-package-list-1." + + javaApiversion.asMajor().toString().charAt(0); } OfflineLink link = new OfflineLink(); - link.setLocation( javaApiListFile.getParent().toAbsolutePath().toString() ); - link.setUrl( javaApiLink ); + link.setLocation(javaApiListFile.getParent().toAbsolutePath().toString()); + link.setUrl(javaApiLink); - InputStream in = this.getClass().getResourceAsStream( resourceName ); - if ( in != null ) - { - try ( InputStream closableIS = in ) - { + InputStream in = this.getClass().getResourceAsStream(resourceName); + if (in != null) { + try (InputStream closableIS = in) { // TODO only copy when changed - Files.copy( closableIS, javaApiListFile, StandardCopyOption.REPLACE_EXISTING ); - } - catch ( IOException ioe ) - { - logError( "Can't get " + resourceName + ": " + ioe.getMessage(), ioe ); + Files.copy(closableIS, javaApiListFile, StandardCopyOption.REPLACE_EXISTING); + } catch (IOException ioe) { + logError("Can't get " + resourceName + ": " + ioe.getMessage(), ioe); return null; } } @@ -6560,24 +5702,20 @@ else if ( javaApiversion.asMajor().isAtLeast( "9" ) ) * @param links Links to follow. * @return Last redirect location of all the links. */ - private Set followLinks( Set links ) - { - Set redirectLinks = new LinkedHashSet<>( links.size() ); - for ( String link : links ) - { - try - { - redirectLinks.add( JavadocUtil.getRedirectUrl( new URI( link ).toURL(), settings ).toString() ); - } - catch ( Exception e ) - { + private Set followLinks(Set links) { + Set redirectLinks = new LinkedHashSet<>(links.size()); + for (String link : links) { + try { + redirectLinks.add(JavadocUtil.getRedirectUrl(new URI(link).toURL(), settings) + .toString()); + } catch (Exception e) { // only print in debug, it should have been logged already in warn/error because link isn't valid - getLog().debug( "Could not follow " + link + ". Reason: " + e.getMessage() ); + getLog().debug("Could not follow " + link + ". Reason: " + e.getMessage()); // Even when link produces error it should be kept in the set because the error might be caused by // incomplete redirect configuration on the server side. // This partially restores the previous behaviour before fix for MJAVADOC-427 - redirectLinks.add( link ); + redirectLinks.add(link); } } return redirectLinks; @@ -6592,102 +5730,71 @@ private Set followLinks( Set links ) * package-list spec * @since 2.6 */ - protected boolean isValidJavadocLink( String link, boolean detecting ) - { - try - { + protected boolean isValidJavadocLink(String link, boolean detecting) { + try { final URI packageListUri; final URI elementListUri; - if ( link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "http:" ) || link.trim().toLowerCase( - Locale.ENGLISH ).startsWith( "https:" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( - "ftp:" ) || link.trim().toLowerCase( Locale.ENGLISH ).startsWith( "file:" ) ) - { - packageListUri = new URI( link + '/' + PACKAGE_LIST ); - elementListUri = new URI( link + '/' + ELEMENT_LIST ); - } - else - { + if (link.trim().toLowerCase(Locale.ENGLISH).startsWith("http:") + || link.trim().toLowerCase(Locale.ENGLISH).startsWith("https:") + || link.trim().toLowerCase(Locale.ENGLISH).startsWith("ftp:") + || link.trim().toLowerCase(Locale.ENGLISH).startsWith("file:")) { + packageListUri = new URI(link + '/' + PACKAGE_LIST); + elementListUri = new URI(link + '/' + ELEMENT_LIST); + } else { // links can be relative paths or files - File dir = new File( link ); - if ( !dir.isAbsolute() ) - { - dir = new File( getOutputDirectory(), link ); + File dir = new File(link); + if (!dir.isAbsolute()) { + dir = new File(getOutputDirectory(), link); } - if ( !dir.isDirectory() ) - { - if ( detecting ) - { - getLog().warn( "The given File link: " + dir + " is not a dir." ); - } - else - { - getLog().error( "The given File link: " + dir + " is not a dir." ); + if (!dir.isDirectory()) { + if (detecting) { + getLog().warn("The given File link: " + dir + " is not a dir."); + } else { + getLog().error("The given File link: " + dir + " is not a dir."); } } - packageListUri = new File( dir, PACKAGE_LIST ).toURI(); - elementListUri = new File( dir, ELEMENT_LIST ).toURI(); + packageListUri = new File(dir, PACKAGE_LIST).toURI(); + elementListUri = new File(dir, ELEMENT_LIST).toURI(); } - - try - { - if ( JavadocUtil.isValidElementList( elementListUri.toURL(), settings, validateLinks ) ) - { + try { + if (JavadocUtil.isValidElementList(elementListUri.toURL(), settings, validateLinks)) { return true; } - } - catch ( IOException e ) - { + } catch (IOException e) { } - if ( JavadocUtil.isValidPackageList( packageListUri.toURL(), settings, validateLinks ) ) - { + if (JavadocUtil.isValidPackageList(packageListUri.toURL(), settings, validateLinks)) { return true; } - if ( getLog().isErrorEnabled() ) - { - if ( detecting ) - { - getLog().warn( "Invalid links: " - + link + " with /" + PACKAGE_LIST + " or / " + ELEMENT_LIST + ". Ignored it." ); - } - else - { - getLog().error( "Invalid links: " - + link + " with /" + PACKAGE_LIST + " or / " + ELEMENT_LIST + ". Ignored it." ); + if (getLog().isErrorEnabled()) { + if (detecting) { + getLog().warn("Invalid links: " + link + " with /" + PACKAGE_LIST + " or / " + ELEMENT_LIST + + ". Ignored it."); + } else { + getLog().error("Invalid links: " + link + " with /" + PACKAGE_LIST + " or / " + ELEMENT_LIST + + ". Ignored it."); } } return false; - } - catch ( URISyntaxException e ) - { - if ( getLog().isErrorEnabled() ) - { - if ( detecting ) - { - getLog().warn( "Malformed link: " + e.getInput() + ". Ignored it." ); - } - else - { - getLog().error( "Malformed link: " + e.getInput() + ". Ignored it." ); + } catch (URISyntaxException e) { + if (getLog().isErrorEnabled()) { + if (detecting) { + getLog().warn("Malformed link: " + e.getInput() + ". Ignored it."); + } else { + getLog().error("Malformed link: " + e.getInput() + ". Ignored it."); } } return false; - } - catch ( IOException e ) - { - if ( getLog().isErrorEnabled() ) - { - if ( detecting ) - { - getLog().warn( "Error fetching link: " + link + ". Ignored it." ); - } - else - { - getLog().error( "Error fetching link: " + link + ". Ignored it." ); + } catch (IOException e) { + if (getLog().isErrorEnabled()) { + if (detecting) { + getLog().warn("Error fetching link: " + link + ". Ignored it."); + } else { + getLog().error("Error fetching link: " + link + ". Ignored it."); } } return false; @@ -6702,23 +5809,18 @@ protected boolean isValidJavadocLink( String link, boolean detecting ) * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6 */ - private void writeDebugJavadocScript( String cmdLine, File javadocOutputDirectory ) - { - File commandLineFile = new File( javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME ); + private void writeDebugJavadocScript(String cmdLine, File javadocOutputDirectory) { + File commandLineFile = new File(javadocOutputDirectory, DEBUG_JAVADOC_SCRIPT_NAME); commandLineFile.getParentFile().mkdirs(); - try - { - FileUtils.fileWrite( commandLineFile.getAbsolutePath(), null /* platform encoding */, cmdLine ); + try { + FileUtils.fileWrite(commandLineFile.getAbsolutePath(), null /* platform encoding */, cmdLine); - if ( !SystemUtils.IS_OS_WINDOWS ) - { - Runtime.getRuntime().exec( new String[]{ "chmod", "a+x", commandLineFile.getAbsolutePath() } ); + if (!SystemUtils.IS_OS_WINDOWS) { + Runtime.getRuntime().exec(new String[] {"chmod", "a+x", commandLineFile.getAbsolutePath()}); } - } - catch ( IOException e ) - { - logError( "Unable to write '" + commandLineFile.getName() + "' debug script file", e ); + } catch (IOException e) { + logError("Unable to write '" + commandLineFile.getName() + "' debug script file", e); } } @@ -6730,13 +5832,12 @@ private void writeDebugJavadocScript( String cmdLine, File javadocOutputDirector * @see #executeJavadocCommandLine(Commandline, File) * @since 2.6.1 */ - private boolean isJavadocVMInitError( String output ) - { + private boolean isJavadocVMInitError(String output) { /* * see main.usage and main.Building_tree keys from * com.sun.tools.javadoc.resources.javadoc bundle in tools.jar */ - return !( output.contains( "Javadoc" ) || output.contains( "javadoc" ) ); + return !(output.contains("Javadoc") || output.contains("javadoc")); } // ---------------------------------------------------------------------- @@ -6749,20 +5850,17 @@ private boolean isJavadocVMInitError( String output ) * destDir is configued in the Javadoc plugin configuration (apidocs by default). * @since 2.6 */ - private static String getJavadocLink( MavenProject p ) - { - if ( p.getUrl() == null ) - { + private static String getJavadocLink(MavenProject p) { + if (p.getUrl() == null) { return null; } - String url = cleanUrl( p.getUrl() ); + String url = cleanUrl(p.getUrl()); String destDir = "apidocs"; // see JavadocReport#destDir final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; - String destDirConfigured = getPluginParameter( p, pluginId, "destDir" ); - if ( destDirConfigured != null ) - { + String destDirConfigured = getPluginParameter(p, pluginId, "destDir"); + if (destDirConfigured != null) { destDir = destDirConfigured; } @@ -6774,17 +5872,14 @@ private static String getJavadocLink( MavenProject p ) * @return the url cleaned or empty if url was null. * @since 2.6 */ - private static String cleanUrl( String url ) - { - if ( url == null ) - { + private static String cleanUrl(String url) { + if (url == null) { return ""; } url = url.trim(); - while ( url.endsWith( "/" ) ) - { - url = url.substring( 0, url.lastIndexOf( "/" ) ); + while (url.endsWith("/")) { + url = url.substring(0, url.lastIndexOf("/")); } return url; @@ -6798,19 +5893,17 @@ private static String cleanUrl( String url ) * ${project.build.pluginManagement}, or null if not defined. * @since 2.6 */ - private static Plugin getPlugin( MavenProject p, String pluginId ) - { - if ( ( p.getBuild() == null ) || ( p.getBuild().getPluginsAsMap() == null ) ) - { + private static Plugin getPlugin(MavenProject p, String pluginId) { + if ((p.getBuild() == null) || (p.getBuild().getPluginsAsMap() == null)) { return null; } - Plugin plugin = p.getBuild().getPluginsAsMap().get( pluginId ); + Plugin plugin = p.getBuild().getPluginsAsMap().get(pluginId); - if ( ( plugin == null ) && ( p.getBuild().getPluginManagement() != null ) && ( - p.getBuild().getPluginManagement().getPluginsAsMap() != null ) ) - { - plugin = p.getBuild().getPluginManagement().getPluginsAsMap().get( pluginId ); + if ((plugin == null) + && (p.getBuild().getPluginManagement() != null) + && (p.getBuild().getPluginManagement().getPluginsAsMap() != null)) { + plugin = p.getBuild().getPluginManagement().getPluginsAsMap().get(pluginId); } return plugin; @@ -6824,17 +5917,15 @@ private static Plugin getPlugin( MavenProject p, String pluginId ) * or null if not found. * @since 2.6 */ - private static String getPluginParameter( MavenProject p, String pluginId, String param ) - { -// p.getGoalConfiguration( pluginGroupId, pluginArtifactId, executionId, goalId ); - Plugin plugin = getPlugin( p, pluginId ); - if ( plugin != null ) - { + private static String getPluginParameter(MavenProject p, String pluginId, String param) { + // p.getGoalConfiguration( pluginGroupId, pluginArtifactId, executionId, goalId ); + Plugin plugin = getPlugin(p, pluginId); + if (plugin != null) { Xpp3Dom xpp3Dom = (Xpp3Dom) plugin.getConfiguration(); - if ( xpp3Dom != null && xpp3Dom.getChild( param ) != null - && StringUtils.isNotEmpty( xpp3Dom.getChild( param ).getValue() ) ) - { - return xpp3Dom.getChild( param ).getValue(); + if (xpp3Dom != null + && xpp3Dom.getChild(param) != null + && StringUtils.isNotEmpty(xpp3Dom.getChild(param).getValue())) { + return xpp3Dom.getChild(param).getValue(); } } @@ -6848,14 +5939,12 @@ private static String getPluginParameter( MavenProject p, String pluginId, Strin * @return The options {@link File} file. * @since 2.7 */ - protected final File getJavadocOptionsFile() - { - if ( javadocOptionsDir != null && !javadocOptionsDir.exists() ) - { + protected final File getJavadocOptionsFile() { + if (javadocOptionsDir != null && !javadocOptionsDir.exists()) { javadocOptionsDir.mkdirs(); } - return new File( javadocOptionsDir, "javadoc-options-" + getAttachmentClassifier() + ".xml" ); + return new File(javadocOptionsDir, "javadoc-options-" + getAttachmentClassifier() + ".xml"); } /** @@ -6867,35 +5956,31 @@ protected final File getJavadocOptionsFile() * @throws IOException {@link IOException} * @since 2.7 */ - protected final JavadocOptions buildJavadocOptions() - throws IOException - { + protected final JavadocOptions buildJavadocOptions() throws IOException { JavadocOptions options = new JavadocOptions(); - options.setBootclasspathArtifacts( toList( bootclasspathArtifacts ) ); - options.setDocfilesSubdirsUsed( docfilessubdirs ); - options.setDocletArtifacts( toList( docletArtifact, docletArtifacts ) ); - options.setExcludedDocfilesSubdirs( excludedocfilessubdir ); - options.setExcludePackageNames( toList( excludePackageNames ) ); - options.setGroups( toList( groups ) ); - options.setLinks( links ); - options.setOfflineLinks( toList( offlineLinks ) ); - options.setResourcesArtifacts( toList( resourcesArtifacts ) ); - options.setTagletArtifacts( toList( tagletArtifact, tagletArtifacts ) ); - options.setTaglets( toList( taglets ) ); - options.setTags( toList( tags ) ); - - if ( getProject() != null && getJavadocDirectory() != null ) - { + options.setBootclasspathArtifacts(toList(bootclasspathArtifacts)); + options.setDocfilesSubdirsUsed(docfilessubdirs); + options.setDocletArtifacts(toList(docletArtifact, docletArtifacts)); + options.setExcludedDocfilesSubdirs(excludedocfilessubdir); + options.setExcludePackageNames(toList(excludePackageNames)); + options.setGroups(toList(groups)); + options.setLinks(links); + options.setOfflineLinks(toList(offlineLinks)); + options.setResourcesArtifacts(toList(resourcesArtifacts)); + options.setTagletArtifacts(toList(tagletArtifact, tagletArtifacts)); + options.setTaglets(toList(taglets)); + options.setTags(toList(tags)); + + if (getProject() != null && getJavadocDirectory() != null) { options.setJavadocResourcesDirectory( - toRelative( getProject().getBasedir(), getJavadocDirectory().getAbsolutePath() ) ); + toRelative(getProject().getBasedir(), getJavadocDirectory().getAbsolutePath())); } File optionsFile = getJavadocOptionsFile(); - try ( Writer writer = WriterFactory.newXmlWriter( optionsFile ) ) - { - new JavadocOptionsXpp3Writer().write( writer, options ); + try (Writer writer = WriterFactory.newXmlWriter(optionsFile)) { + new JavadocOptionsXpp3Writer().write(writer, options); } return options; @@ -6906,8 +5991,7 @@ protected final JavadocOptions buildJavadocOptions() * javadocs. * @return The attachment classifier. */ - protected String getAttachmentClassifier() - { + protected String getAttachmentClassifier() { return JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER; } @@ -6917,15 +6001,11 @@ protected String getAttachmentClassifier() * @param message The message which should be announced. * @param t The throwable part of the message. */ - protected void logError( String message, Throwable t ) - { - if ( getLog().isDebugEnabled() ) - { - getLog().error( message, t ); - } - else - { - getLog().error( message ); + protected void logError(String message, Throwable t) { + if (getLog().isDebugEnabled()) { + getLog().error(message, t); + } else { + getLog().error(message); } } @@ -6934,86 +6014,71 @@ protected void logError( String message, Throwable t ) * @param e The exception. * @throws MojoExecutionException {@link MojoExecutionException} issue while generating report */ - protected void failOnError( String prefix, Exception e ) - throws MojoExecutionException - { - if ( failOnError ) - { - if ( e instanceof RuntimeException ) - { + protected void failOnError(String prefix, Exception e) throws MojoExecutionException { + if (failOnError) { + if (e instanceof RuntimeException) { throw (RuntimeException) e; } - throw new MojoExecutionException( prefix + ": " + e.getMessage(), e ); + throw new MojoExecutionException(prefix + ": " + e.getMessage(), e); } - getLog().error( prefix + ": " + e.getMessage(), e ); + getLog().error(prefix + ": " + e.getMessage(), e); } - /** * * @return List of projects to be part of aggregated javadoc */ - private List getAggregatedProjects() - { - if ( this.reactorProjects == null ) - { - return Collections.emptyList(); + private List getAggregatedProjects() { + if (this.reactorProjects == null) { + return Collections.emptyList(); } Map reactorProjectsMap = new HashMap<>(); - for ( MavenProject reactorProject : this.reactorProjects ) - { - if ( !isSkippedJavadoc( reactorProject ) && // - !isSkippedModule( reactorProject ) ) - { - reactorProjectsMap.put( reactorProject.getBasedir().toPath(), reactorProject ); + for (MavenProject reactorProject : this.reactorProjects) { + if (!isSkippedJavadoc(reactorProject) + && // + !isSkippedModule(reactorProject)) { + reactorProjectsMap.put(reactorProject.getBasedir().toPath(), reactorProject); } } - return new ArrayList<>( modulesForAggregatedProject( project, reactorProjectsMap ) ); + return new ArrayList<>(modulesForAggregatedProject(project, reactorProjectsMap)); } /** * * @return true if the module need to be skipped from aggregate generation */ - protected boolean isSkippedModule( MavenProject mavenProject ) - { - if ( StringUtils.isEmpty( this.skippedModules ) ) - { + protected boolean isSkippedModule(MavenProject mavenProject) { + if (StringUtils.isEmpty(this.skippedModules)) { return false; } - List modulesToSkip = Arrays.asList( StringUtils.split( this.skippedModules, ',' ) ); - return modulesToSkip.contains( mavenProject.getArtifactId() ); + List modulesToSkip = Arrays.asList(StringUtils.split(this.skippedModules, ',')); + return modulesToSkip.contains(mavenProject.getArtifactId()); } /** * * @return true if the pom configuration skip javadoc generation for the project */ - protected boolean isSkippedJavadoc( MavenProject mavenProject ) - { - String property = mavenProject.getProperties().getProperty( "maven.javadoc.skip" ); - if ( property != null ) - { - boolean skip = BooleanUtils.toBoolean( property ); - getLog().debug( "isSkippedJavadoc " + mavenProject + " " + skip ); + protected boolean isSkippedJavadoc(MavenProject mavenProject) { + String property = mavenProject.getProperties().getProperty("maven.javadoc.skip"); + if (property != null) { + boolean skip = BooleanUtils.toBoolean(property); + getLog().debug("isSkippedJavadoc " + mavenProject + " " + skip); return skip; } final String pluginId = "org.apache.maven.plugins:maven-javadoc-plugin"; - property = getPluginParameter( mavenProject, pluginId, "skip" ); - if ( property != null ) - { - boolean skip = BooleanUtils.toBoolean( property ); - getLog().debug( "isSkippedJavadoc " + mavenProject + " " + skip ); + property = getPluginParameter(mavenProject, pluginId, "skip"); + if (property != null) { + boolean skip = BooleanUtils.toBoolean(property); + getLog().debug("isSkippedJavadoc " + mavenProject + " " + skip); return skip; } - if ( mavenProject.getParent() != null ) - { - return isSkippedJavadoc( mavenProject.getParent() ); + if (mavenProject.getParent() != null) { + return isSkippedJavadoc(mavenProject.getParent()); } - getLog().debug( "isSkippedJavadoc " + mavenProject + " " + false ); + getLog().debug("isSkippedJavadoc " + mavenProject + " " + false); return false; } - } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AdditionalDependency.java b/src/main/java/org/apache/maven/plugins/javadoc/AdditionalDependency.java index 8ea467018..a20d60fb0 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AdditionalDependency.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AdditionalDependency.java @@ -1,32 +1,29 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Dependency; - -/** - * Provides syntactic sugar for using the standard {@code Dependency} - * model as a parameter to {@link AbstractJavadocMojo}'s {@code additionalDependencies}. - */ -public class AdditionalDependency - extends Dependency -{ - // no op -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.model.Dependency; + +/** + * Provides syntactic sugar for using the standard {@code Dependency} + * model as a parameter to {@link AbstractJavadocMojo}'s {@code additionalDependencies}. + */ +public class AdditionalDependency extends Dependency { + // no op +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocJar.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocJar.java index aa16c72a7..f8cad3ba9 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocJar.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocJar.java @@ -1,47 +1,46 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - *

Bundles the Javadoc documentation for main Java code in an aggregator project into a jar - * using the standard Javadoc Tool. - *

- * - *

Since version 3.1.0 an aggregated jar is created for every module of a Maven multimodule project.

- * - * @since 2.6 - */ -@Mojo( name = "aggregate-jar", defaultPhase = LifecyclePhase.PACKAGE, aggregator = true, - requiresDependencyResolution = ResolutionScope.COMPILE ) -@Execute( phase = LifecyclePhase.COMPILE ) -public class AggregatorJavadocJar - extends JavadocJar -{ - @Override - protected boolean isAggregator() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + *

Bundles the Javadoc documentation for main Java code in an aggregator project into a jar + * using the standard Javadoc Tool. + *

+ * + *

Since version 3.1.0 an aggregated jar is created for every module of a Maven multimodule project.

+ * + * @since 2.6 + */ +@Mojo( + name = "aggregate-jar", + defaultPhase = LifecyclePhase.PACKAGE, + aggregator = true, + requiresDependencyResolution = ResolutionScope.COMPILE) +@Execute(phase = LifecyclePhase.COMPILE) +public class AggregatorJavadocJar extends JavadocJar { + @Override + protected boolean isAggregator() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocNoForkReport.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocNoForkReport.java index 64867fd48..2a4be07e6 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocNoForkReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocNoForkReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -30,9 +29,6 @@ * * @since 3.1.0 */ -@Mojo( name = "aggregate-no-fork", requiresDependencyResolution = ResolutionScope.COMPILE ) -@Execute( phase = LifecyclePhase.NONE ) -public class AggregatorJavadocNoForkReport - extends AggregatorJavadocReport -{ -} +@Mojo(name = "aggregate-no-fork", requiresDependencyResolution = ResolutionScope.COMPILE) +@Execute(phase = LifecyclePhase.NONE) +public class AggregatorJavadocNoForkReport extends AggregatorJavadocReport {} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReport.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReport.java index 0d6f793c0..642c3ae18 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReport.java @@ -1,46 +1,42 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - *

Generates documentation for the Java code in an aggregator project using the standard - * Javadoc Tool.

- * - *

Since version 3.1.0 an aggregated report is created for every module of a Maven multimodule project.

- * - * @author Vincent Siveton - * @since 2.5 - */ -@Mojo( name = "aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.COMPILE ) -@Execute( phase = LifecyclePhase.COMPILE ) -public class AggregatorJavadocReport - extends JavadocReport -{ - @Override - protected boolean isAggregator() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + *

Generates documentation for the Java code in an aggregator project using the standard + * Javadoc Tool.

+ * + *

Since version 3.1.0 an aggregated report is created for every module of a Maven multimodule project.

+ * + * @author Vincent Siveton + * @since 2.5 + */ +@Mojo(name = "aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.COMPILE) +@Execute(phase = LifecyclePhase.COMPILE) +public class AggregatorJavadocReport extends JavadocReport { + @Override + protected boolean isAggregator() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocJar.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocJar.java index f79b85302..d2686cb23 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocJar.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocJar.java @@ -1,47 +1,46 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - *

Bundles the Javadoc documentation for Java Test code in an aggregator project into a jar - * using the standard Javadoc Tool. - *

- * - *

Since version 3.1.0 an aggregated jar is created for every module of a Maven multimodule project.

- * - * @since 2.6 - */ -@Mojo( name = "test-aggregate-jar", defaultPhase = LifecyclePhase.PACKAGE, aggregator = true, - requiresDependencyResolution = ResolutionScope.TEST ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class AggregatorTestJavadocJar - extends TestJavadocJar -{ - @Override - protected boolean isAggregator() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + *

Bundles the Javadoc documentation for Java Test code in an aggregator project into a jar + * using the standard Javadoc Tool. + *

+ * + *

Since version 3.1.0 an aggregated jar is created for every module of a Maven multimodule project.

+ * + * @since 2.6 + */ +@Mojo( + name = "test-aggregate-jar", + defaultPhase = LifecyclePhase.PACKAGE, + aggregator = true, + requiresDependencyResolution = ResolutionScope.TEST) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class AggregatorTestJavadocJar extends TestJavadocJar { + @Override + protected boolean isAggregator() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocNoForkReport.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocNoForkReport.java index dbd127a11..1cd104ca6 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocNoForkReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocNoForkReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -31,9 +30,6 @@ * @version $Id$ * @since 3.0.1 */ -@Mojo( name = "test-aggregate-no-fork", requiresDependencyResolution = ResolutionScope.TEST ) -@Execute( phase = LifecyclePhase.NONE ) -public class AggregatorTestJavadocNoForkReport - extends AggregatorTestJavadocReport -{ -} +@Mojo(name = "test-aggregate-no-fork", requiresDependencyResolution = ResolutionScope.TEST) +@Execute(phase = LifecyclePhase.NONE) +public class AggregatorTestJavadocNoForkReport extends AggregatorTestJavadocReport {} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocReport.java b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocReport.java index 66e08cd41..3829d46af 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/AggregatorTestJavadocReport.java @@ -1,46 +1,42 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - *

Generates documentation for the Java Test code in an aggregator project using the standard - * Javadoc Tool.

- * - *

Since version 3.1.0 an aggregated report is created for every module of a Maven multimodule project.

- * - * @author Vincent Siveton - * @since 2.5 - */ -@Mojo( name = "test-aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.TEST ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class AggregatorTestJavadocReport - extends TestJavadocReport -{ - @Override - protected boolean isAggregator() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + *

Generates documentation for the Java Test code in an aggregator project using the standard + * Javadoc Tool.

+ * + *

Since version 3.1.0 an aggregated report is created for every module of a Maven multimodule project.

+ * + * @author Vincent Siveton + * @since 2.5 + */ +@Mojo(name = "test-aggregate", aggregator = true, requiresDependencyResolution = ResolutionScope.TEST) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class AggregatorTestJavadocReport extends TestJavadocReport { + @Override + protected boolean isAggregator() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/DependencyLink.java b/src/main/java/org/apache/maven/plugins/javadoc/DependencyLink.java index dacfa040e..4e3e4c3cf 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/DependencyLink.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/DependencyLink.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,59 +16,51 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; /** * In case of autodetectLinks, this class can overwrite the url for that dependency - * + * * @since 3.3.0 */ -public class DependencyLink -{ +public class DependencyLink { private String groupId; - + private String artifactId; - + private String classifier; - + private String url; - - public String getUrl() - { + + public String getUrl() { return url; } - public void setUrl( String url ) - { + public void setUrl(String url) { this.url = url; } - - public String getGroupId() - { + + public String getGroupId() { return groupId; } - public void setGroupId( String groupId ) - { + public void setGroupId(String groupId) { this.groupId = groupId; } - public String getArtifactId() - { + public String getArtifactId() { return artifactId; } - public void setArtifactId( String artifactId ) - { + public void setArtifactId(String artifactId) { this.artifactId = artifactId; } - - public String getClassifier() - { + + public String getClassifier() { return classifier; } - - public void setClassifier( String classifier ) - { + + public void setClassifier(String classifier) { this.classifier = classifier; } } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/FixJavadocMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/FixJavadocMojo.java index 216a7a288..0deafadd9 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/FixJavadocMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/FixJavadocMojo.java @@ -1,40 +1,37 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; - -/** - * Fix Javadoc documentation and tags for the Java code for the project. - * @see Where Tags - * Can Be Used - * @author Vincent Siveton - * @since 2.6 - */ -@Mojo( name = "fix", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) -@Execute( phase = LifecyclePhase.COMPILE ) -public class FixJavadocMojo - extends AbstractFixJavadocMojo -{ - // nop -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + * Fix Javadoc documentation and tags for the Java code for the project. + * @see Where Tags + * Can Be Used + * @author Vincent Siveton + * @since 2.6 + */ +@Mojo(name = "fix", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) +@Execute(phase = LifecyclePhase.COMPILE) +public class FixJavadocMojo extends AbstractFixJavadocMojo { + // nop +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocArchiveConfiguration.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocArchiveConfiguration.java index 441f29538..5dbe8d016 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocArchiveConfiguration.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocArchiveConfiguration.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import org.apache.maven.archiver.MavenArchiveConfiguration; @@ -26,11 +25,8 @@ * * @see MJAVADOC-431 */ -public class JavadocArchiveConfiguration - extends MavenArchiveConfiguration -{ - public JavadocArchiveConfiguration() - { - setAddMavenDescriptor( false ); +public class JavadocArchiveConfiguration extends MavenArchiveConfiguration { + public JavadocArchiveConfiguration() { + setAddMavenDescriptor(false); } } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocJar.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocJar.java index 73cdf745e..e295edd24 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocJar.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocJar.java @@ -1,315 +1,278 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.archiver.MavenArchiveConfiguration; -import org.apache.maven.archiver.MavenArchiver; -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.model.Resource; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProjectHelper; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.archiver.Archiver; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.archiver.jar.JarArchiver; -import org.codehaus.plexus.archiver.jar.ManifestException; - -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Locale; - -/** - * Bundles the Javadoc documentation for main Java code in an NON aggregator project into - * a jar using the standard - * Javadoc Tool. - * - * @since 2.0 - */ -@Mojo( name = "jar", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.COMPILE, - threadSafe = true ) -public class JavadocJar - extends AbstractJavadocMojo -{ - /** - * Includes all generated Javadoc files - */ - private static final String[] DEFAULT_INCLUDES = new String[]{ "**/**" }; - - /** - * Excludes all processing files. - * - * @see AbstractJavadocMojo#DEBUG_JAVADOC_SCRIPT_NAME - * @see AbstractJavadocMojo#OPTIONS_FILE_NAME - * @see AbstractJavadocMojo#PACKAGES_FILE_NAME - * @see AbstractJavadocMojo#ARGFILE_FILE_NAME - * @see AbstractJavadocMojo#FILES_FILE_NAME - */ - private static final String[] DEFAULT_EXCLUDES = - new String[]{ DEBUG_JAVADOC_SCRIPT_NAME, OPTIONS_FILE_NAME, PACKAGES_FILE_NAME, ARGFILE_FILE_NAME, - FILES_FILE_NAME }; - - // ---------------------------------------------------------------------- - // Mojo components - // ---------------------------------------------------------------------- - - /** - * Used for attaching the artifact in the project. - */ - @Component - private MavenProjectHelper projectHelper; - - /** - * The Jar archiver. - * - * @since 2.5 - */ - @Component( role = Archiver.class, hint = "jar" ) - private JarArchiver jarArchiver; - - // ---------------------------------------------------------------------- - // Mojo Parameters - // ---------------------------------------------------------------------- - - /** - * Specifies the destination directory where javadoc saves the generated HTML files. - * @see Doclet option d. - * @deprecated - */ - @Deprecated - @Parameter( property = "destDir" ) - private File destDir; - - /** - * Specifies the directory where the generated jar file will be put. - */ - @Parameter( property = "project.build.directory" ) - private String jarOutputDirectory; - - /** - * Specifies the filename that will be used for the generated jar file. Please note that -javadoc - * or -test-javadoc will be appended to the file name. - */ - @Parameter( property = "project.build.finalName" ) - private String finalName; - - /** - * Specifies whether to attach the generated artifact to the project helper. - *
- */ - @Parameter( property = "attach", defaultValue = "true" ) - private boolean attach; - - /** - * The archive configuration to use. - * See Maven Archiver Reference. - * - * @since 2.5 - */ - @Parameter - private MavenArchiveConfiguration archive = new JavadocArchiveConfiguration(); - - /** - * Path to the default MANIFEST file to use. It will be used if - * useDefaultManifestFile is set to true. - * - * @since 2.5 - */ - @Parameter( defaultValue = "${project.build.outputDirectory}/META-INF/MANIFEST.MF", required = true, - readonly = true ) - private File defaultManifestFile; - - /** - * Set this to true to enable the use of the defaultManifestFile. - *
- * - * @since 2.5 - */ - @Parameter( defaultValue = "false" ) - private boolean useDefaultManifestFile; - - /** - * @since 2.10 - */ - @Parameter( property = "maven.javadoc.classifier", defaultValue = "javadoc", required = true ) - private String classifier; - - /** {@inheritDoc} */ - @Override - public void doExecute() - throws MojoExecutionException - { - if ( skip ) - { - getLog().info( "Skipping javadoc generation" ); - return; - } - - File innerDestDir = this.destDir; - if ( innerDestDir == null ) - { - innerDestDir = new File( getOutputDirectory() ); - } - - if ( !isAggregator() || !"pom".equalsIgnoreCase( project.getPackaging() ) ) - { - ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler(); - if ( !"java".equals( artifactHandler.getLanguage() ) ) - { - getLog().info( "Not executing Javadoc as the project is not a Java classpath-capable package" ); - return; - } - } - - try - { - executeReport( Locale.getDefault() ); - } - catch ( MavenReportException e ) - { - failOnError( "MavenReportException: Error while generating Javadoc", e ); - } - catch ( RuntimeException e ) - { - failOnError( "RuntimeException: Error while generating Javadoc", e ); - } - - if ( innerDestDir.exists() ) - { - try - { - File outputFile = generateArchive( innerDestDir, finalName + "-" + getClassifier() + ".jar" ); - - if ( !attach ) - { - getLog().info( "NOT adding javadoc to attached artifacts list." ); - } - else - { - // TODO: these introduced dependencies on the project are going to become problematic - can we export it - // through metadata instead? - projectHelper.attachArtifact( project, "javadoc", getClassifier(), outputFile ); - } - } - catch ( ArchiverException e ) - { - failOnError( "ArchiverException: Error while creating archive", e ); - } - catch ( IOException e ) - { - failOnError( "IOException: Error while creating archive", e ); - } - catch ( RuntimeException e ) - { - failOnError( "RuntimeException: Error while creating archive", e ); - } - } - } - - // ---------------------------------------------------------------------- - // Protected methods - // ---------------------------------------------------------------------- - - /** - * @return the wanted classifier, i.e. javadoc or test-javadoc - */ - protected String getClassifier() - { - return classifier; - } - - // ---------------------------------------------------------------------- - // private methods - // ---------------------------------------------------------------------- - - /** - * Method that creates the jar file - * - * @param javadocFiles the directory where the generated jar file will be put - * @param jarFileName the filename of the generated jar file - * @return a File object that contains the generated jar file - * @throws ArchiverException {@link ArchiverException} - * @throws IOException {@link IOException} - */ - private File generateArchive( File javadocFiles, String jarFileName ) - throws ArchiverException, IOException - { - File javadocJar = new File( jarOutputDirectory, jarFileName ); - - if ( javadocJar.exists() ) - { - javadocJar.delete(); - } - - MavenArchiver archiver = new MavenArchiver(); - archiver.setCreatedBy( "Maven Javadoc Plugin", "org.apache.maven.plugins", "maven-javadoc-plugin" ); - archiver.setArchiver( jarArchiver ); - archiver.setOutputFile( javadocJar ); - - // configure for Reproducible Builds based on outputTimestamp value - archiver.configureReproducibleBuild( outputTimestamp ); - - if ( !javadocFiles.exists() ) - { - getLog().warn( "JAR will be empty - no content was marked for inclusion!" ); - } - else - { - archiver.getArchiver().addDirectory( javadocFiles, DEFAULT_INCLUDES, DEFAULT_EXCLUDES ); - } - - List resources = project.getBuild().getResources(); - - for ( Resource r : resources ) - { - if ( r.getDirectory().endsWith( "maven-shared-archive-resources" ) ) - { - archiver.getArchiver().addDirectory( new File( r.getDirectory() ) ); - } - } - - if ( useDefaultManifestFile && defaultManifestFile.exists() && archive.getManifestFile() == null ) - { - getLog().info( "Adding existing MANIFEST to archive. Found under: " + defaultManifestFile.getPath() ); - archive.setManifestFile( defaultManifestFile ); - } - - try - { - archiver.createArchive( session, project, archive ); - } - catch ( ManifestException e ) - { - throw new ArchiverException( "ManifestException: " + e.getMessage(), e ); - } - catch ( DependencyResolutionRequiredException e ) - { - throw new ArchiverException( "DependencyResolutionRequiredException: " + e.getMessage(), e ); - } - - return javadocJar; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Locale; + +import org.apache.maven.archiver.MavenArchiveConfiguration; +import org.apache.maven.archiver.MavenArchiver; +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.artifact.handler.ArtifactHandler; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.project.MavenProjectHelper; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.archiver.Archiver; +import org.codehaus.plexus.archiver.ArchiverException; +import org.codehaus.plexus.archiver.jar.JarArchiver; +import org.codehaus.plexus.archiver.jar.ManifestException; + +/** + * Bundles the Javadoc documentation for main Java code in an NON aggregator project into + * a jar using the standard + * Javadoc Tool. + * + * @since 2.0 + */ +@Mojo( + name = "jar", + defaultPhase = LifecyclePhase.PACKAGE, + requiresDependencyResolution = ResolutionScope.COMPILE, + threadSafe = true) +public class JavadocJar extends AbstractJavadocMojo { + /** + * Includes all generated Javadoc files + */ + private static final String[] DEFAULT_INCLUDES = new String[] {"**/**"}; + + /** + * Excludes all processing files. + * + * @see AbstractJavadocMojo#DEBUG_JAVADOC_SCRIPT_NAME + * @see AbstractJavadocMojo#OPTIONS_FILE_NAME + * @see AbstractJavadocMojo#PACKAGES_FILE_NAME + * @see AbstractJavadocMojo#ARGFILE_FILE_NAME + * @see AbstractJavadocMojo#FILES_FILE_NAME + */ + private static final String[] DEFAULT_EXCLUDES = new String[] { + DEBUG_JAVADOC_SCRIPT_NAME, OPTIONS_FILE_NAME, PACKAGES_FILE_NAME, ARGFILE_FILE_NAME, FILES_FILE_NAME + }; + + // ---------------------------------------------------------------------- + // Mojo components + // ---------------------------------------------------------------------- + + /** + * Used for attaching the artifact in the project. + */ + @Component + private MavenProjectHelper projectHelper; + + /** + * The Jar archiver. + * + * @since 2.5 + */ + @Component(role = Archiver.class, hint = "jar") + private JarArchiver jarArchiver; + + // ---------------------------------------------------------------------- + // Mojo Parameters + // ---------------------------------------------------------------------- + + /** + * Specifies the destination directory where javadoc saves the generated HTML files. + * @see Doclet option d. + * @deprecated + */ + @Deprecated + @Parameter(property = "destDir") + private File destDir; + + /** + * Specifies the directory where the generated jar file will be put. + */ + @Parameter(property = "project.build.directory") + private String jarOutputDirectory; + + /** + * Specifies the filename that will be used for the generated jar file. Please note that -javadoc + * or -test-javadoc will be appended to the file name. + */ + @Parameter(property = "project.build.finalName") + private String finalName; + + /** + * Specifies whether to attach the generated artifact to the project helper. + *
+ */ + @Parameter(property = "attach", defaultValue = "true") + private boolean attach; + + /** + * The archive configuration to use. + * See Maven Archiver Reference. + * + * @since 2.5 + */ + @Parameter + private MavenArchiveConfiguration archive = new JavadocArchiveConfiguration(); + + /** + * Path to the default MANIFEST file to use. It will be used if + * useDefaultManifestFile is set to true. + * + * @since 2.5 + */ + @Parameter(defaultValue = "${project.build.outputDirectory}/META-INF/MANIFEST.MF", required = true, readonly = true) + private File defaultManifestFile; + + /** + * Set this to true to enable the use of the defaultManifestFile. + *
+ * + * @since 2.5 + */ + @Parameter(defaultValue = "false") + private boolean useDefaultManifestFile; + + /** + * @since 2.10 + */ + @Parameter(property = "maven.javadoc.classifier", defaultValue = "javadoc", required = true) + private String classifier; + + /** {@inheritDoc} */ + @Override + public void doExecute() throws MojoExecutionException { + if (skip) { + getLog().info("Skipping javadoc generation"); + return; + } + + File innerDestDir = this.destDir; + if (innerDestDir == null) { + innerDestDir = new File(getOutputDirectory()); + } + + if (!isAggregator() || !"pom".equalsIgnoreCase(project.getPackaging())) { + ArtifactHandler artifactHandler = project.getArtifact().getArtifactHandler(); + if (!"java".equals(artifactHandler.getLanguage())) { + getLog().info("Not executing Javadoc as the project is not a Java classpath-capable package"); + return; + } + } + + try { + executeReport(Locale.getDefault()); + } catch (MavenReportException e) { + failOnError("MavenReportException: Error while generating Javadoc", e); + } catch (RuntimeException e) { + failOnError("RuntimeException: Error while generating Javadoc", e); + } + + if (innerDestDir.exists()) { + try { + File outputFile = generateArchive(innerDestDir, finalName + "-" + getClassifier() + ".jar"); + + if (!attach) { + getLog().info("NOT adding javadoc to attached artifacts list."); + } else { + // TODO: these introduced dependencies on the project are going to become problematic - can we + // export it + // through metadata instead? + projectHelper.attachArtifact(project, "javadoc", getClassifier(), outputFile); + } + } catch (ArchiverException e) { + failOnError("ArchiverException: Error while creating archive", e); + } catch (IOException e) { + failOnError("IOException: Error while creating archive", e); + } catch (RuntimeException e) { + failOnError("RuntimeException: Error while creating archive", e); + } + } + } + + // ---------------------------------------------------------------------- + // Protected methods + // ---------------------------------------------------------------------- + + /** + * @return the wanted classifier, i.e. javadoc or test-javadoc + */ + protected String getClassifier() { + return classifier; + } + + // ---------------------------------------------------------------------- + // private methods + // ---------------------------------------------------------------------- + + /** + * Method that creates the jar file + * + * @param javadocFiles the directory where the generated jar file will be put + * @param jarFileName the filename of the generated jar file + * @return a File object that contains the generated jar file + * @throws ArchiverException {@link ArchiverException} + * @throws IOException {@link IOException} + */ + private File generateArchive(File javadocFiles, String jarFileName) throws ArchiverException, IOException { + File javadocJar = new File(jarOutputDirectory, jarFileName); + + if (javadocJar.exists()) { + javadocJar.delete(); + } + + MavenArchiver archiver = new MavenArchiver(); + archiver.setCreatedBy("Maven Javadoc Plugin", "org.apache.maven.plugins", "maven-javadoc-plugin"); + archiver.setArchiver(jarArchiver); + archiver.setOutputFile(javadocJar); + + // configure for Reproducible Builds based on outputTimestamp value + archiver.configureReproducibleBuild(outputTimestamp); + + if (!javadocFiles.exists()) { + getLog().warn("JAR will be empty - no content was marked for inclusion!"); + } else { + archiver.getArchiver().addDirectory(javadocFiles, DEFAULT_INCLUDES, DEFAULT_EXCLUDES); + } + + List resources = project.getBuild().getResources(); + + for (Resource r : resources) { + if (r.getDirectory().endsWith("maven-shared-archive-resources")) { + archiver.getArchiver().addDirectory(new File(r.getDirectory())); + } + } + + if (useDefaultManifestFile && defaultManifestFile.exists() && archive.getManifestFile() == null) { + getLog().info("Adding existing MANIFEST to archive. Found under: " + defaultManifestFile.getPath()); + archive.setManifestFile(defaultManifestFile); + } + + try { + archiver.createArchive(session, project, archive); + } catch (ManifestException e) { + throw new ArchiverException("ManifestException: " + e.getMessage(), e); + } catch (DependencyResolutionRequiredException e) { + throw new ArchiverException("DependencyResolutionRequiredException: " + e.getMessage(), e); + } + + return javadocJar; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocModule.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocModule.java index 85cfc433a..8c477941b 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocModule.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocModule.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import java.io.File; import java.nio.file.Path; @@ -27,12 +26,11 @@ import org.codehaus.plexus.languages.java.jpms.ModuleNameSource; /** - * Represents a unit of Javadoc referring to the binary and java source paths - * + * Represents a unit of Javadoc referring to the binary and java source paths + * * @since 3.3.0 */ -public class JavadocModule -{ +public class JavadocModule { private final String ga; private final File artifactFile; @@ -43,14 +41,16 @@ public class JavadocModule private final ModuleNameSource moduleNameSource; - public JavadocModule( String ga, File artifactFile, Collection sourcePaths ) - { - this( ga, artifactFile, sourcePaths, null, null ); + public JavadocModule(String ga, File artifactFile, Collection sourcePaths) { + this(ga, artifactFile, sourcePaths, null, null); } - public JavadocModule( String ga, File artifactFile, Collection sourcePaths, - JavaModuleDescriptor moduleDescriptor, ModuleNameSource moduleNameSource ) - { + public JavadocModule( + String ga, + File artifactFile, + Collection sourcePaths, + JavaModuleDescriptor moduleDescriptor, + ModuleNameSource moduleNameSource) { this.ga = ga; this.artifactFile = artifactFile; this.sourcePaths = sourcePaths; @@ -58,28 +58,23 @@ public JavadocModule( String ga, File artifactFile, Collection sourcePaths this.moduleNameSource = moduleNameSource; } - public String getGa() - { + public String getGa() { return ga; } - public Collection getSourcePaths() - { + public Collection getSourcePaths() { return sourcePaths; } - public File getArtifactFile() - { + public File getArtifactFile() { return artifactFile; } - public JavaModuleDescriptor getModuleDescriptor() - { + public JavaModuleDescriptor getModuleDescriptor() { return moduleDescriptor; } - public ModuleNameSource getModuleNameSource() - { + public ModuleNameSource getModuleNameSource() { return moduleNameSource; } } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocNoForkReport.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocNoForkReport.java index a796bd632..4410e12f2 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocNoForkReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocNoForkReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -34,9 +33,6 @@ * @see Javadoc Tool * @see Javadoc Options */ -@Mojo( name = "javadoc-no-fork", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) -@Execute( phase = LifecyclePhase.NONE ) -public class JavadocNoForkReport - extends JavadocReport -{ -} +@Mojo(name = "javadoc-no-fork", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) +@Execute(phase = LifecyclePhase.NONE) +public class JavadocNoForkReport extends JavadocReport {} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocReport.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocReport.java index ebdfccd54..14e138ecf 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocReport.java @@ -1,365 +1,326 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.nio.file.Path; -import java.util.Collection; -import java.util.Locale; -import java.util.Map; -import java.util.ResourceBundle; -import java.util.stream.Collectors; - -import org.apache.maven.doxia.sink.Sink; -import org.apache.maven.doxia.sink.SinkFactory; -import org.apache.maven.doxia.siterenderer.RenderingContext; -import org.apache.maven.doxia.siterenderer.sink.SiteRendererSink; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.reporting.MavenMultiPageReport; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.util.StringUtils; - -/** - * Generates documentation for the Java code in an NON aggregator project using the standard - * Javadoc Tool. - * - * @author Emmanuel Venisse - * @author Vincent Siveton - * @since 2.0 - * @see Javadoc Tool - */ -@Mojo( name = "javadoc", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) -@Execute( phase = LifecyclePhase.GENERATE_SOURCES ) -public class JavadocReport - extends AbstractJavadocMojo - implements MavenMultiPageReport -{ - // ---------------------------------------------------------------------- - // Report Mojo Parameters - // ---------------------------------------------------------------------- - - /** - * Specifies the destination directory where javadoc saves the generated HTML files. - */ - @Parameter( property = "reportOutputDirectory", defaultValue = "${project.reporting.outputDirectory}/apidocs", - required = true ) - private File reportOutputDirectory; - - /** - * The name of the destination directory. - *
- * - * @since 2.1 - */ - @Parameter( property = "destDir", defaultValue = "apidocs" ) - private String destDir; - - /** - * The name of the Javadoc report to be displayed in the Maven Generated Reports page - * (i.e. project-reports.html). - * - * @since 2.1 - */ - @Parameter( property = "name" ) - private String name; - - /** - * The description of the Javadoc report to be displayed in the Maven Generated Reports page - * (i.e. project-reports.html). - * - * @since 2.1 - */ - @Parameter( property = "description" ) - private String description; - - // ---------------------------------------------------------------------- - // Report public methods - // ---------------------------------------------------------------------- - - /** {@inheritDoc} */ - @Override - public String getName( Locale locale ) - { - if ( StringUtils.isEmpty( name ) ) - { - return getBundle( locale ).getString( "report.javadoc.name" ); - } - - return name; - } - - /** {@inheritDoc} */ - @Override - public String getDescription( Locale locale ) - { - if ( StringUtils.isEmpty( description ) ) - { - return getBundle( locale ).getString( "report.javadoc.description" ); - } - - return description; - } - - /** {@inheritDoc} */ - @Override - public void generate( org.codehaus.doxia.sink.Sink sink, Locale locale ) - throws MavenReportException - { - generate( sink, null, locale ); - } - - public void generate( Sink sink, Locale locale ) - throws MavenReportException - { - generate( sink, null, locale ); - } - - /** {@inheritDoc} */ - @Override - public void generate( Sink sink, SinkFactory sinkFactory, Locale locale ) - throws MavenReportException - { - outputDirectory = getReportOutputDirectory(); - - try - { - executeReport( locale ); - } - catch ( MavenReportException | RuntimeException e ) - { - if ( failOnError ) - { - throw e; - } - getLog().error( "Error while creating javadoc report: " + e.getMessage(), e ); - } - } - - /** {@inheritDoc} */ - @Override - public String getOutputName() - { - return destDir + "/index"; - } - - /** {@inheritDoc} */ - @Override - public boolean isExternalReport() - { - return true; - } - - /** - * {@inheritDoc} - * - *
- * The logic is the following: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Can-generate-report Matrix
isAggregator hasSourceFiles isRootProject Generate Report
TrueTrueTrueTrue
TrueTrueFalseFalse
TrueFalseTrueFalse
TrueFalseFalseFalse
FalseTrueTrueTrue
FalseTrueFalseTrue
FalseFalseTrueFalse
FalseFalseFalseFalse
- */ - @Override - public boolean canGenerateReport() - { - boolean canGenerate = false; - - if ( this.isAggregator() || !"pom".equals( this.project.getPackaging() ) ) - { - Collection sourcePaths; - Map> files; - try - { - sourcePaths = getSourcePaths().stream() - .flatMap( e -> e.getSourcePaths().stream() ) - .collect( Collectors.toList() ); - files = getFiles( sourcePaths ); - } - catch ( MavenReportException e ) - { - getLog().error( e.getMessage(), e ); - return false; - } - - canGenerate = canGenerateReport( files ); - } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( " canGenerateReport = " + canGenerate + " for project " + this.project ); - } - return canGenerate; - } - - /** {@inheritDoc} */ - @Override - public String getCategoryName() - { - return CATEGORY_PROJECT_REPORTS; - } - - /** {@inheritDoc} */ - @Override - public File getReportOutputDirectory() - { - if ( reportOutputDirectory == null ) - { - return outputDirectory; - } - - return reportOutputDirectory; - } - - /** - * Method to set the directory where the generated reports will be put - * - * @param reportOutputDirectory the directory file to be set - */ - @Override - public void setReportOutputDirectory( File reportOutputDirectory ) - { - updateReportOutputDirectory( reportOutputDirectory, destDir ); - } - - /** - * @param theDestDir The destination directory. - */ - public void setDestDir( String theDestDir ) - { - this.destDir = theDestDir; - updateReportOutputDirectory( reportOutputDirectory, theDestDir ); - } - - private void updateReportOutputDirectory( File reportOutputDirectory, String destDir ) - { - if ( reportOutputDirectory != null && destDir != null - && !reportOutputDirectory.getAbsolutePath().endsWith( destDir ) ) - { - this.reportOutputDirectory = new File( reportOutputDirectory, destDir ); - } - else - { - this.reportOutputDirectory = reportOutputDirectory; - } - } - - /** {@inheritDoc} */ - @Override - public void doExecute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "Skipping javadoc generation" ); - return; - } - - File outputDirectory = new File( getOutputDirectory() ); - - String filename = getOutputName() + ".html"; - - Locale locale = Locale.getDefault(); - - try - { - // TODO Replace null with real value - RenderingContext docRenderingContext = new RenderingContext( outputDirectory, filename, null ); - - SiteRendererSink sink = new SiteRendererSink( docRenderingContext ); - - generate( sink, null, locale ); - - } - catch ( MavenReportException | RuntimeException e ) - { - failOnError( "An error has occurred in " + getName( Locale.ENGLISH ) + " report generation", e ); - } - } - - /** - * Gets the resource bundle for the specified locale. - * - * @param locale The locale of the currently generated report. - * @return The resource bundle for the requested locale. - */ - private ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "javadoc-report", locale, getClass().getClassLoader() ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.nio.file.Path; +import java.util.Collection; +import java.util.Locale; +import java.util.Map; +import java.util.ResourceBundle; +import java.util.stream.Collectors; + +import org.apache.maven.doxia.sink.Sink; +import org.apache.maven.doxia.sink.SinkFactory; +import org.apache.maven.doxia.siterenderer.RenderingContext; +import org.apache.maven.doxia.siterenderer.sink.SiteRendererSink; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.reporting.MavenMultiPageReport; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.util.StringUtils; + +/** + * Generates documentation for the Java code in an NON aggregator project using the standard + * Javadoc Tool. + * + * @author Emmanuel Venisse + * @author Vincent Siveton + * @since 2.0 + * @see Javadoc Tool + */ +@Mojo(name = "javadoc", requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true) +@Execute(phase = LifecyclePhase.GENERATE_SOURCES) +public class JavadocReport extends AbstractJavadocMojo implements MavenMultiPageReport { + // ---------------------------------------------------------------------- + // Report Mojo Parameters + // ---------------------------------------------------------------------- + + /** + * Specifies the destination directory where javadoc saves the generated HTML files. + */ + @Parameter( + property = "reportOutputDirectory", + defaultValue = "${project.reporting.outputDirectory}/apidocs", + required = true) + private File reportOutputDirectory; + + /** + * The name of the destination directory. + *
+ * + * @since 2.1 + */ + @Parameter(property = "destDir", defaultValue = "apidocs") + private String destDir; + + /** + * The name of the Javadoc report to be displayed in the Maven Generated Reports page + * (i.e. project-reports.html). + * + * @since 2.1 + */ + @Parameter(property = "name") + private String name; + + /** + * The description of the Javadoc report to be displayed in the Maven Generated Reports page + * (i.e. project-reports.html). + * + * @since 2.1 + */ + @Parameter(property = "description") + private String description; + + // ---------------------------------------------------------------------- + // Report public methods + // ---------------------------------------------------------------------- + + /** {@inheritDoc} */ + @Override + public String getName(Locale locale) { + if (StringUtils.isEmpty(name)) { + return getBundle(locale).getString("report.javadoc.name"); + } + + return name; + } + + /** {@inheritDoc} */ + @Override + public String getDescription(Locale locale) { + if (StringUtils.isEmpty(description)) { + return getBundle(locale).getString("report.javadoc.description"); + } + + return description; + } + + /** {@inheritDoc} */ + @Override + public void generate(org.codehaus.doxia.sink.Sink sink, Locale locale) throws MavenReportException { + generate(sink, null, locale); + } + + public void generate(Sink sink, Locale locale) throws MavenReportException { + generate(sink, null, locale); + } + + /** {@inheritDoc} */ + @Override + public void generate(Sink sink, SinkFactory sinkFactory, Locale locale) throws MavenReportException { + outputDirectory = getReportOutputDirectory(); + + try { + executeReport(locale); + } catch (MavenReportException | RuntimeException e) { + if (failOnError) { + throw e; + } + getLog().error("Error while creating javadoc report: " + e.getMessage(), e); + } + } + + /** {@inheritDoc} */ + @Override + public String getOutputName() { + return destDir + "/index"; + } + + /** {@inheritDoc} */ + @Override + public boolean isExternalReport() { + return true; + } + + /** + * {@inheritDoc} + * + *
+ * The logic is the following: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Can-generate-report Matrix
isAggregator hasSourceFiles isRootProject Generate Report
TrueTrueTrueTrue
TrueTrueFalseFalse
TrueFalseTrueFalse
TrueFalseFalseFalse
FalseTrueTrueTrue
FalseTrueFalseTrue
FalseFalseTrueFalse
FalseFalseFalseFalse
+ */ + @Override + public boolean canGenerateReport() { + boolean canGenerate = false; + + if (this.isAggregator() || !"pom".equals(this.project.getPackaging())) { + Collection sourcePaths; + Map> files; + try { + sourcePaths = getSourcePaths().stream() + .flatMap(e -> e.getSourcePaths().stream()) + .collect(Collectors.toList()); + files = getFiles(sourcePaths); + } catch (MavenReportException e) { + getLog().error(e.getMessage(), e); + return false; + } + + canGenerate = canGenerateReport(files); + } + if (getLog().isDebugEnabled()) { + getLog().debug(" canGenerateReport = " + canGenerate + " for project " + this.project); + } + return canGenerate; + } + + /** {@inheritDoc} */ + @Override + public String getCategoryName() { + return CATEGORY_PROJECT_REPORTS; + } + + /** {@inheritDoc} */ + @Override + public File getReportOutputDirectory() { + if (reportOutputDirectory == null) { + return outputDirectory; + } + + return reportOutputDirectory; + } + + /** + * Method to set the directory where the generated reports will be put + * + * @param reportOutputDirectory the directory file to be set + */ + @Override + public void setReportOutputDirectory(File reportOutputDirectory) { + updateReportOutputDirectory(reportOutputDirectory, destDir); + } + + /** + * @param theDestDir The destination directory. + */ + public void setDestDir(String theDestDir) { + this.destDir = theDestDir; + updateReportOutputDirectory(reportOutputDirectory, theDestDir); + } + + private void updateReportOutputDirectory(File reportOutputDirectory, String destDir) { + if (reportOutputDirectory != null + && destDir != null + && !reportOutputDirectory.getAbsolutePath().endsWith(destDir)) { + this.reportOutputDirectory = new File(reportOutputDirectory, destDir); + } else { + this.reportOutputDirectory = reportOutputDirectory; + } + } + + /** {@inheritDoc} */ + @Override + public void doExecute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("Skipping javadoc generation"); + return; + } + + File outputDirectory = new File(getOutputDirectory()); + + String filename = getOutputName() + ".html"; + + Locale locale = Locale.getDefault(); + + try { + // TODO Replace null with real value + RenderingContext docRenderingContext = new RenderingContext(outputDirectory, filename, null); + + SiteRendererSink sink = new SiteRendererSink(docRenderingContext); + + generate(sink, null, locale); + + } catch (MavenReportException | RuntimeException e) { + failOnError("An error has occurred in " + getName(Locale.ENGLISH) + " report generation", e); + } + } + + /** + * Gets the resource bundle for the specified locale. + * + * @param locale The locale of the currently generated report. + * @return The resource bundle for the requested locale. + */ + private ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle("javadoc-report", locale, getClass().getClassLoader()); + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocUtil.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocUtil.java index 0e5eda018..bcad646e8 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocUtil.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocUtil.java @@ -1,1892 +1,1620 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.PrintStream; -import java.io.UnsupportedEncodingException; -import java.lang.reflect.Modifier; -import java.net.SocketTimeoutException; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.IllegalCharsetNameException; -import java.nio.file.FileVisitResult; -import java.nio.file.Files; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.nio.file.SimpleFileVisitor; -import java.nio.file.attribute.BasicFileAttributes; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.NoSuchElementException; -import java.util.Properties; -import java.util.Set; -import java.util.StringTokenizer; -import java.util.jar.JarEntry; -import java.util.jar.JarInputStream; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.regex.PatternSyntaxException; - -import org.apache.http.HttpHeaders; -import org.apache.http.HttpHost; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.Credentials; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.CredentialsProvider; -import org.apache.http.client.config.CookieSpecs; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.protocol.HttpClientContext; -import org.apache.http.config.Registry; -import org.apache.http.config.RegistryBuilder; -import org.apache.http.conn.socket.ConnectionSocketFactory; -import org.apache.http.conn.socket.PlainConnectionSocketFactory; -import org.apache.http.conn.ssl.SSLConnectionSocketFactory; -import org.apache.http.impl.client.BasicCredentialsProvider; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; -import org.apache.http.message.BasicHeader; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.project.MavenProject; -import org.apache.maven.settings.Proxy; -import org.apache.maven.settings.Settings; -import org.apache.maven.shared.invoker.DefaultInvocationRequest; -import org.apache.maven.shared.invoker.DefaultInvoker; -import org.apache.maven.shared.invoker.InvocationOutputHandler; -import org.apache.maven.shared.invoker.InvocationRequest; -import org.apache.maven.shared.invoker.InvocationResult; -import org.apache.maven.shared.invoker.Invoker; -import org.apache.maven.shared.invoker.MavenInvocationException; -import org.apache.maven.shared.invoker.PrintStreamHandler; -import org.apache.maven.wagon.proxy.ProxyInfo; -import org.apache.maven.wagon.proxy.ProxyUtils; -import org.codehaus.plexus.languages.java.version.JavaVersion; -import org.codehaus.plexus.util.DirectoryScanner; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.Os; -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.cli.CommandLineException; -import org.codehaus.plexus.util.cli.CommandLineUtils; -import org.codehaus.plexus.util.cli.Commandline; - -/** - * Set of utilities methods for Javadoc. - * - * @author Vincent Siveton - * @since 2.4 - */ -public class JavadocUtil -{ - /** The default timeout used when fetching url, i.e. 2000. */ - public static final int DEFAULT_TIMEOUT = 2000; - - /** Error message when VM could not be started using invoker. */ - protected static final String ERROR_INIT_VM = - "Error occurred during initialization of VM, try to reduce the Java heap size for the MAVEN_OPTS " - + "environment variable using -Xms: and -Xmx:."; - - /** - * Method that removes the invalid directories in the specified directories. Note: All elements in - * dirs could be an absolute or relative against the project's base directory String path. - * - * @param project the current Maven project not null - * @param dirs the collection of String directories path that will be validated. - * @return a List of valid String directories absolute paths. - */ - public static Collection pruneDirs( MavenProject project, Collection dirs ) - { - final Path projectBasedir = project.getBasedir().toPath(); - - Set pruned = new LinkedHashSet<>( dirs.size() ); - for ( String dir : dirs ) - { - if ( dir == null ) - { - continue; - } - - Path directory = projectBasedir.resolve( dir ); - - if ( Files.isDirectory( directory ) ) - { - pruned.add( directory.toAbsolutePath() ); - } - } - - return pruned; - } - - /** - * Method that removes the invalid files in the specified files. Note: All elements in files - * should be an absolute String path. - * - * @param files the list of String files paths that will be validated. - * @return a List of valid File objects. - */ - protected static List pruneFiles( Collection files ) - { - List pruned = new ArrayList<>( files.size() ); - for ( String f : files ) - { - if ( !shouldPruneFile( f, pruned ) ) - { - pruned.add( f ); - } - } - - return pruned; - } - - /** - * Determine whether a file should be excluded from the provided list of paths, based on whether it exists and is - * already present in the list. - * - * @param f The files. - * @param pruned The list of pruned files.. - * @return true if the file could be pruned false otherwise. - */ - public static boolean shouldPruneFile( String f, List pruned ) - { - if ( f != null ) - { - if ( Files.isRegularFile( Paths.get( f ) ) && !pruned.contains( f ) ) - { - return false; - } - } - - return true; - } - - /** - * Method that gets all the source files to be excluded from the javadoc on the given source paths. - * - * @param sourcePaths the path to the source files - * @param excludedPackages the package names to be excluded in the javadoc - * @return a List of the packages to be excluded in the generated javadoc - */ - protected static List getExcludedPackages( Collection sourcePaths, - Collection excludedPackages ) - { - List excludedNames = new ArrayList<>(); - for ( Path sourcePath : sourcePaths ) - { - excludedNames.addAll( getExcludedPackages( sourcePath, excludedPackages ) ); - } - - return excludedNames; - } - - /** - * Convenience method to wrap an argument value in single quotes (i.e. '). Intended for values which - * may contain whitespaces.
- * To prevent javadoc error, the line separator (i.e. \n) are skipped. - * - * @param value the argument value. - * @return argument with quote - */ - protected static String quotedArgument( String value ) - { - String arg = value; - - if ( StringUtils.isNotEmpty( arg ) ) - { - if ( arg.contains( "'" ) ) - { - arg = StringUtils.replace( arg, "'", "\\'" ); - } - arg = "'" + arg + "'"; - - // To prevent javadoc error - arg = StringUtils.replace( arg, "\n", " " ); - } - - return arg; - } - - /** - * Convenience method to format a path argument so that it is properly interpreted by the javadoc tool. Intended for - * path values which may contain whitespaces. - * - * @param value the argument value. - * @return path argument with quote - */ - protected static String quotedPathArgument( String value ) - { - String path = value; - - if ( StringUtils.isNotEmpty( path ) ) - { - path = path.replace( '\\', '/' ); - if ( path.contains( "'" ) ) - { - StringBuilder pathBuilder = new StringBuilder(); - pathBuilder.append( '\'' ); - String[] split = path.split( "'" ); - - for ( int i = 0; i < split.length; i++ ) - { - if ( i != split.length - 1 ) - { - pathBuilder.append( split[i] ).append( "\\'" ); - } - else - { - pathBuilder.append( split[i] ); - } - } - pathBuilder.append( '\'' ); - path = pathBuilder.toString(); - } - else - { - path = "'" + path + "'"; - } - } - - return path; - } - - /** - * Convenience method that copy all doc-files directories from javadocDir to the - * outputDirectory. - * - * @param outputDirectory the output directory - * @param javadocDir the javadoc directory - * @param excludedocfilessubdir the excludedocfilessubdir parameter - * @throws IOException if any - * @since 2.5 - */ - protected static void copyJavadocResources( File outputDirectory, File javadocDir, String excludedocfilessubdir ) - throws IOException - { - if ( !javadocDir.isDirectory() ) - { - return; - } - - List excludes = new ArrayList<>( Arrays.asList( FileUtils.getDefaultExcludes() ) ); - - if ( StringUtils.isNotEmpty( excludedocfilessubdir ) ) - { - StringTokenizer st = new StringTokenizer( excludedocfilessubdir, ":" ); - String current; - while ( st.hasMoreTokens() ) - { - current = st.nextToken(); - excludes.add( "**/" + current + "/**" ); - } - } - - List docFiles = - FileUtils.getDirectoryNames( javadocDir, "resources,**/doc-files", - StringUtils.join( excludes.iterator(), "," ), false, true ); - for ( String docFile : docFiles ) - { - File docFileOutput = new File( outputDirectory, docFile ); - FileUtils.mkdir( docFileOutput.getAbsolutePath() ); - FileUtils.copyDirectoryStructure( new File( javadocDir, docFile ), docFileOutput ); - List files = - FileUtils.getFileAndDirectoryNames( docFileOutput, StringUtils.join( excludes.iterator(), "," ), null, - true, true, true, true ); - for ( String filename : files ) - { - File file = new File( filename ); - - if ( file.isDirectory() ) - { - FileUtils.deleteDirectory( file ); - } - else - { - file.delete(); - } - } - } - } - - /** - * Method that gets the files or classes that would be included in the javadocs using the subpackages parameter. - * - * @param sourceDirectory the directory where the source files are located - * @param fileList the list of all relative files found in the sourceDirectory - * @param excludePackages package names to be excluded in the javadoc - * @return a StringBuilder that contains the appended file names of the files to be included in the javadoc - */ - protected static List getIncludedFiles( File sourceDirectory, String[] fileList, - Collection excludePackages ) - { - List files = new ArrayList<>(); - - List excludePackagePatterns = new ArrayList<>( excludePackages.size() ); - for ( String excludePackage : excludePackages ) - { - excludePackagePatterns.add( Pattern.compile( excludePackage.replace( '.', File.separatorChar ) - .replace( "\\", "\\\\" ) - .replace( "*", ".+" ) - .concat( "[\\\\/][^\\\\/]+\\.java" ) - ) ); - } - - for ( String file : fileList ) - { - boolean excluded = false; - for ( Pattern excludePackagePattern : excludePackagePatterns ) - { - if ( excludePackagePattern.matcher( file ).matches() ) - { - excluded = true; - break; - } - } - - if ( !excluded ) - { - files.add( file.replace( '\\', '/' ) ); - } - } - - return files; - } - - /** - * Method that gets the complete package names (including subpackages) of the packages that were defined in the - * excludePackageNames parameter. - * - * @param sourceDirectory the directory where the source files are located - * @param excludePackagenames package names to be excluded in the javadoc - * @return a List of the packagenames to be excluded - */ - protected static Collection getExcludedPackages( final Path sourceDirectory, - Collection excludePackagenames ) - { - final String regexFileSeparator = File.separator.replace( "\\", "\\\\" ); - - final Collection fileList = new ArrayList<>(); - - try - { - Files.walkFileTree( sourceDirectory, new SimpleFileVisitor() - { - @Override - public FileVisitResult visitFile( Path file, BasicFileAttributes attrs ) - throws IOException - { - if ( file.getFileName().toString().endsWith( ".java" ) ) - { - fileList.add( sourceDirectory.relativize( file.getParent() ).toString() ); - } - return FileVisitResult.CONTINUE; - } - } ); - } - catch ( IOException e ) - { - // noop - } - - List files = new ArrayList<>(); - for ( String excludePackagename : excludePackagenames ) - { - // Usage of wildcard was bad specified and bad implemented, i.e. using String.contains() - // without respecting surrounding context - // Following implementation should match requirements as defined in the examples: - // - A wildcard at the beginning should match 1 or more folders - // - Any other wildcard must match exactly one folder - Pattern p = Pattern.compile( excludePackagename.replace( ".", regexFileSeparator ) - .replaceFirst( "^\\*", ".+" ) - .replace( "*", "[^" + regexFileSeparator + "]+" ) ); - - for ( String aFileList : fileList ) - { - if ( p.matcher( aFileList ).matches() ) - { - files.add( aFileList.replace( File.separatorChar, '.' ) ); - } - } - } - - return files; - } - - /** - * Convenience method that gets the files to be included in the javadoc. - * - * @param sourceDirectory the directory where the source files are located - * @param excludePackages the packages to be excluded in the javadocs - * @param sourceFileIncludes files to include. - * @param sourceFileExcludes files to exclude. - */ - protected static List getFilesFromSource( File sourceDirectory, List sourceFileIncludes, - List sourceFileExcludes, - Collection excludePackages ) - { - DirectoryScanner ds = new DirectoryScanner(); - if ( sourceFileIncludes == null ) - { - sourceFileIncludes = Collections.singletonList( "**/*.java" ); - } - ds.setIncludes( sourceFileIncludes.toArray( new String[sourceFileIncludes.size()] ) ); - if ( sourceFileExcludes != null && sourceFileExcludes.size() > 0 ) - { - ds.setExcludes( sourceFileExcludes.toArray( new String[sourceFileExcludes.size()] ) ); - } - ds.setBasedir( sourceDirectory ); - ds.scan(); - - String[] fileList = ds.getIncludedFiles(); - - List files = new ArrayList<>(); - if ( fileList.length != 0 ) - { - files.addAll( getIncludedFiles( sourceDirectory, fileList, excludePackages ) ); - } - - return files; - } - - /** - * Call the Javadoc tool and parse its output to find its version, i.e.: - * - *
-     * javadoc.exe( or.sh ) - J - version
-     * 
- * - * @param javadocExe not null file - * @return the javadoc version as float - * @throws IOException if javadocExe is null, doesn't exist or is not a file - * @throws CommandLineException if any - * @throws IllegalArgumentException if no output was found in the command line - * @throws PatternSyntaxException if the output contains a syntax error in the regular-expression pattern. - * @see #extractJavadocVersion(String) - */ - protected static JavaVersion getJavadocVersion( File javadocExe ) - throws IOException, CommandLineException, IllegalArgumentException - { - if ( ( javadocExe == null ) || ( !javadocExe.exists() ) || ( !javadocExe.isFile() ) ) - { - throw new IOException( "The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. " ); - } - - Commandline cmd = new Commandline(); - cmd.setExecutable( javadocExe.getAbsolutePath() ); - cmd.setWorkingDirectory( javadocExe.getParentFile() ); - cmd.createArg().setValue( "-J-version" ); - - CommandLineUtils.StringStreamConsumer out = new JavadocOutputStreamConsumer(); - CommandLineUtils.StringStreamConsumer err = new JavadocOutputStreamConsumer(); - - int exitCode = CommandLineUtils.executeCommandLine( cmd, out, err ); - - if ( exitCode != 0 ) - { - StringBuilder msg = new StringBuilder( "Exit code: " + exitCode + " - " + err.getOutput() ); - msg.append( '\n' ); - msg.append( "Command line was:" ).append( CommandLineUtils.toString( cmd.getCommandline() ) ); - throw new CommandLineException( msg.toString() ); - } - - if ( StringUtils.isNotEmpty( err.getOutput() ) ) - { - return JavaVersion.parse( extractJavadocVersion( err.getOutput() ) ); - } - else if ( StringUtils.isNotEmpty( out.getOutput() ) ) - { - return JavaVersion.parse( extractJavadocVersion( out.getOutput() ) ); - } - - throw new IllegalArgumentException( "No output found from the command line 'javadoc -J-version'" ); - } - - private static final Pattern EXTRACT_JAVADOC_VERSION_PATTERN = - Pattern.compile( "(?s).*?[^a-zA-Z](([0-9]+\\.?[0-9]*)(\\.[0-9]+)?).*" ); - - /** - * Parse the output for 'javadoc -J-version' and return the javadoc version recognized.
- * Here are some output for 'javadoc -J-version' depending the JDK used: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Output for 'javadoc -J-version' per JDK
JDKOutput for 'javadoc -J-version'
Sun 1.4java full version "1.4.2_12-b03"
Sun 1.5java full version "1.5.0_07-164"
IBM 1.4javadoc full version "J2RE 1.4.2 IBM Windows 32 build cn1420-20040626"
IBM 1.5 (French JVM)javadoc version complète de "J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a"
FreeBSD 1.5java full version "diablo-1.5.0-b01"
BEA jrockit 1.5java full version "1.5.0_11-b03"
- * - * @param output for 'javadoc -J-version' - * @return the version of the javadoc for the output, only digits and dots - * @throws PatternSyntaxException if the output doesn't match with the output pattern - * {@code (?s).*?[^a-zA-Z]([0-9]+\\.?[0-9]*)(\\.([0-9]+))?.*}. - * @throws IllegalArgumentException if the output is null - */ - protected static String extractJavadocVersion( String output ) - throws IllegalArgumentException - { - if ( StringUtils.isEmpty( output ) ) - { - throw new IllegalArgumentException( "The output could not be null." ); - } - - Pattern pattern = EXTRACT_JAVADOC_VERSION_PATTERN; - - Matcher matcher = pattern.matcher( output ); - if ( !matcher.matches() ) - { - throw new PatternSyntaxException( "Unrecognized version of Javadoc: '" + output + "'", pattern.pattern(), - pattern.toString().length() - 1 ); - } - - return matcher.group( 1 ); - } - - private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_0 = - Pattern.compile( "^\\s*(\\d+)\\s*?\\s*$" ); - - private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_1 = - Pattern.compile( "^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE ); - - private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_2 = - Pattern.compile( "^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE ); - - private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_3 = - Pattern.compile( "^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE ); - - private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_4 = - Pattern.compile( "^\\s*(\\d+)\\s*t(b)?\\s*$", Pattern.CASE_INSENSITIVE ); - - /** - * Parse a memory string which be used in the JVM arguments -Xms or -Xmx.
- * Here are some supported memory string depending the JDK used: - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - * - *
Memory argument support per JDK
JDKMemory argument support for -Xms or -Xmx
SUN1024k | 128m | 1g | 1t
IBM1024k | 1024b | 128m | 128mb | 1g | 1gb
BEA1024k | 1024kb | 128m | 128mb | 1g | 1gb
- * - * @param memory the memory to be parsed, not null. - * @return the memory parsed with a supported unit. If no unit specified in the memory parameter, the - * default unit is m. The units g | gb or t | tb will be converted in - * m. - * @throws IllegalArgumentException if the memory parameter is null or doesn't match any pattern. - */ - protected static String parseJavadocMemory( String memory ) - throws IllegalArgumentException - { - if ( StringUtils.isEmpty( memory ) ) - { - throw new IllegalArgumentException( "The memory could not be null." ); - } - - Matcher m0 = PARSE_JAVADOC_MEMORY_PATTERN_0.matcher( memory ); - if ( m0.matches() ) - { - return m0.group( 1 ) + "m"; - } - - Matcher m1 = PARSE_JAVADOC_MEMORY_PATTERN_1.matcher( memory ); - if ( m1.matches() ) - { - return m1.group( 1 ) + "k"; - } - - Matcher m2 = PARSE_JAVADOC_MEMORY_PATTERN_2.matcher( memory ); - if ( m2.matches() ) - { - return m2.group( 1 ) + "m"; - } - - Matcher m3 = PARSE_JAVADOC_MEMORY_PATTERN_3.matcher( memory ); - if ( m3.matches() ) - { - return ( Integer.parseInt( m3.group( 1 ) ) * 1024 ) + "m"; - } - - Matcher m4 = PARSE_JAVADOC_MEMORY_PATTERN_4.matcher( memory ); - if ( m4.matches() ) - { - return ( Integer.parseInt( m4.group( 1 ) ) * 1024 * 1024 ) + "m"; - } - - throw new IllegalArgumentException( "Could convert not to a memory size: " + memory ); - } - - /** - * Validate if a charset is supported on this platform. - * - * @param charsetName the charsetName to be check. - * @return true if the given charset is supported by the JVM, false otherwise. - */ - protected static boolean validateEncoding( String charsetName ) - { - if ( StringUtils.isEmpty( charsetName ) ) - { - return false; - } - - try - { - return Charset.isSupported( charsetName ); - } - catch ( IllegalCharsetNameException e ) - { - return false; - } - } - - /** - * Auto-detect the class names of the implementation of com.sun.tools.doclets.Taglet class from a given - * jar file.
- * Note: JAVA_HOME/lib/tools.jar is a requirement to find - * com.sun.tools.doclets.Taglet class. - * - * @param jarFile not null - * @return the list of com.sun.tools.doclets.Taglet class names from a given jarFile. - * @throws IOException if jarFile is invalid or not found, or if the JAVA_HOME/lib/tools.jar is not - * found. - * @throws ClassNotFoundException if any - * @throws NoClassDefFoundError if any - */ - protected static List getTagletClassNames( File jarFile ) - throws IOException, ClassNotFoundException, NoClassDefFoundError - { - List classes = getClassNamesFromJar( jarFile ); - URLClassLoader cl; - - // Needed to find com.sun.tools.doclets.Taglet class - File tools = new File( System.getProperty( "java.home" ), "../lib/tools.jar" ); - if ( tools.exists() && tools.isFile() ) - { - cl = new URLClassLoader( new URL[] { jarFile.toURI().toURL(), tools.toURI().toURL() }, null ); - } - else - { - cl = new URLClassLoader( new URL[] { jarFile.toURI().toURL() }, ClassLoader.getSystemClassLoader() ); - } - - List tagletClasses = new ArrayList<>(); - - Class tagletClass; - - try - { - tagletClass = cl.loadClass( "com.sun.tools.doclets.Taglet" ); - } - catch ( ClassNotFoundException e ) - { - tagletClass = cl.loadClass( "jdk.javadoc.doclet.Taglet" ); - } - - for ( String s : classes ) - { - Class c = cl.loadClass( s ); - - if ( tagletClass.isAssignableFrom( c ) && !Modifier.isAbstract( c.getModifiers() ) ) - { - tagletClasses.add( c.getName() ); - } - } - - try - { - cl.close(); - } - catch ( IOException ex ) - { - // no big deal - } - - return tagletClasses; - } - - /** - * Copy the given url to the given file. - * - * @param url not null url - * @param file not null file where the url will be created - * @throws IOException if any - * @since 2.6 - */ - protected static void copyResource( URL url, File file ) - throws IOException - { - if ( file == null ) - { - throw new IOException( "The file can't be null." ); - } - if ( url == null ) - { - throw new IOException( "The url could not be null." ); - } - - FileUtils.copyURLToFile( url, file ); - } - - /** - * Invoke Maven for the given project file with a list of goals and properties, the output will be in the invokerlog - * file.
- * Note: the Maven Home should be defined in the maven.home Java system property or defined in - * M2_HOME system env variables. - * - * @param log a logger could be null. - * @param localRepositoryDir the localRepository not null. - * @param projectFile a not null project file. - * @param goals a not null goals list. - * @param properties the properties for the goals, could be null. - * @param invokerLog the log file where the invoker will be written, if null using System.out. - * @param globalSettingsFile reference to settings file, could be null. - * @throws MavenInvocationException if any - * @since 2.6 - */ - protected static void invokeMaven( Log log, File localRepositoryDir, File projectFile, List goals, - Properties properties, File invokerLog, File globalSettingsFile ) - throws MavenInvocationException - { - if ( projectFile == null ) - { - throw new IllegalArgumentException( "projectFile should be not null." ); - } - if ( !projectFile.isFile() ) - { - throw new IllegalArgumentException( projectFile.getAbsolutePath() + " is not a file." ); - } - if ( goals == null || goals.size() == 0 ) - { - throw new IllegalArgumentException( "goals should be not empty." ); - } - if ( localRepositoryDir == null || !localRepositoryDir.isDirectory() ) - { - throw new IllegalArgumentException( "localRepositoryDir '" + localRepositoryDir - + "' should be a directory." ); - } - - String mavenHome = getMavenHome( log ); - if ( StringUtils.isEmpty( mavenHome ) ) - { - String msg = "Could NOT invoke Maven because no Maven Home is defined. You need to have set the M2_HOME " - + "system env variable or a maven.home Java system properties."; - if ( log != null ) - { - log.error( msg ); - } - else - { - System.err.println( msg ); - } - return; - } - - Invoker invoker = new DefaultInvoker(); - invoker.setMavenHome( new File( mavenHome ) ); - invoker.setLocalRepositoryDirectory( localRepositoryDir ); - - InvocationRequest request = new DefaultInvocationRequest(); - request.setBaseDirectory( projectFile.getParentFile() ); - request.setPomFile( projectFile ); - request.setGlobalSettingsFile( globalSettingsFile ); - request.setBatchMode( true ); - if ( log != null ) - { - request.setDebug( log.isDebugEnabled() ); - } - else - { - request.setDebug( true ); - } - request.setGoals( goals ); - if ( properties != null ) - { - request.setProperties( properties ); - } - File javaHome = getJavaHome( log ); - if ( javaHome != null ) - { - request.setJavaHome( javaHome ); - } - - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "Invoking Maven for the goals: " + goals + " with " - + ( properties == null ? "no properties" : "properties=" + properties ) ); - } - InvocationResult result = invoke( log, invoker, request, invokerLog, goals, properties, null ); - - if ( result.getExitCode() != 0 ) - { - String invokerLogContent = readFile( invokerLog, "UTF-8" ); - - // see DefaultMaven - if ( invokerLogContent != null && ( !invokerLogContent.contains( "Scanning for projects..." ) - || invokerLogContent.contains( OutOfMemoryError.class.getName() ) ) ) - { - if ( log != null ) - { - log.error( "Error occurred during initialization of VM, trying to use an empty MAVEN_OPTS..." ); - - if ( log.isDebugEnabled() ) - { - log.debug( "Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS..." ); - } - } - result = invoke( log, invoker, request, invokerLog, goals, properties, "" ); - } - } - - if ( result.getExitCode() != 0 ) - { - String invokerLogContent = readFile( invokerLog, "UTF-8" ); - - // see DefaultMaven - if ( invokerLogContent != null && ( !invokerLogContent.contains( "Scanning for projects..." ) - || invokerLogContent.contains( OutOfMemoryError.class.getName() ) ) ) - { - throw new MavenInvocationException( ERROR_INIT_VM ); - } - - throw new MavenInvocationException( "Error when invoking Maven, consult the invoker log file: " - + invokerLog.getAbsolutePath() ); - } - } - - /** - * Read the given file and return the content or null if an IOException occurs. - * - * @param javaFile not null - * @param encoding could be null - * @return the content with unified line separator of the given javaFile using the given encoding. - * @see FileUtils#fileRead(File, String) - * @since 2.6.1 - */ - protected static String readFile( final File javaFile, final String encoding ) - { - try - { - return FileUtils.fileRead( javaFile, encoding ); - } - catch ( IOException e ) - { - return null; - } - } - - /** - * Split the given path with colon and semi-colon, to support Solaris and Windows path. Examples: - * - *
-     * splitPath( "/home:/tmp" )     = ["/home", "/tmp"]
-     * splitPath( "/home;/tmp" )     = ["/home", "/tmp"]
-     * splitPath( "C:/home:C:/tmp" ) = ["C:/home", "C:/tmp"]
-     * splitPath( "C:/home;C:/tmp" ) = ["C:/home", "C:/tmp"]
-     * 
- * - * @param path which can contain multiple paths separated with a colon (:) or a semi-colon - * (;), platform independent. Could be null. - * @return the path splitted by colon or semi-colon or null if path was null. - * @since 2.6.1 - */ - protected static String[] splitPath( final String path ) - { - if ( path == null ) - { - return null; - } - - List subpaths = new ArrayList<>(); - PathTokenizer pathTokenizer = new PathTokenizer( path ); - while ( pathTokenizer.hasMoreTokens() ) - { - subpaths.add( pathTokenizer.nextToken() ); - } - - return subpaths.toArray( new String[subpaths.size()] ); - } - - /** - * Unify the given path with the current System path separator, to be platform independent. Examples: - * - *
-     * unifyPathSeparator( "/home:/tmp" ) = "/home:/tmp" (Solaris box)
-     * unifyPathSeparator( "/home:/tmp" ) = "/home;/tmp" (Windows box)
-     * 
- * - * @param path which can contain multiple paths by separating them with a colon (:) or a semi-colon - * (;), platform independent. Could be null. - * @return the same path but separated with the current System path separator or null if path was - * null. - * @since 2.6.1 - * @see #splitPath(String) - * @see File#pathSeparator - */ - protected static String unifyPathSeparator( final String path ) - { - if ( path == null ) - { - return null; - } - - return StringUtils.join( splitPath( path ), File.pathSeparator ); - } - - // ---------------------------------------------------------------------- - // private methods - // ---------------------------------------------------------------------- - - /** - * @param jarFile not null - * @return all class names from the given jar file. - * @throws IOException if any or if the jarFile is null or doesn't exist. - */ - private static List getClassNamesFromJar( File jarFile ) - throws IOException - { - if ( jarFile == null || !jarFile.exists() || !jarFile.isFile() ) - { - throw new IOException( "The jar '" + jarFile + "' doesn't exist or is not a file." ); - } - - List classes = new ArrayList<>(); - Pattern pattern = - Pattern.compile( "(?i)^(META-INF/versions/(?[0-9]+)/)?(?.+)[.]class$" ); - try ( JarInputStream jarStream = new JarInputStream( new FileInputStream( jarFile ) ) ) - { - for ( JarEntry jarEntry = jarStream.getNextJarEntry(); jarEntry != null; jarEntry = - jarStream.getNextJarEntry() ) - { - Matcher matcher = pattern.matcher( jarEntry.getName() ); - if ( matcher.matches() ) - { - String version = matcher.group( "v" ); - if ( StringUtils.isEmpty( version ) || JavaVersion.JAVA_VERSION.isAtLeast( version ) ) - { - String name = matcher.group( "n" ); - - classes.add( name.replaceAll( "/", "\\." ) ); - } - } - - jarStream.closeEntry(); - } - } - - return classes; - } - - /** - * @param log could be null - * @param invoker not null - * @param request not null - * @param invokerLog not null - * @param goals not null - * @param properties could be null - * @param mavenOpts could be null - * @return the invocation result - * @throws MavenInvocationException if any - * @since 2.6 - */ - private static InvocationResult invoke( Log log, Invoker invoker, InvocationRequest request, File invokerLog, - List goals, Properties properties, String mavenOpts ) - throws MavenInvocationException - { - PrintStream ps; - OutputStream os = null; - if ( invokerLog != null ) - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "Using " + invokerLog.getAbsolutePath() + " to log the invoker" ); - } - - try - { - if ( !invokerLog.exists() ) - { - // noinspection ResultOfMethodCallIgnored - invokerLog.getParentFile().mkdirs(); - } - os = new FileOutputStream( invokerLog ); - ps = new PrintStream( os, true, "UTF-8" ); - } - catch ( FileNotFoundException e ) - { - if ( log != null && log.isErrorEnabled() ) - { - log.error( "FileNotFoundException: " + e.getMessage() + ". Using System.out to log the invoker." ); - } - ps = System.out; - } - catch ( UnsupportedEncodingException e ) - { - if ( log != null && log.isErrorEnabled() ) - { - log.error( "UnsupportedEncodingException: " + e.getMessage() - + ". Using System.out to log the invoker." ); - } - ps = System.out; - } - } - else - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "Using System.out to log the invoker." ); - } - - ps = System.out; - } - - if ( mavenOpts != null ) - { - request.setMavenOpts( mavenOpts ); - } - - InvocationOutputHandler outputHandler = new PrintStreamHandler( ps, false ); - request.setOutputHandler( outputHandler ); - - try - { - outputHandler.consumeLine( "Invoking Maven for the goals: " + goals + " with " - + ( properties == null ? "no properties" : "properties=" + properties ) ); - outputHandler.consumeLine( "" ); - outputHandler.consumeLine( "M2_HOME=" + getMavenHome( log ) ); - outputHandler.consumeLine( "MAVEN_OPTS=" + getMavenOpts( log ) ); - outputHandler.consumeLine( "JAVA_HOME=" + getJavaHome( log ) ); - outputHandler.consumeLine( "JAVA_OPTS=" + getJavaOpts( log ) ); - outputHandler.consumeLine( "" ); - } - catch ( IOException ioe ) - { - throw new MavenInvocationException( "IOException while consuming invocation output", ioe ); - } - - try - { - return invoker.execute( request ); - } - finally - { - IOUtil.close( os ); - } - } - - /** - * @param log a logger could be null - * @return the Maven home defined in the maven.home system property or defined in M2_HOME - * system env variables or null if never set. - * @since 2.6 - */ - private static String getMavenHome( Log log ) - { - String mavenHome = System.getProperty( "maven.home" ); - if ( mavenHome == null ) - { - try - { - mavenHome = CommandLineUtils.getSystemEnvVars().getProperty( "M2_HOME" ); - } - catch ( IOException e ) - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "IOException: " + e.getMessage() ); - } - } - } - - File m2Home = new File( mavenHome ); - if ( !m2Home.exists() ) - { - if ( log != null && log.isErrorEnabled() ) - { - log.error( "Cannot find Maven application directory. Either specify 'maven.home' system property, or " - + "M2_HOME environment variable." ); - } - } - - return mavenHome; - } - - /** - * @param log a logger could be null - * @return the MAVEN_OPTS env variable value - * @since 2.6 - */ - private static String getMavenOpts( Log log ) - { - String mavenOpts = null; - try - { - mavenOpts = CommandLineUtils.getSystemEnvVars().getProperty( "MAVEN_OPTS" ); - } - catch ( IOException e ) - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "IOException: " + e.getMessage() ); - } - } - - return mavenOpts; - } - - /** - * @param log a logger could be null - * @return the JAVA_HOME from System.getProperty( "java.home" ) By default, - * System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME should be in the - * JDK_HOME - * @since 2.6 - */ - private static File getJavaHome( Log log ) - { - File javaHome = null; - - String javaHomeValue = null; - try - { - javaHomeValue = CommandLineUtils.getSystemEnvVars().getProperty( "JAVA_HOME" ); - } - catch ( IOException e ) - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "IOException: " + e.getMessage() ); - } - } - - // if maven.home is set, we can assume JAVA_HOME must be used for testing - if ( System.getProperty( "maven.home" ) == null || javaHomeValue == null ) - { - // JEP220 (Java9) restructured the JRE/JDK runtime image - if ( SystemUtils.IS_OS_MAC_OSX || JavaVersion.JAVA_VERSION.isAtLeast( "9" ) ) - { - javaHome = SystemUtils.getJavaHome(); - } - else - { - javaHome = new File( SystemUtils.getJavaHome(), ".." ); - } - } - - if ( javaHome == null || !javaHome.exists() ) - { - javaHome = new File( javaHomeValue ); - } - - if ( javaHome == null || !javaHome.exists() ) - { - if ( log != null && log.isErrorEnabled() ) - { - log.error( "Cannot find Java application directory. Either specify 'java.home' system property, or " - + "JAVA_HOME environment variable." ); - } - } - - return javaHome; - } - - /** - * @param log a logger could be null - * @return the JAVA_OPTS env variable value - * @since 2.6 - */ - private static String getJavaOpts( Log log ) - { - String javaOpts = null; - try - { - javaOpts = CommandLineUtils.getSystemEnvVars().getProperty( "JAVA_OPTS" ); - } - catch ( IOException e ) - { - if ( log != null && log.isDebugEnabled() ) - { - log.debug( "IOException: " + e.getMessage() ); - } - } - - return javaOpts; - } - - /** - * A Path tokenizer takes a path and returns the components that make up that path. The path can use path separators - * of either ':' or ';' and file separators of either '/' or '\'. - * - * @version revision 439418 taken on 2009-09-12 from Ant Project (see - * http://svn.apache.org/repos/asf/ant/core/trunk/src/main/org/apache/tools/ant/PathTokenizer.java) - */ - private static class PathTokenizer - { - /** - * A tokenizer to break the string up based on the ':' or ';' separators. - */ - private StringTokenizer tokenizer; - - /** - * A String which stores any path components which have been read ahead due to DOS filesystem compensation. - */ - private String lookahead = null; - - /** - * A boolean that determines if we are running on Novell NetWare, which exhibits slightly different path name - * characteristics (multi-character volume / drive names) - */ - private boolean onNetWare = Os.isFamily( "netware" ); - - /** - * Flag to indicate whether or not we are running on a platform with a DOS style filesystem - */ - private boolean dosStyleFilesystem; - - /** - * Constructs a path tokenizer for the specified path. - * - * @param path The path to tokenize. Must not be null. - */ - PathTokenizer( String path ) - { - if ( onNetWare ) - { - // For NetWare, use the boolean=true mode, so we can use delimiter - // information to make a better decision later. - tokenizer = new StringTokenizer( path, ":;", true ); - } - else - { - // on Windows and Unix, we can ignore delimiters and still have - // enough information to tokenize correctly. - tokenizer = new StringTokenizer( path, ":;", false ); - } - dosStyleFilesystem = File.pathSeparatorChar == ';'; - } - - /** - * Tests if there are more path elements available from this tokenizer's path. If this method returns - * true, then a subsequent call to nextToken will successfully return a token. - * - * @return true if and only if there is at least one token in the string after the current - * position; false otherwise. - */ - public boolean hasMoreTokens() - { - return lookahead != null || tokenizer.hasMoreTokens(); - - } - - /** - * Returns the next path element from this tokenizer. - * - * @return the next path element from this tokenizer. - * @exception NoSuchElementException if there are no more elements in this tokenizer's path. - */ - public String nextToken() - throws NoSuchElementException - { - String token; - if ( lookahead != null ) - { - token = lookahead; - lookahead = null; - } - else - { - token = tokenizer.nextToken().trim(); - } - - if ( !onNetWare ) - { - if ( token.length() == 1 && Character.isLetter( token.charAt( 0 ) ) && dosStyleFilesystem - && tokenizer.hasMoreTokens() ) - { - // we are on a dos style system so this path could be a drive - // spec. We look at the next token - String nextToken = tokenizer.nextToken().trim(); - if ( nextToken.startsWith( "\\" ) || nextToken.startsWith( "/" ) ) - { - // we know we are on a DOS style platform and the next path - // starts with a slash or backslash, so we know this is a - // drive spec - token += ":" + nextToken; - } - else - { - // store the token just read for next time - lookahead = nextToken; - } - } - } - else - { - // we are on NetWare, tokenizing is handled a little differently, - // due to the fact that NetWare has multiple-character volume names. - if ( token.equals( File.pathSeparator ) || token.equals( ":" ) ) - { - // ignore ";" and get the next token - token = tokenizer.nextToken().trim(); - } - - if ( tokenizer.hasMoreTokens() ) - { - // this path could be a drive spec, so look at the next token - String nextToken = tokenizer.nextToken().trim(); - - // make sure we aren't going to get the path separator next - if ( !nextToken.equals( File.pathSeparator ) ) - { - if ( nextToken.equals( ":" ) ) - { - if ( !token.startsWith( "/" ) && !token.startsWith( "\\" ) && !token.startsWith( "." ) - && !token.startsWith( ".." ) ) - { - // it indeed is a drive spec, get the next bit - String oneMore = tokenizer.nextToken().trim(); - if ( !oneMore.equals( File.pathSeparator ) ) - { - token += ":" + oneMore; - } - else - { - token += ":"; - lookahead = oneMore; - } - } - // implicit else: ignore the ':' since we have either a - // UNIX or a relative path - } - else - { - // store the token just read for next time - lookahead = nextToken; - } - } - } - } - return token; - } - } - - /** - * Ignores line like 'Picked up JAVA_TOOL_OPTIONS: ...' as can happen on CI servers. - * - * @author Robert Scholte - * @since 3.0.1 - */ - protected static class JavadocOutputStreamConsumer - extends CommandLineUtils.StringStreamConsumer - { - @Override - public void consumeLine( String line ) - { - if ( !line.startsWith( "Picked up " ) ) - { - super.consumeLine( line ); - } - } - } - - static List toList( String src ) - { - return toList( src, null, null ); - } - - static List toList( String src, String elementPrefix, String elementSuffix ) - { - if ( StringUtils.isEmpty( src ) ) - { - return null; - } - - List result = new ArrayList<>(); - - StringTokenizer st = new StringTokenizer( src, "[,:;]" ); - StringBuilder sb = new StringBuilder( 256 ); - while ( st.hasMoreTokens() ) - { - sb.setLength( 0 ); - if ( StringUtils.isNotEmpty( elementPrefix ) ) - { - sb.append( elementPrefix ); - } - - sb.append( st.nextToken() ); - - if ( StringUtils.isNotEmpty( elementSuffix ) ) - { - sb.append( elementSuffix ); - } - - result.add( sb.toString() ); - } - - return result; - } - - static List toList( T[] multiple ) - { - return toList( null, multiple ); - } - - static List toList( T single, T[] multiple ) - { - if ( single == null && ( multiple == null || multiple.length < 1 ) ) - { - return null; - } - - List result = new ArrayList<>(); - if ( single != null ) - { - result.add( single ); - } - - if ( multiple != null && multiple.length > 0 ) - { - result.addAll( Arrays.asList( multiple ) ); - } - - return result; - } - - // TODO: move to plexus-utils or use something appropriate from there - public static String toRelative( File basedir, String absolutePath ) - { - String relative; - - absolutePath = absolutePath.replace( '\\', '/' ); - String basedirPath = basedir.getAbsolutePath().replace( '\\', '/' ); - - if ( absolutePath.startsWith( basedirPath ) ) - { - relative = absolutePath.substring( basedirPath.length() ); - if ( relative.startsWith( "/" ) ) - { - relative = relative.substring( 1 ); - } - if ( relative.length() <= 0 ) - { - relative = "."; - } - } - else - { - relative = absolutePath; - } - - return relative; - } - - /** - * Convenience method to determine that a collection is not empty or null. - * @param collection the collection to verify - * @return {@code true} if not {@code null} and not empty, otherwise {@code false} - */ - public static boolean isNotEmpty( final Collection collection ) - { - return collection != null && !collection.isEmpty(); - } - - /** - * Convenience method to determine that a collection is empty or null. - * @param collection the collection to verify - * @return {@code true} if {@code null} or empty, otherwise {@code false} - */ - public static boolean isEmpty( final Collection collection ) - { - return collection == null || collection.isEmpty(); - } - - /** - * Execute an Http request at the given URL, follows redirects, and returns the last redirect locations. For URLs - * that aren't http/https, this does nothing and simply returns the given URL unchanged. - * - * @param url URL. - * @param settings Maven settings. - * @return Last redirect location. - * @throws IOException if there was an error during the Http request. - */ - protected static URL getRedirectUrl( URL url, Settings settings ) - throws IOException - { - String protocol = url.getProtocol(); - if ( !"http".equals( protocol ) && !"https".equals( protocol ) ) - { - return url; - } - - try ( CloseableHttpClient httpClient = createHttpClient( settings, url ) ) - { - HttpClientContext httpContext = HttpClientContext.create(); - HttpGet httpMethod = new HttpGet( url.toString() ); - HttpResponse response = httpClient.execute( httpMethod, httpContext ); - int status = response.getStatusLine().getStatusCode(); - if ( status != HttpStatus.SC_OK ) - { - throw new FileNotFoundException( "Unexpected HTTP status code " + status + " getting resource " - + url.toExternalForm() + "." ); - } - - List redirects = httpContext.getRedirectLocations(); - - if ( isEmpty( redirects ) ) - { - return url; - } - else - { - URI last = redirects.get( redirects.size() - 1 ); - - // URI must refer to directory, so prevent redirects to index.html - // see https://issues.apache.org/jira/browse/MJAVADOC-539 - String truncate = "index.html"; - if ( last.getPath().endsWith( "/" + truncate ) ) - { - try - { - String fixedPath = last.getPath().substring( 0, last.getPath().length() - truncate.length() ); - last = new URI( last.getScheme(), last.getAuthority(), fixedPath, last.getQuery(), - last.getFragment() ); - } - catch ( URISyntaxException ex ) - { - // not supposed to happen, but when it does just keep the last URI - } - } - return last.toURL(); - } - } - } - - /** - * Validates an URL to point to a valid package-list resource. - * - * @param url The URL to validate. - * @param settings The user settings used to configure the connection to the URL or {@code null}. - * @param validateContent true to validate the content of the package-list resource; - * false to only check the existence of the package-list resource. - * @return true if url points to a valid package-list resource; - * false else. - * @throws IOException if reading the resource fails. - * @see #createHttpClient(org.apache.maven.settings.Settings, java.net.URL) - * @since 2.8 - */ - protected static boolean isValidPackageList( URL url, Settings settings, boolean validateContent ) - throws IOException - { - if ( url == null ) - { - throw new IllegalArgumentException( "The url is null" ); - } - - try ( BufferedReader reader = getReader( url, settings ) ) - { - if ( validateContent ) - { - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - if ( !isValidPackageName( line ) ) - { - return false; - } - } - } - return true; - } - } - - protected static boolean isValidElementList( URL url, Settings settings, boolean validateContent ) - throws IOException - { - if ( url == null ) - { - throw new IllegalArgumentException( "The url is null" ); - } - - try ( BufferedReader reader = getReader( url, settings ) ) - { - if ( validateContent ) - { - for ( String line = reader.readLine(); line != null; line = reader.readLine() ) - { - if ( line.startsWith( "module:" ) ) - { - continue; - } - - if ( !isValidPackageName( line ) ) - { - return false; - } - } - } - return true; - } - } - - private static BufferedReader getReader( URL url, Settings settings ) throws IOException - { - BufferedReader reader = null; - - if ( "file".equals( url.getProtocol() ) ) - { - // Intentionally using the platform default encoding here since this is what Javadoc uses internally. - reader = new BufferedReader( new InputStreamReader( url.openStream() ) ); - } - else - { - // http, https... - final CloseableHttpClient httpClient = createHttpClient( settings, url ); - - final HttpGet httpMethod = new HttpGet( url.toString() ); - - HttpResponse response; - HttpClientContext httpContext = HttpClientContext.create(); - try - { - response = httpClient.execute( httpMethod, httpContext ); - } - catch ( SocketTimeoutException e ) - { - // could be a sporadic failure, one more retry before we give up - response = httpClient.execute( httpMethod, httpContext ); - } - - int status = response.getStatusLine().getStatusCode(); - if ( status != HttpStatus.SC_OK ) - { - throw new FileNotFoundException( "Unexpected HTTP status code " + status + " getting resource " - + url.toExternalForm() + "." ); - } - else - { - int pos = url.getPath().lastIndexOf( '/' ); - List redirects = httpContext.getRedirectLocations(); - if ( pos >= 0 && isNotEmpty( redirects ) ) - { - URI location = redirects.get( redirects.size() - 1 ); - String suffix = url.getPath().substring( pos ); - // Redirections shall point to the same file, e.g. /package-list - if ( !location.getPath().endsWith( suffix ) ) - { - throw new FileNotFoundException( url.toExternalForm() + " redirects to " - + location.toURL().toExternalForm() + "." ); - } - } - } - - // Intentionally using the platform default encoding here since this is what Javadoc uses internally. - reader = new BufferedReader( new InputStreamReader( response.getEntity().getContent() ) ) - { - @Override - public void close() - throws IOException - { - super.close(); - - if ( httpMethod != null ) - { - httpMethod.releaseConnection(); - } - if ( httpClient != null ) - { - httpClient.close(); - } - } - }; - } - - return reader; - } - - private static boolean isValidPackageName( String str ) - { - if ( StringUtils.isEmpty( str ) ) - { - // unnamed package is valid (even if bad practice :) ) - return true; - } - - int idx; - while ( ( idx = str.indexOf( '.' ) ) != -1 ) - { - if ( !isValidClassName( str.substring( 0, idx ) ) ) - { - return false; - } - - str = str.substring( idx + 1 ); - } - - return isValidClassName( str ); - } - - private static boolean isValidClassName( String str ) - { - if ( StringUtils.isEmpty( str ) || !Character.isJavaIdentifierStart( str.charAt( 0 ) ) ) - { - return false; - } - - for ( int i = str.length() - 1; i > 0; i-- ) - { - if ( !Character.isJavaIdentifierPart( str.charAt( i ) ) ) - { - return false; - } - } - - return true; - } - - /** - * Creates a new {@code HttpClient} instance. - * - * @param settings The settings to use for setting up the client or {@code null}. - * @param url The {@code URL} to use for setting up the client or {@code null}. - * @return A new {@code HttpClient} instance. - * @see #DEFAULT_TIMEOUT - * @since 2.8 - */ - private static CloseableHttpClient createHttpClient( Settings settings, URL url ) - { - HttpClientBuilder builder = HttpClients.custom(); - - Registry csfRegistry = - RegistryBuilder.create() - .register( "http", PlainConnectionSocketFactory.getSocketFactory() ) - .register( "https", SSLConnectionSocketFactory.getSystemSocketFactory() ) - .build(); - - builder.setConnectionManager( new PoolingHttpClientConnectionManager( csfRegistry ) ); - builder.setDefaultRequestConfig( RequestConfig.custom() - .setSocketTimeout( DEFAULT_TIMEOUT ) - .setConnectTimeout( DEFAULT_TIMEOUT ) - .setCircularRedirectsAllowed( true ) - .setCookieSpec( CookieSpecs.IGNORE_COOKIES ) - .build() ); - - // Some web servers don't allow the default user-agent sent by httpClient - builder.setUserAgent( "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)" ); - - // Some server reject requests that do not have an Accept header - builder.setDefaultHeaders( Arrays.asList( new BasicHeader( HttpHeaders.ACCEPT, "*/*" ) ) ); - - if ( settings != null && settings.getActiveProxy() != null ) - { - Proxy activeProxy = settings.getActiveProxy(); - - ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setNonProxyHosts( activeProxy.getNonProxyHosts() ); - - if ( StringUtils.isNotEmpty( activeProxy.getHost() ) - && ( url == null || !ProxyUtils.validateNonProxyHosts( proxyInfo, url.getHost() ) ) ) - { - HttpHost proxy = new HttpHost( activeProxy.getHost(), activeProxy.getPort() ); - builder.setProxy( proxy ); - - if ( StringUtils.isNotEmpty( activeProxy.getUsername() ) && activeProxy.getPassword() != null ) - { - Credentials credentials = - new UsernamePasswordCredentials( activeProxy.getUsername(), activeProxy.getPassword() ); - - CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); - credentialsProvider.setCredentials( AuthScope.ANY, credentials ); - builder.setDefaultCredentialsProvider( credentialsProvider ); - } - } - } - return builder.build(); - } - - static boolean equalsIgnoreCase( String value, String... strings ) - { - for ( String s : strings ) - { - if ( s.equalsIgnoreCase( value ) ) - { - return true; - } - } - return false; - } - - static boolean equals( String value, String... strings ) - { - for ( String s : strings ) - { - if ( s.equals( value ) ) - { - return true; - } - } - return false; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Modifier; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.charset.Charset; +import java.nio.charset.IllegalCharsetNameException; +import java.nio.file.FileVisitResult; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.SimpleFileVisitor; +import java.nio.file.attribute.BasicFileAttributes; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.Properties; +import java.util.Set; +import java.util.StringTokenizer; +import java.util.jar.JarEntry; +import java.util.jar.JarInputStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.apache.http.HttpHeaders; +import org.apache.http.HttpHost; +import org.apache.http.HttpResponse; +import org.apache.http.HttpStatus; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.Credentials; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.CredentialsProvider; +import org.apache.http.client.config.CookieSpecs; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.protocol.HttpClientContext; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.BasicCredentialsProvider; +import org.apache.http.impl.client.CloseableHttpClient; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.client.HttpClients; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.message.BasicHeader; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.project.MavenProject; +import org.apache.maven.settings.Proxy; +import org.apache.maven.settings.Settings; +import org.apache.maven.shared.invoker.DefaultInvocationRequest; +import org.apache.maven.shared.invoker.DefaultInvoker; +import org.apache.maven.shared.invoker.InvocationOutputHandler; +import org.apache.maven.shared.invoker.InvocationRequest; +import org.apache.maven.shared.invoker.InvocationResult; +import org.apache.maven.shared.invoker.Invoker; +import org.apache.maven.shared.invoker.MavenInvocationException; +import org.apache.maven.shared.invoker.PrintStreamHandler; +import org.apache.maven.wagon.proxy.ProxyInfo; +import org.apache.maven.wagon.proxy.ProxyUtils; +import org.codehaus.plexus.languages.java.version.JavaVersion; +import org.codehaus.plexus.util.DirectoryScanner; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.IOUtil; +import org.codehaus.plexus.util.Os; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.cli.CommandLineException; +import org.codehaus.plexus.util.cli.CommandLineUtils; +import org.codehaus.plexus.util.cli.Commandline; + +/** + * Set of utilities methods for Javadoc. + * + * @author Vincent Siveton + * @since 2.4 + */ +public class JavadocUtil { + /** The default timeout used when fetching url, i.e. 2000. */ + public static final int DEFAULT_TIMEOUT = 2000; + + /** Error message when VM could not be started using invoker. */ + protected static final String ERROR_INIT_VM = + "Error occurred during initialization of VM, try to reduce the Java heap size for the MAVEN_OPTS " + + "environment variable using -Xms: and -Xmx:."; + + /** + * Method that removes the invalid directories in the specified directories. Note: All elements in + * dirs could be an absolute or relative against the project's base directory String path. + * + * @param project the current Maven project not null + * @param dirs the collection of String directories path that will be validated. + * @return a List of valid String directories absolute paths. + */ + public static Collection pruneDirs(MavenProject project, Collection dirs) { + final Path projectBasedir = project.getBasedir().toPath(); + + Set pruned = new LinkedHashSet<>(dirs.size()); + for (String dir : dirs) { + if (dir == null) { + continue; + } + + Path directory = projectBasedir.resolve(dir); + + if (Files.isDirectory(directory)) { + pruned.add(directory.toAbsolutePath()); + } + } + + return pruned; + } + + /** + * Method that removes the invalid files in the specified files. Note: All elements in files + * should be an absolute String path. + * + * @param files the list of String files paths that will be validated. + * @return a List of valid File objects. + */ + protected static List pruneFiles(Collection files) { + List pruned = new ArrayList<>(files.size()); + for (String f : files) { + if (!shouldPruneFile(f, pruned)) { + pruned.add(f); + } + } + + return pruned; + } + + /** + * Determine whether a file should be excluded from the provided list of paths, based on whether it exists and is + * already present in the list. + * + * @param f The files. + * @param pruned The list of pruned files.. + * @return true if the file could be pruned false otherwise. + */ + public static boolean shouldPruneFile(String f, List pruned) { + if (f != null) { + if (Files.isRegularFile(Paths.get(f)) && !pruned.contains(f)) { + return false; + } + } + + return true; + } + + /** + * Method that gets all the source files to be excluded from the javadoc on the given source paths. + * + * @param sourcePaths the path to the source files + * @param excludedPackages the package names to be excluded in the javadoc + * @return a List of the packages to be excluded in the generated javadoc + */ + protected static List getExcludedPackages( + Collection sourcePaths, Collection excludedPackages) { + List excludedNames = new ArrayList<>(); + for (Path sourcePath : sourcePaths) { + excludedNames.addAll(getExcludedPackages(sourcePath, excludedPackages)); + } + + return excludedNames; + } + + /** + * Convenience method to wrap an argument value in single quotes (i.e. '). Intended for values which + * may contain whitespaces.
+ * To prevent javadoc error, the line separator (i.e. \n) are skipped. + * + * @param value the argument value. + * @return argument with quote + */ + protected static String quotedArgument(String value) { + String arg = value; + + if (StringUtils.isNotEmpty(arg)) { + if (arg.contains("'")) { + arg = StringUtils.replace(arg, "'", "\\'"); + } + arg = "'" + arg + "'"; + + // To prevent javadoc error + arg = StringUtils.replace(arg, "\n", " "); + } + + return arg; + } + + /** + * Convenience method to format a path argument so that it is properly interpreted by the javadoc tool. Intended for + * path values which may contain whitespaces. + * + * @param value the argument value. + * @return path argument with quote + */ + protected static String quotedPathArgument(String value) { + String path = value; + + if (StringUtils.isNotEmpty(path)) { + path = path.replace('\\', '/'); + if (path.contains("'")) { + StringBuilder pathBuilder = new StringBuilder(); + pathBuilder.append('\''); + String[] split = path.split("'"); + + for (int i = 0; i < split.length; i++) { + if (i != split.length - 1) { + pathBuilder.append(split[i]).append("\\'"); + } else { + pathBuilder.append(split[i]); + } + } + pathBuilder.append('\''); + path = pathBuilder.toString(); + } else { + path = "'" + path + "'"; + } + } + + return path; + } + + /** + * Convenience method that copy all doc-files directories from javadocDir to the + * outputDirectory. + * + * @param outputDirectory the output directory + * @param javadocDir the javadoc directory + * @param excludedocfilessubdir the excludedocfilessubdir parameter + * @throws IOException if any + * @since 2.5 + */ + protected static void copyJavadocResources(File outputDirectory, File javadocDir, String excludedocfilessubdir) + throws IOException { + if (!javadocDir.isDirectory()) { + return; + } + + List excludes = new ArrayList<>(Arrays.asList(FileUtils.getDefaultExcludes())); + + if (StringUtils.isNotEmpty(excludedocfilessubdir)) { + StringTokenizer st = new StringTokenizer(excludedocfilessubdir, ":"); + String current; + while (st.hasMoreTokens()) { + current = st.nextToken(); + excludes.add("**/" + current + "/**"); + } + } + + List docFiles = FileUtils.getDirectoryNames( + javadocDir, "resources,**/doc-files", StringUtils.join(excludes.iterator(), ","), false, true); + for (String docFile : docFiles) { + File docFileOutput = new File(outputDirectory, docFile); + FileUtils.mkdir(docFileOutput.getAbsolutePath()); + FileUtils.copyDirectoryStructure(new File(javadocDir, docFile), docFileOutput); + List files = FileUtils.getFileAndDirectoryNames( + docFileOutput, StringUtils.join(excludes.iterator(), ","), null, true, true, true, true); + for (String filename : files) { + File file = new File(filename); + + if (file.isDirectory()) { + FileUtils.deleteDirectory(file); + } else { + file.delete(); + } + } + } + } + + /** + * Method that gets the files or classes that would be included in the javadocs using the subpackages parameter. + * + * @param sourceDirectory the directory where the source files are located + * @param fileList the list of all relative files found in the sourceDirectory + * @param excludePackages package names to be excluded in the javadoc + * @return a StringBuilder that contains the appended file names of the files to be included in the javadoc + */ + protected static List getIncludedFiles( + File sourceDirectory, String[] fileList, Collection excludePackages) { + List files = new ArrayList<>(); + + List excludePackagePatterns = new ArrayList<>(excludePackages.size()); + for (String excludePackage : excludePackages) { + excludePackagePatterns.add(Pattern.compile(excludePackage + .replace('.', File.separatorChar) + .replace("\\", "\\\\") + .replace("*", ".+") + .concat("[\\\\/][^\\\\/]+\\.java"))); + } + + for (String file : fileList) { + boolean excluded = false; + for (Pattern excludePackagePattern : excludePackagePatterns) { + if (excludePackagePattern.matcher(file).matches()) { + excluded = true; + break; + } + } + + if (!excluded) { + files.add(file.replace('\\', '/')); + } + } + + return files; + } + + /** + * Method that gets the complete package names (including subpackages) of the packages that were defined in the + * excludePackageNames parameter. + * + * @param sourceDirectory the directory where the source files are located + * @param excludePackagenames package names to be excluded in the javadoc + * @return a List of the packagenames to be excluded + */ + protected static Collection getExcludedPackages( + final Path sourceDirectory, Collection excludePackagenames) { + final String regexFileSeparator = File.separator.replace("\\", "\\\\"); + + final Collection fileList = new ArrayList<>(); + + try { + Files.walkFileTree(sourceDirectory, new SimpleFileVisitor() { + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { + if (file.getFileName().toString().endsWith(".java")) { + fileList.add( + sourceDirectory.relativize(file.getParent()).toString()); + } + return FileVisitResult.CONTINUE; + } + }); + } catch (IOException e) { + // noop + } + + List files = new ArrayList<>(); + for (String excludePackagename : excludePackagenames) { + // Usage of wildcard was bad specified and bad implemented, i.e. using String.contains() + // without respecting surrounding context + // Following implementation should match requirements as defined in the examples: + // - A wildcard at the beginning should match 1 or more folders + // - Any other wildcard must match exactly one folder + Pattern p = Pattern.compile(excludePackagename + .replace(".", regexFileSeparator) + .replaceFirst("^\\*", ".+") + .replace("*", "[^" + regexFileSeparator + "]+")); + + for (String aFileList : fileList) { + if (p.matcher(aFileList).matches()) { + files.add(aFileList.replace(File.separatorChar, '.')); + } + } + } + + return files; + } + + /** + * Convenience method that gets the files to be included in the javadoc. + * + * @param sourceDirectory the directory where the source files are located + * @param excludePackages the packages to be excluded in the javadocs + * @param sourceFileIncludes files to include. + * @param sourceFileExcludes files to exclude. + */ + protected static List getFilesFromSource( + File sourceDirectory, + List sourceFileIncludes, + List sourceFileExcludes, + Collection excludePackages) { + DirectoryScanner ds = new DirectoryScanner(); + if (sourceFileIncludes == null) { + sourceFileIncludes = Collections.singletonList("**/*.java"); + } + ds.setIncludes(sourceFileIncludes.toArray(new String[sourceFileIncludes.size()])); + if (sourceFileExcludes != null && sourceFileExcludes.size() > 0) { + ds.setExcludes(sourceFileExcludes.toArray(new String[sourceFileExcludes.size()])); + } + ds.setBasedir(sourceDirectory); + ds.scan(); + + String[] fileList = ds.getIncludedFiles(); + + List files = new ArrayList<>(); + if (fileList.length != 0) { + files.addAll(getIncludedFiles(sourceDirectory, fileList, excludePackages)); + } + + return files; + } + + /** + * Call the Javadoc tool and parse its output to find its version, i.e.: + * + *
+     * javadoc.exe( or.sh ) - J - version
+     * 
+ * + * @param javadocExe not null file + * @return the javadoc version as float + * @throws IOException if javadocExe is null, doesn't exist or is not a file + * @throws CommandLineException if any + * @throws IllegalArgumentException if no output was found in the command line + * @throws PatternSyntaxException if the output contains a syntax error in the regular-expression pattern. + * @see #extractJavadocVersion(String) + */ + protected static JavaVersion getJavadocVersion(File javadocExe) + throws IOException, CommandLineException, IllegalArgumentException { + if ((javadocExe == null) || (!javadocExe.exists()) || (!javadocExe.isFile())) { + throw new IOException("The javadoc executable '" + javadocExe + "' doesn't exist or is not a file. "); + } + + Commandline cmd = new Commandline(); + cmd.setExecutable(javadocExe.getAbsolutePath()); + cmd.setWorkingDirectory(javadocExe.getParentFile()); + cmd.createArg().setValue("-J-version"); + + CommandLineUtils.StringStreamConsumer out = new JavadocOutputStreamConsumer(); + CommandLineUtils.StringStreamConsumer err = new JavadocOutputStreamConsumer(); + + int exitCode = CommandLineUtils.executeCommandLine(cmd, out, err); + + if (exitCode != 0) { + StringBuilder msg = new StringBuilder("Exit code: " + exitCode + " - " + err.getOutput()); + msg.append('\n'); + msg.append("Command line was:").append(CommandLineUtils.toString(cmd.getCommandline())); + throw new CommandLineException(msg.toString()); + } + + if (StringUtils.isNotEmpty(err.getOutput())) { + return JavaVersion.parse(extractJavadocVersion(err.getOutput())); + } else if (StringUtils.isNotEmpty(out.getOutput())) { + return JavaVersion.parse(extractJavadocVersion(out.getOutput())); + } + + throw new IllegalArgumentException("No output found from the command line 'javadoc -J-version'"); + } + + private static final Pattern EXTRACT_JAVADOC_VERSION_PATTERN = + Pattern.compile("(?s).*?[^a-zA-Z](([0-9]+\\.?[0-9]*)(\\.[0-9]+)?).*"); + + /** + * Parse the output for 'javadoc -J-version' and return the javadoc version recognized.
+ * Here are some output for 'javadoc -J-version' depending the JDK used: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Output for 'javadoc -J-version' per JDK
JDKOutput for 'javadoc -J-version'
Sun 1.4java full version "1.4.2_12-b03"
Sun 1.5java full version "1.5.0_07-164"
IBM 1.4javadoc full version "J2RE 1.4.2 IBM Windows 32 build cn1420-20040626"
IBM 1.5 (French JVM)javadoc version complète de "J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a"
FreeBSD 1.5java full version "diablo-1.5.0-b01"
BEA jrockit 1.5java full version "1.5.0_11-b03"
+ * + * @param output for 'javadoc -J-version' + * @return the version of the javadoc for the output, only digits and dots + * @throws PatternSyntaxException if the output doesn't match with the output pattern + * {@code (?s).*?[^a-zA-Z]([0-9]+\\.?[0-9]*)(\\.([0-9]+))?.*}. + * @throws IllegalArgumentException if the output is null + */ + protected static String extractJavadocVersion(String output) throws IllegalArgumentException { + if (StringUtils.isEmpty(output)) { + throw new IllegalArgumentException("The output could not be null."); + } + + Pattern pattern = EXTRACT_JAVADOC_VERSION_PATTERN; + + Matcher matcher = pattern.matcher(output); + if (!matcher.matches()) { + throw new PatternSyntaxException( + "Unrecognized version of Javadoc: '" + output + "'", + pattern.pattern(), + pattern.toString().length() - 1); + } + + return matcher.group(1); + } + + private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_0 = Pattern.compile("^\\s*(\\d+)\\s*?\\s*$"); + + private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_1 = + Pattern.compile("^\\s*(\\d+)\\s*k(b)?\\s*$", Pattern.CASE_INSENSITIVE); + + private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_2 = + Pattern.compile("^\\s*(\\d+)\\s*m(b)?\\s*$", Pattern.CASE_INSENSITIVE); + + private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_3 = + Pattern.compile("^\\s*(\\d+)\\s*g(b)?\\s*$", Pattern.CASE_INSENSITIVE); + + private static final Pattern PARSE_JAVADOC_MEMORY_PATTERN_4 = + Pattern.compile("^\\s*(\\d+)\\s*t(b)?\\s*$", Pattern.CASE_INSENSITIVE); + + /** + * Parse a memory string which be used in the JVM arguments -Xms or -Xmx.
+ * Here are some supported memory string depending the JDK used: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
Memory argument support per JDK
JDKMemory argument support for -Xms or -Xmx
SUN1024k | 128m | 1g | 1t
IBM1024k | 1024b | 128m | 128mb | 1g | 1gb
BEA1024k | 1024kb | 128m | 128mb | 1g | 1gb
+ * + * @param memory the memory to be parsed, not null. + * @return the memory parsed with a supported unit. If no unit specified in the memory parameter, the + * default unit is m. The units g | gb or t | tb will be converted in + * m. + * @throws IllegalArgumentException if the memory parameter is null or doesn't match any pattern. + */ + protected static String parseJavadocMemory(String memory) throws IllegalArgumentException { + if (StringUtils.isEmpty(memory)) { + throw new IllegalArgumentException("The memory could not be null."); + } + + Matcher m0 = PARSE_JAVADOC_MEMORY_PATTERN_0.matcher(memory); + if (m0.matches()) { + return m0.group(1) + "m"; + } + + Matcher m1 = PARSE_JAVADOC_MEMORY_PATTERN_1.matcher(memory); + if (m1.matches()) { + return m1.group(1) + "k"; + } + + Matcher m2 = PARSE_JAVADOC_MEMORY_PATTERN_2.matcher(memory); + if (m2.matches()) { + return m2.group(1) + "m"; + } + + Matcher m3 = PARSE_JAVADOC_MEMORY_PATTERN_3.matcher(memory); + if (m3.matches()) { + return (Integer.parseInt(m3.group(1)) * 1024) + "m"; + } + + Matcher m4 = PARSE_JAVADOC_MEMORY_PATTERN_4.matcher(memory); + if (m4.matches()) { + return (Integer.parseInt(m4.group(1)) * 1024 * 1024) + "m"; + } + + throw new IllegalArgumentException("Could convert not to a memory size: " + memory); + } + + /** + * Validate if a charset is supported on this platform. + * + * @param charsetName the charsetName to be check. + * @return true if the given charset is supported by the JVM, false otherwise. + */ + protected static boolean validateEncoding(String charsetName) { + if (StringUtils.isEmpty(charsetName)) { + return false; + } + + try { + return Charset.isSupported(charsetName); + } catch (IllegalCharsetNameException e) { + return false; + } + } + + /** + * Auto-detect the class names of the implementation of com.sun.tools.doclets.Taglet class from a given + * jar file.
+ * Note: JAVA_HOME/lib/tools.jar is a requirement to find + * com.sun.tools.doclets.Taglet class. + * + * @param jarFile not null + * @return the list of com.sun.tools.doclets.Taglet class names from a given jarFile. + * @throws IOException if jarFile is invalid or not found, or if the JAVA_HOME/lib/tools.jar is not + * found. + * @throws ClassNotFoundException if any + * @throws NoClassDefFoundError if any + */ + protected static List getTagletClassNames(File jarFile) + throws IOException, ClassNotFoundException, NoClassDefFoundError { + List classes = getClassNamesFromJar(jarFile); + URLClassLoader cl; + + // Needed to find com.sun.tools.doclets.Taglet class + File tools = new File(System.getProperty("java.home"), "../lib/tools.jar"); + if (tools.exists() && tools.isFile()) { + cl = new URLClassLoader( + new URL[] {jarFile.toURI().toURL(), tools.toURI().toURL()}, null); + } else { + cl = new URLClassLoader(new URL[] {jarFile.toURI().toURL()}, ClassLoader.getSystemClassLoader()); + } + + List tagletClasses = new ArrayList<>(); + + Class tagletClass; + + try { + tagletClass = cl.loadClass("com.sun.tools.doclets.Taglet"); + } catch (ClassNotFoundException e) { + tagletClass = cl.loadClass("jdk.javadoc.doclet.Taglet"); + } + + for (String s : classes) { + Class c = cl.loadClass(s); + + if (tagletClass.isAssignableFrom(c) && !Modifier.isAbstract(c.getModifiers())) { + tagletClasses.add(c.getName()); + } + } + + try { + cl.close(); + } catch (IOException ex) { + // no big deal + } + + return tagletClasses; + } + + /** + * Copy the given url to the given file. + * + * @param url not null url + * @param file not null file where the url will be created + * @throws IOException if any + * @since 2.6 + */ + protected static void copyResource(URL url, File file) throws IOException { + if (file == null) { + throw new IOException("The file can't be null."); + } + if (url == null) { + throw new IOException("The url could not be null."); + } + + FileUtils.copyURLToFile(url, file); + } + + /** + * Invoke Maven for the given project file with a list of goals and properties, the output will be in the invokerlog + * file.
+ * Note: the Maven Home should be defined in the maven.home Java system property or defined in + * M2_HOME system env variables. + * + * @param log a logger could be null. + * @param localRepositoryDir the localRepository not null. + * @param projectFile a not null project file. + * @param goals a not null goals list. + * @param properties the properties for the goals, could be null. + * @param invokerLog the log file where the invoker will be written, if null using System.out. + * @param globalSettingsFile reference to settings file, could be null. + * @throws MavenInvocationException if any + * @since 2.6 + */ + protected static void invokeMaven( + Log log, + File localRepositoryDir, + File projectFile, + List goals, + Properties properties, + File invokerLog, + File globalSettingsFile) + throws MavenInvocationException { + if (projectFile == null) { + throw new IllegalArgumentException("projectFile should be not null."); + } + if (!projectFile.isFile()) { + throw new IllegalArgumentException(projectFile.getAbsolutePath() + " is not a file."); + } + if (goals == null || goals.size() == 0) { + throw new IllegalArgumentException("goals should be not empty."); + } + if (localRepositoryDir == null || !localRepositoryDir.isDirectory()) { + throw new IllegalArgumentException( + "localRepositoryDir '" + localRepositoryDir + "' should be a directory."); + } + + String mavenHome = getMavenHome(log); + if (StringUtils.isEmpty(mavenHome)) { + String msg = "Could NOT invoke Maven because no Maven Home is defined. You need to have set the M2_HOME " + + "system env variable or a maven.home Java system properties."; + if (log != null) { + log.error(msg); + } else { + System.err.println(msg); + } + return; + } + + Invoker invoker = new DefaultInvoker(); + invoker.setMavenHome(new File(mavenHome)); + invoker.setLocalRepositoryDirectory(localRepositoryDir); + + InvocationRequest request = new DefaultInvocationRequest(); + request.setBaseDirectory(projectFile.getParentFile()); + request.setPomFile(projectFile); + request.setGlobalSettingsFile(globalSettingsFile); + request.setBatchMode(true); + if (log != null) { + request.setDebug(log.isDebugEnabled()); + } else { + request.setDebug(true); + } + request.setGoals(goals); + if (properties != null) { + request.setProperties(properties); + } + File javaHome = getJavaHome(log); + if (javaHome != null) { + request.setJavaHome(javaHome); + } + + if (log != null && log.isDebugEnabled()) { + log.debug("Invoking Maven for the goals: " + goals + " with " + + (properties == null ? "no properties" : "properties=" + properties)); + } + InvocationResult result = invoke(log, invoker, request, invokerLog, goals, properties, null); + + if (result.getExitCode() != 0) { + String invokerLogContent = readFile(invokerLog, "UTF-8"); + + // see DefaultMaven + if (invokerLogContent != null + && (!invokerLogContent.contains("Scanning for projects...") + || invokerLogContent.contains(OutOfMemoryError.class.getName()))) { + if (log != null) { + log.error("Error occurred during initialization of VM, trying to use an empty MAVEN_OPTS..."); + + if (log.isDebugEnabled()) { + log.debug("Reinvoking Maven for the goals: " + goals + " with an empty MAVEN_OPTS..."); + } + } + result = invoke(log, invoker, request, invokerLog, goals, properties, ""); + } + } + + if (result.getExitCode() != 0) { + String invokerLogContent = readFile(invokerLog, "UTF-8"); + + // see DefaultMaven + if (invokerLogContent != null + && (!invokerLogContent.contains("Scanning for projects...") + || invokerLogContent.contains(OutOfMemoryError.class.getName()))) { + throw new MavenInvocationException(ERROR_INIT_VM); + } + + throw new MavenInvocationException( + "Error when invoking Maven, consult the invoker log file: " + invokerLog.getAbsolutePath()); + } + } + + /** + * Read the given file and return the content or null if an IOException occurs. + * + * @param javaFile not null + * @param encoding could be null + * @return the content with unified line separator of the given javaFile using the given encoding. + * @see FileUtils#fileRead(File, String) + * @since 2.6.1 + */ + protected static String readFile(final File javaFile, final String encoding) { + try { + return FileUtils.fileRead(javaFile, encoding); + } catch (IOException e) { + return null; + } + } + + /** + * Split the given path with colon and semi-colon, to support Solaris and Windows path. Examples: + * + *
+     * splitPath( "/home:/tmp" )     = ["/home", "/tmp"]
+     * splitPath( "/home;/tmp" )     = ["/home", "/tmp"]
+     * splitPath( "C:/home:C:/tmp" ) = ["C:/home", "C:/tmp"]
+     * splitPath( "C:/home;C:/tmp" ) = ["C:/home", "C:/tmp"]
+     * 
+ * + * @param path which can contain multiple paths separated with a colon (:) or a semi-colon + * (;), platform independent. Could be null. + * @return the path splitted by colon or semi-colon or null if path was null. + * @since 2.6.1 + */ + protected static String[] splitPath(final String path) { + if (path == null) { + return null; + } + + List subpaths = new ArrayList<>(); + PathTokenizer pathTokenizer = new PathTokenizer(path); + while (pathTokenizer.hasMoreTokens()) { + subpaths.add(pathTokenizer.nextToken()); + } + + return subpaths.toArray(new String[subpaths.size()]); + } + + /** + * Unify the given path with the current System path separator, to be platform independent. Examples: + * + *
+     * unifyPathSeparator( "/home:/tmp" ) = "/home:/tmp" (Solaris box)
+     * unifyPathSeparator( "/home:/tmp" ) = "/home;/tmp" (Windows box)
+     * 
+ * + * @param path which can contain multiple paths by separating them with a colon (:) or a semi-colon + * (;), platform independent. Could be null. + * @return the same path but separated with the current System path separator or null if path was + * null. + * @since 2.6.1 + * @see #splitPath(String) + * @see File#pathSeparator + */ + protected static String unifyPathSeparator(final String path) { + if (path == null) { + return null; + } + + return StringUtils.join(splitPath(path), File.pathSeparator); + } + + // ---------------------------------------------------------------------- + // private methods + // ---------------------------------------------------------------------- + + /** + * @param jarFile not null + * @return all class names from the given jar file. + * @throws IOException if any or if the jarFile is null or doesn't exist. + */ + private static List getClassNamesFromJar(File jarFile) throws IOException { + if (jarFile == null || !jarFile.exists() || !jarFile.isFile()) { + throw new IOException("The jar '" + jarFile + "' doesn't exist or is not a file."); + } + + List classes = new ArrayList<>(); + Pattern pattern = Pattern.compile("(?i)^(META-INF/versions/(?[0-9]+)/)?(?.+)[.]class$"); + try (JarInputStream jarStream = new JarInputStream(new FileInputStream(jarFile))) { + for (JarEntry jarEntry = jarStream.getNextJarEntry(); + jarEntry != null; + jarEntry = jarStream.getNextJarEntry()) { + Matcher matcher = pattern.matcher(jarEntry.getName()); + if (matcher.matches()) { + String version = matcher.group("v"); + if (StringUtils.isEmpty(version) || JavaVersion.JAVA_VERSION.isAtLeast(version)) { + String name = matcher.group("n"); + + classes.add(name.replaceAll("/", "\\.")); + } + } + + jarStream.closeEntry(); + } + } + + return classes; + } + + /** + * @param log could be null + * @param invoker not null + * @param request not null + * @param invokerLog not null + * @param goals not null + * @param properties could be null + * @param mavenOpts could be null + * @return the invocation result + * @throws MavenInvocationException if any + * @since 2.6 + */ + private static InvocationResult invoke( + Log log, + Invoker invoker, + InvocationRequest request, + File invokerLog, + List goals, + Properties properties, + String mavenOpts) + throws MavenInvocationException { + PrintStream ps; + OutputStream os = null; + if (invokerLog != null) { + if (log != null && log.isDebugEnabled()) { + log.debug("Using " + invokerLog.getAbsolutePath() + " to log the invoker"); + } + + try { + if (!invokerLog.exists()) { + // noinspection ResultOfMethodCallIgnored + invokerLog.getParentFile().mkdirs(); + } + os = new FileOutputStream(invokerLog); + ps = new PrintStream(os, true, "UTF-8"); + } catch (FileNotFoundException e) { + if (log != null && log.isErrorEnabled()) { + log.error("FileNotFoundException: " + e.getMessage() + ". Using System.out to log the invoker."); + } + ps = System.out; + } catch (UnsupportedEncodingException e) { + if (log != null && log.isErrorEnabled()) { + log.error("UnsupportedEncodingException: " + e.getMessage() + + ". Using System.out to log the invoker."); + } + ps = System.out; + } + } else { + if (log != null && log.isDebugEnabled()) { + log.debug("Using System.out to log the invoker."); + } + + ps = System.out; + } + + if (mavenOpts != null) { + request.setMavenOpts(mavenOpts); + } + + InvocationOutputHandler outputHandler = new PrintStreamHandler(ps, false); + request.setOutputHandler(outputHandler); + + try { + outputHandler.consumeLine("Invoking Maven for the goals: " + goals + " with " + + (properties == null ? "no properties" : "properties=" + properties)); + outputHandler.consumeLine(""); + outputHandler.consumeLine("M2_HOME=" + getMavenHome(log)); + outputHandler.consumeLine("MAVEN_OPTS=" + getMavenOpts(log)); + outputHandler.consumeLine("JAVA_HOME=" + getJavaHome(log)); + outputHandler.consumeLine("JAVA_OPTS=" + getJavaOpts(log)); + outputHandler.consumeLine(""); + } catch (IOException ioe) { + throw new MavenInvocationException("IOException while consuming invocation output", ioe); + } + + try { + return invoker.execute(request); + } finally { + IOUtil.close(os); + } + } + + /** + * @param log a logger could be null + * @return the Maven home defined in the maven.home system property or defined in M2_HOME + * system env variables or null if never set. + * @since 2.6 + */ + private static String getMavenHome(Log log) { + String mavenHome = System.getProperty("maven.home"); + if (mavenHome == null) { + try { + mavenHome = CommandLineUtils.getSystemEnvVars().getProperty("M2_HOME"); + } catch (IOException e) { + if (log != null && log.isDebugEnabled()) { + log.debug("IOException: " + e.getMessage()); + } + } + } + + File m2Home = new File(mavenHome); + if (!m2Home.exists()) { + if (log != null && log.isErrorEnabled()) { + log.error("Cannot find Maven application directory. Either specify 'maven.home' system property, or " + + "M2_HOME environment variable."); + } + } + + return mavenHome; + } + + /** + * @param log a logger could be null + * @return the MAVEN_OPTS env variable value + * @since 2.6 + */ + private static String getMavenOpts(Log log) { + String mavenOpts = null; + try { + mavenOpts = CommandLineUtils.getSystemEnvVars().getProperty("MAVEN_OPTS"); + } catch (IOException e) { + if (log != null && log.isDebugEnabled()) { + log.debug("IOException: " + e.getMessage()); + } + } + + return mavenOpts; + } + + /** + * @param log a logger could be null + * @return the JAVA_HOME from System.getProperty( "java.home" ) By default, + * System.getProperty( "java.home" ) = JRE_HOME and JRE_HOME should be in the + * JDK_HOME + * @since 2.6 + */ + private static File getJavaHome(Log log) { + File javaHome = null; + + String javaHomeValue = null; + try { + javaHomeValue = CommandLineUtils.getSystemEnvVars().getProperty("JAVA_HOME"); + } catch (IOException e) { + if (log != null && log.isDebugEnabled()) { + log.debug("IOException: " + e.getMessage()); + } + } + + // if maven.home is set, we can assume JAVA_HOME must be used for testing + if (System.getProperty("maven.home") == null || javaHomeValue == null) { + // JEP220 (Java9) restructured the JRE/JDK runtime image + if (SystemUtils.IS_OS_MAC_OSX || JavaVersion.JAVA_VERSION.isAtLeast("9")) { + javaHome = SystemUtils.getJavaHome(); + } else { + javaHome = new File(SystemUtils.getJavaHome(), ".."); + } + } + + if (javaHome == null || !javaHome.exists()) { + javaHome = new File(javaHomeValue); + } + + if (javaHome == null || !javaHome.exists()) { + if (log != null && log.isErrorEnabled()) { + log.error("Cannot find Java application directory. Either specify 'java.home' system property, or " + + "JAVA_HOME environment variable."); + } + } + + return javaHome; + } + + /** + * @param log a logger could be null + * @return the JAVA_OPTS env variable value + * @since 2.6 + */ + private static String getJavaOpts(Log log) { + String javaOpts = null; + try { + javaOpts = CommandLineUtils.getSystemEnvVars().getProperty("JAVA_OPTS"); + } catch (IOException e) { + if (log != null && log.isDebugEnabled()) { + log.debug("IOException: " + e.getMessage()); + } + } + + return javaOpts; + } + + /** + * A Path tokenizer takes a path and returns the components that make up that path. The path can use path separators + * of either ':' or ';' and file separators of either '/' or '\'. + * + * @version revision 439418 taken on 2009-09-12 from Ant Project (see + * http://svn.apache.org/repos/asf/ant/core/trunk/src/main/org/apache/tools/ant/PathTokenizer.java) + */ + private static class PathTokenizer { + /** + * A tokenizer to break the string up based on the ':' or ';' separators. + */ + private StringTokenizer tokenizer; + + /** + * A String which stores any path components which have been read ahead due to DOS filesystem compensation. + */ + private String lookahead = null; + + /** + * A boolean that determines if we are running on Novell NetWare, which exhibits slightly different path name + * characteristics (multi-character volume / drive names) + */ + private boolean onNetWare = Os.isFamily("netware"); + + /** + * Flag to indicate whether or not we are running on a platform with a DOS style filesystem + */ + private boolean dosStyleFilesystem; + + /** + * Constructs a path tokenizer for the specified path. + * + * @param path The path to tokenize. Must not be null. + */ + PathTokenizer(String path) { + if (onNetWare) { + // For NetWare, use the boolean=true mode, so we can use delimiter + // information to make a better decision later. + tokenizer = new StringTokenizer(path, ":;", true); + } else { + // on Windows and Unix, we can ignore delimiters and still have + // enough information to tokenize correctly. + tokenizer = new StringTokenizer(path, ":;", false); + } + dosStyleFilesystem = File.pathSeparatorChar == ';'; + } + + /** + * Tests if there are more path elements available from this tokenizer's path. If this method returns + * true, then a subsequent call to nextToken will successfully return a token. + * + * @return true if and only if there is at least one token in the string after the current + * position; false otherwise. + */ + public boolean hasMoreTokens() { + return lookahead != null || tokenizer.hasMoreTokens(); + } + + /** + * Returns the next path element from this tokenizer. + * + * @return the next path element from this tokenizer. + * @exception NoSuchElementException if there are no more elements in this tokenizer's path. + */ + public String nextToken() throws NoSuchElementException { + String token; + if (lookahead != null) { + token = lookahead; + lookahead = null; + } else { + token = tokenizer.nextToken().trim(); + } + + if (!onNetWare) { + if (token.length() == 1 + && Character.isLetter(token.charAt(0)) + && dosStyleFilesystem + && tokenizer.hasMoreTokens()) { + // we are on a dos style system so this path could be a drive + // spec. We look at the next token + String nextToken = tokenizer.nextToken().trim(); + if (nextToken.startsWith("\\") || nextToken.startsWith("/")) { + // we know we are on a DOS style platform and the next path + // starts with a slash or backslash, so we know this is a + // drive spec + token += ":" + nextToken; + } else { + // store the token just read for next time + lookahead = nextToken; + } + } + } else { + // we are on NetWare, tokenizing is handled a little differently, + // due to the fact that NetWare has multiple-character volume names. + if (token.equals(File.pathSeparator) || token.equals(":")) { + // ignore ";" and get the next token + token = tokenizer.nextToken().trim(); + } + + if (tokenizer.hasMoreTokens()) { + // this path could be a drive spec, so look at the next token + String nextToken = tokenizer.nextToken().trim(); + + // make sure we aren't going to get the path separator next + if (!nextToken.equals(File.pathSeparator)) { + if (nextToken.equals(":")) { + if (!token.startsWith("/") + && !token.startsWith("\\") + && !token.startsWith(".") + && !token.startsWith("..")) { + // it indeed is a drive spec, get the next bit + String oneMore = tokenizer.nextToken().trim(); + if (!oneMore.equals(File.pathSeparator)) { + token += ":" + oneMore; + } else { + token += ":"; + lookahead = oneMore; + } + } + // implicit else: ignore the ':' since we have either a + // UNIX or a relative path + } else { + // store the token just read for next time + lookahead = nextToken; + } + } + } + } + return token; + } + } + + /** + * Ignores line like 'Picked up JAVA_TOOL_OPTIONS: ...' as can happen on CI servers. + * + * @author Robert Scholte + * @since 3.0.1 + */ + protected static class JavadocOutputStreamConsumer extends CommandLineUtils.StringStreamConsumer { + @Override + public void consumeLine(String line) { + if (!line.startsWith("Picked up ")) { + super.consumeLine(line); + } + } + } + + static List toList(String src) { + return toList(src, null, null); + } + + static List toList(String src, String elementPrefix, String elementSuffix) { + if (StringUtils.isEmpty(src)) { + return null; + } + + List result = new ArrayList<>(); + + StringTokenizer st = new StringTokenizer(src, "[,:;]"); + StringBuilder sb = new StringBuilder(256); + while (st.hasMoreTokens()) { + sb.setLength(0); + if (StringUtils.isNotEmpty(elementPrefix)) { + sb.append(elementPrefix); + } + + sb.append(st.nextToken()); + + if (StringUtils.isNotEmpty(elementSuffix)) { + sb.append(elementSuffix); + } + + result.add(sb.toString()); + } + + return result; + } + + static List toList(T[] multiple) { + return toList(null, multiple); + } + + static List toList(T single, T[] multiple) { + if (single == null && (multiple == null || multiple.length < 1)) { + return null; + } + + List result = new ArrayList<>(); + if (single != null) { + result.add(single); + } + + if (multiple != null && multiple.length > 0) { + result.addAll(Arrays.asList(multiple)); + } + + return result; + } + + // TODO: move to plexus-utils or use something appropriate from there + public static String toRelative(File basedir, String absolutePath) { + String relative; + + absolutePath = absolutePath.replace('\\', '/'); + String basedirPath = basedir.getAbsolutePath().replace('\\', '/'); + + if (absolutePath.startsWith(basedirPath)) { + relative = absolutePath.substring(basedirPath.length()); + if (relative.startsWith("/")) { + relative = relative.substring(1); + } + if (relative.length() <= 0) { + relative = "."; + } + } else { + relative = absolutePath; + } + + return relative; + } + + /** + * Convenience method to determine that a collection is not empty or null. + * @param collection the collection to verify + * @return {@code true} if not {@code null} and not empty, otherwise {@code false} + */ + public static boolean isNotEmpty(final Collection collection) { + return collection != null && !collection.isEmpty(); + } + + /** + * Convenience method to determine that a collection is empty or null. + * @param collection the collection to verify + * @return {@code true} if {@code null} or empty, otherwise {@code false} + */ + public static boolean isEmpty(final Collection collection) { + return collection == null || collection.isEmpty(); + } + + /** + * Execute an Http request at the given URL, follows redirects, and returns the last redirect locations. For URLs + * that aren't http/https, this does nothing and simply returns the given URL unchanged. + * + * @param url URL. + * @param settings Maven settings. + * @return Last redirect location. + * @throws IOException if there was an error during the Http request. + */ + protected static URL getRedirectUrl(URL url, Settings settings) throws IOException { + String protocol = url.getProtocol(); + if (!"http".equals(protocol) && !"https".equals(protocol)) { + return url; + } + + try (CloseableHttpClient httpClient = createHttpClient(settings, url)) { + HttpClientContext httpContext = HttpClientContext.create(); + HttpGet httpMethod = new HttpGet(url.toString()); + HttpResponse response = httpClient.execute(httpMethod, httpContext); + int status = response.getStatusLine().getStatusCode(); + if (status != HttpStatus.SC_OK) { + throw new FileNotFoundException( + "Unexpected HTTP status code " + status + " getting resource " + url.toExternalForm() + "."); + } + + List redirects = httpContext.getRedirectLocations(); + + if (isEmpty(redirects)) { + return url; + } else { + URI last = redirects.get(redirects.size() - 1); + + // URI must refer to directory, so prevent redirects to index.html + // see https://issues.apache.org/jira/browse/MJAVADOC-539 + String truncate = "index.html"; + if (last.getPath().endsWith("/" + truncate)) { + try { + String fixedPath = + last.getPath().substring(0, last.getPath().length() - truncate.length()); + last = new URI( + last.getScheme(), last.getAuthority(), fixedPath, last.getQuery(), last.getFragment()); + } catch (URISyntaxException ex) { + // not supposed to happen, but when it does just keep the last URI + } + } + return last.toURL(); + } + } + } + + /** + * Validates an URL to point to a valid package-list resource. + * + * @param url The URL to validate. + * @param settings The user settings used to configure the connection to the URL or {@code null}. + * @param validateContent true to validate the content of the package-list resource; + * false to only check the existence of the package-list resource. + * @return true if url points to a valid package-list resource; + * false else. + * @throws IOException if reading the resource fails. + * @see #createHttpClient(org.apache.maven.settings.Settings, java.net.URL) + * @since 2.8 + */ + protected static boolean isValidPackageList(URL url, Settings settings, boolean validateContent) + throws IOException { + if (url == null) { + throw new IllegalArgumentException("The url is null"); + } + + try (BufferedReader reader = getReader(url, settings)) { + if (validateContent) { + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + if (!isValidPackageName(line)) { + return false; + } + } + } + return true; + } + } + + protected static boolean isValidElementList(URL url, Settings settings, boolean validateContent) + throws IOException { + if (url == null) { + throw new IllegalArgumentException("The url is null"); + } + + try (BufferedReader reader = getReader(url, settings)) { + if (validateContent) { + for (String line = reader.readLine(); line != null; line = reader.readLine()) { + if (line.startsWith("module:")) { + continue; + } + + if (!isValidPackageName(line)) { + return false; + } + } + } + return true; + } + } + + private static BufferedReader getReader(URL url, Settings settings) throws IOException { + BufferedReader reader = null; + + if ("file".equals(url.getProtocol())) { + // Intentionally using the platform default encoding here since this is what Javadoc uses internally. + reader = new BufferedReader(new InputStreamReader(url.openStream())); + } else { + // http, https... + final CloseableHttpClient httpClient = createHttpClient(settings, url); + + final HttpGet httpMethod = new HttpGet(url.toString()); + + HttpResponse response; + HttpClientContext httpContext = HttpClientContext.create(); + try { + response = httpClient.execute(httpMethod, httpContext); + } catch (SocketTimeoutException e) { + // could be a sporadic failure, one more retry before we give up + response = httpClient.execute(httpMethod, httpContext); + } + + int status = response.getStatusLine().getStatusCode(); + if (status != HttpStatus.SC_OK) { + throw new FileNotFoundException( + "Unexpected HTTP status code " + status + " getting resource " + url.toExternalForm() + "."); + } else { + int pos = url.getPath().lastIndexOf('/'); + List redirects = httpContext.getRedirectLocations(); + if (pos >= 0 && isNotEmpty(redirects)) { + URI location = redirects.get(redirects.size() - 1); + String suffix = url.getPath().substring(pos); + // Redirections shall point to the same file, e.g. /package-list + if (!location.getPath().endsWith(suffix)) { + throw new FileNotFoundException(url.toExternalForm() + " redirects to " + + location.toURL().toExternalForm() + "."); + } + } + } + + // Intentionally using the platform default encoding here since this is what Javadoc uses internally. + reader = new BufferedReader( + new InputStreamReader(response.getEntity().getContent())) { + @Override + public void close() throws IOException { + super.close(); + + if (httpMethod != null) { + httpMethod.releaseConnection(); + } + if (httpClient != null) { + httpClient.close(); + } + } + }; + } + + return reader; + } + + private static boolean isValidPackageName(String str) { + if (StringUtils.isEmpty(str)) { + // unnamed package is valid (even if bad practice :) ) + return true; + } + + int idx; + while ((idx = str.indexOf('.')) != -1) { + if (!isValidClassName(str.substring(0, idx))) { + return false; + } + + str = str.substring(idx + 1); + } + + return isValidClassName(str); + } + + private static boolean isValidClassName(String str) { + if (StringUtils.isEmpty(str) || !Character.isJavaIdentifierStart(str.charAt(0))) { + return false; + } + + for (int i = str.length() - 1; i > 0; i--) { + if (!Character.isJavaIdentifierPart(str.charAt(i))) { + return false; + } + } + + return true; + } + + /** + * Creates a new {@code HttpClient} instance. + * + * @param settings The settings to use for setting up the client or {@code null}. + * @param url The {@code URL} to use for setting up the client or {@code null}. + * @return A new {@code HttpClient} instance. + * @see #DEFAULT_TIMEOUT + * @since 2.8 + */ + private static CloseableHttpClient createHttpClient(Settings settings, URL url) { + HttpClientBuilder builder = HttpClients.custom(); + + Registry csfRegistry = RegistryBuilder.create() + .register("http", PlainConnectionSocketFactory.getSocketFactory()) + .register("https", SSLConnectionSocketFactory.getSystemSocketFactory()) + .build(); + + builder.setConnectionManager(new PoolingHttpClientConnectionManager(csfRegistry)); + builder.setDefaultRequestConfig(RequestConfig.custom() + .setSocketTimeout(DEFAULT_TIMEOUT) + .setConnectTimeout(DEFAULT_TIMEOUT) + .setCircularRedirectsAllowed(true) + .setCookieSpec(CookieSpecs.IGNORE_COOKIES) + .build()); + + // Some web servers don't allow the default user-agent sent by httpClient + builder.setUserAgent("Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)"); + + // Some server reject requests that do not have an Accept header + builder.setDefaultHeaders(Arrays.asList(new BasicHeader(HttpHeaders.ACCEPT, "*/*"))); + + if (settings != null && settings.getActiveProxy() != null) { + Proxy activeProxy = settings.getActiveProxy(); + + ProxyInfo proxyInfo = new ProxyInfo(); + proxyInfo.setNonProxyHosts(activeProxy.getNonProxyHosts()); + + if (StringUtils.isNotEmpty(activeProxy.getHost()) + && (url == null || !ProxyUtils.validateNonProxyHosts(proxyInfo, url.getHost()))) { + HttpHost proxy = new HttpHost(activeProxy.getHost(), activeProxy.getPort()); + builder.setProxy(proxy); + + if (StringUtils.isNotEmpty(activeProxy.getUsername()) && activeProxy.getPassword() != null) { + Credentials credentials = + new UsernamePasswordCredentials(activeProxy.getUsername(), activeProxy.getPassword()); + + CredentialsProvider credentialsProvider = new BasicCredentialsProvider(); + credentialsProvider.setCredentials(AuthScope.ANY, credentials); + builder.setDefaultCredentialsProvider(credentialsProvider); + } + } + } + return builder.build(); + } + + static boolean equalsIgnoreCase(String value, String... strings) { + for (String s : strings) { + if (s.equalsIgnoreCase(value)) { + return true; + } + } + return false; + } + + static boolean equals(String value, String... strings) { + for (String s : strings) { + if (s.equals(value)) { + return true; + } + } + return false; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/JavadocVersion.java b/src/main/java/org/apache/maven/plugins/javadoc/JavadocVersion.java index 27661b90b..743fea1cb 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/JavadocVersion.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/JavadocVersion.java @@ -1,89 +1,80 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.codehaus.plexus.util.StringUtils; - -/** - * Once the plugin requires Java9, this class can be replaced with java.lang.Runtime.Version - *

- * Note: Ensure the methods match, although parse+compareTo+toString should be enough. - *

- * - * - * @author Robert Scholte - * @since 3.0.0 - * @deprecated Use {@link org.codehaus.plexus.languages.java.version.JavaVersion} instead - */ -@Deprecated -public class JavadocVersion implements Comparable -{ - private String rawVersion; - - private JavadocVersion( String rawVersion ) - { - if ( StringUtils.isEmpty( rawVersion ) ) - { - throw new IllegalArgumentException( "The rawVersion could not be null." ); - } - this.rawVersion = rawVersion; - } - - /** - * Parser only the version-scheme. - * - * @param s the version string - * @return the version wrapped in a JavadocVersion - */ - static JavadocVersion parse( String s ) - { - return new JavadocVersion( s ); - } - - @Override - public int compareTo( JavadocVersion other ) - { - String[] thisSegments = this.rawVersion.split( "\\." ); - String[] otherSegments = other.rawVersion.split( "\\." ); - - int minSegments = Math.min( thisSegments.length, otherSegments.length ); - - for ( int index = 0; index < minSegments; index++ ) - { - int thisValue = Integer.parseInt( thisSegments[index] ); - int otherValue = Integer.parseInt( otherSegments[index] ); - - int compareValue = Integer.compare( thisValue, otherValue ); - - if ( compareValue != 0 ) - { - return compareValue; - } - } - - return ( thisSegments.length - otherSegments.length ); - } - - @Override - public String toString() - { - return rawVersion; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import org.codehaus.plexus.util.StringUtils; + +/** + * Once the plugin requires Java9, this class can be replaced with java.lang.Runtime.Version + *

+ * Note: Ensure the methods match, although parse+compareTo+toString should be enough. + *

+ * + * + * @author Robert Scholte + * @since 3.0.0 + * @deprecated Use {@link org.codehaus.plexus.languages.java.version.JavaVersion} instead + */ +@Deprecated +public class JavadocVersion implements Comparable { + private String rawVersion; + + private JavadocVersion(String rawVersion) { + if (StringUtils.isEmpty(rawVersion)) { + throw new IllegalArgumentException("The rawVersion could not be null."); + } + this.rawVersion = rawVersion; + } + + /** + * Parser only the version-scheme. + * + * @param s the version string + * @return the version wrapped in a JavadocVersion + */ + static JavadocVersion parse(String s) { + return new JavadocVersion(s); + } + + @Override + public int compareTo(JavadocVersion other) { + String[] thisSegments = this.rawVersion.split("\\."); + String[] otherSegments = other.rawVersion.split("\\."); + + int minSegments = Math.min(thisSegments.length, otherSegments.length); + + for (int index = 0; index < minSegments; index++) { + int thisValue = Integer.parseInt(thisSegments[index]); + int otherValue = Integer.parseInt(otherSegments[index]); + + int compareValue = Integer.compare(thisValue, otherValue); + + if (compareValue != 0) { + return compareValue; + } + } + + return (thisSegments.length - otherSegments.length); + } + + @Override + public String toString() { + return rawVersion; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/ResourcesBundleMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/ResourcesBundleMojo.java index 4ba0c0bfe..d93926e5b 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/ResourcesBundleMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/ResourcesBundleMojo.java @@ -1,143 +1,131 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Component; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProjectHelper; -import org.codehaus.plexus.archiver.Archiver; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.archiver.manager.ArchiverManager; -import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; -import org.codehaus.plexus.archiver.util.DefaultFileSet; - -import java.io.File; -import java.io.IOException; - -/** - * Bundle {@link AbstractJavadocMojo#javadocDirectory}, along with javadoc configuration options such - * as taglet, doclet, and link information into a deployable artifact. This artifact can then be consumed - * by the javadoc plugin mojos when used by the includeDependencySources option, to generate - * javadocs that are somewhat consistent with those generated in the original project itself. - * - * @since 2.7 - */ -@Mojo( name = "resource-bundle", defaultPhase = LifecyclePhase.PACKAGE, - requiresDependencyResolution = ResolutionScope.COMPILE, threadSafe = true ) -public class ResourcesBundleMojo -extends AbstractJavadocMojo -{ - - /** - * Bundle options path. - */ - public static final String BUNDLE_OPTIONS_PATH = "META-INF/maven/javadoc-options.xml"; - - /** - * Resources directory path. - */ - public static final String RESOURCES_DIR_PATH = "resources"; - - /** - * Base name of artifacts produced by this project. This will be combined with - * {@link ResourcesBundleMojo#getAttachmentClassifier()} to produce the name for this bundle - * jar. - */ - @Parameter( defaultValue = "${project.build.finalName}", readonly = true ) - private String finalName; - - /** - * Helper component to provide an easy mechanism for attaching an artifact to the project for - * installation/deployment. - */ - @Component - private MavenProjectHelper projectHelper; - - /** - * Archiver manager, used to manage jar builder. - */ - @Component - private ArchiverManager archiverManager; - - /** - * Assemble a new {@link org.apache.maven.plugins.javadoc.options.JavadocOptions JavadocOptions} instance that - * contains the configuration options in this - * mojo, which are a subset of those provided in derivatives of the {@link AbstractJavadocMojo} - * class (most of the javadoc mojos, in other words). Then, bundle the contents of the - * javadocDirectory along with the assembled JavadocOptions instance (serialized to - * META-INF/maven/javadoc-options.xml) into a project attachment for installation/deployment. - * - * {@inheritDoc} - * @see org.apache.maven.plugin.Mojo#execute() - */ - @Override - public void doExecute() - throws MojoExecutionException, MojoFailureException - { - try - { - buildJavadocOptions(); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Failed to generate javadoc-options file: " + e.getMessage(), e ); - } - - Archiver archiver; - try - { - archiver = archiverManager.getArchiver( "jar" ); - } - catch ( NoSuchArchiverException e ) - { - throw new MojoExecutionException( "Failed to retrieve jar archiver component from manager.", e ); - } - - File optionsFile = getJavadocOptionsFile(); - File bundleFile = - new File( getProject().getBuild().getDirectory(), finalName + "-" + getAttachmentClassifier() + ".jar" ); - try - { - archiver.addFile( optionsFile, BUNDLE_OPTIONS_PATH ); - - File javadocDir = getJavadocDirectory(); - if ( javadocDir.isDirectory() ) - { - DefaultFileSet fileSet = DefaultFileSet.fileSet( javadocDir ).prefixed( RESOURCES_DIR_PATH + "/" ); - archiver.addFileSet( fileSet ); - } - - archiver.setDestFile( bundleFile ); - archiver.createArchive(); - } - catch ( ArchiverException | IOException e ) - { - throw new MojoExecutionException( "Failed to assemble javadoc-resources bundle archive. Reason: " - + e.getMessage(), e ); - } - - projectHelper.attachArtifact( getProject(), bundleFile, getAttachmentClassifier() ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.io.IOException; + +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Component; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.project.MavenProjectHelper; +import org.codehaus.plexus.archiver.Archiver; +import org.codehaus.plexus.archiver.ArchiverException; +import org.codehaus.plexus.archiver.manager.ArchiverManager; +import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; +import org.codehaus.plexus.archiver.util.DefaultFileSet; + +/** + * Bundle {@link AbstractJavadocMojo#javadocDirectory}, along with javadoc configuration options such + * as taglet, doclet, and link information into a deployable artifact. This artifact can then be consumed + * by the javadoc plugin mojos when used by the includeDependencySources option, to generate + * javadocs that are somewhat consistent with those generated in the original project itself. + * + * @since 2.7 + */ +@Mojo( + name = "resource-bundle", + defaultPhase = LifecyclePhase.PACKAGE, + requiresDependencyResolution = ResolutionScope.COMPILE, + threadSafe = true) +public class ResourcesBundleMojo extends AbstractJavadocMojo { + + /** + * Bundle options path. + */ + public static final String BUNDLE_OPTIONS_PATH = "META-INF/maven/javadoc-options.xml"; + + /** + * Resources directory path. + */ + public static final String RESOURCES_DIR_PATH = "resources"; + + /** + * Base name of artifacts produced by this project. This will be combined with + * {@link ResourcesBundleMojo#getAttachmentClassifier()} to produce the name for this bundle + * jar. + */ + @Parameter(defaultValue = "${project.build.finalName}", readonly = true) + private String finalName; + + /** + * Helper component to provide an easy mechanism for attaching an artifact to the project for + * installation/deployment. + */ + @Component + private MavenProjectHelper projectHelper; + + /** + * Archiver manager, used to manage jar builder. + */ + @Component + private ArchiverManager archiverManager; + + /** + * Assemble a new {@link org.apache.maven.plugins.javadoc.options.JavadocOptions JavadocOptions} instance that + * contains the configuration options in this + * mojo, which are a subset of those provided in derivatives of the {@link AbstractJavadocMojo} + * class (most of the javadoc mojos, in other words). Then, bundle the contents of the + * javadocDirectory along with the assembled JavadocOptions instance (serialized to + * META-INF/maven/javadoc-options.xml) into a project attachment for installation/deployment. + * + * {@inheritDoc} + * @see org.apache.maven.plugin.Mojo#execute() + */ + @Override + public void doExecute() throws MojoExecutionException, MojoFailureException { + try { + buildJavadocOptions(); + } catch (IOException e) { + throw new MojoExecutionException("Failed to generate javadoc-options file: " + e.getMessage(), e); + } + + Archiver archiver; + try { + archiver = archiverManager.getArchiver("jar"); + } catch (NoSuchArchiverException e) { + throw new MojoExecutionException("Failed to retrieve jar archiver component from manager.", e); + } + + File optionsFile = getJavadocOptionsFile(); + File bundleFile = + new File(getProject().getBuild().getDirectory(), finalName + "-" + getAttachmentClassifier() + ".jar"); + try { + archiver.addFile(optionsFile, BUNDLE_OPTIONS_PATH); + + File javadocDir = getJavadocDirectory(); + if (javadocDir.isDirectory()) { + DefaultFileSet fileSet = DefaultFileSet.fileSet(javadocDir).prefixed(RESOURCES_DIR_PATH + "/"); + archiver.addFileSet(fileSet); + } + + archiver.setDestFile(bundleFile); + archiver.createArchive(); + } catch (ArchiverException | IOException e) { + throw new MojoExecutionException( + "Failed to assemble javadoc-resources bundle archive. Reason: " + e.getMessage(), e); + } + + projectHelper.attachArtifact(getProject(), bundleFile, getAttachmentClassifier()); + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/StaleHelper.java b/src/main/java/org/apache/maven/plugins/javadoc/StaleHelper.java index a5aa5864c..86cc52acf 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/StaleHelper.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/StaleHelper.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import java.io.File; import java.io.IOException; @@ -40,8 +39,7 @@ * Helper class to compute and write data used to detect a * stale javadoc. */ -public class StaleHelper -{ +public class StaleHelper { /** * Compute the data used to detect a stale javadoc @@ -50,82 +48,62 @@ public class StaleHelper * @return the stale data * @throws MavenReportException if an error occurs */ - public static String getStaleData( Commandline cmd ) - throws MavenReportException - { - try - { + public static String getStaleData(Commandline cmd) throws MavenReportException { + try { List ignored = new ArrayList<>(); List options = new ArrayList<>(); Path dir = cmd.getWorkingDirectory().toPath().toAbsolutePath().normalize(); String[] args = cmd.getArguments(); - Collections.addAll( options, args ); - + Collections.addAll(options, args); + final Charset cs; - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "9" ) - && JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "12" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9") + && JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("12")) { cs = StandardCharsets.UTF_8; - } - else - { + } else { cs = Charset.defaultCharset(); } - - for ( String arg : args ) - { - if ( arg.startsWith( "@" ) ) - { - String name = arg.substring( 1 ); - options.addAll( Files.readAllLines( dir.resolve( name ), cs ) ); - ignored.add( name ); + + for (String arg : args) { + if (arg.startsWith("@")) { + String name = arg.substring(1); + options.addAll(Files.readAllLines(dir.resolve(name), cs)); + ignored.add(name); } } - List state = new ArrayList<>( options ); + List state = new ArrayList<>(options); boolean cp = false; boolean sp = false; - for ( String arg : options ) - { - if ( cp ) - { - String s = unquote( arg ); - for ( String ps : s.split( File.pathSeparator ) ) - { - Path p = dir.resolve( ps ); - state.add( p + " = " + lastmod( p ) ); + for (String arg : options) { + if (cp) { + String s = unquote(arg); + for (String ps : s.split(File.pathSeparator)) { + Path p = dir.resolve(ps); + state.add(p + " = " + lastmod(p)); } - } - else if ( sp ) - { - String s = unquote( arg ); - for ( String ps : s.split( File.pathSeparator ) ) - { - Path p = dir.resolve( ps ); - for ( Path c : walk( p ) ) - { - if ( Files.isRegularFile( c ) ) - { - state.add( c + " = " + lastmod( c ) ); + } else if (sp) { + String s = unquote(arg); + for (String ps : s.split(File.pathSeparator)) { + Path p = dir.resolve(ps); + for (Path c : walk(p)) { + if (Files.isRegularFile(c)) { + state.add(c + " = " + lastmod(c)); } } - state.add( p + " = " + lastmod( p ) ); + state.add(p + " = " + lastmod(p)); } } - cp = "-classpath".equals( arg ); - sp = "-sourcepath".equals( arg ); + cp = "-classpath".equals(arg); + sp = "-sourcepath".equals(arg); } - for ( Path p : walk( dir ) ) - { - if ( Files.isRegularFile( p ) && !ignored.contains( p.getFileName().toString() ) ) - { - state.add( p + " = " + lastmod( p ) ); + for (Path p : walk(dir)) { + if (Files.isRegularFile(p) && !ignored.contains(p.getFileName().toString())) { + state.add(p + " = " + lastmod(p)); } } - return StringUtils.join( state.iterator(), SystemUtils.LINE_SEPARATOR ); - } - catch ( Exception e ) - { - throw new MavenReportException( "Unable to compute stale date", e ); + return StringUtils.join(state.iterator(), SystemUtils.LINE_SEPARATOR); + } catch (Exception e) { + throw new MavenReportException("Unable to compute stale date", e); } } @@ -136,60 +114,41 @@ else if ( sp ) * @param path the stale data path * @throws MavenReportException if an error occurs */ - public static void writeStaleData( Commandline cmd, Path path ) - throws MavenReportException - { - try - { - String curdata = getStaleData( cmd ); - Files.createDirectories( path.getParent() ); - Files.write( path, Collections.singleton( curdata ), Charset.defaultCharset() ); - } - catch ( IOException e ) - { - throw new MavenReportException( "Error checking stale data", e ); + public static void writeStaleData(Commandline cmd, Path path) throws MavenReportException { + try { + String curdata = getStaleData(cmd); + Files.createDirectories(path.getParent()); + Files.write(path, Collections.singleton(curdata), Charset.defaultCharset()); + } catch (IOException e) { + throw new MavenReportException("Error checking stale data", e); } } - private static Collection walk( Path dir ) - { + private static Collection walk(Path dir) { Collection paths = new ArrayList<>(); - try ( DirectoryStream directoryStream = Files.newDirectoryStream( dir ) ) - { - for ( Path p : directoryStream ) - { - paths.add( p ); + try (DirectoryStream directoryStream = Files.newDirectoryStream(dir)) { + for (Path p : directoryStream) { + paths.add(p); } return paths; - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } - private static String unquote( String s ) - { - if ( s.startsWith( "'" ) && s.endsWith( "'" ) ) - { - return s.substring( 1, s.length() - 1 ).replaceAll( "\\\\'", "'" ); - } - else - { + private static String unquote(String s) { + if (s.startsWith("'") && s.endsWith("'")) { + return s.substring(1, s.length() - 1).replaceAll("\\\\'", "'"); + } else { return s; } } - private static long lastmod( Path p ) - { - try - { - return Files.getLastModifiedTime( p ).toMillis(); - } - catch ( IOException e ) - { + private static long lastmod(Path p) { + try { + return Files.getLastModifiedTime(p).toMillis(); + } catch (IOException e) { return 0; } } - } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/SystemUtils.java b/src/main/java/org/apache/maven/plugins/javadoc/SystemUtils.java index 84675b345..d17addba9 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/SystemUtils.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/SystemUtils.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,18 +16,18 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import java.io.File; /** * Contains several OS-specific methods from Commons-Lang3's SystemUtils. We don't want to use that class because it * uses enums for Java versions, which implies that with every new Java version a new commons-lang3 is required. - * + * * @author Robert Scholte * @since 3.0.1 */ -class SystemUtils -{ +class SystemUtils { /** *

* The {@code os.name} System Property. Operating system name. @@ -46,7 +44,7 @@ class SystemUtils * * @since Java 1.1 */ - public static final String OS_NAME = getSystemProperty( "os.name" ); + public static final String OS_NAME = getSystemProperty("os.name"); /** * The prefix String for all Windows OS. @@ -61,7 +59,7 @@ class SystemUtils * The field will return {@code false} if {@code OS_NAME} is {@code null}. *

*/ - public static final boolean IS_OS_AIX = getOSMatchesName( "AIX" ); + public static final boolean IS_OS_AIX = getOSMatchesName("AIX"); /** *

@@ -71,7 +69,7 @@ class SystemUtils * The field will return {@code false} if {@code OS_NAME} is {@code null}. *

*/ - public static final boolean IS_OS_MAC_OSX = getOSMatchesName( "Mac OS X" ); + public static final boolean IS_OS_MAC_OSX = getOSMatchesName("Mac OS X"); /** *

@@ -81,7 +79,7 @@ class SystemUtils * The field will return {@code false} if {@code OS_NAME} is {@code null}. *

*/ - public static final boolean IS_OS_WINDOWS = getOSMatchesName( OS_NAME_WINDOWS_PREFIX ); + public static final boolean IS_OS_WINDOWS = getOSMatchesName(OS_NAME_WINDOWS_PREFIX); /** * The System property key for the Java home directory. @@ -104,7 +102,7 @@ class SystemUtils * * @since Java 1.1 */ - public static final String LINE_SEPARATOR = getSystemProperty( "line.separator" ); + public static final String LINE_SEPARATOR = getSystemProperty("line.separator"); /** * Decides if the operating system matches. @@ -112,9 +110,8 @@ class SystemUtils * @param osNamePrefix the prefix for the os name * @return true if matches, or false if not or can't determine */ - private static boolean getOSMatchesName( final String osNamePrefix ) - { - return isOSNameMatch( OS_NAME, osNamePrefix ); + private static boolean getOSMatchesName(final String osNamePrefix) { + return isOSNameMatch(OS_NAME, osNamePrefix); } /** @@ -127,13 +124,11 @@ private static boolean getOSMatchesName( final String osNamePrefix ) * @param osNamePrefix the prefix for the expected OS name * @return true if matches, or false if not or can't determine */ - static boolean isOSNameMatch( final String osName, final String osNamePrefix ) - { - if ( osName == null ) - { + static boolean isOSNameMatch(final String osName, final String osNamePrefix) { + if (osName == null) { return false; } - return osName.startsWith( osNamePrefix ); + return osName.startsWith(osNamePrefix); } /** @@ -147,9 +142,8 @@ static boolean isOSNameMatch( final String osName, final String osNamePrefix ) * @see System#getProperty(String) * @since 2.1 */ - public static File getJavaHome() - { - return new File( System.getProperty( JAVA_HOME_KEY ) ); + public static File getJavaHome() { + return new File(System.getProperty(JAVA_HOME_KEY)); } /** @@ -164,17 +158,13 @@ public static File getJavaHome() * @param property the system property name * @return the system property value or {@code null} if a security problem occurs */ - private static String getSystemProperty( final String property ) - { - try - { - return System.getProperty( property ); - } - catch ( final SecurityException ex ) - { + private static String getSystemProperty(final String property) { + try { + return System.getProperty(property); + } catch (final SecurityException ex) { // we are not allowed to look at this property - System.err.println( "Caught a SecurityException reading the system property '" + property - + "'; the SystemUtils property value will default to null." ); + System.err.println("Caught a SecurityException reading the system property '" + property + + "'; the SystemUtils property value will default to null."); return null; } } diff --git a/src/main/java/org/apache/maven/plugins/javadoc/TestFixJavadocMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/TestFixJavadocMojo.java index c652a9279..877c5f2d7 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/TestFixJavadocMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/TestFixJavadocMojo.java @@ -1,81 +1,74 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.DependencyResolutionRequiredException; -import org.apache.maven.plugin.MojoExecutionException; -import org.apache.maven.plugin.MojoFailureException; -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.project.MavenProject; - -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; - -/** - * Fix Javadoc documentation and tags for the Test Java code for the project. - * @see Where Tags Can - * Be Used. - * @author Vincent Siveton - * @since 2.6 - */ -@Mojo( name = "test-fix", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -@Execute( phase = LifecyclePhase.TEST_COMPILE ) -public class TestFixJavadocMojo - extends AbstractFixJavadocMojo -{ - /** {@inheritDoc} */ - @Override - protected List getProjectSourceRoots( MavenProject p ) - { - return ( p.getTestCompileSourceRoots() == null ? Collections.emptyList() - : new LinkedList<>( p.getTestCompileSourceRoots() ) ); - } - - /** {@inheritDoc} */ - @Override - protected List getCompileClasspathElements( MavenProject p ) - throws DependencyResolutionRequiredException - { - return ( p.getTestClasspathElements() == null ? Collections.emptyList() - : new LinkedList<>( p.getTestClasspathElements() ) ); - } - - /** {@inheritDoc} */ - @Override - protected String getArtifactType( MavenProject p ) - { - return "test-jar"; - } - - /** {@inheritDoc} */ - @Override - public void execute() - throws MojoExecutionException, MojoFailureException - { - // clirr doesn't analyze test code, so ignore it - ignoreClirr = true; - - super.execute(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; + +import org.apache.maven.artifact.DependencyResolutionRequiredException; +import org.apache.maven.plugin.MojoExecutionException; +import org.apache.maven.plugin.MojoFailureException; +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.project.MavenProject; + +/** + * Fix Javadoc documentation and tags for the Test Java code for the project. + * @see Where Tags Can + * Be Used. + * @author Vincent Siveton + * @since 2.6 + */ +@Mojo(name = "test-fix", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +@Execute(phase = LifecyclePhase.TEST_COMPILE) +public class TestFixJavadocMojo extends AbstractFixJavadocMojo { + /** {@inheritDoc} */ + @Override + protected List getProjectSourceRoots(MavenProject p) { + return (p.getTestCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getTestCompileSourceRoots())); + } + + /** {@inheritDoc} */ + @Override + protected List getCompileClasspathElements(MavenProject p) throws DependencyResolutionRequiredException { + return (p.getTestClasspathElements() == null + ? Collections.emptyList() + : new LinkedList<>(p.getTestClasspathElements())); + } + + /** {@inheritDoc} */ + @Override + protected String getArtifactType(MavenProject p) { + return "test-jar"; + } + + /** {@inheritDoc} */ + @Override + public void execute() throws MojoExecutionException, MojoFailureException { + // clirr doesn't analyze test code, so ignore it + ignoreClirr = true; + + super.execute(); + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocJar.java b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocJar.java index e282d121c..3da918223 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocJar.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocJar.java @@ -1,216 +1,207 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.plugins.javadoc.resolver.SourceResolverConfig; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.StringUtils; -import org.eclipse.aether.util.filter.ScopeDependencyFilter; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * Bundles the Javadoc documentation for test Java code in an NON aggregator project into - * a jar using the standard - * Javadoc Tool. - * - * @author Vincent Siveton - * @since 2.5 - */ -@Mojo( name = "test-jar", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.TEST, - threadSafe = true ) -public class TestJavadocJar - extends JavadocJar -{ - // ---------------------------------------------------------------------- - // Javadoc Options (should be inline with Javadoc options defined in TestJavadocReport) - // ---------------------------------------------------------------------- - - /** - * Specifies the destination directory where Javadoc saves the generated HTML files. - * @see Doclet option d. - */ - @Parameter( defaultValue = "${project.build.directory}/testapidocs", required = true ) - private File outputDirectory; - - /** - * Specifies the Test title to be placed near the top of the overview summary file. - * @see Doclet option doctitle. - * @since 2.5 - */ - @Parameter( property = "testDoctitle", alias = "doctitle", - defaultValue = "${project.name} ${project.version} Test API" ) - private String testDoctitle; - - /** - * Specifies that Javadoc should retrieve the text for the Test overview documentation from the "source" file - * specified by path/filename and place it on the Overview page (overview-summary.html). - * @see Doclet option overview. - * @since 2.5 - */ - @Parameter( property = "testOverview", alias = "overview", - defaultValue = "${basedir}/src/test/javadoc/overview.html" ) - private File testOverview; - - /** - * Specifies the Test title to be placed in the HTML title tag. - * @see Doclet option windowtitle. - * @since 2.5 - */ - @Parameter( property = "testWindowtitle", alias = "windowtitle", - defaultValue = "${project.name} ${project.version} Test API" ) - private String testWindowtitle; - - // ---------------------------------------------------------------------- - // Mojo Parameters (should be inline with options defined in TestJavadocReport) - // ---------------------------------------------------------------------- - - /** - * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). - * - * @since 2.5 - */ - @Parameter( alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc" ) - private File testJavadocDirectory; - - /** - * @since 2.10 - */ - @Parameter( property = "maven.javadoc.testClassifier", defaultValue = "test-javadoc", required = true ) - private String testClassifier; - - // ---------------------------------------------------------------------- - // Protected methods - // ---------------------------------------------------------------------- - - @Override - protected String getClassifier() - { - return testClassifier; - } - - // ---------------------------------------------------------------------- - // Important Note: should be inline with methods defined in TestJavadocReport - // ---------------------------------------------------------------------- - - @Override - protected String getOutputDirectory() - { - return outputDirectory.getAbsoluteFile().toString(); - } - - @Override - protected File getJavadocDirectory() - { - return testJavadocDirectory; - } - - @Override - protected String getDoctitle() - { - return testDoctitle; - } - - @Override - protected File getOverview() - { - return testOverview; - } - - @Override - protected String getWindowtitle() - { - return testWindowtitle; - } - - @Override - protected List getProjectBuildOutputDirs( MavenProject p ) - { - List dirs = new ArrayList<>(); - if ( StringUtils.isNotEmpty( p.getBuild().getOutputDirectory() ) ) - { - dirs.add( new File( p.getBuild().getOutputDirectory() ) ); - } - if ( StringUtils.isNotEmpty( p.getBuild().getTestOutputDirectory() ) ) - { - dirs.add( new File( p.getBuild().getTestOutputDirectory() ) ); - } - - return dirs; - } - - @Override - protected List getProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getPackaging().toLowerCase() ) ) - { - return Collections.emptyList(); - } - - return p.getTestCompileSourceRoots(); - } - - @Override - protected List getExecutionProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getExecutionProject().getPackaging().toLowerCase() ) ) - { - return Collections.emptyList(); - } - - return p.getExecutionProject().getTestCompileSourceRoots(); - } - - @Override - protected ScopeDependencyFilter getDependencyScopeFilter() - { - return new ScopeDependencyFilter( Arrays.asList( - Artifact.SCOPE_COMPILE, - Artifact.SCOPE_PROVIDED, - Artifact.SCOPE_SYSTEM, - Artifact.SCOPE_TEST ), null ); - } - - /** - * Overriden to enable the resolution of -test-sources jar files. - * - * {@inheritDoc} - */ - @Override - protected SourceResolverConfig configureDependencySourceResolution( final SourceResolverConfig config ) - { - return super.configureDependencySourceResolution( config ).withoutCompileSources().withTestSources(); - } - - @Override - protected boolean isTest() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.plugins.javadoc.resolver.SourceResolverConfig; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.StringUtils; +import org.eclipse.aether.util.filter.ScopeDependencyFilter; + +/** + * Bundles the Javadoc documentation for test Java code in an NON aggregator project into + * a jar using the standard + * Javadoc Tool. + * + * @author Vincent Siveton + * @since 2.5 + */ +@Mojo( + name = "test-jar", + defaultPhase = LifecyclePhase.PACKAGE, + requiresDependencyResolution = ResolutionScope.TEST, + threadSafe = true) +public class TestJavadocJar extends JavadocJar { + // ---------------------------------------------------------------------- + // Javadoc Options (should be inline with Javadoc options defined in TestJavadocReport) + // ---------------------------------------------------------------------- + + /** + * Specifies the destination directory where Javadoc saves the generated HTML files. + * @see Doclet option d. + */ + @Parameter(defaultValue = "${project.build.directory}/testapidocs", required = true) + private File outputDirectory; + + /** + * Specifies the Test title to be placed near the top of the overview summary file. + * @see Doclet option doctitle. + * @since 2.5 + */ + @Parameter( + property = "testDoctitle", + alias = "doctitle", + defaultValue = "${project.name} ${project.version} Test API") + private String testDoctitle; + + /** + * Specifies that Javadoc should retrieve the text for the Test overview documentation from the "source" file + * specified by path/filename and place it on the Overview page (overview-summary.html). + * @see Doclet option overview. + * @since 2.5 + */ + @Parameter( + property = "testOverview", + alias = "overview", + defaultValue = "${basedir}/src/test/javadoc/overview.html") + private File testOverview; + + /** + * Specifies the Test title to be placed in the HTML title tag. + * @see Doclet option windowtitle. + * @since 2.5 + */ + @Parameter( + property = "testWindowtitle", + alias = "windowtitle", + defaultValue = "${project.name} ${project.version} Test API") + private String testWindowtitle; + + // ---------------------------------------------------------------------- + // Mojo Parameters (should be inline with options defined in TestJavadocReport) + // ---------------------------------------------------------------------- + + /** + * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). + * + * @since 2.5 + */ + @Parameter(alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc") + private File testJavadocDirectory; + + /** + * @since 2.10 + */ + @Parameter(property = "maven.javadoc.testClassifier", defaultValue = "test-javadoc", required = true) + private String testClassifier; + + // ---------------------------------------------------------------------- + // Protected methods + // ---------------------------------------------------------------------- + + @Override + protected String getClassifier() { + return testClassifier; + } + + // ---------------------------------------------------------------------- + // Important Note: should be inline with methods defined in TestJavadocReport + // ---------------------------------------------------------------------- + + @Override + protected String getOutputDirectory() { + return outputDirectory.getAbsoluteFile().toString(); + } + + @Override + protected File getJavadocDirectory() { + return testJavadocDirectory; + } + + @Override + protected String getDoctitle() { + return testDoctitle; + } + + @Override + protected File getOverview() { + return testOverview; + } + + @Override + protected String getWindowtitle() { + return testWindowtitle; + } + + @Override + protected List getProjectBuildOutputDirs(MavenProject p) { + List dirs = new ArrayList<>(); + if (StringUtils.isNotEmpty(p.getBuild().getOutputDirectory())) { + dirs.add(new File(p.getBuild().getOutputDirectory())); + } + if (StringUtils.isNotEmpty(p.getBuild().getTestOutputDirectory())) { + dirs.add(new File(p.getBuild().getTestOutputDirectory())); + } + + return dirs; + } + + @Override + protected List getProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getPackaging().toLowerCase())) { + return Collections.emptyList(); + } + + return p.getTestCompileSourceRoots(); + } + + @Override + protected List getExecutionProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getExecutionProject().getPackaging().toLowerCase())) { + return Collections.emptyList(); + } + + return p.getExecutionProject().getTestCompileSourceRoots(); + } + + @Override + protected ScopeDependencyFilter getDependencyScopeFilter() { + return new ScopeDependencyFilter( + Arrays.asList( + Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_TEST), + null); + } + + /** + * Overriden to enable the resolution of -test-sources jar files. + * + * {@inheritDoc} + */ + @Override + protected SourceResolverConfig configureDependencySourceResolution(final SourceResolverConfig config) { + return super.configureDependencySourceResolution(config) + .withoutCompileSources() + .withTestSources(); + } + + @Override + protected boolean isTest() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocNoForkReport.java b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocNoForkReport.java index 7e64b954b..f86b48328 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocNoForkReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocNoForkReport.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import org.apache.maven.plugins.annotations.Execute; import org.apache.maven.plugins.annotations.LifecyclePhase; @@ -35,9 +34,6 @@ * @see Javadoc Tool * @see Javadoc Options */ -@Mojo( name = "test-javadoc-no-fork", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -@Execute( phase = LifecyclePhase.NONE ) -public class TestJavadocNoForkReport - extends TestJavadocReport -{ -} +@Mojo(name = "test-javadoc-no-fork", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +@Execute(phase = LifecyclePhase.NONE) +public class TestJavadocNoForkReport extends TestJavadocReport {} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocReport.java b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocReport.java index f419f7f3a..efcf1353a 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocReport.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/TestJavadocReport.java @@ -1,347 +1,324 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.plugins.annotations.Execute; -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; -import org.apache.maven.plugins.javadoc.resolver.SourceResolverConfig; -import org.apache.maven.project.MavenProject; -import org.apache.maven.reporting.MavenReportException; -import org.codehaus.plexus.util.StringUtils; -import org.eclipse.aether.util.filter.ScopeDependencyFilter; - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.ResourceBundle; - -/** - * Generates documentation for the Java Test code in an NON aggregator project using the standard - * Javadoc Tool. - * - * @author Vincent Siveton - * @since 2.3 - * @see Javadoc Tool - */ -@Mojo( name = "test-javadoc", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -@Execute( phase = LifecyclePhase.GENERATE_TEST_SOURCES ) -public class TestJavadocReport - extends JavadocReport -{ - // ---------------------------------------------------------------------- - // Javadoc Options (should be inline with options defined in TestJavadocJar) - // ---------------------------------------------------------------------- - - /** - * Specifies the Test title to be placed near the top of the overview summary file. - * @see Doclet option doctitle. - * @since 2.5 - */ - @Parameter( property = "testDoctitle", alias = "doctitle", - defaultValue = "${project.name} ${project.version} Test API" ) - private String testDoctitle; - - /** - * Specifies that Javadoc should retrieve the text for the Test overview documentation from the "source" file - * specified by path/filename and place it on the Overview page (overview-summary.html). - * @see Doclet option overview. - * @since 2.5 - */ - @Parameter( property = "testOverview", alias = "overview", - defaultValue = "${basedir}/src/test/javadoc/overview.html" ) - private File testOverview; - - /** - * Specifies the Test title to be placed in the HTML title tag. - * @see Doclet option windowtitle. - * @since 2.5 - */ - @Parameter( property = "testWindowtitle", alias = "windowtitle", - defaultValue = "${project.name} ${project.version} Test API" ) - private String testWindowtitle; - - // ---------------------------------------------------------------------- - // Mojo Parameters (should be inline with options defined in TestJavadocJar) - // ---------------------------------------------------------------------- - - /** - * Specifies the destination directory where test Javadoc saves the generated HTML files. - */ - @Parameter( property = "reportTestOutputDirectory", - defaultValue = "${project.reporting.outputDirectory}/testapidocs", required = true ) - private File reportOutputDirectory; - - /** - * The name of the destination directory. - *
- */ - @Parameter( property = "destDir", defaultValue = "testapidocs" ) - private String destDir; - - /** - * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). - *
- * Could be used in addition of docfilessubdirs parameter. - *
- * See docfilessubdirs. - * - * @since 2.5 - */ - @Parameter( alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc" ) - private File testJavadocDirectory; - - // ---------------------------------------------------------------------- - // Report Mojo Parameters - // ---------------------------------------------------------------------- - - /** - * The name of the Test Javadoc report to be displayed in the Maven Generated Reports page - * (i.e. project-reports.html). - * - * @since 2.5 - */ - @Parameter( property = "testName", alias = "name" ) - private String testName; - - /** - * The description of the Test Javadoc report to be displayed in the Maven Generated Reports page - * (i.e. project-reports.html). - * - * @since 2.5 - */ - @Parameter( property = "testDescription", alias = "description" ) - private String testDescription; - - // ---------------------------------------------------------------------- - // Report public methods - // ---------------------------------------------------------------------- - - @Override - protected void executeReport( Locale unusedLocale ) - throws MavenReportException - { - addMainJavadocLink(); - - super.executeReport( unusedLocale ); - } - - @Override - public String getName( Locale locale ) - { - if ( StringUtils.isEmpty( testName ) ) - { - return getBundle( locale ).getString( "report.test-javadoc.name" ); - } - - return testName; - } - - @Override - public String getDescription( Locale locale ) - { - if ( StringUtils.isEmpty( testDescription ) ) - { - return getBundle( locale ).getString( "report.test-javadoc.description" ); - } - - return testDescription; - } - - @Override - public String getOutputName() - { - return destDir + "/index"; - } - - @Override - public File getReportOutputDirectory() - { - if ( reportOutputDirectory == null ) - { - return outputDirectory; - } - - return reportOutputDirectory; - } - - /** - * Method to set the directory where the generated reports will be put - * - * @param reportOutputDirectory the directory file to be set - */ - @Override - public void setReportOutputDirectory( File reportOutputDirectory ) - { - updateReportOutputDirectory( reportOutputDirectory, destDir ); - } - - @Override - public void setDestDir( String destDir ) - { - this.destDir = destDir; - updateReportOutputDirectory( reportOutputDirectory, destDir ); - } - - private void updateReportOutputDirectory( File reportOutputDirectory, String destDir ) - { - if ( reportOutputDirectory != null && destDir != null - && !reportOutputDirectory.getAbsolutePath().endsWith( destDir ) ) - { - this.reportOutputDirectory = new File( reportOutputDirectory, destDir ); - } - else - { - this.reportOutputDirectory = reportOutputDirectory; - } - } - - // ---------------------------------------------------------------------- - // Protected methods - // Important Note: should be inline with methods defined in TestJavadocJar - // ---------------------------------------------------------------------- - - @Override - protected List getProjectBuildOutputDirs( MavenProject p ) - { - List dirs = new ArrayList<>(); - if ( StringUtils.isNotEmpty( p.getBuild().getOutputDirectory() ) ) - { - dirs.add( new File( p.getBuild().getOutputDirectory() ) ); - } - if ( StringUtils.isNotEmpty( p.getBuild().getTestOutputDirectory() ) ) - { - dirs.add( new File( p.getBuild().getTestOutputDirectory() ) ); - } - - return dirs; - } - - @Override - protected List getProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getPackaging().toLowerCase() ) ) - { - return Collections.emptyList(); - } - - return ( p.getTestCompileSourceRoots() == null ? Collections.emptyList() - : new LinkedList<>( p.getTestCompileSourceRoots() ) ); - } - - @Override - protected List getExecutionProjectSourceRoots( MavenProject p ) - { - if ( "pom".equals( p.getExecutionProject().getPackaging().toLowerCase() ) ) - { - return Collections.emptyList(); - } - - return ( p.getExecutionProject().getTestCompileSourceRoots() == null ? Collections.emptyList() - : new LinkedList<>( p.getExecutionProject().getTestCompileSourceRoots() ) ); - } - - @Override - protected File getJavadocDirectory() - { - return testJavadocDirectory; - } - - @Override - protected String getDoctitle() - { - return testDoctitle; - } - - @Override - protected File getOverview() - { - return testOverview; - } - - @Override - protected String getWindowtitle() - { - return testWindowtitle; - } - - @Override - protected ScopeDependencyFilter getDependencyScopeFilter() - { - return new ScopeDependencyFilter( Arrays.asList( - Artifact.SCOPE_COMPILE, - Artifact.SCOPE_PROVIDED, - Artifact.SCOPE_SYSTEM, - Artifact.SCOPE_TEST ), null ); - } - - /** - * Gets the resource bundle for the specified locale. - * - * @param locale The locale of the currently generated report. - * @return The resource bundle for the requested locale. - */ - private ResourceBundle getBundle( Locale locale ) - { - return ResourceBundle.getBundle( "test-javadoc-report", locale, getClass().getClassLoader() ); - } - - /** - * Add the ../apidocs to the links parameter so Test report could be linked to the Main report. - */ - private void addMainJavadocLink() - { - if ( links == null ) - { - links = new ArrayList<>(); - } - - // TODO the prerequisite is that the main report is in apidocs - File apidocs = new File( getReportOutputDirectory().getParentFile(), "apidocs" ); - if ( apidocs.isDirectory() && !links.contains( "../apidocs" ) ) - { - links.add( "../apidocs" ); - } - } - - /** - * Overridden to enable the resolution of -test-sources jar files. - * - * {@inheritDoc} - */ - @Override - protected SourceResolverConfig configureDependencySourceResolution( final SourceResolverConfig config ) - { - return super.configureDependencySourceResolution( config ).withoutCompileSources().withTestSources(); - } - - @Override - protected boolean isTest() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.ResourceBundle; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.plugins.annotations.Execute; +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; +import org.apache.maven.plugins.javadoc.resolver.SourceResolverConfig; +import org.apache.maven.project.MavenProject; +import org.apache.maven.reporting.MavenReportException; +import org.codehaus.plexus.util.StringUtils; +import org.eclipse.aether.util.filter.ScopeDependencyFilter; + +/** + * Generates documentation for the Java Test code in an NON aggregator project using the standard + * Javadoc Tool. + * + * @author Vincent Siveton + * @since 2.3 + * @see Javadoc Tool + */ +@Mojo(name = "test-javadoc", requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true) +@Execute(phase = LifecyclePhase.GENERATE_TEST_SOURCES) +public class TestJavadocReport extends JavadocReport { + // ---------------------------------------------------------------------- + // Javadoc Options (should be inline with options defined in TestJavadocJar) + // ---------------------------------------------------------------------- + + /** + * Specifies the Test title to be placed near the top of the overview summary file. + * @see Doclet option doctitle. + * @since 2.5 + */ + @Parameter( + property = "testDoctitle", + alias = "doctitle", + defaultValue = "${project.name} ${project.version} Test API") + private String testDoctitle; + + /** + * Specifies that Javadoc should retrieve the text for the Test overview documentation from the "source" file + * specified by path/filename and place it on the Overview page (overview-summary.html). + * @see Doclet option overview. + * @since 2.5 + */ + @Parameter( + property = "testOverview", + alias = "overview", + defaultValue = "${basedir}/src/test/javadoc/overview.html") + private File testOverview; + + /** + * Specifies the Test title to be placed in the HTML title tag. + * @see Doclet option windowtitle. + * @since 2.5 + */ + @Parameter( + property = "testWindowtitle", + alias = "windowtitle", + defaultValue = "${project.name} ${project.version} Test API") + private String testWindowtitle; + + // ---------------------------------------------------------------------- + // Mojo Parameters (should be inline with options defined in TestJavadocJar) + // ---------------------------------------------------------------------- + + /** + * Specifies the destination directory where test Javadoc saves the generated HTML files. + */ + @Parameter( + property = "reportTestOutputDirectory", + defaultValue = "${project.reporting.outputDirectory}/testapidocs", + required = true) + private File reportOutputDirectory; + + /** + * The name of the destination directory. + *
+ */ + @Parameter(property = "destDir", defaultValue = "testapidocs") + private String destDir; + + /** + * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). + *
+ * Could be used in addition of docfilessubdirs parameter. + *
+ * See docfilessubdirs. + * + * @since 2.5 + */ + @Parameter(alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc") + private File testJavadocDirectory; + + // ---------------------------------------------------------------------- + // Report Mojo Parameters + // ---------------------------------------------------------------------- + + /** + * The name of the Test Javadoc report to be displayed in the Maven Generated Reports page + * (i.e. project-reports.html). + * + * @since 2.5 + */ + @Parameter(property = "testName", alias = "name") + private String testName; + + /** + * The description of the Test Javadoc report to be displayed in the Maven Generated Reports page + * (i.e. project-reports.html). + * + * @since 2.5 + */ + @Parameter(property = "testDescription", alias = "description") + private String testDescription; + + // ---------------------------------------------------------------------- + // Report public methods + // ---------------------------------------------------------------------- + + @Override + protected void executeReport(Locale unusedLocale) throws MavenReportException { + addMainJavadocLink(); + + super.executeReport(unusedLocale); + } + + @Override + public String getName(Locale locale) { + if (StringUtils.isEmpty(testName)) { + return getBundle(locale).getString("report.test-javadoc.name"); + } + + return testName; + } + + @Override + public String getDescription(Locale locale) { + if (StringUtils.isEmpty(testDescription)) { + return getBundle(locale).getString("report.test-javadoc.description"); + } + + return testDescription; + } + + @Override + public String getOutputName() { + return destDir + "/index"; + } + + @Override + public File getReportOutputDirectory() { + if (reportOutputDirectory == null) { + return outputDirectory; + } + + return reportOutputDirectory; + } + + /** + * Method to set the directory where the generated reports will be put + * + * @param reportOutputDirectory the directory file to be set + */ + @Override + public void setReportOutputDirectory(File reportOutputDirectory) { + updateReportOutputDirectory(reportOutputDirectory, destDir); + } + + @Override + public void setDestDir(String destDir) { + this.destDir = destDir; + updateReportOutputDirectory(reportOutputDirectory, destDir); + } + + private void updateReportOutputDirectory(File reportOutputDirectory, String destDir) { + if (reportOutputDirectory != null + && destDir != null + && !reportOutputDirectory.getAbsolutePath().endsWith(destDir)) { + this.reportOutputDirectory = new File(reportOutputDirectory, destDir); + } else { + this.reportOutputDirectory = reportOutputDirectory; + } + } + + // ---------------------------------------------------------------------- + // Protected methods + // Important Note: should be inline with methods defined in TestJavadocJar + // ---------------------------------------------------------------------- + + @Override + protected List getProjectBuildOutputDirs(MavenProject p) { + List dirs = new ArrayList<>(); + if (StringUtils.isNotEmpty(p.getBuild().getOutputDirectory())) { + dirs.add(new File(p.getBuild().getOutputDirectory())); + } + if (StringUtils.isNotEmpty(p.getBuild().getTestOutputDirectory())) { + dirs.add(new File(p.getBuild().getTestOutputDirectory())); + } + + return dirs; + } + + @Override + protected List getProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getPackaging().toLowerCase())) { + return Collections.emptyList(); + } + + return (p.getTestCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getTestCompileSourceRoots())); + } + + @Override + protected List getExecutionProjectSourceRoots(MavenProject p) { + if ("pom".equals(p.getExecutionProject().getPackaging().toLowerCase())) { + return Collections.emptyList(); + } + + return (p.getExecutionProject().getTestCompileSourceRoots() == null + ? Collections.emptyList() + : new LinkedList<>(p.getExecutionProject().getTestCompileSourceRoots())); + } + + @Override + protected File getJavadocDirectory() { + return testJavadocDirectory; + } + + @Override + protected String getDoctitle() { + return testDoctitle; + } + + @Override + protected File getOverview() { + return testOverview; + } + + @Override + protected String getWindowtitle() { + return testWindowtitle; + } + + @Override + protected ScopeDependencyFilter getDependencyScopeFilter() { + return new ScopeDependencyFilter( + Arrays.asList( + Artifact.SCOPE_COMPILE, Artifact.SCOPE_PROVIDED, Artifact.SCOPE_SYSTEM, Artifact.SCOPE_TEST), + null); + } + + /** + * Gets the resource bundle for the specified locale. + * + * @param locale The locale of the currently generated report. + * @return The resource bundle for the requested locale. + */ + private ResourceBundle getBundle(Locale locale) { + return ResourceBundle.getBundle( + "test-javadoc-report", locale, getClass().getClassLoader()); + } + + /** + * Add the ../apidocs to the links parameter so Test report could be linked to the Main report. + */ + private void addMainJavadocLink() { + if (links == null) { + links = new ArrayList<>(); + } + + // TODO the prerequisite is that the main report is in apidocs + File apidocs = new File(getReportOutputDirectory().getParentFile(), "apidocs"); + if (apidocs.isDirectory() && !links.contains("../apidocs")) { + links.add("../apidocs"); + } + } + + /** + * Overridden to enable the resolution of -test-sources jar files. + * + * {@inheritDoc} + */ + @Override + protected SourceResolverConfig configureDependencySourceResolution(final SourceResolverConfig config) { + return super.configureDependencySourceResolution(config) + .withoutCompileSources() + .withTestSources(); + } + + @Override + protected boolean isTest() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/TestResourcesBundleMojo.java b/src/main/java/org/apache/maven/plugins/javadoc/TestResourcesBundleMojo.java index f550be8a0..7bdab3e1a 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/TestResourcesBundleMojo.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/TestResourcesBundleMojo.java @@ -1,67 +1,64 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.annotations.LifecyclePhase; -import org.apache.maven.plugins.annotations.Mojo; -import org.apache.maven.plugins.annotations.Parameter; -import org.apache.maven.plugins.annotations.ResolutionScope; - -import java.io.File; - -/** - * Bundle {@link TestJavadocJar#testJavadocDirectory}, along with javadoc configuration options from - * {@link AbstractJavadocMojo} such as taglet, doclet, and link information into a deployable - * artifact. This artifact can then be consumed by the javadoc plugin mojos when used by the - * includeDependencySources option, to generate javadocs that are somewhat consistent - * with those generated in the original project itself. - * - * @since 2.7 - */ -@Mojo( name = "test-resource-bundle", defaultPhase = LifecyclePhase.PACKAGE, - requiresDependencyResolution = ResolutionScope.TEST, threadSafe = true ) -public class TestResourcesBundleMojo - extends ResourcesBundleMojo -{ - - /** - * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). - */ - @Parameter( alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc" ) - private File testJavadocDirectory; - - @Override - protected String getAttachmentClassifier() - { - return TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER; - } - - @Override - protected File getJavadocDirectory() - { - return testJavadocDirectory; - } - - @Override - protected boolean isTest() - { - return true; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; + +import org.apache.maven.plugins.annotations.LifecyclePhase; +import org.apache.maven.plugins.annotations.Mojo; +import org.apache.maven.plugins.annotations.Parameter; +import org.apache.maven.plugins.annotations.ResolutionScope; + +/** + * Bundle {@link TestJavadocJar#testJavadocDirectory}, along with javadoc configuration options from + * {@link AbstractJavadocMojo} such as taglet, doclet, and link information into a deployable + * artifact. This artifact can then be consumed by the javadoc plugin mojos when used by the + * includeDependencySources option, to generate javadocs that are somewhat consistent + * with those generated in the original project itself. + * + * @since 2.7 + */ +@Mojo( + name = "test-resource-bundle", + defaultPhase = LifecyclePhase.PACKAGE, + requiresDependencyResolution = ResolutionScope.TEST, + threadSafe = true) +public class TestResourcesBundleMojo extends ResourcesBundleMojo { + + /** + * Specifies the Test Javadoc resources directory to be included in the Javadoc (i.e. package.html, images...). + */ + @Parameter(alias = "javadocDirectory", defaultValue = "${basedir}/src/test/javadoc") + private File testJavadocDirectory; + + @Override + protected String getAttachmentClassifier() { + return TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER; + } + + @Override + protected File getJavadocDirectory() { + return testJavadocDirectory; + } + + @Override + protected boolean isTest() { + return true; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/resolver/JavadocBundle.java b/src/main/java/org/apache/maven/plugins/javadoc/resolver/JavadocBundle.java index d61f98544..9bcad5571 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/resolver/JavadocBundle.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/resolver/JavadocBundle.java @@ -1,62 +1,56 @@ -package org.apache.maven.plugins.javadoc.resolver; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugins.javadoc.options.JavadocOptions; - -import java.io.File; - -/** - * - */ -public class JavadocBundle -{ - - private final File resourcesDirectory; - - private final JavadocOptions options; - - /** - * @param options {@link JavadocOptions} - * @param resourcesDirectory The resources directory. - */ - public JavadocBundle( final JavadocOptions options, final File resourcesDirectory ) - { - this.options = options; - this.resourcesDirectory = resourcesDirectory; - } - - /** - * @return {@link #resourcesDirectory} - */ - public File getResourcesDirectory() - { - return resourcesDirectory; - } - - /** - * @return {@link #options} - */ - public JavadocOptions getOptions() - { - return options; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.resolver; + +import java.io.File; + +import org.apache.maven.plugins.javadoc.options.JavadocOptions; + +/** + * + */ +public class JavadocBundle { + + private final File resourcesDirectory; + + private final JavadocOptions options; + + /** + * @param options {@link JavadocOptions} + * @param resourcesDirectory The resources directory. + */ + public JavadocBundle(final JavadocOptions options, final File resourcesDirectory) { + this.options = options; + this.resourcesDirectory = resourcesDirectory; + } + + /** + * @return {@link #resourcesDirectory} + */ + public File getResourcesDirectory() { + return resourcesDirectory; + } + + /** + * @return {@link #options} + */ + public JavadocOptions getOptions() { + return options; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/resolver/ResourceResolver.java b/src/main/java/org/apache/maven/plugins/javadoc/resolver/ResourceResolver.java index a8c968f41..ffbd0b464 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/resolver/ResourceResolver.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/resolver/ResourceResolver.java @@ -1,459 +1,384 @@ -package org.apache.maven.plugins.javadoc.resolver; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; - -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.maven.RepositoryUtils; -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.resolver.ArtifactNotFoundException; -import org.apache.maven.artifact.resolver.ArtifactResolutionException; -import org.apache.maven.plugins.javadoc.AbstractJavadocMojo; -import org.apache.maven.plugins.javadoc.JavadocModule; -import org.apache.maven.plugins.javadoc.JavadocUtil; -import org.apache.maven.plugins.javadoc.ResourcesBundleMojo; -import org.apache.maven.plugins.javadoc.options.JavadocOptions; -import org.apache.maven.plugins.javadoc.options.io.xpp3.JavadocOptionsXpp3Reader; -import org.apache.maven.project.MavenProject; -import org.apache.maven.shared.artifact.filter.resolve.transform.ArtifactIncludeFilterTransformer; -import org.apache.maven.shared.artifact.filter.resolve.transform.EclipseAetherFilterTransformer; -import org.codehaus.plexus.archiver.ArchiverException; -import org.codehaus.plexus.archiver.UnArchiver; -import org.codehaus.plexus.archiver.manager.ArchiverManager; -import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; -import org.codehaus.plexus.logging.AbstractLogEnabled; -import org.codehaus.plexus.util.xml.pull.XmlPullParserException; -import org.eclipse.aether.RepositorySystem; -import org.eclipse.aether.RepositorySystemSession; -import org.eclipse.aether.graph.DefaultDependencyNode; -import org.eclipse.aether.graph.DependencyFilter; -import org.eclipse.aether.resolution.ArtifactRequest; -import org.eclipse.aether.resolution.ArtifactResult; - -/** - * - */ -@Named -@Singleton -public final class ResourceResolver extends AbstractLogEnabled -{ - @Inject - private RepositorySystem repoSystem; - - @Inject - private ArchiverManager archiverManager; - - /** - * The classifier for sources. - */ - public static final String SOURCES_CLASSIFIER = "sources"; - - /** - * The classifier for test sources - */ - public static final String TEST_SOURCES_CLASSIFIER = "test-sources"; - - private static final List SOURCE_VALID_CLASSIFIERS = Arrays.asList( SOURCES_CLASSIFIER, - TEST_SOURCES_CLASSIFIER ); - - private static final List RESOURCE_VALID_CLASSIFIERS = - Arrays.asList( AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, - AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER ); - - /** - * @param config {@link SourceResolverConfig} - * @return list of {@link JavadocBundle}. - * @throws IOException {@link IOException} - */ - public List resolveDependencyJavadocBundles( final SourceResolverConfig config ) - throws IOException - { - final List bundles = new ArrayList<>(); - - final Map projectMap = new HashMap<>(); - if ( config.reactorProjects() != null ) - { - for ( final MavenProject p : config.reactorProjects() ) - { - projectMap.put( key( p.getGroupId(), p.getArtifactId() ), p ); - } - } - - final List artifacts = config.project().getTestArtifacts(); - - final List forResourceResolution = new ArrayList<>( artifacts.size() ); - for ( final Artifact artifact : artifacts ) - { - final String key = key( artifact.getGroupId(), artifact.getArtifactId() ); - final MavenProject p = projectMap.get( key ); - if ( p != null ) - { - bundles.addAll( resolveBundleFromProject( config, p, artifact ) ); - } - else - { - forResourceResolution.add( artifact ); - } - } - - bundles.addAll( resolveBundlesFromArtifacts( config, forResourceResolution ) ); - - return bundles; - } - - /** - * @param config {@link SourceResolverConfig} - * @return The list of resolved dependencies. - * @throws ArtifactResolutionException {@link ArtifactResolutionException} - * @throws ArtifactNotFoundException {@link ArtifactNotFoundException} - */ - public Collection resolveDependencySourcePaths( final SourceResolverConfig config ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - final Collection mappedDirs = new ArrayList<>(); - - final Map projectMap = new HashMap<>(); - if ( config.reactorProjects() != null ) - { - for ( final MavenProject p : config.reactorProjects() ) - { - projectMap.put( key( p.getGroupId(), p.getArtifactId() ), p ); - } - } - - final List artifacts = config.project().getTestArtifacts(); - - for ( final Artifact artifact : artifacts ) - { - final String key = key( artifact.getGroupId(), artifact.getArtifactId() ); - final MavenProject p = projectMap.get( key ); - if ( p != null ) - { - mappedDirs.add( new JavadocModule( key, - artifact.getFile(), - resolveFromProject( config, p, artifact ) ) ); - } - else - { - JavadocModule m = resolveFromArtifact( config, artifact ); - if ( m != null ) - { - mappedDirs.add( m ); - } - } - } - - - return mappedDirs; - } - - private static List resolveBundleFromProject( SourceResolverConfig config, MavenProject project, - Artifact artifact ) throws IOException - { - List bundles = new ArrayList<>(); - - List classifiers = new ArrayList<>(); - if ( config.includeCompileSources() ) - { - classifiers.add( AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER ); - } - - if ( config.includeTestSources() ) - { - classifiers.add( AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER ); - } - - for ( String classifier : classifiers ) - { - File optionsFile = - new File( project.getBuild().getDirectory(), "javadoc-bundle-options/javadoc-options-" + classifier - + ".xml" ); - if ( !optionsFile.exists() ) - { - continue; - } - - - try ( FileInputStream stream = new FileInputStream( optionsFile ) ) - { - JavadocOptions options = new JavadocOptionsXpp3Reader().read( stream ); - bundles.add( new JavadocBundle( options, new File( project.getBasedir(), - options.getJavadocResourcesDirectory() ) ) ); - } - catch ( XmlPullParserException e ) - { - IOException error = - new IOException( "Failed to read javadoc options from: " + optionsFile + "\nReason: " - + e.getMessage(), e ); - throw error; - } - } - - return bundles; - } - - private List resolveBundlesFromArtifacts( final SourceResolverConfig config, - final List artifacts ) - throws IOException - { - final List toResolve = new ArrayList<>( artifacts.size() ); - - for ( final Artifact artifact : artifacts ) - { - if ( config.filter() != null - && !new ArtifactIncludeFilterTransformer().transform( config.filter() ).include( artifact ) ) - { - continue; - } - - if ( config.includeCompileSources() ) - { - toResolve.add( createResourceArtifact( artifact, - AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, - config ) ); - } - - if ( config.includeTestSources() ) - { - toResolve.add( createResourceArtifact( artifact, - AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, - config ) ); - } - } - - Collection dirs = new ArrayList<>( toResolve.size() ); - try - { - dirs = resolveAndUnpack( toResolve, config, RESOURCE_VALID_CLASSIFIERS, false ); - } - catch ( ArtifactResolutionException | ArtifactNotFoundException e ) - { - if ( getLogger().isDebugEnabled() ) - { - getLogger().debug( e.getMessage(), e ); - } - } - - List result = new ArrayList<>(); - - for ( Path d : dirs ) - { - File dir = d.toFile(); - File resources = new File( dir, ResourcesBundleMojo.RESOURCES_DIR_PATH ); - JavadocOptions options = null; - - File javadocOptions = new File( dir, ResourcesBundleMojo.BUNDLE_OPTIONS_PATH ); - if ( javadocOptions.exists() ) - { - try ( FileInputStream reader = new FileInputStream( javadocOptions ) ) - { - options = new JavadocOptionsXpp3Reader().read( reader ); - } - catch ( XmlPullParserException e ) - { - IOException error = new IOException( "Failed to parse javadoc options: " + e.getMessage(), e ); - throw error; - } - } - - result.add( new JavadocBundle( options, resources ) ); - } - - return result; - } - - private JavadocModule resolveFromArtifact( final SourceResolverConfig config, - final Artifact artifact ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - final List toResolve = new ArrayList<>( 2 ); - - if ( config.filter() != null - && !new ArtifactIncludeFilterTransformer().transform( config.filter() ).include( artifact ) ) - { - return null; - } - - if ( config.includeCompileSources() ) - { - toResolve.add( createResourceArtifact( artifact, SOURCES_CLASSIFIER, config ) ); - } - - if ( config.includeTestSources() ) - { - toResolve.add( createResourceArtifact( artifact, TEST_SOURCES_CLASSIFIER, config ) ); - } - - Collection sourcePaths = resolveAndUnpack( toResolve, config, SOURCE_VALID_CLASSIFIERS, true ); - - return new JavadocModule( key( artifact.getGroupId(), artifact.getArtifactId() ), - artifact.getFile(), - sourcePaths ); - } - - private org.eclipse.aether.artifact.Artifact createResourceArtifact( final Artifact artifact, - final String classifier, - final SourceResolverConfig config ) - { - return new org.eclipse.aether.artifact.DefaultArtifact( artifact.getGroupId(), - artifact.getArtifactId(), - classifier, - "jar", - artifact.getVersion() ); - } - - /** - * - * @param artifacts the artifacts to resolve - * @param config the configuration - * @param validClassifiers - * @param propagateErrors - * @return list of - * @throws ArtifactResolutionException if an exception occurs - * @throws ArtifactNotFoundException if an exception occurs - */ - private Collection resolveAndUnpack( final List artifacts, - final SourceResolverConfig config, - final List validClassifiers, - final boolean propagateErrors ) - throws ArtifactResolutionException, ArtifactNotFoundException - { - // NOTE: Since these are '-sources' and '-test-sources' artifacts, they won't actually - // resolve transitively...this is just used to aggregate resolution failures into a single - // exception. - final Set artifactSet = new LinkedHashSet<>( artifacts ); - - final DependencyFilter filter; - if ( config.filter() != null ) - { - filter = new EclipseAetherFilterTransformer().transform( config.filter() ); - } - else - { - filter = null; - } - - final List result = new ArrayList<>( artifacts.size() ); - for ( final org.eclipse.aether.artifact.Artifact a : artifactSet ) - { - if ( !validClassifiers.contains( a.getClassifier() ) || ( filter != null - && !filter.accept( new DefaultDependencyNode( a ), Collections.emptyList() ) ) ) - { - continue; - } - - Artifact resolvedArtifact; - ArtifactRequest req = new ArtifactRequest( a, config.project().getRemoteProjectRepositories(), null ); - try - { - RepositorySystemSession repoSession = config.getBuildingRequest().getRepositorySession(); - ArtifactResult resolutionResult = repoSystem.resolveArtifact( repoSession, req ); - resolvedArtifact = RepositoryUtils.toArtifact( resolutionResult.getArtifact() ); - } - catch ( org.eclipse.aether.resolution.ArtifactResolutionException e ) - { - continue; - } - final File d = - new File( config.outputBasedir(), a.getArtifactId() + "-" + a.getVersion() + "-" + a.getClassifier() ); - - if ( !d.exists() ) - { - d.mkdirs(); - } - - try - { - final UnArchiver unArchiver = archiverManager.getUnArchiver( a.getExtension() ); - - unArchiver.setDestDirectory( d ); - unArchiver.setSourceFile( resolvedArtifact.getFile() ); - - unArchiver.extract(); - - result.add( d.toPath().toAbsolutePath() ); - } - catch ( final NoSuchArchiverException e ) - { - if ( propagateErrors ) - { - throw new ArtifactResolutionException( "Failed to retrieve valid un-archiver component: " - + a.getExtension(), RepositoryUtils.toArtifact( a ), e ); - } - } - catch ( final ArchiverException e ) - { - if ( propagateErrors ) - { - throw new ArtifactResolutionException( "Failed to unpack: " + a, - RepositoryUtils.toArtifact( a ), e ); - } - } - } - - return result; - } - - private static Collection resolveFromProject( final SourceResolverConfig config, - final MavenProject reactorProject, final Artifact artifact ) - { - final List dirs = new ArrayList<>(); - - if ( config.filter() == null - || new ArtifactIncludeFilterTransformer().transform( config.filter() ).include( artifact ) ) - { - if ( config.includeCompileSources() ) - { - final List srcRoots = reactorProject.getCompileSourceRoots(); - dirs.addAll( srcRoots ); - } - - if ( config.includeTestSources() ) - { - final List srcRoots = reactorProject.getTestCompileSourceRoots(); - dirs.addAll( srcRoots ); - } - } - - return JavadocUtil.pruneDirs( reactorProject, dirs ); - } - - private static String key( final String gid, final String aid ) - { - return gid + ":" + aid; - } - -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.resolver; + +import javax.inject.Inject; +import javax.inject.Named; +import javax.inject.Singleton; + +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.apache.maven.RepositoryUtils; +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.resolver.ArtifactNotFoundException; +import org.apache.maven.artifact.resolver.ArtifactResolutionException; +import org.apache.maven.plugins.javadoc.AbstractJavadocMojo; +import org.apache.maven.plugins.javadoc.JavadocModule; +import org.apache.maven.plugins.javadoc.JavadocUtil; +import org.apache.maven.plugins.javadoc.ResourcesBundleMojo; +import org.apache.maven.plugins.javadoc.options.JavadocOptions; +import org.apache.maven.plugins.javadoc.options.io.xpp3.JavadocOptionsXpp3Reader; +import org.apache.maven.project.MavenProject; +import org.apache.maven.shared.artifact.filter.resolve.transform.ArtifactIncludeFilterTransformer; +import org.apache.maven.shared.artifact.filter.resolve.transform.EclipseAetherFilterTransformer; +import org.codehaus.plexus.archiver.ArchiverException; +import org.codehaus.plexus.archiver.UnArchiver; +import org.codehaus.plexus.archiver.manager.ArchiverManager; +import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; +import org.codehaus.plexus.logging.AbstractLogEnabled; +import org.codehaus.plexus.util.xml.pull.XmlPullParserException; +import org.eclipse.aether.RepositorySystem; +import org.eclipse.aether.RepositorySystemSession; +import org.eclipse.aether.graph.DefaultDependencyNode; +import org.eclipse.aether.graph.DependencyFilter; +import org.eclipse.aether.resolution.ArtifactRequest; +import org.eclipse.aether.resolution.ArtifactResult; + +/** + * + */ +@Named +@Singleton +public final class ResourceResolver extends AbstractLogEnabled { + @Inject + private RepositorySystem repoSystem; + + @Inject + private ArchiverManager archiverManager; + + /** + * The classifier for sources. + */ + public static final String SOURCES_CLASSIFIER = "sources"; + + /** + * The classifier for test sources + */ + public static final String TEST_SOURCES_CLASSIFIER = "test-sources"; + + private static final List SOURCE_VALID_CLASSIFIERS = + Arrays.asList(SOURCES_CLASSIFIER, TEST_SOURCES_CLASSIFIER); + + private static final List RESOURCE_VALID_CLASSIFIERS = Arrays.asList( + AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, + AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER); + + /** + * @param config {@link SourceResolverConfig} + * @return list of {@link JavadocBundle}. + * @throws IOException {@link IOException} + */ + public List resolveDependencyJavadocBundles(final SourceResolverConfig config) throws IOException { + final List bundles = new ArrayList<>(); + + final Map projectMap = new HashMap<>(); + if (config.reactorProjects() != null) { + for (final MavenProject p : config.reactorProjects()) { + projectMap.put(key(p.getGroupId(), p.getArtifactId()), p); + } + } + + final List artifacts = config.project().getTestArtifacts(); + + final List forResourceResolution = new ArrayList<>(artifacts.size()); + for (final Artifact artifact : artifacts) { + final String key = key(artifact.getGroupId(), artifact.getArtifactId()); + final MavenProject p = projectMap.get(key); + if (p != null) { + bundles.addAll(resolveBundleFromProject(config, p, artifact)); + } else { + forResourceResolution.add(artifact); + } + } + + bundles.addAll(resolveBundlesFromArtifacts(config, forResourceResolution)); + + return bundles; + } + + /** + * @param config {@link SourceResolverConfig} + * @return The list of resolved dependencies. + * @throws ArtifactResolutionException {@link ArtifactResolutionException} + * @throws ArtifactNotFoundException {@link ArtifactNotFoundException} + */ + public Collection resolveDependencySourcePaths(final SourceResolverConfig config) + throws ArtifactResolutionException, ArtifactNotFoundException { + final Collection mappedDirs = new ArrayList<>(); + + final Map projectMap = new HashMap<>(); + if (config.reactorProjects() != null) { + for (final MavenProject p : config.reactorProjects()) { + projectMap.put(key(p.getGroupId(), p.getArtifactId()), p); + } + } + + final List artifacts = config.project().getTestArtifacts(); + + for (final Artifact artifact : artifacts) { + final String key = key(artifact.getGroupId(), artifact.getArtifactId()); + final MavenProject p = projectMap.get(key); + if (p != null) { + mappedDirs.add(new JavadocModule(key, artifact.getFile(), resolveFromProject(config, p, artifact))); + } else { + JavadocModule m = resolveFromArtifact(config, artifact); + if (m != null) { + mappedDirs.add(m); + } + } + } + + return mappedDirs; + } + + private static List resolveBundleFromProject( + SourceResolverConfig config, MavenProject project, Artifact artifact) throws IOException { + List bundles = new ArrayList<>(); + + List classifiers = new ArrayList<>(); + if (config.includeCompileSources()) { + classifiers.add(AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER); + } + + if (config.includeTestSources()) { + classifiers.add(AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER); + } + + for (String classifier : classifiers) { + File optionsFile = new File( + project.getBuild().getDirectory(), "javadoc-bundle-options/javadoc-options-" + classifier + ".xml"); + if (!optionsFile.exists()) { + continue; + } + + try (FileInputStream stream = new FileInputStream(optionsFile)) { + JavadocOptions options = new JavadocOptionsXpp3Reader().read(stream); + bundles.add(new JavadocBundle( + options, new File(project.getBasedir(), options.getJavadocResourcesDirectory()))); + } catch (XmlPullParserException e) { + IOException error = new IOException( + "Failed to read javadoc options from: " + optionsFile + "\nReason: " + e.getMessage(), e); + throw error; + } + } + + return bundles; + } + + private List resolveBundlesFromArtifacts( + final SourceResolverConfig config, final List artifacts) throws IOException { + final List toResolve = new ArrayList<>(artifacts.size()); + + for (final Artifact artifact : artifacts) { + if (config.filter() != null + && !new ArtifactIncludeFilterTransformer() + .transform(config.filter()) + .include(artifact)) { + continue; + } + + if (config.includeCompileSources()) { + toResolve.add(createResourceArtifact( + artifact, AbstractJavadocMojo.JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, config)); + } + + if (config.includeTestSources()) { + toResolve.add(createResourceArtifact( + artifact, AbstractJavadocMojo.TEST_JAVADOC_RESOURCES_ATTACHMENT_CLASSIFIER, config)); + } + } + + Collection dirs = new ArrayList<>(toResolve.size()); + try { + dirs = resolveAndUnpack(toResolve, config, RESOURCE_VALID_CLASSIFIERS, false); + } catch (ArtifactResolutionException | ArtifactNotFoundException e) { + if (getLogger().isDebugEnabled()) { + getLogger().debug(e.getMessage(), e); + } + } + + List result = new ArrayList<>(); + + for (Path d : dirs) { + File dir = d.toFile(); + File resources = new File(dir, ResourcesBundleMojo.RESOURCES_DIR_PATH); + JavadocOptions options = null; + + File javadocOptions = new File(dir, ResourcesBundleMojo.BUNDLE_OPTIONS_PATH); + if (javadocOptions.exists()) { + try (FileInputStream reader = new FileInputStream(javadocOptions)) { + options = new JavadocOptionsXpp3Reader().read(reader); + } catch (XmlPullParserException e) { + IOException error = new IOException("Failed to parse javadoc options: " + e.getMessage(), e); + throw error; + } + } + + result.add(new JavadocBundle(options, resources)); + } + + return result; + } + + private JavadocModule resolveFromArtifact(final SourceResolverConfig config, final Artifact artifact) + throws ArtifactResolutionException, ArtifactNotFoundException { + final List toResolve = new ArrayList<>(2); + + if (config.filter() != null + && !new ArtifactIncludeFilterTransformer() + .transform(config.filter()) + .include(artifact)) { + return null; + } + + if (config.includeCompileSources()) { + toResolve.add(createResourceArtifact(artifact, SOURCES_CLASSIFIER, config)); + } + + if (config.includeTestSources()) { + toResolve.add(createResourceArtifact(artifact, TEST_SOURCES_CLASSIFIER, config)); + } + + Collection sourcePaths = resolveAndUnpack(toResolve, config, SOURCE_VALID_CLASSIFIERS, true); + + return new JavadocModule(key(artifact.getGroupId(), artifact.getArtifactId()), artifact.getFile(), sourcePaths); + } + + private org.eclipse.aether.artifact.Artifact createResourceArtifact( + final Artifact artifact, final String classifier, final SourceResolverConfig config) { + return new org.eclipse.aether.artifact.DefaultArtifact( + artifact.getGroupId(), artifact.getArtifactId(), classifier, "jar", artifact.getVersion()); + } + + /** + * + * @param artifacts the artifacts to resolve + * @param config the configuration + * @param validClassifiers + * @param propagateErrors + * @return list of + * @throws ArtifactResolutionException if an exception occurs + * @throws ArtifactNotFoundException if an exception occurs + */ + private Collection resolveAndUnpack( + final List artifacts, + final SourceResolverConfig config, + final List validClassifiers, + final boolean propagateErrors) + throws ArtifactResolutionException, ArtifactNotFoundException { + // NOTE: Since these are '-sources' and '-test-sources' artifacts, they won't actually + // resolve transitively...this is just used to aggregate resolution failures into a single + // exception. + final Set artifactSet = new LinkedHashSet<>(artifacts); + + final DependencyFilter filter; + if (config.filter() != null) { + filter = new EclipseAetherFilterTransformer().transform(config.filter()); + } else { + filter = null; + } + + final List result = new ArrayList<>(artifacts.size()); + for (final org.eclipse.aether.artifact.Artifact a : artifactSet) { + if (!validClassifiers.contains(a.getClassifier()) + || (filter != null && !filter.accept(new DefaultDependencyNode(a), Collections.emptyList()))) { + continue; + } + + Artifact resolvedArtifact; + ArtifactRequest req = new ArtifactRequest(a, config.project().getRemoteProjectRepositories(), null); + try { + RepositorySystemSession repoSession = + config.getBuildingRequest().getRepositorySession(); + ArtifactResult resolutionResult = repoSystem.resolveArtifact(repoSession, req); + resolvedArtifact = RepositoryUtils.toArtifact(resolutionResult.getArtifact()); + } catch (org.eclipse.aether.resolution.ArtifactResolutionException e) { + continue; + } + final File d = new File( + config.outputBasedir(), a.getArtifactId() + "-" + a.getVersion() + "-" + a.getClassifier()); + + if (!d.exists()) { + d.mkdirs(); + } + + try { + final UnArchiver unArchiver = archiverManager.getUnArchiver(a.getExtension()); + + unArchiver.setDestDirectory(d); + unArchiver.setSourceFile(resolvedArtifact.getFile()); + + unArchiver.extract(); + + result.add(d.toPath().toAbsolutePath()); + } catch (final NoSuchArchiverException e) { + if (propagateErrors) { + throw new ArtifactResolutionException( + "Failed to retrieve valid un-archiver component: " + a.getExtension(), + RepositoryUtils.toArtifact(a), + e); + } + } catch (final ArchiverException e) { + if (propagateErrors) { + throw new ArtifactResolutionException("Failed to unpack: " + a, RepositoryUtils.toArtifact(a), e); + } + } + } + + return result; + } + + private static Collection resolveFromProject( + final SourceResolverConfig config, final MavenProject reactorProject, final Artifact artifact) { + final List dirs = new ArrayList<>(); + + if (config.filter() == null + || new ArtifactIncludeFilterTransformer() + .transform(config.filter()) + .include(artifact)) { + if (config.includeCompileSources()) { + final List srcRoots = reactorProject.getCompileSourceRoots(); + dirs.addAll(srcRoots); + } + + if (config.includeTestSources()) { + final List srcRoots = reactorProject.getTestCompileSourceRoots(); + dirs.addAll(srcRoots); + } + } + + return JavadocUtil.pruneDirs(reactorProject, dirs); + } + + private static String key(final String gid, final String aid) { + return gid + ":" + aid; + } +} diff --git a/src/main/java/org/apache/maven/plugins/javadoc/resolver/SourceResolverConfig.java b/src/main/java/org/apache/maven/plugins/javadoc/resolver/SourceResolverConfig.java index 1dd2af4d3..d1d82dbf0 100644 --- a/src/main/java/org/apache/maven/plugins/javadoc/resolver/SourceResolverConfig.java +++ b/src/main/java/org/apache/maven/plugins/javadoc/resolver/SourceResolverConfig.java @@ -1,172 +1,156 @@ -package org.apache.maven.plugins.javadoc.resolver; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.List; - -import org.apache.maven.project.MavenProject; -import org.apache.maven.project.ProjectBuildingRequest; -import org.apache.maven.shared.artifact.filter.resolve.AndFilter; - -/** - * - */ -public class SourceResolverConfig -{ - private ProjectBuildingRequest buildingRequest; - - private final MavenProject project; - - private AndFilter filter; - - private List reactorProjects; - - private final File outputBasedir; - - private boolean compileSourceIncluded; - - private boolean testSourceIncluded; - - /** - * @param project {@link MavenProject} - * @param buildingRequest {@link ProjectBuildingRequest} - * @param outputBasedir The output base directory. - */ - public SourceResolverConfig( final MavenProject project, final ProjectBuildingRequest buildingRequest, - final File outputBasedir ) - { - this.project = project; - this.buildingRequest = buildingRequest; - this.outputBasedir = outputBasedir; - } - - /** - * @param filter {@link AndFilter} - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withFilter( final AndFilter filter ) - { - this.filter = filter; - return this; - } - - /** - * @param reactorProjects The list of reactor projects. - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withReactorProjects( final List reactorProjects ) - { - this.reactorProjects = reactorProjects; - return this; - } - - /** - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withCompileSources() - { - compileSourceIncluded = true; - return this; - } - - /** - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withoutCompileSources() - { - compileSourceIncluded = false; - return this; - } - - /** - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withTestSources() - { - testSourceIncluded = true; - return this; - } - - /** - * @return {@link SourceResolverConfig} - */ - public SourceResolverConfig withoutTestSources() - { - testSourceIncluded = false; - return this; - } - - /** - * @return {@link MavenProject} - */ - public MavenProject project() - { - return project; - } - - /** - * @return {@link ProjectBuildingRequest} - */ - public ProjectBuildingRequest getBuildingRequest() - { - return buildingRequest; - } - - /** - * @return {@link AndFilter} - */ - public AndFilter filter() - { - return filter; - } - - /** - * @return list of {@link MavenProject} - */ - public List reactorProjects() - { - return reactorProjects; - } - - /** - * @return {@link #outputBasedir} - */ - public File outputBasedir() - { - return outputBasedir; - } - - /** - * @return {@link #compileSourceIncluded} - */ - public boolean includeCompileSources() - { - return compileSourceIncluded; - } - - /** - * @return {@link #testSourceIncluded} - */ - public boolean includeTestSources() - { - return testSourceIncluded; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.resolver; + +import java.io.File; +import java.util.List; + +import org.apache.maven.project.MavenProject; +import org.apache.maven.project.ProjectBuildingRequest; +import org.apache.maven.shared.artifact.filter.resolve.AndFilter; + +/** + * + */ +public class SourceResolverConfig { + private ProjectBuildingRequest buildingRequest; + + private final MavenProject project; + + private AndFilter filter; + + private List reactorProjects; + + private final File outputBasedir; + + private boolean compileSourceIncluded; + + private boolean testSourceIncluded; + + /** + * @param project {@link MavenProject} + * @param buildingRequest {@link ProjectBuildingRequest} + * @param outputBasedir The output base directory. + */ + public SourceResolverConfig( + final MavenProject project, final ProjectBuildingRequest buildingRequest, final File outputBasedir) { + this.project = project; + this.buildingRequest = buildingRequest; + this.outputBasedir = outputBasedir; + } + + /** + * @param filter {@link AndFilter} + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withFilter(final AndFilter filter) { + this.filter = filter; + return this; + } + + /** + * @param reactorProjects The list of reactor projects. + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withReactorProjects(final List reactorProjects) { + this.reactorProjects = reactorProjects; + return this; + } + + /** + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withCompileSources() { + compileSourceIncluded = true; + return this; + } + + /** + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withoutCompileSources() { + compileSourceIncluded = false; + return this; + } + + /** + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withTestSources() { + testSourceIncluded = true; + return this; + } + + /** + * @return {@link SourceResolverConfig} + */ + public SourceResolverConfig withoutTestSources() { + testSourceIncluded = false; + return this; + } + + /** + * @return {@link MavenProject} + */ + public MavenProject project() { + return project; + } + + /** + * @return {@link ProjectBuildingRequest} + */ + public ProjectBuildingRequest getBuildingRequest() { + return buildingRequest; + } + + /** + * @return {@link AndFilter} + */ + public AndFilter filter() { + return filter; + } + + /** + * @return list of {@link MavenProject} + */ + public List reactorProjects() { + return reactorProjects; + } + + /** + * @return {@link #outputBasedir} + */ + public File outputBasedir() { + return outputBasedir; + } + + /** + * @return {@link #compileSourceIncluded} + */ + public boolean includeCompileSources() { + return compileSourceIncluded; + } + + /** + * @return {@link #testSourceIncluded} + */ + public boolean includeTestSources() { + return testSourceIncluded; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojoTest.java b/src/test/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojoTest.java index 54c5dc6e7..9ac6415b8 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/AbstractFixJavadocMojoTest.java @@ -1,180 +1,146 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.StringReader; - -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.model.JavaClass; -import com.thoughtworks.qdox.model.JavaSource; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class AbstractFixJavadocMojoTest -{ - private JavaSource getJavaSource( String source ) - { - return new JavaProjectBuilder().addSource( new StringReader( source ) ); - } - - @Test - public void testReplaceLinkTags_noLinkTag() - { - String comment = "/** @see ConnectException */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class NoLinkTag {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "NoLinkTag" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - - assertThat( newComment ).isEqualTo( "/** @see ConnectException */" ); - } - - @Test - public void testReplaceLinkTags_oneLinkTag() - { - String comment = "/** {@link ConnectException} */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class OneLinkTag {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "OneLinkTag" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException} */" ); - } - - @Test - public void testReplaceLinkTags_missingEndBrace() - { - String comment = "/** {@link ConnectException */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class MissingEndBrace {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "MissingEndBrace" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link ConnectException */" ); - } - - @Test - public void testReplaceLinkTags_spacesAfterLinkTag() - { - String comment = "/** {@link ConnectException} */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class SpacesAfterLinkTag {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "SpacesAfterLinkTag" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException} */" ); - } - - @Test - public void testReplaceLinkTags_spacesAfterClassName() - { - String comment = "/** {@link ConnectException } */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class SpacesAfterClassName {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "SpacesAfterClassName" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException} */" ); - } - - @Test - public void testReplaceLinkTags_spacesAfterMethod() - { - String comment = "/** {@link ConnectException#getMessage() } */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class SpacesAfterMethod {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "SpacesAfterMethod" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException#getMessage()} */" ); - } - - @Test - public void testReplaceLinkTags_containingHash() - { - String comment = "/** {@link ConnectException#getMessage()} */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class ContainingHashes {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "ContainingHashes" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException#getMessage()} */" ); - } - - @Test - public void testReplaceLinkTags_followedByHash() - { - String comment = "/** {@link ConnectException} ##important## */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class FollowedByHash {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "FollowedByHash" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** {@link java.net.ConnectException} ##important## */" ); - } - - @Test - public void testReplaceLinkTags_twoLinks() - { - String comment = "/** Use {@link ConnectException} instead of {@link Exception} */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class TwoLinks {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "TwoLinks" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( - "/** Use {@link java.net.ConnectException} instead of {@link java.lang.Exception} */" ); - } - - @Test - public void testReplaceLinkTags_OnlyAnchor() - { - String comment = "/** There's a {@link #getClass()} but no setClass() */"; - String source = "import java.net.ConnectException;\n" - + comment + "\n" - + "public class OnlyAnchor {}"; - - JavaClass clazz = getJavaSource( source ).getClassByName( "OnlyAnchor" ); - - String newComment = AbstractFixJavadocMojo.replaceLinkTags( comment, clazz ); - assertThat( newComment ).isEqualTo( "/** There's a {@link #getClass()} but no setClass() */" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.StringReader; + +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.JavaClass; +import com.thoughtworks.qdox.model.JavaSource; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class AbstractFixJavadocMojoTest { + private JavaSource getJavaSource(String source) { + return new JavaProjectBuilder().addSource(new StringReader(source)); + } + + @Test + public void testReplaceLinkTags_noLinkTag() { + String comment = "/** @see ConnectException */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class NoLinkTag {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("NoLinkTag"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + + assertThat(newComment).isEqualTo("/** @see ConnectException */"); + } + + @Test + public void testReplaceLinkTags_oneLinkTag() { + String comment = "/** {@link ConnectException} */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class OneLinkTag {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("OneLinkTag"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException} */"); + } + + @Test + public void testReplaceLinkTags_missingEndBrace() { + String comment = "/** {@link ConnectException */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class MissingEndBrace {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("MissingEndBrace"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link ConnectException */"); + } + + @Test + public void testReplaceLinkTags_spacesAfterLinkTag() { + String comment = "/** {@link ConnectException} */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class SpacesAfterLinkTag {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("SpacesAfterLinkTag"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException} */"); + } + + @Test + public void testReplaceLinkTags_spacesAfterClassName() { + String comment = "/** {@link ConnectException } */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class SpacesAfterClassName {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("SpacesAfterClassName"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException} */"); + } + + @Test + public void testReplaceLinkTags_spacesAfterMethod() { + String comment = "/** {@link ConnectException#getMessage() } */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class SpacesAfterMethod {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("SpacesAfterMethod"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException#getMessage()} */"); + } + + @Test + public void testReplaceLinkTags_containingHash() { + String comment = "/** {@link ConnectException#getMessage()} */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class ContainingHashes {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("ContainingHashes"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException#getMessage()} */"); + } + + @Test + public void testReplaceLinkTags_followedByHash() { + String comment = "/** {@link ConnectException} ##important## */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class FollowedByHash {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("FollowedByHash"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** {@link java.net.ConnectException} ##important## */"); + } + + @Test + public void testReplaceLinkTags_twoLinks() { + String comment = "/** Use {@link ConnectException} instead of {@link Exception} */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class TwoLinks {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("TwoLinks"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment) + .isEqualTo("/** Use {@link java.net.ConnectException} instead of {@link java.lang.Exception} */"); + } + + @Test + public void testReplaceLinkTags_OnlyAnchor() { + String comment = "/** There's a {@link #getClass()} but no setClass() */"; + String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class OnlyAnchor {}"; + + JavaClass clazz = getJavaSource(source).getClassByName("OnlyAnchor"); + + String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz); + assertThat(newComment).isEqualTo("/** There's a {@link #getClass()} but no setClass() */"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojoTest.java b/src/test/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojoTest.java index 78046118d..8a6d5b4c2 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/AbstractJavadocMojoTest.java @@ -1,88 +1,83 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.never; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -import java.io.File; - -import org.apache.maven.plugin.logging.Log; - -import org.junit.Before; -import org.junit.Test; - -public class AbstractJavadocMojoTest -{ - AbstractJavadocMojo mojo; - - @Before - public void setUp() - { - mojo = new AbstractJavadocMojo() - { - @Override - public void doExecute() - { - } - }; - } - - @Test - public void testMJAVADOC432_DetectLinksMessages() - { - Log log = mock( Log.class ); - when( log.isErrorEnabled() ).thenReturn( true ); - mojo.setLog( log ); - mojo.outputDirectory = new File( "target/test-classes" ); - - // first continues after warning, next exits with warning - assertThat( mojo.isValidJavadocLink( new File( "pom.xml" ).getPath(), true ) ).isFalse(); - assertThat( mojo.isValidJavadocLink( "file://%%", true ) ).isFalse(); - assertThat( mojo.isValidJavadocLink( new File( "pom.xml" ).toURI().toString(), true ) ).isFalse(); - verify( log, times( 4 ) ).warn( anyString() ); - verify( log, never() ).error( anyString() ); - - // first continues after error, next exits with error - assertThat( mojo.isValidJavadocLink( new File( "pom.xml" ).getPath(), false ) ).isFalse(); - assertThat( mojo.isValidJavadocLink( "file://%%", false ) ).isFalse(); - assertThat( mojo.isValidJavadocLink( new File( "pom.xml" ).toURI().toString(), false ) ).isFalse(); - verify( log, times( 4 ) ).error( anyString() ); - verify( log, times( 4 ) ).warn( anyString() ); // no extra warnings - } - - @Test - public void testMJAVADOC527_DetectLinksRecursion() - { - Log log = mock( Log.class ); - when( log.isErrorEnabled() ).thenReturn( true ); - mojo.setLog( log ); - mojo.outputDirectory = new File( "target/test-classes" ); - - assertThat( mojo.isValidJavadocLink( "http://javamail.java.net/mailapi/apidocs", false ) ).isFalse(); - assertThat( - mojo.isValidJavadocLink( "http://commons.apache.org/proper/commons-lang/apidocs", false ) ).isTrue(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; + +import org.apache.maven.plugin.logging.Log; +import org.junit.Before; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +public class AbstractJavadocMojoTest { + AbstractJavadocMojo mojo; + + @Before + public void setUp() { + mojo = new AbstractJavadocMojo() { + @Override + public void doExecute() {} + }; + } + + @Test + public void testMJAVADOC432_DetectLinksMessages() { + Log log = mock(Log.class); + when(log.isErrorEnabled()).thenReturn(true); + mojo.setLog(log); + mojo.outputDirectory = new File("target/test-classes"); + + // first continues after warning, next exits with warning + assertThat(mojo.isValidJavadocLink(new File("pom.xml").getPath(), true)).isFalse(); + assertThat(mojo.isValidJavadocLink("file://%%", true)).isFalse(); + assertThat(mojo.isValidJavadocLink(new File("pom.xml").toURI().toString(), true)) + .isFalse(); + verify(log, times(4)).warn(anyString()); + verify(log, never()).error(anyString()); + + // first continues after error, next exits with error + assertThat(mojo.isValidJavadocLink(new File("pom.xml").getPath(), false)) + .isFalse(); + assertThat(mojo.isValidJavadocLink("file://%%", false)).isFalse(); + assertThat(mojo.isValidJavadocLink(new File("pom.xml").toURI().toString(), false)) + .isFalse(); + verify(log, times(4)).error(anyString()); + verify(log, times(4)).warn(anyString()); // no extra warnings + } + + @Test + public void testMJAVADOC527_DetectLinksRecursion() { + Log log = mock(Log.class); + when(log.isErrorEnabled()).thenReturn(true); + mojo.setLog(log); + mojo.outputDirectory = new File("target/test-classes"); + + assertThat(mojo.isValidJavadocLink("http://javamail.java.net/mailapi/apidocs", false)) + .isFalse(); + assertThat(mojo.isValidJavadocLink("http://commons.apache.org/proper/commons-lang/apidocs", false)) + .isTrue(); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReportTest.java b/src/test/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReportTest.java index 85d84305e..9097ab9e8 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReportTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/AggregatorJavadocReportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc; import java.io.BufferedReader; import java.io.File; @@ -38,9 +37,7 @@ import org.eclipse.aether.internal.impl.SimpleLocalRepositoryManagerFactory; import org.eclipse.aether.repository.LocalRepository; -public class AggregatorJavadocReportTest - extends AbstractMojoTestCase -{ +public class AggregatorJavadocReportTest extends AbstractMojoTestCase { private static final char LINE_SEPARATOR = ' '; /** flag to copy repo only one time */ @@ -52,35 +49,32 @@ public class AggregatorJavadocReportTest /** {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - unit = new File( getBasedir(), "src/test/resources/unit" ); + unit = new File(getBasedir(), "src/test/resources/unit"); - localRepo = new File( getBasedir(), "target/local-repo/" ); + localRepo = new File(getBasedir(), "target/local-repo/"); createTestRepo(); } - private JavadocReport lookupMojo( File testPom ) - throws Exception - { - JavadocReport mojo = (JavadocReport) lookupMojo( "aggregate", testPom ); + private JavadocReport lookupMojo(File testPom) throws Exception { + JavadocReport mojo = (JavadocReport) lookupMojo("aggregate", testPom); - MojoExecution mojoExec = new MojoExecution( new Plugin(), "aggregate", null ); - setVariableValueToObject( mojo, "mojo", mojoExec ); + MojoExecution mojoExec = new MojoExecution(new Plugin(), "aggregate", null); + setVariableValueToObject(mojo, "mojo", mojoExec); MavenProject currentProject = new MavenProjectStub(); - currentProject.setGroupId( "GROUPID" ); - currentProject.setArtifactId( "ARTIFACTID" ); + currentProject.setGroupId("GROUPID"); + currentProject.setArtifactId("ARTIFACTID"); - MavenSession session = newMavenSession( currentProject ); + MavenSession session = newMavenSession(currentProject); DefaultRepositorySystemSession repoSysSession = (DefaultRepositorySystemSession) session.getRepositorySession(); - repoSysSession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repoSysSession, new LocalRepository( localRepo ) ) ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repoSysSession ); + repoSysSession.setLocalRepositoryManager( + new SimpleLocalRepositoryManagerFactory().newInstance(repoSysSession, new LocalRepository(localRepo))); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repoSysSession); return mojo; } @@ -89,11 +83,8 @@ private JavadocReport lookupMojo( File testPom ) * * @throws IOException if any */ - private void createTestRepo() - throws IOException - { - if ( TEST_REPO_CREATED ) - { + private void createTestRepo() throws IOException { + if (TEST_REPO_CREATED) { return; } @@ -103,56 +94,52 @@ private void createTestRepo() // UMLGraph // ---------------------------------------------------------------------- - File sourceDir = new File( unit, "doclet-test/artifact-doclet" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); + File sourceDir = new File(unit, "doclet-test/artifact-doclet"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); // ---------------------------------------------------------------------- // UMLGraph-bis // ---------------------------------------------------------------------- - sourceDir = new File( unit, "doclet-path-test/artifact-doclet" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); + sourceDir = new File(unit, "doclet-path-test/artifact-doclet"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); // ---------------------------------------------------------------------- // commons-attributes-compiler // http://www.tullmann.org/pat/taglets/ // ---------------------------------------------------------------------- - sourceDir = new File( unit, "taglet-test/artifact-taglet" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); + sourceDir = new File(unit, "taglet-test/artifact-taglet"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); // ---------------------------------------------------------------------- // stylesheetfile-test // ---------------------------------------------------------------------- - sourceDir = new File( unit, "stylesheetfile-test/artifact-stylesheetfile" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); + sourceDir = new File(unit, "stylesheetfile-test/artifact-stylesheetfile"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); // ---------------------------------------------------------------------- // helpfile-test // ---------------------------------------------------------------------- - sourceDir = new File( unit, "helpfile-test/artifact-helpfile" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); + sourceDir = new File(unit, "helpfile-test/artifact-helpfile"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); // Remove SCM files - List files = FileUtils.getFileAndDirectoryNames( localRepo, FileUtils.getDefaultExcludesAsString(), - null, true, true, true, true ); - for ( String filename : files ) - { - File file = new File( filename ); - - if ( file.isDirectory() ) - { - FileUtils.deleteDirectory( file ); - } - else - { + List files = FileUtils.getFileAndDirectoryNames( + localRepo, FileUtils.getDefaultExcludesAsString(), null, true, true, true, true); + for (String filename : files) { + File file = new File(filename); + + if (file.isDirectory()) { + FileUtils.deleteDirectory(file); + } else { file.delete(); } } @@ -169,16 +156,14 @@ private void createTestRepo() * @return a String object that contains the contents of the file * @throws IOException if any */ - private static String readFile( File file ) - throws IOException - { - StringBuilder str = new StringBuilder( (int) file.length() ); + private static String readFile(File file) throws IOException { + StringBuilder str = new StringBuilder((int) file.length()); try (BufferedReader in = new BufferedReader(new FileReader(file))) { - for ( String strTmp ; ( strTmp = in.readLine() ) != null ; ) { - str.append( LINE_SEPARATOR ); - str.append( strTmp ); + for (String strTmp; (strTmp = in.readLine()) != null; ) { + str.append(LINE_SEPARATOR); + str.append(strTmp); } } @@ -190,26 +175,24 @@ private static String readFile( File file ) * * @throws Exception if any */ - public void testAggregate() - throws Exception - { - File testPom = new File( unit, "aggregate-test/aggregate-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testAggregate() throws Exception { + File testPom = new File(unit, "aggregate-test/aggregate-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - File apidocs = new File( getBasedir(), "target/test/unit/aggregate-test/target/site/apidocs/" ); + File apidocs = new File(getBasedir(), "target/test/unit/aggregate-test/target/site/apidocs/"); // check if project1 api files exist - assertTrue( new File( apidocs, "aggregate/test/project1/Project1App.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project1/Project1AppSample.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project1/Project1Sample.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project1/Project1Test.html" ).exists() ); + assertTrue(new File(apidocs, "aggregate/test/project1/Project1App.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project1/Project1AppSample.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project1/Project1Sample.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project1/Project1Test.html").exists()); // check if project2 api files exist - assertTrue( new File( apidocs, "aggregate/test/project2/Project2App.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project2/Project2AppSample.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project2/Project2Sample.html" ).exists() ); - assertTrue( new File( apidocs, "aggregate/test/project2/Project2Test.html" ).exists() ); + assertTrue(new File(apidocs, "aggregate/test/project2/Project2App.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project2/Project2AppSample.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project2/Project2Sample.html").exists()); + assertTrue(new File(apidocs, "aggregate/test/project2/Project2Test.html").exists()); } /** @@ -217,52 +200,47 @@ public void testAggregate() * * @throws Exception if any */ - public void testAggregateJavadocResources() - throws Exception - { - File testPom = new File( unit, "aggregate-resources-test/aggregate-resources-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testAggregateJavadocResources() throws Exception { + File testPom = new File(unit, "aggregate-resources-test/aggregate-resources-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - File apidocs = new File( getBasedir(), "target/test/unit/aggregate-resources-test/target/site/apidocs" ); + File apidocs = new File(getBasedir(), "target/test/unit/aggregate-resources-test/target/site/apidocs"); // Test overview File overviewSummary = getOverviewSummary(apidocs); - assertTrue( overviewSummary.exists() ); - String overview = readFile( overviewSummary ).toLowerCase( Locale.ENGLISH ); - assertTrue( overview.contains( "resources.test" ) ); - assertTrue( overview.contains( ">blablaresources.test2" ) ); - assertTrue( overview.contains( "resources2.test" ) ); - assertTrue( overview.contains( "resources2.test2" ) ); + assertTrue(overviewSummary.exists()); + String overview = readFile(overviewSummary).toLowerCase(Locale.ENGLISH); + assertTrue(overview.contains("resources.test")); + assertTrue(overview.contains(">blablaresources.test2")); + assertTrue(overview.contains("resources2.test")); + assertTrue(overview.contains("resources2.test2")); // Test doc-files - File app = new File( apidocs, "resources/test/App.html" ); - assertTrue( app.exists() ); - overview = readFile( app ); - assertTrue( overview.contains( "\"Maven\"" ) ); - assertTrue( new File( apidocs, "resources/test/doc-files/maven-feather.png" ).exists() ); + File app = new File(apidocs, "resources/test/App.html"); + assertTrue(app.exists()); + overview = readFile(app); + assertTrue(overview.contains("\"Maven\"")); + assertTrue(new File(apidocs, "resources/test/doc-files/maven-feather.png").exists()); } - public void testAggregateWithModulsNotInSubFolders() throws Exception - { - File testPom = new File( unit, "aggregate-modules-not-in-subfolders-test/all/pom.xml"); - JavadocReport mojo = lookupMojo( testPom ); - mojo.execute(); + public void testAggregateWithModulsNotInSubFolders() throws Exception { + File testPom = new File(unit, "aggregate-modules-not-in-subfolders-test/all/pom.xml"); + JavadocReport mojo = lookupMojo(testPom); + mojo.execute(); - File apidocs = new File( getBasedir(), "target/test/unit/aggregate-modules-not-in-subfolders-test/target/site/apidocs" ); - assertTrue( apidocs.isDirectory() ); - assertTrue( getOverviewSummary( apidocs ).isFile() ); + File apidocs = + new File(getBasedir(), "target/test/unit/aggregate-modules-not-in-subfolders-test/target/site/apidocs"); + assertTrue(apidocs.isDirectory()); + assertTrue(getOverviewSummary(apidocs).isFile()); } - private static File getOverviewSummary(File apidocs) - { - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "11" ) ) - { - return new File( apidocs, "overview-summary.html" ); - } - return new File( apidocs, "index.html" ); + private static File getOverviewSummary(File apidocs) { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) { + return new File(apidocs, "overview-summary.html"); + } + return new File(apidocs, "index.html"); } - } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/FixJavadocMojoTest.java b/src/test/java/org/apache/maven/plugins/javadoc/FixJavadocMojoTest.java index d4f4b908d..4a00d9f37 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/FixJavadocMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/FixJavadocMojoTest.java @@ -1,658 +1,614 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.io.IOException; -import java.io.StringReader; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Properties; - -import org.apache.maven.execution.MavenSession; -import org.apache.maven.plugin.logging.Log; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.plugins.javadoc.AbstractFixJavadocMojo.JavaEntityTags; -import org.apache.maven.shared.invoker.MavenInvocationException; -import org.codehaus.plexus.languages.java.version.JavaVersion; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.StringUtils; - -import com.thoughtworks.qdox.JavaProjectBuilder; -import com.thoughtworks.qdox.model.DocletTag; -import com.thoughtworks.qdox.model.JavaClass; -import com.thoughtworks.qdox.model.JavaMethod; - -import static org.apache.commons.lang3.reflect.MethodUtils.invokeMethod; - -/** - * @author Vincent Siveton - */ -public class FixJavadocMojoTest - extends AbstractMojoTestCase -{ - /** The vm line separator */ - private static final String EOL = System.getProperty( "line.separator" ); - - /** flag to copy repo only one time */ - private static boolean TEST_REPO_CREATED = false; - - /** {@inheritDoc} */ - @Override - protected void setUp() - throws Exception - { - super.setUp(); - - createTestRepo(); - } - - /** - * Create test repository in target directory. - * - * @throws IOException if any - */ - private void createTestRepo() - throws Exception - { - if ( TEST_REPO_CREATED ) - { - return; - } - - File localRepo = new File( getBasedir(), "target/local-repo/" ); - localRepo.mkdirs(); - - // ---------------------------------------------------------------------- - // fix-test-1.0.jar - // ---------------------------------------------------------------------- - - File sourceDir = new File( getBasedir(), "src/test/resources/unit/fix-test/repo/" ); - assertTrue( sourceDir.exists() ); - FileUtils.copyDirectoryStructure( sourceDir, localRepo ); - - - // Remove SCM files - List files = - FileUtils.getFileAndDirectoryNames( localRepo, FileUtils.getDefaultExcludesAsString(), null, true, - true, true, true ); - for ( String filename : files ) - { - File file = new File( filename ); - - if ( file.isDirectory() ) - { - FileUtils.deleteDirectory( file ); - } - else - { - file.delete(); - } - } - - TEST_REPO_CREATED = true; - } - - /** - * @throws Exception if any - */ - public void testFix() - throws Exception - { - File testPomBasedir = new File( getBasedir(), "target/test/unit/fix-test" ); - - executeMojoAndTest( testPomBasedir, new String[] { "ClassWithJavadoc.java", "ClassWithNoJavadoc.java", - "InterfaceWithJavadoc.java", "InterfaceWithNoJavadoc.java" } ); - } - - // ---------------------------------------------------------------------- - // Test private static methods - // ---------------------------------------------------------------------- - - /** - * @throws Exception if any - */ - public void testAutodetectIndentation() - throws Exception - { - Method method = AbstractFixJavadocMojo.class.getDeclaredMethod( "autodetectIndentation", String.class ); - method.setAccessible( true ); - - String s = null; - assertEquals( "", (String) method.invoke( null, s ) ); - - s = "no indentation"; - assertEquals( "", (String) method.invoke( null, s ) ); - - s = "no indentation with right spaces "; - assertEquals( "", (String) method.invoke( null, s ) ); - - s = " indentation"; - assertEquals( " ", (String) method.invoke( null, s ) ); - - s = " indentation with right spaces "; - assertEquals( " ", (String) method.invoke( null, s ) ); - - s = "\ttab indentation"; - assertEquals( "\t", (String) method.invoke( null, s ) ); - - s = " \n indentation with right spaces "; - assertEquals( " \n ", (String) method.invoke( null, s ) ); - } - - /** - * @throws Exception if any - */ - public void testTrimLeft() - throws Exception - { - Method method = AbstractFixJavadocMojo.class.getDeclaredMethod( "trimLeft", String.class ); - method.setAccessible( true ); - - assertEquals( "", (String) method.invoke( null, (String) null ) ); - assertEquals( "", (String) method.invoke( null, " " ) ); - assertEquals( "", (String) method.invoke( null, " \t " ) ); - assertEquals( "a", (String) method.invoke( null, "a" ) ); - assertEquals( "a", (String) method.invoke( null, " a" ) ); - assertEquals( "a", (String) method.invoke( null, "\ta" ) ); - assertEquals( "a ", (String) method.invoke( null, " a " ) ); - assertEquals( "a\t", (String) method.invoke( null, "\ta\t" ) ); - } - - /** - * @throws Exception if any - */ - public void testTrimRight() - throws Exception - { - Method method = AbstractFixJavadocMojo.class.getDeclaredMethod( "trimRight", String.class ); - method.setAccessible( true ); - - assertEquals( "", (String) method.invoke( null, (String)null ) ); - assertEquals( "", (String) method.invoke( null, " " ) ); - assertEquals( "", (String) method.invoke( null, " \t " ) ); - assertEquals( "a", (String) method.invoke( null, "a" ) ); - assertEquals( "a", (String) method.invoke( null, "a " ) ); - assertEquals( "a", (String) method.invoke( null, "a\t" ) ); - assertEquals( " a", (String) method.invoke( null, " a " ) ); - assertEquals( "\ta", (String) method.invoke( null, "\ta\t" ) ); - } - - /** - * @throws Exception if any - */ - public void testHasInheritedTag() - throws Exception - { - Method method = AbstractFixJavadocMojo.class.getDeclaredMethod( "hasInheritedTag", String.class ); - method.setAccessible( true ); - - String content = "/** {@inheritDoc} */"; - Boolean has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.TRUE, has ); - - content = "/**{@inheritDoc}*/"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.TRUE, has ); - - content = "/**{@inheritDoc } */"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.TRUE, has ); - - content = "/** {@inheritDoc } */"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.TRUE, has ); - - content = "/** */"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.FALSE, has ); - - content = "/**{ @inheritDoc }*/"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.FALSE, has ); - - content = "/**{@ inheritDoc}*/"; - has = (Boolean) method.invoke( null, content ); - assertEquals( Boolean.FALSE, has ); - } - - /** - * @throws Throwable if any - */ - public void testJavadocComment() - throws Throwable - { - String content = "/**" + EOL + - " * Dummy Class." + EOL + - " */" + EOL + - "public class DummyClass" + EOL + - "{" + EOL + - " /**" + EOL + - " *" + EOL + - " * Dummy" + EOL + - " *" + EOL + - " * Method." + EOL + - " *" + EOL + - " * @param args not" + EOL + - " *" + EOL + - " * null" + EOL + - " * @param i non negative" + EOL + - " * @param object could" + EOL + - " * be" + EOL + - " * null" + EOL + - " * @return a" + EOL + - " * String" + EOL + - " *" + EOL + - " * @throws Exception if" + EOL + - " * any" + EOL + - " *" + EOL + - " */" + EOL + - " public static String dummyMethod( String[] args, int i, Object object )" + EOL + - " throws Exception" + EOL + - " {" + EOL + - " return null;" + EOL + - " }" + EOL + - "}"; - - JavaProjectBuilder builder = new JavaProjectBuilder(); - builder.setEncoding( "UTF-8" ); - builder.addSource( new StringReader( content ) ); - - JavaClass clazz = builder.addSource( new StringReader( content ) ).getClassByName( "DummyClass" ); - - JavaMethod javaMethod = clazz.getMethods().get( 0 ); - - String javadoc = AbstractFixJavadocMojo.extractOriginalJavadoc( content, javaMethod ); - assertEquals( " /**" + EOL + - " *" + EOL + - " * Dummy" + EOL + - " *" + EOL + - " * Method." + EOL + - " *" + EOL + - " * @param args not" + EOL + - " *" + EOL + - " * null" + EOL + - " * @param i non negative" + EOL + - " * @param object could" + EOL + - " * be" + EOL + - " * null" + EOL + - " * @return a" + EOL + - " * String" + EOL + - " *" + EOL + - " * @throws Exception if" + EOL + - " * any" + EOL + - " *" + EOL + - " */", javadoc ); - - String javadocContent = AbstractFixJavadocMojo.extractOriginalJavadocContent( content, javaMethod ); - assertEquals( " *" + EOL + - " * Dummy" + EOL + - " *" + EOL + - " * Method." + EOL + - " *" + EOL + - " * @param args not" + EOL + - " *" + EOL + - " * null" + EOL + - " * @param i non negative" + EOL + - " * @param object could" + EOL + - " * be" + EOL + - " * null" + EOL + - " * @return a" + EOL + - " * String" + EOL + - " *" + EOL + - " * @throws Exception if" + EOL + - " * any" + EOL + - " *", javadocContent ); - - Method method = AbstractFixJavadocMojo.class.getDeclaredMethod( "removeLastEmptyJavadocLines", String.class ); - method.setAccessible( true ); - - String withoutEmptyJavadocLines = (String) method.invoke( null, javadocContent ); - assertTrue( withoutEmptyJavadocLines.endsWith( "any" ) ); - - String methodJavadoc = AbstractFixJavadocMojo.getJavadocComment( content, javaMethod ); - assertEquals( " *" + EOL + - " * Dummy" + EOL + - " *" + EOL + - " * Method." + EOL + - " *", methodJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, methodJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "Method." ) ); - - assertEquals( 5, javaMethod.getTags().size() ); - - AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); - setVariableValueToObject( mojoInstance, "fixTagsSplitted", new String[] { "all" } ); - - DocletTag tag = javaMethod.getTags().get( 0 ); - String tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag); - assertEquals( " * @param args not" + EOL + - " *" + EOL + - " * null", tagJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, tagJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "null" ) ); - - tag = javaMethod.getTags().get( 1 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @param i non negative", tagJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, tagJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "negative" ) ); - - tag = javaMethod.getTags().get( 2 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @param object could" + EOL + - " * be" + EOL + - " * null", tagJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, tagJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "null" ) ); - - tag = javaMethod.getTags().get( 3 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @return a" + EOL + - " * String" + EOL + - " *", tagJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, tagJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "String" ) ); - - tag = javaMethod.getTags().get( 4 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @throws Exception if" + EOL + - " * any" + EOL + - " *", tagJavadoc ); - withoutEmptyJavadocLines = (String) method.invoke( null, tagJavadoc ); - assertTrue( withoutEmptyJavadocLines.endsWith( "any" ) ); - } - - public void testJavadocCommentJdk5() - throws Exception - { - String content = "/**" + EOL + - " * Dummy Class." + EOL + - " */" + EOL + - "public class DummyClass" + EOL + - "{" + EOL + - " /**" + EOL + - " * Dummy method." + EOL + - " *" + EOL + - " * @param The Key type for the method" + EOL + - " * @param The Value type for the method" + EOL + - " * @param name The name." + EOL + - " * @return A map configured." + EOL + - " */" + EOL + - " public java.util.Map dummyMethod( String name )" + EOL + - " {" + EOL + - " return null;" + EOL + - " }" + EOL + - "}"; - - JavaProjectBuilder builder = new JavaProjectBuilder(); - builder.setEncoding( "UTF-8" ); - JavaClass clazz = builder.addSource( new StringReader( content ) ).getClassByName( "DummyClass" ); - - JavaMethod javaMethod = clazz.getMethods().get( 0 ); - - String methodJavadoc = AbstractFixJavadocMojo.getJavadocComment( content, javaMethod ); - assertEquals( " * Dummy method." + EOL + - " *", methodJavadoc ); - - assertEquals( 4, javaMethod.getTags().size() ); - - AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); - setVariableValueToObject( mojoInstance, "fixTagsSplitted", new String[] { "all" } ); - - DocletTag tag = javaMethod.getTags().get( 0 ); - String tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @param The Key type for the method", tagJavadoc ); - - tag = javaMethod.getTags().get( 1 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @param The Value type for the method", tagJavadoc ); - - tag = javaMethod.getTags().get( 2 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @param name The name.", tagJavadoc ); - - tag = javaMethod.getTags().get( 3 ); - tagJavadoc = mojoInstance.getJavadocComment( content, javaMethod, tag ); - assertEquals( " * @return A map configured.", tagJavadoc ); - } - - public void testInitParameters() - throws Throwable - { - AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); - setVariableValueToObject( mojoInstance, "fixTags", "author, version, since, param, return, throws, link" ); - setVariableValueToObject(mojoInstance, "defaultSince", "1.0"); - setVariableValueToObject(mojoInstance, "level", "protected"); - - invokeMethod( mojoInstance, true, "init" ); - - String[] fixTags = (String[]) getVariableValueFromObject(mojoInstance, "fixTagsSplitted"); - - assertEquals("author", fixTags[0]); - assertEquals("version", fixTags[1]); - assertEquals("since", fixTags[2]); - assertEquals("param", fixTags[3]); - assertEquals("return", fixTags[4]); - assertEquals("throws", fixTags[5]); - assertEquals("link", fixTags[6]); - assertEquals(7, fixTags.length); - - setVariableValueToObject( mojoInstance, "fixTags", "return, fake_value" ); - invokeMethod( mojoInstance, true, "init" ); - fixTags = (String[]) getVariableValueFromObject(mojoInstance, "fixTagsSplitted"); - - assertEquals("return", fixTags[0]); - assertEquals(1, fixTags.length); - } - - public void testRemoveUnknownExceptions() throws Exception - { - AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); - setVariableValueToObject( mojoInstance, "fixTagsSplitted", new String[] { "all" } ); - setVariableValueToObject( mojoInstance, "project", new MavenProjectStub() ); - - String source = "package a.b.c;" + EOL - + "public class Clazz {" + EOL - + " /**" + EOL - + " * @throws java.lang.RuntimeException" + EOL - + " * @throws NumberFormatException" + EOL - + " * @throws java.lang.Exception" + EOL // not thrown and no RTE -> remove - + " * @throws com.foo.FatalException" + EOL // not on classpath (?!) -> see removeUnknownThrows - + " */" + EOL - + " public void method() {}" + EOL - + "}"; - - JavaProjectBuilder builder = new JavaProjectBuilder(); - JavaMethod javaMethod = builder.addSource( new StringReader( source ) ).getClassByName( "Clazz" ).getMethods().get( 0 ); - - JavaEntityTags javaEntityTags = mojoInstance.parseJavadocTags( source, javaMethod, "", true ); - - StringBuilder sb = new StringBuilder(); - mojoInstance.writeThrowsTag( sb, javaMethod, javaEntityTags, Collections.singletonList("java.lang" + - ".RuntimeException")); - assertEquals( " * @throws java.lang.RuntimeException", sb.toString() ); - - sb = new StringBuilder(); - mojoInstance.writeThrowsTag( sb, javaMethod, javaEntityTags, Collections.singletonList("NumberFormatException")); - assertEquals( " * @throws java.lang.NumberFormatException", sb.toString() ); - - sb = new StringBuilder(); - mojoInstance.writeThrowsTag( sb, javaMethod, javaEntityTags, Collections.singletonList("java.lang.Exception")); - assertEquals( "", sb.toString() ); - - setVariableValueToObject( mojoInstance, "removeUnknownThrows", true ); - sb = new StringBuilder(); - mojoInstance.writeThrowsTag( sb, javaMethod, javaEntityTags, Collections.singletonList("com.foo.FatalException")); - assertEquals( "", sb.toString() ); - - setVariableValueToObject( mojoInstance, "removeUnknownThrows", false ); - sb = new StringBuilder(); - mojoInstance.writeThrowsTag( sb, javaMethod, javaEntityTags, Collections.singletonList("com.foo.FatalException")); - assertEquals( " * @throws com.foo.FatalException if any.", sb.toString() ); - } - - // ---------------------------------------------------------------------- - // private methods - // ---------------------------------------------------------------------- - - /** - * @param testPomBasedir the basedir for the test project - * @param clazzToCompare an array of the classes name to compare - * @throws Exception if any - */ - private void executeMojoAndTest( File testPomBasedir, String[] clazzToCompare ) - throws Exception - { - prepareTestProjects( testPomBasedir.getName() ); - - File testPom = new File( testPomBasedir, "pom.xml" ); - assertTrue( testPom.getAbsolutePath() + " should exist", testPom.exists() ); - - FixJavadocMojo mojo = (FixJavadocMojo) lookupMojo( "fix", testPom ); - assertNotNull( mojo ); - - MavenSession session = newMavenSession( mojo.getProject() ); - // Ensure remote repo connection uses SSL - File globalSettingsFile = new File( getBasedir(), "target/test-classes/unit/settings.xml" ); - session.getRequest().setGlobalSettingsFile( globalSettingsFile ); - setVariableValueToObject( mojo, "session", session ); - - // compile the test project - invokeCompileGoal( testPom, globalSettingsFile, mojo.getLog() ); - assertTrue( new File( testPomBasedir, "target/classes" ).exists() ); - - mojo.execute(); - - File expectedDir = new File( testPomBasedir, "expected/src/main/java/fix/test" ); - assertTrue( expectedDir.exists() ); - - File generatedDir = new File( testPomBasedir, "target/generated/fix/test" ); - assertTrue( generatedDir.exists() ); - - for (String className : clazzToCompare) { - assertEquals(new File(expectedDir, className), new File(generatedDir, className)); - } - } - - /** - * Invoke the compilation on the given pom file. - * - * @param testPom not null - * @param log not null - * @throws MavenInvocationException if any - */ - private void invokeCompileGoal( File testPom, File globalSettingsFile, Log log ) - throws Exception - { - List goals = new ArrayList<>(); - goals.add( "clean" ); - goals.add( "compile" ); - File invokerDir = new File( getBasedir(), "target/invoker" ); - invokerDir.mkdirs(); - File invokerLogFile = FileUtils.createTempFile( "FixJavadocMojoTest", ".txt", invokerDir ); - - Properties properties = new Properties(); - - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "12" ) ) - { - properties.put( "maven.compiler.source", "1.7" ); - properties.put( "maven.compiler.target", "1.7" ); - } - else if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "9" ) ) - { - properties.put( "maven.compiler.source", "1.6" ); - properties.put( "maven.compiler.target", "1.6" ); - } - - // @todo unittests shouldn't need to go remote - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "8" ) ) - { - // ensure that Java7 picks up TLSv1.2 when connecting with Central - properties.put( "https.protocols", "TLSv1.2" ); - } - - JavadocUtil.invokeMaven( log, new File( getBasedir(), "target/local-repo" ), testPom, goals, properties, - invokerLogFile, globalSettingsFile ); - } - - // ---------------------------------------------------------------------- - // static methods - // ---------------------------------------------------------------------- - - /** - * Asserts that files are equal. If they are not an AssertionFailedError is thrown. - * - * @throws IOException if any - */ - private static void assertEquals( File expected, File actual ) - throws Exception - { - assertTrue( " Expected file DNE: " + expected, expected.exists() ); - String expectedContent = StringUtils.unifyLineSeparators( readFile( expected ) ); - - assertTrue( " Actual file DNE: " + actual, actual.exists() ); - String actualContent = StringUtils.unifyLineSeparators( readFile( actual ) ); - - assertEquals( "Expected file: " + expected.getAbsolutePath() + ", actual file: " - + actual.getAbsolutePath(), expectedContent, actualContent ); - } - - /** - * @param testProjectDirName not null - * @throws IOException if any - */ - private static void prepareTestProjects( String testProjectDirName ) - throws Exception - { - File testPomBasedir = new File( getBasedir(), "target/test/unit/" + testProjectDirName ); - - // Using unit test dir - FileUtils - .copyDirectoryStructure( - new File( getBasedir(), "src/test/resources/unit/" + testProjectDirName ), - testPomBasedir ); - List scmFiles = FileUtils.getDirectoryNames( testPomBasedir, "**/.svn", null, true ); - for ( String filename : scmFiles ) - { - File dir = new File( filename ); - - if ( dir.isDirectory() ) - { - FileUtils.deleteDirectory( dir ); - } - } - } - - /** - * @param file not null - * @return the content of the given file - * @throws IOException if any - */ - private static String readFile( File file ) - throws Exception - { - String content = FileUtils.fileRead( file, "UTF-8" ); - return content; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Properties; + +import com.thoughtworks.qdox.JavaProjectBuilder; +import com.thoughtworks.qdox.model.DocletTag; +import com.thoughtworks.qdox.model.JavaClass; +import com.thoughtworks.qdox.model.JavaMethod; +import org.apache.maven.execution.MavenSession; +import org.apache.maven.plugin.logging.Log; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.plugins.javadoc.AbstractFixJavadocMojo.JavaEntityTags; +import org.apache.maven.shared.invoker.MavenInvocationException; +import org.codehaus.plexus.languages.java.version.JavaVersion; +import org.codehaus.plexus.util.FileUtils; +import org.codehaus.plexus.util.StringUtils; + +import static org.apache.commons.lang3.reflect.MethodUtils.invokeMethod; + +/** + * @author Vincent Siveton + */ +public class FixJavadocMojoTest extends AbstractMojoTestCase { + /** The vm line separator */ + private static final String EOL = System.getProperty("line.separator"); + + /** flag to copy repo only one time */ + private static boolean TEST_REPO_CREATED = false; + + /** {@inheritDoc} */ + @Override + protected void setUp() throws Exception { + super.setUp(); + + createTestRepo(); + } + + /** + * Create test repository in target directory. + * + * @throws IOException if any + */ + private void createTestRepo() throws Exception { + if (TEST_REPO_CREATED) { + return; + } + + File localRepo = new File(getBasedir(), "target/local-repo/"); + localRepo.mkdirs(); + + // ---------------------------------------------------------------------- + // fix-test-1.0.jar + // ---------------------------------------------------------------------- + + File sourceDir = new File(getBasedir(), "src/test/resources/unit/fix-test/repo/"); + assertTrue(sourceDir.exists()); + FileUtils.copyDirectoryStructure(sourceDir, localRepo); + + // Remove SCM files + List files = FileUtils.getFileAndDirectoryNames( + localRepo, FileUtils.getDefaultExcludesAsString(), null, true, true, true, true); + for (String filename : files) { + File file = new File(filename); + + if (file.isDirectory()) { + FileUtils.deleteDirectory(file); + } else { + file.delete(); + } + } + + TEST_REPO_CREATED = true; + } + + /** + * @throws Exception if any + */ + public void testFix() throws Exception { + File testPomBasedir = new File(getBasedir(), "target/test/unit/fix-test"); + + executeMojoAndTest(testPomBasedir, new String[] { + "ClassWithJavadoc.java", + "ClassWithNoJavadoc.java", + "InterfaceWithJavadoc.java", + "InterfaceWithNoJavadoc.java" + }); + } + + // ---------------------------------------------------------------------- + // Test private static methods + // ---------------------------------------------------------------------- + + /** + * @throws Exception if any + */ + public void testAutodetectIndentation() throws Exception { + Method method = AbstractFixJavadocMojo.class.getDeclaredMethod("autodetectIndentation", String.class); + method.setAccessible(true); + + String s = null; + assertEquals("", (String) method.invoke(null, s)); + + s = "no indentation"; + assertEquals("", (String) method.invoke(null, s)); + + s = "no indentation with right spaces "; + assertEquals("", (String) method.invoke(null, s)); + + s = " indentation"; + assertEquals(" ", (String) method.invoke(null, s)); + + s = " indentation with right spaces "; + assertEquals(" ", (String) method.invoke(null, s)); + + s = "\ttab indentation"; + assertEquals("\t", (String) method.invoke(null, s)); + + s = " \n indentation with right spaces "; + assertEquals(" \n ", (String) method.invoke(null, s)); + } + + /** + * @throws Exception if any + */ + public void testTrimLeft() throws Exception { + Method method = AbstractFixJavadocMojo.class.getDeclaredMethod("trimLeft", String.class); + method.setAccessible(true); + + assertEquals("", (String) method.invoke(null, (String) null)); + assertEquals("", (String) method.invoke(null, " ")); + assertEquals("", (String) method.invoke(null, " \t ")); + assertEquals("a", (String) method.invoke(null, "a")); + assertEquals("a", (String) method.invoke(null, " a")); + assertEquals("a", (String) method.invoke(null, "\ta")); + assertEquals("a ", (String) method.invoke(null, " a ")); + assertEquals("a\t", (String) method.invoke(null, "\ta\t")); + } + + /** + * @throws Exception if any + */ + public void testTrimRight() throws Exception { + Method method = AbstractFixJavadocMojo.class.getDeclaredMethod("trimRight", String.class); + method.setAccessible(true); + + assertEquals("", (String) method.invoke(null, (String) null)); + assertEquals("", (String) method.invoke(null, " ")); + assertEquals("", (String) method.invoke(null, " \t ")); + assertEquals("a", (String) method.invoke(null, "a")); + assertEquals("a", (String) method.invoke(null, "a ")); + assertEquals("a", (String) method.invoke(null, "a\t")); + assertEquals(" a", (String) method.invoke(null, " a ")); + assertEquals("\ta", (String) method.invoke(null, "\ta\t")); + } + + /** + * @throws Exception if any + */ + public void testHasInheritedTag() throws Exception { + Method method = AbstractFixJavadocMojo.class.getDeclaredMethod("hasInheritedTag", String.class); + method.setAccessible(true); + + String content = "/** {@inheritDoc} */"; + Boolean has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.TRUE, has); + + content = "/**{@inheritDoc}*/"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.TRUE, has); + + content = "/**{@inheritDoc } */"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.TRUE, has); + + content = "/** {@inheritDoc } */"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.TRUE, has); + + content = "/** */"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.FALSE, has); + + content = "/**{ @inheritDoc }*/"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.FALSE, has); + + content = "/**{@ inheritDoc}*/"; + has = (Boolean) method.invoke(null, content); + assertEquals(Boolean.FALSE, has); + } + + /** + * @throws Throwable if any + */ + public void testJavadocComment() throws Throwable { + String content = "/**" + EOL + " * Dummy Class." + + EOL + " */" + + EOL + "public class DummyClass" + + EOL + "{" + + EOL + " /**" + + EOL + " *" + + EOL + " * Dummy" + + EOL + " *" + + EOL + " * Method." + + EOL + " *" + + EOL + " * @param args not" + + EOL + " *" + + EOL + " * null" + + EOL + " * @param i non negative" + + EOL + " * @param object could" + + EOL + " * be" + + EOL + " * null" + + EOL + " * @return a" + + EOL + " * String" + + EOL + " *" + + EOL + " * @throws Exception if" + + EOL + " * any" + + EOL + " *" + + EOL + " */" + + EOL + " public static String dummyMethod( String[] args, int i, Object object )" + + EOL + " throws Exception" + + EOL + " {" + + EOL + " return null;" + + EOL + " }" + + EOL + "}"; + + JavaProjectBuilder builder = new JavaProjectBuilder(); + builder.setEncoding("UTF-8"); + builder.addSource(new StringReader(content)); + + JavaClass clazz = builder.addSource(new StringReader(content)).getClassByName("DummyClass"); + + JavaMethod javaMethod = clazz.getMethods().get(0); + + String javadoc = AbstractFixJavadocMojo.extractOriginalJavadoc(content, javaMethod); + assertEquals( + " /**" + EOL + " *" + + EOL + " * Dummy" + + EOL + " *" + + EOL + " * Method." + + EOL + " *" + + EOL + " * @param args not" + + EOL + " *" + + EOL + " * null" + + EOL + " * @param i non negative" + + EOL + " * @param object could" + + EOL + " * be" + + EOL + " * null" + + EOL + " * @return a" + + EOL + " * String" + + EOL + " *" + + EOL + " * @throws Exception if" + + EOL + " * any" + + EOL + " *" + + EOL + " */", + javadoc); + + String javadocContent = AbstractFixJavadocMojo.extractOriginalJavadocContent(content, javaMethod); + assertEquals( + " *" + EOL + " * Dummy" + + EOL + " *" + + EOL + " * Method." + + EOL + " *" + + EOL + " * @param args not" + + EOL + " *" + + EOL + " * null" + + EOL + " * @param i non negative" + + EOL + " * @param object could" + + EOL + " * be" + + EOL + " * null" + + EOL + " * @return a" + + EOL + " * String" + + EOL + " *" + + EOL + " * @throws Exception if" + + EOL + " * any" + + EOL + " *", + javadocContent); + + Method method = AbstractFixJavadocMojo.class.getDeclaredMethod("removeLastEmptyJavadocLines", String.class); + method.setAccessible(true); + + String withoutEmptyJavadocLines = (String) method.invoke(null, javadocContent); + assertTrue(withoutEmptyJavadocLines.endsWith("any")); + + String methodJavadoc = AbstractFixJavadocMojo.getJavadocComment(content, javaMethod); + assertEquals( + " *" + EOL + " * Dummy" + EOL + " *" + EOL + " * Method." + EOL + " *", + methodJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, methodJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("Method.")); + + assertEquals(5, javaMethod.getTags().size()); + + AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); + setVariableValueToObject(mojoInstance, "fixTagsSplitted", new String[] {"all"}); + + DocletTag tag = javaMethod.getTags().get(0); + String tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param args not" + EOL + " *" + EOL + " * null", tagJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, tagJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("null")); + + tag = javaMethod.getTags().get(1); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param i non negative", tagJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, tagJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("negative")); + + tag = javaMethod.getTags().get(2); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param object could" + EOL + " * be" + EOL + " * null", tagJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, tagJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("null")); + + tag = javaMethod.getTags().get(3); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @return a" + EOL + " * String" + EOL + " *", tagJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, tagJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("String")); + + tag = javaMethod.getTags().get(4); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @throws Exception if" + EOL + " * any" + EOL + " *", tagJavadoc); + withoutEmptyJavadocLines = (String) method.invoke(null, tagJavadoc); + assertTrue(withoutEmptyJavadocLines.endsWith("any")); + } + + public void testJavadocCommentJdk5() throws Exception { + String content = "/**" + EOL + " * Dummy Class." + + EOL + " */" + + EOL + "public class DummyClass" + + EOL + "{" + + EOL + " /**" + + EOL + " * Dummy method." + + EOL + " *" + + EOL + " * @param The Key type for the method" + + EOL + " * @param The Value type for the method" + + EOL + " * @param name The name." + + EOL + " * @return A map configured." + + EOL + " */" + + EOL + " public java.util.Map dummyMethod( String name )" + + EOL + " {" + + EOL + " return null;" + + EOL + " }" + + EOL + "}"; + + JavaProjectBuilder builder = new JavaProjectBuilder(); + builder.setEncoding("UTF-8"); + JavaClass clazz = builder.addSource(new StringReader(content)).getClassByName("DummyClass"); + + JavaMethod javaMethod = clazz.getMethods().get(0); + + String methodJavadoc = AbstractFixJavadocMojo.getJavadocComment(content, javaMethod); + assertEquals(" * Dummy method." + EOL + " *", methodJavadoc); + + assertEquals(4, javaMethod.getTags().size()); + + AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); + setVariableValueToObject(mojoInstance, "fixTagsSplitted", new String[] {"all"}); + + DocletTag tag = javaMethod.getTags().get(0); + String tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param The Key type for the method", tagJavadoc); + + tag = javaMethod.getTags().get(1); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param The Value type for the method", tagJavadoc); + + tag = javaMethod.getTags().get(2); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @param name The name.", tagJavadoc); + + tag = javaMethod.getTags().get(3); + tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag); + assertEquals(" * @return A map configured.", tagJavadoc); + } + + public void testInitParameters() throws Throwable { + AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); + setVariableValueToObject(mojoInstance, "fixTags", "author, version, since, param, return, throws, link"); + setVariableValueToObject(mojoInstance, "defaultSince", "1.0"); + setVariableValueToObject(mojoInstance, "level", "protected"); + + invokeMethod(mojoInstance, true, "init"); + + String[] fixTags = (String[]) getVariableValueFromObject(mojoInstance, "fixTagsSplitted"); + + assertEquals("author", fixTags[0]); + assertEquals("version", fixTags[1]); + assertEquals("since", fixTags[2]); + assertEquals("param", fixTags[3]); + assertEquals("return", fixTags[4]); + assertEquals("throws", fixTags[5]); + assertEquals("link", fixTags[6]); + assertEquals(7, fixTags.length); + + setVariableValueToObject(mojoInstance, "fixTags", "return, fake_value"); + invokeMethod(mojoInstance, true, "init"); + fixTags = (String[]) getVariableValueFromObject(mojoInstance, "fixTagsSplitted"); + + assertEquals("return", fixTags[0]); + assertEquals(1, fixTags.length); + } + + public void testRemoveUnknownExceptions() throws Exception { + AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo(); + setVariableValueToObject(mojoInstance, "fixTagsSplitted", new String[] {"all"}); + setVariableValueToObject(mojoInstance, "project", new MavenProjectStub()); + + String source = "package a.b.c;" + EOL + + "public class Clazz {" + EOL + + " /**" + EOL + + " * @throws java.lang.RuntimeException" + EOL + + " * @throws NumberFormatException" + EOL + + " * @throws java.lang.Exception" + EOL // not thrown and no RTE -> remove + + " * @throws com.foo.FatalException" + EOL // not on classpath (?!) -> see removeUnknownThrows + + " */" + EOL + + " public void method() {}" + EOL + + "}"; + + JavaProjectBuilder builder = new JavaProjectBuilder(); + JavaMethod javaMethod = builder.addSource(new StringReader(source)) + .getClassByName("Clazz") + .getMethods() + .get(0); + + JavaEntityTags javaEntityTags = mojoInstance.parseJavadocTags(source, javaMethod, "", true); + + StringBuilder sb = new StringBuilder(); + mojoInstance.writeThrowsTag( + sb, javaMethod, javaEntityTags, Collections.singletonList("java.lang" + ".RuntimeException")); + assertEquals(" * @throws java.lang.RuntimeException", sb.toString()); + + sb = new StringBuilder(); + mojoInstance.writeThrowsTag(sb, javaMethod, javaEntityTags, Collections.singletonList("NumberFormatException")); + assertEquals(" * @throws java.lang.NumberFormatException", sb.toString()); + + sb = new StringBuilder(); + mojoInstance.writeThrowsTag(sb, javaMethod, javaEntityTags, Collections.singletonList("java.lang.Exception")); + assertEquals("", sb.toString()); + + setVariableValueToObject(mojoInstance, "removeUnknownThrows", true); + sb = new StringBuilder(); + mojoInstance.writeThrowsTag( + sb, javaMethod, javaEntityTags, Collections.singletonList("com.foo.FatalException")); + assertEquals("", sb.toString()); + + setVariableValueToObject(mojoInstance, "removeUnknownThrows", false); + sb = new StringBuilder(); + mojoInstance.writeThrowsTag( + sb, javaMethod, javaEntityTags, Collections.singletonList("com.foo.FatalException")); + assertEquals(" * @throws com.foo.FatalException if any.", sb.toString()); + } + + // ---------------------------------------------------------------------- + // private methods + // ---------------------------------------------------------------------- + + /** + * @param testPomBasedir the basedir for the test project + * @param clazzToCompare an array of the classes name to compare + * @throws Exception if any + */ + private void executeMojoAndTest(File testPomBasedir, String[] clazzToCompare) throws Exception { + prepareTestProjects(testPomBasedir.getName()); + + File testPom = new File(testPomBasedir, "pom.xml"); + assertTrue(testPom.getAbsolutePath() + " should exist", testPom.exists()); + + FixJavadocMojo mojo = (FixJavadocMojo) lookupMojo("fix", testPom); + assertNotNull(mojo); + + MavenSession session = newMavenSession(mojo.getProject()); + // Ensure remote repo connection uses SSL + File globalSettingsFile = new File(getBasedir(), "target/test-classes/unit/settings.xml"); + session.getRequest().setGlobalSettingsFile(globalSettingsFile); + setVariableValueToObject(mojo, "session", session); + + // compile the test project + invokeCompileGoal(testPom, globalSettingsFile, mojo.getLog()); + assertTrue(new File(testPomBasedir, "target/classes").exists()); + + mojo.execute(); + + File expectedDir = new File(testPomBasedir, "expected/src/main/java/fix/test"); + assertTrue(expectedDir.exists()); + + File generatedDir = new File(testPomBasedir, "target/generated/fix/test"); + assertTrue(generatedDir.exists()); + + for (String className : clazzToCompare) { + assertEquals(new File(expectedDir, className), new File(generatedDir, className)); + } + } + + /** + * Invoke the compilation on the given pom file. + * + * @param testPom not null + * @param log not null + * @throws MavenInvocationException if any + */ + private void invokeCompileGoal(File testPom, File globalSettingsFile, Log log) throws Exception { + List goals = new ArrayList<>(); + goals.add("clean"); + goals.add("compile"); + File invokerDir = new File(getBasedir(), "target/invoker"); + invokerDir.mkdirs(); + File invokerLogFile = FileUtils.createTempFile("FixJavadocMojoTest", ".txt", invokerDir); + + Properties properties = new Properties(); + + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("12")) { + properties.put("maven.compiler.source", "1.7"); + properties.put("maven.compiler.target", "1.7"); + } else if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9")) { + properties.put("maven.compiler.source", "1.6"); + properties.put("maven.compiler.target", "1.6"); + } + + // @todo unittests shouldn't need to go remote + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("8")) { + // ensure that Java7 picks up TLSv1.2 when connecting with Central + properties.put("https.protocols", "TLSv1.2"); + } + + JavadocUtil.invokeMaven( + log, + new File(getBasedir(), "target/local-repo"), + testPom, + goals, + properties, + invokerLogFile, + globalSettingsFile); + } + + // ---------------------------------------------------------------------- + // static methods + // ---------------------------------------------------------------------- + + /** + * Asserts that files are equal. If they are not an AssertionFailedError is thrown. + * + * @throws IOException if any + */ + private static void assertEquals(File expected, File actual) throws Exception { + assertTrue(" Expected file DNE: " + expected, expected.exists()); + String expectedContent = StringUtils.unifyLineSeparators(readFile(expected)); + + assertTrue(" Actual file DNE: " + actual, actual.exists()); + String actualContent = StringUtils.unifyLineSeparators(readFile(actual)); + + assertEquals( + "Expected file: " + expected.getAbsolutePath() + ", actual file: " + actual.getAbsolutePath(), + expectedContent, + actualContent); + } + + /** + * @param testProjectDirName not null + * @throws IOException if any + */ + private static void prepareTestProjects(String testProjectDirName) throws Exception { + File testPomBasedir = new File(getBasedir(), "target/test/unit/" + testProjectDirName); + + // Using unit test dir + FileUtils.copyDirectoryStructure( + new File(getBasedir(), "src/test/resources/unit/" + testProjectDirName), testPomBasedir); + List scmFiles = FileUtils.getDirectoryNames(testPomBasedir, "**/.svn", null, true); + for (String filename : scmFiles) { + File dir = new File(filename); + + if (dir.isDirectory()) { + FileUtils.deleteDirectory(dir); + } + } + } + + /** + * @param file not null + * @return the content of the given file + * @throws IOException if any + */ + private static String readFile(File file) throws Exception { + String content = FileUtils.fileRead(file, "UTF-8"); + return content; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/JavadocJarTest.java b/src/test/java/org/apache/maven/plugins/javadoc/JavadocJarTest.java index eb46b6c2e..c36668f75 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/JavadocJarTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/JavadocJarTest.java @@ -1,202 +1,185 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - - -import java.io.File; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.Set; -import java.util.zip.ZipEntry; -import java.util.zip.ZipFile; - -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.languages.java.version.JavaVersion; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Maria Odea Ching - */ -public class JavadocJarTest - extends AbstractMojoTestCase -{ - - private JavadocJar lookupMojo( File testPom ) - throws Exception - { - JavadocJar mojo = (JavadocJar) lookupMojo( "jar", testPom ); - - MojoExecution mojoExec = new MojoExecution( new Plugin(), "javadoc", null ); - - setVariableValueToObject( mojo, "mojo", mojoExec ); - - MavenProject currentProject = new MavenProjectStub(); - currentProject.setGroupId( "GROUPID" ); - currentProject.setArtifactId( "ARTIFACTID" ); - - setVariableValueToObject( mojo, "session", newMavenSession( currentProject ) ); - - return mojo; - } - - - /** - * Test when default configuration is provided - * - * @throws Exception if any - */ - public void testDefaultConfig() - throws Exception - { - File testPom = - new File( getBasedir(), "src/test/resources/unit/javadocjar-default/javadocjar-default-plugin-config.xml" ); - JavadocJar mojo = lookupMojo( testPom ); - mojo.execute(); - - //check if the javadoc jar file was generated - File generatedFile = - new File( getBasedir(), "target/test/unit/javadocjar-default/target/javadocjar-default-javadoc.jar" ); - assertThat( generatedFile ).exists(); - - Set set = new HashSet<>(); - - //validate contents of jar file - try ( ZipFile jar = new ZipFile( generatedFile ) ) - { - for( Enumeration entries = jar.entries(); entries.hasMoreElements(); ) - { - ZipEntry entry = entries.nextElement(); - set.add( entry.getName() ); - } - } - - assertTrue( set.contains( "stylesheet.css" ) ); - JavaVersion javadocVersion = (JavaVersion) getVariableValueFromObject( mojo, "javadocRuntimeVersion" ); - if ( javadocVersion.isBefore( "1.7" ) ) - { - assertTrue( set.contains( "resources/inherit.gif" ) ); - } - else if ( javadocVersion.isBefore( "1.8" ) ) - { - assertTrue( set.contains( "resources/background.gif" ) /* JDK7 */); - } - else - { - // JDK8 has no resources anymore - assertFalse( set.contains( "resources" ) ); - } - - assertTrue( set.contains( "javadocjar/def/package-use.html" ) ); - assertTrue( set.contains( "javadocjar/def/package-tree.html" ) ); - assertTrue( set.contains( "javadocjar/def/package-summary.html" ) ); - // package frame not generated anymore since Java 11 - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "11" ) ) - { - assertTrue( set.contains( "javadocjar/def/package-frame.html" ) ); - } - assertTrue( set.contains( "javadocjar/def/class-use/AppSample.html" ) ); - assertTrue( set.contains( "index.html" ) ); - assertTrue( set.contains( "javadocjar/def/App.html" ) ); - assertTrue( set.contains( "javadocjar/def/AppSample.html" ) ); - assertTrue( set.contains( "javadocjar/def/class-use/App.html" ) ); - - assertFalse( set.contains( AbstractJavadocMojo.ARGFILE_FILE_NAME ) ); - assertFalse( set.contains( AbstractJavadocMojo.FILES_FILE_NAME ) ); - assertFalse( set.contains( AbstractJavadocMojo.OPTIONS_FILE_NAME ) ); - assertFalse( set.contains( AbstractJavadocMojo.PACKAGES_FILE_NAME ) ); - - //check if the javadoc files were created - generatedFile = - new File( getBasedir(), "target/test/unit/javadocjar-default/target/site/apidocs/javadocjar/def/App.html" ); - assertThat(generatedFile).exists(); - - generatedFile = new File( getBasedir(), - "target/test/unit/javadocjar-default/target/site/apidocs/javadocjar/def/AppSample.html" ); - assertThat( generatedFile ).exists(); - } - - /** - * Test when the specified destDir parameter has an invalid value - * - * @throws Exception if any - */ - public void testInvalidDestdir() - throws Exception - { - File testPom = new File( getBasedir(), - "src/test/resources/unit/javadocjar-invalid-destdir/javadocjar-invalid-destdir-plugin-config.xml" ); - JavadocJar mojo = lookupMojo( testPom ); - mojo.execute(); - - //check if the javadoc jar file was generated - File generatedFile = new File( getBasedir(), - "target/test/unit/javadocjar-invalid-destdir/target/javadocjar-invalid-destdir-javadoc.jar" ); - assertThat( generatedFile ).doesNotExist(); - } - - public void testContinueIfFailOnErrorIsFalse() throws Exception - { - File testPom = - new File( getBasedir(), "src/test/resources/unit/javadocjar-failonerror/javadocjar-failonerror-plugin-config.xml" ); - JavadocJar mojo = lookupMojo( testPom ); - mojo.execute(); - - //check if the javadoc jar file was generated - File generatedFile = - new File( getBasedir(), "target/test/unit/javadocjar-failonerror/target/javadocjar-failonerror-javadoc.jar" ); - assertThat( generatedFile ).exists(); - } - - public void testIncludeMavenDescriptorWhenExplicitlyConfigured() throws Exception - { - File testPom = - new File( getBasedir(), "src/test/resources/unit/javadocjar-archive-config/javadocjar-archive-config.xml" ); - JavadocJar mojo = lookupMojo( testPom ); - mojo.execute(); - - //check if the javadoc jar file was generated - File generatedFile = - new File( getBasedir(), "target/test/unit/javadocjar-archive-config/target/javadocjar-archive-config-javadoc.jar" ); - assertThat( generatedFile ).exists(); - - //validate contents of jar file - ZipFile jar = new ZipFile( generatedFile ); - Set set = new HashSet<>(); - for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) - { - ZipEntry entry = entries.nextElement(); - set.add( entry.getName() ); - } - jar.close(); - - assertThat( set ).contains( - "META-INF/", - "META-INF/maven/", - "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/", - "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/", - "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/pom.xml", - "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/pom.properties" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.Set; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +import org.apache.maven.model.Plugin; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.languages.java.version.JavaVersion; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Maria Odea Ching + */ +public class JavadocJarTest extends AbstractMojoTestCase { + + private JavadocJar lookupMojo(File testPom) throws Exception { + JavadocJar mojo = (JavadocJar) lookupMojo("jar", testPom); + + MojoExecution mojoExec = new MojoExecution(new Plugin(), "javadoc", null); + + setVariableValueToObject(mojo, "mojo", mojoExec); + + MavenProject currentProject = new MavenProjectStub(); + currentProject.setGroupId("GROUPID"); + currentProject.setArtifactId("ARTIFACTID"); + + setVariableValueToObject(mojo, "session", newMavenSession(currentProject)); + + return mojo; + } + + /** + * Test when default configuration is provided + * + * @throws Exception if any + */ + public void testDefaultConfig() throws Exception { + File testPom = new File( + getBasedir(), "src/test/resources/unit/javadocjar-default/javadocjar-default-plugin-config.xml"); + JavadocJar mojo = lookupMojo(testPom); + mojo.execute(); + + // check if the javadoc jar file was generated + File generatedFile = + new File(getBasedir(), "target/test/unit/javadocjar-default/target/javadocjar-default-javadoc.jar"); + assertThat(generatedFile).exists(); + + Set set = new HashSet<>(); + + // validate contents of jar file + try (ZipFile jar = new ZipFile(generatedFile)) { + for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) { + ZipEntry entry = entries.nextElement(); + set.add(entry.getName()); + } + } + + assertTrue(set.contains("stylesheet.css")); + JavaVersion javadocVersion = (JavaVersion) getVariableValueFromObject(mojo, "javadocRuntimeVersion"); + if (javadocVersion.isBefore("1.7")) { + assertTrue(set.contains("resources/inherit.gif")); + } else if (javadocVersion.isBefore("1.8")) { + assertTrue(set.contains("resources/background.gif") /* JDK7 */); + } else { + // JDK8 has no resources anymore + assertFalse(set.contains("resources")); + } + + assertTrue(set.contains("javadocjar/def/package-use.html")); + assertTrue(set.contains("javadocjar/def/package-tree.html")); + assertTrue(set.contains("javadocjar/def/package-summary.html")); + // package frame not generated anymore since Java 11 + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) { + assertTrue(set.contains("javadocjar/def/package-frame.html")); + } + assertTrue(set.contains("javadocjar/def/class-use/AppSample.html")); + assertTrue(set.contains("index.html")); + assertTrue(set.contains("javadocjar/def/App.html")); + assertTrue(set.contains("javadocjar/def/AppSample.html")); + assertTrue(set.contains("javadocjar/def/class-use/App.html")); + + assertFalse(set.contains(AbstractJavadocMojo.ARGFILE_FILE_NAME)); + assertFalse(set.contains(AbstractJavadocMojo.FILES_FILE_NAME)); + assertFalse(set.contains(AbstractJavadocMojo.OPTIONS_FILE_NAME)); + assertFalse(set.contains(AbstractJavadocMojo.PACKAGES_FILE_NAME)); + + // check if the javadoc files were created + generatedFile = new File( + getBasedir(), "target/test/unit/javadocjar-default/target/site/apidocs/javadocjar/def/App.html"); + assertThat(generatedFile).exists(); + + generatedFile = new File( + getBasedir(), "target/test/unit/javadocjar-default/target/site/apidocs/javadocjar/def/AppSample.html"); + assertThat(generatedFile).exists(); + } + + /** + * Test when the specified destDir parameter has an invalid value + * + * @throws Exception if any + */ + public void testInvalidDestdir() throws Exception { + File testPom = new File( + getBasedir(), + "src/test/resources/unit/javadocjar-invalid-destdir/javadocjar-invalid-destdir-plugin-config.xml"); + JavadocJar mojo = lookupMojo(testPom); + mojo.execute(); + + // check if the javadoc jar file was generated + File generatedFile = new File( + getBasedir(), + "target/test/unit/javadocjar-invalid-destdir/target/javadocjar-invalid-destdir-javadoc.jar"); + assertThat(generatedFile).doesNotExist(); + } + + public void testContinueIfFailOnErrorIsFalse() throws Exception { + File testPom = new File( + getBasedir(), + "src/test/resources/unit/javadocjar-failonerror/javadocjar-failonerror-plugin-config.xml"); + JavadocJar mojo = lookupMojo(testPom); + mojo.execute(); + + // check if the javadoc jar file was generated + File generatedFile = new File( + getBasedir(), "target/test/unit/javadocjar-failonerror/target/javadocjar-failonerror-javadoc.jar"); + assertThat(generatedFile).exists(); + } + + public void testIncludeMavenDescriptorWhenExplicitlyConfigured() throws Exception { + File testPom = new File( + getBasedir(), "src/test/resources/unit/javadocjar-archive-config/javadocjar-archive-config.xml"); + JavadocJar mojo = lookupMojo(testPom); + mojo.execute(); + + // check if the javadoc jar file was generated + File generatedFile = new File( + getBasedir(), + "target/test/unit/javadocjar-archive-config/target/javadocjar-archive-config-javadoc.jar"); + assertThat(generatedFile).exists(); + + // validate contents of jar file + ZipFile jar = new ZipFile(generatedFile); + Set set = new HashSet<>(); + for (Enumeration entries = jar.entries(); entries.hasMoreElements(); ) { + ZipEntry entry = entries.nextElement(); + set.add(entry.getName()); + } + jar.close(); + + assertThat(set) + .contains( + "META-INF/", + "META-INF/maven/", + "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/", + "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/", + "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/pom.xml", + "META-INF/maven/org.apache.maven.plugins.maven-javadoc-plugin.unit/javadocjar-archive-config/pom.properties"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/JavadocReportTest.java b/src/test/java/org/apache/maven/plugins/javadoc/JavadocReportTest.java index cd9af54e7..502e6d66f 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/JavadocReportTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/JavadocReportTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,18 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import static org.apache.commons.io.FileUtils.copyDirectory; -import static org.apache.commons.io.FileUtils.deleteDirectory; -import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assume.assumeThat; -import static org.hamcrest.CoreMatchers.anyOf; -import static org.hamcrest.CoreMatchers.containsString; -import static org.hamcrest.CoreMatchers.is; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.spy; -import static org.mockito.Mockito.when; +package org.apache.maven.plugins.javadoc; import java.io.File; import java.io.IOException; @@ -67,15 +54,24 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static org.apache.commons.io.FileUtils.copyDirectory; +import static org.apache.commons.io.FileUtils.deleteDirectory; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hamcrest.CoreMatchers.anyOf; +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.CoreMatchers.is; +import static org.junit.Assume.assumeThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + /** * Test {@link org.apache.maven.plugins.javadoc.JavadocReport} class. * * @author Maria Odea Ching * @author Vincent Siveton */ -public class JavadocReportTest - extends AbstractMojoTestCase -{ +public class JavadocReportTest extends AbstractMojoTestCase { private static final char LINE_SEPARATOR = ' '; @@ -88,39 +84,34 @@ public class JavadocReportTest private File localRepo; - private static final Logger LOGGER = LoggerFactory.getLogger( JavadocReportTest.class ); + private static final Logger LOGGER = LoggerFactory.getLogger(JavadocReportTest.class); /** {@inheritDoc} */ @Override - protected void setUp() - throws Exception - { + protected void setUp() throws Exception { super.setUp(); - unit = new File( getBasedir(), "src/test/resources/unit" ).toPath(); + unit = new File(getBasedir(), "src/test/resources/unit").toPath(); - localRepo = new File( getBasedir(), "target/local-repo/" ); + localRepo = new File(getBasedir(), "target/local-repo/"); createTestRepo(); } + private JavadocReport lookupMojo(Path testPom) throws Exception { + JavadocReport mojo = (JavadocReport) lookupMojo("javadoc", testPom.toFile()); - private JavadocReport lookupMojo( Path testPom ) - throws Exception - { - JavadocReport mojo = (JavadocReport) lookupMojo( "javadoc", testPom.toFile() ); - - MojoExecution mojoExec = new MojoExecution( new Plugin(), "javadoc", null ); + MojoExecution mojoExec = new MojoExecution(new Plugin(), "javadoc", null); - setVariableValueToObject( mojo, "mojo", mojoExec ); + setVariableValueToObject(mojo, "mojo", mojoExec); MavenProject currentProject = new MavenProjectStub(); - currentProject.setGroupId( "GROUPID" ); - currentProject.setArtifactId( "ARTIFACTID" ); + currentProject.setGroupId("GROUPID"); + currentProject.setArtifactId("ARTIFACTID"); - MavenSession session = newMavenSession( currentProject ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", session.getRepositorySession() ); + MavenSession session = newMavenSession(currentProject); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", session.getRepositorySession()); return mojo; } @@ -129,11 +120,8 @@ private JavadocReport lookupMojo( Path testPom ) * * @throws IOException if any */ - private void createTestRepo() - throws IOException - { - if ( TEST_REPO_CREATED ) - { + private void createTestRepo() throws IOException { + if (TEST_REPO_CREATED) { return; } @@ -143,57 +131,52 @@ private void createTestRepo() // UMLGraph // ---------------------------------------------------------------------- - Path sourceDir = unit.resolve( "doclet-test/artifact-doclet" ); - assertThat( sourceDir ).exists(); - copyDirectory( sourceDir.toFile(), localRepo ); + Path sourceDir = unit.resolve("doclet-test/artifact-doclet"); + assertThat(sourceDir).exists(); + copyDirectory(sourceDir.toFile(), localRepo); // ---------------------------------------------------------------------- // UMLGraph-bis // ---------------------------------------------------------------------- - sourceDir = unit.resolve( "doclet-path-test/artifact-doclet" ); - assertThat( sourceDir ).exists(); - copyDirectory( sourceDir.toFile(), localRepo ); + sourceDir = unit.resolve("doclet-path-test/artifact-doclet"); + assertThat(sourceDir).exists(); + copyDirectory(sourceDir.toFile(), localRepo); // ---------------------------------------------------------------------- // commons-attributes-compiler // http://www.tullmann.org/pat/taglets/ // ---------------------------------------------------------------------- - sourceDir = unit.resolve( "taglet-test/artifact-taglet" ); - assertThat( sourceDir ).exists(); - copyDirectory( sourceDir.toFile(), localRepo ); + sourceDir = unit.resolve("taglet-test/artifact-taglet"); + assertThat(sourceDir).exists(); + copyDirectory(sourceDir.toFile(), localRepo); // ---------------------------------------------------------------------- // stylesheetfile-test // ---------------------------------------------------------------------- - sourceDir = unit.resolve( "stylesheetfile-test/artifact-stylesheetfile" ); - assertThat( sourceDir ).exists(); - copyDirectory( sourceDir.toFile(), localRepo ); + sourceDir = unit.resolve("stylesheetfile-test/artifact-stylesheetfile"); + assertThat(sourceDir).exists(); + copyDirectory(sourceDir.toFile(), localRepo); // ---------------------------------------------------------------------- // helpfile-test // ---------------------------------------------------------------------- - sourceDir = unit.resolve( "helpfile-test/artifact-helpfile" ); - assertThat( sourceDir ).exists(); - copyDirectory( sourceDir.toFile(), localRepo ); + sourceDir = unit.resolve("helpfile-test/artifact-helpfile"); + assertThat(sourceDir).exists(); + copyDirectory(sourceDir.toFile(), localRepo); // Remove SCM files - List files = - FileUtils.getFileAndDirectoryNames( localRepo, FileUtils.getDefaultExcludesAsString(), null, true, - true, true, true ); - for ( String filename : files ) - { - File file = new File( filename ); - - if ( file.isDirectory() ) - { - deleteDirectory( file ); - } - else - { + List files = FileUtils.getFileAndDirectoryNames( + localRepo, FileUtils.getDefaultExcludesAsString(), null, true, true, true, true); + for (String filename : files) { + File file = new File(filename); + + if (file.isDirectory()) { + deleteDirectory(file); + } else { file.delete(); } } @@ -210,10 +193,8 @@ private void createTestRepo() * @return a String object that contains the contents of the file * @throws IOException if any */ - private static String readFile( Path file ) - throws IOException - { - return readFile( file, StandardCharsets.UTF_8 ); + private static String readFile(Path file) throws IOException { + return readFile(file, StandardCharsets.UTF_8); } /** @@ -226,15 +207,12 @@ private static String readFile( Path file ) * @return a String object that contains the contents of the file * @throws IOException if any */ - private static String readFile( Path file, Charset cs ) - throws IOException - { - StringBuilder str = new StringBuilder( (int) Files.size( file ) ); - - for ( String strTmp : Files.readAllLines( file, cs ) ) - { - str.append( LINE_SEPARATOR); - str.append( strTmp ); + private static String readFile(Path file, Charset cs) throws IOException { + StringBuilder str = new StringBuilder((int) Files.size(file)); + + for (String strTmp : Files.readAllLines(file, cs)) { + str.append(LINE_SEPARATOR); + str.append(strTmp); } return str.toString(); @@ -245,95 +223,87 @@ private static String readFile( Path file, Charset cs ) * * @throws Exception if any */ - public void testDefaultConfiguration() - throws Exception - { - Path testPom = unit.resolve( "default-configuration/default-configuration-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testDefaultConfiguration() throws Exception { + Path testPom = unit.resolve("default-configuration/default-configuration-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); // package level generated javadoc files - Path apidocs = new File( getBasedir(), "target/test/unit/default-configuration/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/default-configuration/target/site/apidocs").toPath(); String appHtml = "def/configuration/App.html"; - Path generatedFile = apidocs.resolve( appHtml ); - assertThat( generatedFile ).exists(); - - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "16" ) ) - { - String url = Objects.requireNonNull( mojo.getDefaultJavadocApiLink() ).getUrl(); - HttpURLConnection connection = (HttpURLConnection) new URL( url ).openConnection(); - connection.setRequestMethod( "HEAD" ); - try - { + Path generatedFile = apidocs.resolve(appHtml); + assertThat(generatedFile).exists(); + + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("16")) { + String url = Objects.requireNonNull(mojo.getDefaultJavadocApiLink()).getUrl(); + HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); + connection.setRequestMethod("HEAD"); + try { // only test when URL can be reached - if ( connection.getResponseCode() == HttpURLConnection.HTTP_OK ) - { - try - { - assumeThat( connection.getURL().toString(), is( url ) ); + if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { + try { + assumeThat(connection.getURL().toString(), is(url)); // https://bugs.openjdk.java.net/browse/JDK-8216497 - MatcherAssert.assertThat( url + " available, but " + appHtml + " is missing link to java.lang.Object", - new String( Files.readAllBytes(generatedFile), StandardCharsets.UTF_8 ), - anyOf( containsString( "/docs/api/java/lang/Object.html" ), - containsString( "/docs/api/java.base/java/lang/Object.html" ) ) ); - } - catch ( AssumptionViolatedException e ) - { - LOGGER.warn( "ignoring defaultAPI check: {}", e.getMessage() ); + MatcherAssert.assertThat( + url + " available, but " + appHtml + " is missing link to java.lang.Object", + new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8), + anyOf( + containsString("/docs/api/java/lang/Object.html"), + containsString("/docs/api/java.base/java/lang/Object.html"))); + } catch (AssumptionViolatedException e) { + LOGGER.warn("ignoring defaultAPI check: {}", e.getMessage()); } } - } - catch (Exception e) - { + } catch (Exception e) { LOGGER.error("error connecting to javadoc URL: {}", url); throw e; } - } - else - { - MatcherAssert.assertThat( new String( Files.readAllBytes(generatedFile), StandardCharsets.UTF_8 ), - containsString( "/docs/api/java.base/java/lang/Object.html" ) ); + } else { + MatcherAssert.assertThat( + new String(Files.readAllBytes(generatedFile), StandardCharsets.UTF_8), + containsString("/docs/api/java.base/java/lang/Object.html")); } - assertThat( apidocs.resolve( "def/configuration/AppSample.html" )).exists(); - assertThat( apidocs.resolve( "def/configuration/package-summary.html" )).exists(); - assertThat( apidocs.resolve( "def/configuration/package-tree.html" )).exists(); - assertThat( apidocs.resolve( "def/configuration/package-use.html" )).exists(); + assertThat(apidocs.resolve("def/configuration/AppSample.html")).exists(); + assertThat(apidocs.resolve("def/configuration/package-summary.html")).exists(); + assertThat(apidocs.resolve("def/configuration/package-tree.html")).exists(); + assertThat(apidocs.resolve("def/configuration/package-use.html")).exists(); // package-frame and allclasses-(no)frame not generated anymore since Java 11 - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "11" ) ) - { - assertThat( apidocs.resolve( "def/configuration/package-frame.html" )).exists(); - assertThat( apidocs.resolve( "allclasses-frame.html" )).exists() - .content().containsOnlyOnce("def/configuration/App.html") - .containsOnlyOnce("def/configuration/AppSample.html"); - assertThat( apidocs.resolve( "allclasses-noframe.html" )).exists() - .content().containsOnlyOnce("def/configuration/App.html") - .containsOnlyOnce("def/configuration/AppSample.html"); + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) { + assertThat(apidocs.resolve("def/configuration/package-frame.html")).exists(); + assertThat(apidocs.resolve("allclasses-frame.html")) + .exists() + .content() + .containsOnlyOnce("def/configuration/App.html") + .containsOnlyOnce("def/configuration/AppSample.html"); + assertThat(apidocs.resolve("allclasses-noframe.html")) + .exists() + .content() + .containsOnlyOnce("def/configuration/App.html") + .containsOnlyOnce("def/configuration/AppSample.html"); } // class level generated javadoc files - assertThat( apidocs.resolve( "def/configuration/class-use/App.html" )).exists(); - assertThat( apidocs.resolve( "def/configuration/class-use/AppSample.html" )).exists(); + assertThat(apidocs.resolve("def/configuration/class-use/App.html")).exists(); + assertThat(apidocs.resolve("def/configuration/class-use/AppSample.html")) + .exists(); // project level generated javadoc files - assertThat( apidocs.resolve( "constant-values.html" )).exists(); - assertThat( apidocs.resolve( "deprecated-list.html" ) ).exists(); - assertThat( apidocs.resolve( "help-doc.html" )).exists(); - assertThat( apidocs.resolve( "index-all.html" )).exists(); - assertThat( apidocs.resolve( "index.html" )).exists(); - assertThat( apidocs.resolve( "overview-tree.html" )).exists(); - assertThat( apidocs.resolve( "stylesheet.css" )).exists(); - - if ( JavaVersion.JAVA_VERSION.isAtLeast( "10" ) ) - { - assertThat( apidocs.resolve( "element-list" )).exists(); - } - else - { - assertThat( apidocs.resolve( "package-list" )).exists(); + assertThat(apidocs.resolve("constant-values.html")).exists(); + assertThat(apidocs.resolve("deprecated-list.html")).exists(); + assertThat(apidocs.resolve("help-doc.html")).exists(); + assertThat(apidocs.resolve("index-all.html")).exists(); + assertThat(apidocs.resolve("index.html")).exists(); + assertThat(apidocs.resolve("overview-tree.html")).exists(); + assertThat(apidocs.resolve("stylesheet.css")).exists(); + + if (JavaVersion.JAVA_VERSION.isAtLeast("10")) { + assertThat(apidocs.resolve("element-list")).exists(); + } else { + assertThat(apidocs.resolve("package-list")).exists(); } } @@ -342,41 +312,42 @@ public void testDefaultConfiguration() * * @throws Exception if any */ - public void testSubpackages() - throws Exception - { - Path testPom = unit.resolve( "subpackages-test/subpackages-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testSubpackages() throws Exception { + Path testPom = unit.resolve("subpackages-test/subpackages-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/subpackages-test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/subpackages-test/target/site/apidocs").toPath(); // check the excluded packages - assertThat( apidocs.resolve( "subpackages/test/excluded" ) ).doesNotExist(); - assertThat( apidocs.resolve( "subpackages/test/included/exclude" ) ).doesNotExist(); + assertThat(apidocs.resolve("subpackages/test/excluded")).doesNotExist(); + assertThat(apidocs.resolve("subpackages/test/included/exclude")).doesNotExist(); // check if the classes in the specified subpackages were included - assertThat( apidocs.resolve( "subpackages/test/App.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/AppSample.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/included/IncludedApp.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/included/IncludedAppSample.html" ) ).exists(); + assertThat(apidocs.resolve("subpackages/test/App.html")).exists(); + assertThat(apidocs.resolve("subpackages/test/AppSample.html")).exists(); + assertThat(apidocs.resolve("subpackages/test/included/IncludedApp.html")) + .exists(); + assertThat(apidocs.resolve("subpackages/test/included/IncludedAppSample.html")) + .exists(); } - public void testIncludesExcludes() - throws Exception - { - Path testPom = unit.resolve( "file-include-exclude-test/file-include-exclude-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testIncludesExcludes() throws Exception { + Path testPom = unit.resolve("file-include-exclude-test/file-include-exclude-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/file-include-exclude-test/target/site/apidocs" ).toPath(); + Path apidocs = + new File(getBasedir(), "target/test/unit/file-include-exclude-test/target/site/apidocs").toPath(); // check if the classes in the specified subpackages were included - assertThat( apidocs.resolve( "subpackages/test/App.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/AppSample.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/included/IncludedApp.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/included/IncludedAppSample.html" ) ).exists(); - assertThat( apidocs.resolve( "subpackages/test/PariahApp.html" ) ).doesNotExist(); + assertThat(apidocs.resolve("subpackages/test/App.html")).exists(); + assertThat(apidocs.resolve("subpackages/test/AppSample.html")).exists(); + assertThat(apidocs.resolve("subpackages/test/included/IncludedApp.html")) + .exists(); + assertThat(apidocs.resolve("subpackages/test/included/IncludedAppSample.html")) + .exists(); + assertThat(apidocs.resolve("subpackages/test/PariahApp.html")).doesNotExist(); } /** @@ -384,31 +355,30 @@ public void testIncludesExcludes() * * @throws Exception if any */ - public void testDocfiles() - throws Exception - { + public void testDocfiles() throws Exception { // Should be an assumption, but not supported by TestCase // Seems like a bug in Javadoc 9 and above - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "9" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9")) { return; } - Path testPom = unit.resolve( "docfiles-test/docfiles-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("docfiles-test/docfiles-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/docfiles-test/target/site/apidocs/" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/docfiles-test/target/site/apidocs/").toPath(); // check if the doc-files subdirectories were copied - assertThat( apidocs.resolve( "docfiles/test/doc-files" )).exists(); - assertThat( apidocs.resolve( "docfiles/test/doc-files/included-dir1/sample-included1.gif" )).exists(); - assertThat( apidocs.resolve( "docfiles/test/doc-files/included-dir2/sample-included2.gif" )).exists(); - assertThat( apidocs.resolve( "docfiles/test/doc-files/excluded-dir1" )).doesNotExist(); - assertThat( apidocs.resolve( "docfiles/test/doc-files/excluded-dir2" )).doesNotExist(); - - testPom = unit.resolve( "docfiles-with-java-test/docfiles-with-java-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); + assertThat(apidocs.resolve("docfiles/test/doc-files")).exists(); + assertThat(apidocs.resolve("docfiles/test/doc-files/included-dir1/sample-included1.gif")) + .exists(); + assertThat(apidocs.resolve("docfiles/test/doc-files/included-dir2/sample-included2.gif")) + .exists(); + assertThat(apidocs.resolve("docfiles/test/doc-files/excluded-dir1")).doesNotExist(); + assertThat(apidocs.resolve("docfiles/test/doc-files/excluded-dir2")).doesNotExist(); + + testPom = unit.resolve("docfiles-with-java-test/docfiles-with-java-test-plugin-config.xml"); + mojo = lookupMojo(testPom); mojo.execute(); } @@ -418,71 +388,68 @@ public void testDocfiles() * * @throws Exception if any */ - public void testCustomConfiguration() - throws Exception - { - Path testPom = unit.resolve( "custom-configuration/custom-configuration-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testCustomConfiguration() throws Exception { + Path testPom = unit.resolve("custom-configuration/custom-configuration-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/custom-configuration/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/custom-configuration/target/site/apidocs").toPath(); // check if there is a tree page generated (notree == true) - assertThat( apidocs.resolve( "overview-tree.html" ) ).doesNotExist(); - assertThat( apidocs.resolve( "custom/configuration/package-tree.html" ) ).doesNotExist(); + assertThat(apidocs.resolve("overview-tree.html")).doesNotExist(); + assertThat(apidocs.resolve("custom/configuration/package-tree.html")).doesNotExist(); // check if the main index page was generated (noindex == true) - assertThat( apidocs.resolve( "index-all.html" ) ).doesNotExist(); + assertThat(apidocs.resolve("index-all.html")).doesNotExist(); // check if the deprecated list and the deprecated api were generated (nodeprecated == true) // @todo Fix: the class-use of the deprecated api is still created eventhough the deprecated api of that class // is no longer generated - assertThat( apidocs.resolve( "deprecated-list.html" ) ).doesNotExist(); - assertThat( apidocs.resolve( "custom/configuration/App.html" ) ).doesNotExist(); + assertThat(apidocs.resolve("deprecated-list.html")).doesNotExist(); + assertThat(apidocs.resolve("custom/configuration/App.html")).doesNotExist(); // read the contents of the html files based on some of the parameter values // author == false - String str = readFile( apidocs.resolve( "custom/configuration/AppSample.html" ) ); - assertFalse( str.toLowerCase().contains( "author" ) ); + String str = readFile(apidocs.resolve("custom/configuration/AppSample.html")); + assertFalse(str.toLowerCase().contains("author")); // bottom - assertTrue( str.toUpperCase().contains( "SAMPLE BOTTOM CONTENT" ) ); + assertTrue(str.toUpperCase().contains("SAMPLE BOTTOM CONTENT")); // offlineLinks - if ( JavaVersion.JAVA_VERSION.isBefore( "11.0.2" ) ) - { - assertThat( str ).containsIgnoringCase( - "href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/string.html" ); - } - else - { - assertTrue( str.toLowerCase().contains( - "href=\"http://java.sun.com/j2se/1.4.2/docs/api/java.base/java/lang/string.html" ) ); + if (JavaVersion.JAVA_VERSION.isBefore("11.0.2")) { + assertThat(str) + .containsIgnoringCase("href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/lang/string.html"); + } else { + assertTrue(str.toLowerCase() + .contains("href=\"http://java.sun.com/j2se/1.4.2/docs/api/java.base/java/lang/string.html")); } // header - assertTrue( str.toUpperCase().contains( "MAVEN JAVADOC PLUGIN TEST" ) ); + assertTrue(str.toUpperCase().contains("MAVEN JAVADOC PLUGIN TEST")); // footer - if ( JavaVersion.JAVA_VERSION.isBefore( "16-ea" ) ) - { - assertTrue( str.toUpperCase().contains( "MAVEN JAVADOC PLUGIN TEST FOOTER" ) ); + if (JavaVersion.JAVA_VERSION.isBefore("16-ea")) { + assertTrue(str.toUpperCase().contains("MAVEN JAVADOC PLUGIN TEST FOOTER")); } // nohelp == true - assertFalse( str.toUpperCase().contains( "/HELP-DOC.HTML" ) ); + assertFalse(str.toUpperCase().contains("/HELP-DOC.HTML")); // check the wildcard (*) package exclusions -- excludePackageNames parameter - assertThat( apidocs.resolve( "custom/configuration/exclude1/Exclude1App.html" ) ).exists(); - assertThat( apidocs.resolve( "custom/configuration/exclude1/subexclude/SubexcludeApp.html" ) ).doesNotExist(); - assertThat( apidocs.resolve( "custom/configuration/exclude2/Exclude2App.html" ) ).doesNotExist(); + assertThat(apidocs.resolve("custom/configuration/exclude1/Exclude1App.html")) + .exists(); + assertThat(apidocs.resolve("custom/configuration/exclude1/subexclude/SubexcludeApp.html")) + .doesNotExist(); + assertThat(apidocs.resolve("custom/configuration/exclude2/Exclude2App.html")) + .doesNotExist(); - assertThat( apidocs.resolve( "options" ) ).isRegularFile(); + assertThat(apidocs.resolve("options")).isRegularFile(); - String contentOptions = new String( Files.readAllBytes( apidocs.resolve( "options" ) ), StandardCharsets.UTF_8 ); + String contentOptions = new String(Files.readAllBytes(apidocs.resolve("options")), StandardCharsets.UTF_8); - assertNotNull( contentOptions ); - assertThat( contentOptions ).contains( "-link" ).contains( "http://java.sun.com/j2se/" ); + assertNotNull(contentOptions); + assertThat(contentOptions).contains("-link").contains("http://java.sun.com/j2se/"); } /** @@ -490,11 +457,8 @@ public void testCustomConfiguration() * * @throws Exception if any */ - public void testDoclets() - throws Exception - { - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "13" ) ) - { + public void testDoclets() throws Exception { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("13")) { // As of JDK 13, the com.sun.javadoc API is no longer supported. return; } @@ -504,51 +468,54 @@ public void testDoclets() // doclet path contains the UmlGraph artifact // ---------------------------------------------------------------------- - Path testPom = unit.resolve( "doclet-test/doclet-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("doclet-test/doclet-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - Path generatedFile = new File( getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot" ).toPath(); - assertThat( generatedFile ).exists(); + Path generatedFile = + new File(getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot").toPath(); + assertThat(generatedFile).exists(); - Path optionsFile = new File( mojo.getOutputDirectory(), "options" ).toPath(); - assertThat( optionsFile ).exists(); - String options = readFile( optionsFile ); - assertThat( options ).contains( "/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar" ); + Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath(); + assertThat(optionsFile).exists(); + String options = readFile(optionsFile); + assertThat(options).contains("/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar"); // ---------------------------------------------------------------------- // doclet-path: check if the file generated by UmlGraph exists and if // doclet path contains the twice UmlGraph artifacts // ---------------------------------------------------------------------- - testPom = unit.resolve( "doclet-path-test/doclet-path-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + testPom = unit.resolve("doclet-path-test/doclet-path-test-plugin-config.xml"); + mojo = lookupMojo(testPom); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - generatedFile = new File( getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot" ).toPath(); - assertThat( generatedFile ).exists(); + generatedFile = new File(getBasedir(), "target/test/unit/doclet-test/target/site/apidocs/graph.dot").toPath(); + assertThat(generatedFile).exists(); - optionsFile = new File( mojo.getOutputDirectory(), "options" ).toPath(); - assertThat( optionsFile ).exists(); - options = readFile( optionsFile ); - assertThat( options ).contains( "/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar" ) - .contains( "/target/local-repo/umlgraph/UMLGraph-bis/2.1/UMLGraph-bis-2.1.jar" ); + optionsFile = new File(mojo.getOutputDirectory(), "options").toPath(); + assertThat(optionsFile).exists(); + options = readFile(optionsFile); + assertThat(options) + .contains("/target/local-repo/umlgraph/UMLGraph/2.1/UMLGraph-2.1.jar") + .contains("/target/local-repo/umlgraph/UMLGraph-bis/2.1/UMLGraph-bis-2.1.jar"); } /** @@ -556,32 +523,27 @@ public void testDoclets() * * @throws Exception if any */ - public void testQuotedPath() - throws Exception - { - Path testPom = unit.resolve( "quotedpath'test/quotedpath-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testQuotedPath() throws Exception { + Path testPom = unit.resolve("quotedpath'test/quotedpath-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/quotedpath'test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/quotedpath'test/target/site/apidocs").toPath(); // package level generated javadoc files - assertThat( apidocs.resolve( "quotedpath/test/App.html" ) ).exists(); - assertThat( apidocs.resolve( "quotedpath/test/AppSample.html" ) ).exists(); + assertThat(apidocs.resolve("quotedpath/test/App.html")).exists(); + assertThat(apidocs.resolve("quotedpath/test/AppSample.html")).exists(); // project level generated javadoc files - assertThat( apidocs.resolve( "index-all.html" ) ).exists(); - assertThat( apidocs.resolve( "index.html" ) ).exists(); - assertThat( apidocs.resolve( "overview-tree.html" ) ).exists(); - assertThat( apidocs.resolve( "stylesheet.css" ) ).exists(); - - if ( JavaVersion.JAVA_VERSION.isBefore( "10" ) ) - { - assertThat( apidocs.resolve( "package-list" ) ).exists(); - } - else - { - assertThat( apidocs.resolve( "element-list" ) ).exists(); + assertThat(apidocs.resolve("index-all.html")).exists(); + assertThat(apidocs.resolve("index.html")).exists(); + assertThat(apidocs.resolve("overview-tree.html")).exists(); + assertThat(apidocs.resolve("stylesheet.css")).exists(); + + if (JavaVersion.JAVA_VERSION.isBefore("10")) { + assertThat(apidocs.resolve("package-list")).exists(); + } else { + assertThat(apidocs.resolve("element-list")).exists(); } } @@ -590,78 +552,63 @@ public void testQuotedPath() * * @throws Exception if any */ - public void testOptionsUmlautEncoding() - throws Exception - { - Path testPom = unit.resolve( "optionsumlautencoding-test/optionsumlautencoding-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testOptionsUmlautEncoding() throws Exception { + Path testPom = unit.resolve("optionsumlautencoding-test/optionsumlautencoding-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path optionsFile = new File( mojo.getOutputDirectory(), "options" ).toPath(); - assertThat( optionsFile ).exists(); + Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath(); + assertThat(optionsFile).exists(); // check for a part of the window title String content; String expected; - if ( JavaVersion.JAVA_VERSION.isAtLeast( "9" ) && JavaVersion.JAVA_VERSION.isBefore( "12" ) ) - { - content = readFile( optionsFile, StandardCharsets.UTF_8 ); + if (JavaVersion.JAVA_VERSION.isAtLeast("9") && JavaVersion.JAVA_VERSION.isBefore("12")) { + content = readFile(optionsFile, StandardCharsets.UTF_8); expected = OPTIONS_UMLAUT_ENCODING; - } - else - { - content = readFile( optionsFile, Charset.defaultCharset() ); - expected = new String( OPTIONS_UMLAUT_ENCODING.getBytes( Charset.defaultCharset() ) ); + } else { + content = readFile(optionsFile, Charset.defaultCharset()); + expected = new String(OPTIONS_UMLAUT_ENCODING.getBytes(Charset.defaultCharset())); } - assertThat( content ).contains( expected ); + assertThat(content).contains(expected); - Path apidocs = new File( getBasedir(), "target/test/unit/optionsumlautencoding-test/target/site/apidocs" ).toPath(); + Path apidocs = + new File(getBasedir(), "target/test/unit/optionsumlautencoding-test/target/site/apidocs").toPath(); // package level generated javadoc files - assertThat( apidocs.resolve( "optionsumlautencoding/test/App.html" ) ).exists(); - assertThat( apidocs.resolve( "optionsumlautencoding/test/AppSample.html" ) ).exists(); + assertThat(apidocs.resolve("optionsumlautencoding/test/App.html")).exists(); + assertThat(apidocs.resolve("optionsumlautencoding/test/AppSample.html")).exists(); // project level generated javadoc files - assertThat( apidocs.resolve( "index-all.html" ) ).exists(); - assertThat( apidocs.resolve( "index.html" ) ).exists(); - assertThat( apidocs.resolve( "overview-tree.html" ) ).exists(); - assertThat( apidocs.resolve( "stylesheet.css" ) ).exists(); - - if ( JavaVersion.JAVA_VERSION.isBefore( "10" ) ) - { - assertThat( apidocs.resolve( "package-list" )).exists(); - } - else - { - assertThat( apidocs.resolve( "element-list" )).exists(); + assertThat(apidocs.resolve("index-all.html")).exists(); + assertThat(apidocs.resolve("index.html")).exists(); + assertThat(apidocs.resolve("overview-tree.html")).exists(); + assertThat(apidocs.resolve("stylesheet.css")).exists(); + + if (JavaVersion.JAVA_VERSION.isBefore("10")) { + assertThat(apidocs.resolve("package-list")).exists(); + } else { + assertThat(apidocs.resolve("element-list")).exists(); } } /** * @throws Exception if any */ - public void testExceptions() - throws Exception - { - try - { - Path testPom = unit.resolve( "default-configuration/exception-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testExceptions() throws Exception { + try { + Path testPom = unit.resolve("default-configuration/exception-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - fail( "Must throw exception." ); - } - catch ( Exception e ) - { - assertTrue( true ); + fail("Must throw exception."); + } catch (Exception e) { + assertTrue(true); - try - { - deleteDirectory( new File( getBasedir(), "exception" ) ); - } - catch ( IOException ie ) - { + try { + deleteDirectory(new File(getBasedir(), "exception")); + } catch (IOException ie) { // nop } } @@ -672,9 +619,7 @@ public void testExceptions() * * @throws Exception if any */ - public void testTaglets() - throws Exception - { + public void testTaglets() throws Exception { // ---------------------------------------------------------------------- // taglet-test: check if a taglet is used // ---------------------------------------------------------------------- @@ -682,38 +627,38 @@ public void testTaglets() // Should be an assumption, but not supported by TestCase // com.sun.tools.doclets.Taglet not supported by Java9 anymore // Should be refactored with jdk.javadoc.doclet.Taglet - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "10" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("10")) { return; } - Path testPom = unit.resolve( "taglet-test/taglet-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("taglet-test/taglet-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/taglet-test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/taglet-test/target/site/apidocs").toPath(); - assertThat( apidocs.resolve( "index.html" )).exists(); + assertThat(apidocs.resolve("index.html")).exists(); - Path appFile = apidocs.resolve( "taglet/test/App.html" ); - assertThat( appFile ).exists(); - String appString = readFile( appFile ); - assertThat( appString ).contains( "To Do:" ); + Path appFile = apidocs.resolve("taglet/test/App.html"); + assertThat(appFile).exists(); + String appString = readFile(appFile); + assertThat(appString).contains("To Do:"); } /** @@ -721,33 +666,30 @@ public void testTaglets() * * @throws Exception if any */ - public void testJdk5() - throws Exception - { + public void testJdk5() throws Exception { // Should be an assumption, but not supported by TestCase // Java 5 not supported by Java9 anymore - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "9" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("9")) { return; } - Path testPom = unit.resolve( "jdk5-test/jdk5-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("jdk5-test/jdk5-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/jdk5-test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/jdk5-test/target/site/apidocs").toPath(); - assertThat( apidocs.resolve( "index.html" ) ).exists(); + assertThat(apidocs.resolve("index.html")).exists(); - Path overviewSummary = apidocs.resolve( "overview-summary.html" ); - assertThat( overviewSummary ).exists(); - String content = readFile( overviewSummary ); - assertThat( content ).contains( "Test the package-info" ); + Path overviewSummary = apidocs.resolve("overview-summary.html"); + assertThat(overviewSummary).exists(); + String content = readFile(overviewSummary); + assertThat(content).contains("Test the package-info"); - Path packageSummary = apidocs.resolve( "jdk5/test/package-summary.html" ); - assertThat( packageSummary ).exists(); - content = readFile( packageSummary ); - assertThat( content ).contains( "Test the package-info" ); + Path packageSummary = apidocs.resolve("jdk5/test/package-summary.html"); + assertThat(packageSummary).exists(); + content = readFile(packageSummary); + assertThat(content).contains("Test the package-info"); } /** @@ -756,17 +698,15 @@ public void testJdk5() * * @throws Exception if any */ - public void testToFindJavadoc() - throws Exception - { - String oldJreHome = System.getProperty( "java.home" ); - System.setProperty( "java.home", "foo/bar" ); - - Path testPom = unit.resolve( "javaHome-test/javaHome-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testToFindJavadoc() throws Exception { + String oldJreHome = System.getProperty("java.home"); + System.setProperty("java.home", "foo/bar"); + + Path testPom = unit.resolve("javaHome-test/javaHome-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - System.setProperty( "java.home", oldJreHome ); + System.setProperty("java.home", oldJreHome); } /** @@ -774,60 +714,59 @@ public void testToFindJavadoc() * * @throws Exception if any */ - public void testJavadocResources() - throws Exception - { - Path testPom = unit.resolve( "resources-test/resources-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testJavadocResources() throws Exception { + Path testPom = unit.resolve("resources-test/resources-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/resources-test/target/site/apidocs/" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/resources-test/target/site/apidocs/").toPath(); - Path app = apidocs.resolve( "resources/test/App.html" ); - assertThat( app ).exists(); - String content = readFile( app ); - assertThat( content ).contains( "\"Maven\"" ); - assertThat( apidocs.resolve( "resources/test/doc-files/maven-feather.png" )).exists(); + Path app = apidocs.resolve("resources/test/App.html"); + assertThat(app).exists(); + String content = readFile(app); + assertThat(content).contains("\"Maven\""); + assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png")) + .exists(); - Path app2 = apidocs.resolve( "resources/test2/App2.html" ); - assertThat( app2 ).exists(); - content = readFile( app2 ); - assertThat( content ).contains( "\"Maven\"" ); - assertThat( apidocs.resolve( "resources/test2/doc-files/maven-feather.png" )).doesNotExist(); + Path app2 = apidocs.resolve("resources/test2/App2.html"); + assertThat(app2).exists(); + content = readFile(app2); + assertThat(content).contains("\"Maven\""); + assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png")) + .doesNotExist(); // with excludes - testPom = unit.resolve( "resources-with-excludes-test/resources-with-excludes-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); + testPom = unit.resolve("resources-with-excludes-test/resources-with-excludes-test-plugin-config.xml"); + mojo = lookupMojo(testPom); mojo.execute(); - apidocs = new File( getBasedir(), - "target/test/unit/resources-with-excludes-test/target/site/apidocs" ).toPath(); + apidocs = new File(getBasedir(), "target/test/unit/resources-with-excludes-test/target/site/apidocs").toPath(); - app = apidocs.resolve( "resources/test/App.html" ); - assertThat( app ).exists(); - content = readFile( app ); - assertThat( content ).contains( "\"Maven\"" ); + app = apidocs.resolve("resources/test/App.html"); + assertThat(app).exists(); + content = readFile(app); + assertThat(content).contains("\"Maven\""); - JavaVersion javadocVersion = (JavaVersion) getVariableValueFromObject( mojo, "javadocRuntimeVersion" ); - if( javadocVersion.isAtLeast( "1.8" ) /* && javadocVersion.isBefore( "14" ) */ ) - { + JavaVersion javadocVersion = (JavaVersion) getVariableValueFromObject(mojo, "javadocRuntimeVersion"); + if (javadocVersion.isAtLeast("1.8") /* && javadocVersion.isBefore( "14" ) */) { // https://bugs.openjdk.java.net/browse/JDK-8032205 - assertThat( apidocs.resolve( "resources/test/doc-files/maven-feather.png" )) + assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png")) .as("Javadoc runtime version: " + javadocVersion + "\nThis bug appeared in JDK8 and was planned to be fixed in JDK9, see JDK-8032205") .exists(); + } else { + assertThat(apidocs.resolve("resources/test/doc-files/maven-feather.png")) + .doesNotExist(); } - else - { - assertThat( apidocs.resolve( "resources/test/doc-files/maven-feather.png" ) ).doesNotExist(); - } - assertThat( apidocs.resolve( "resources/test2/doc-files/maven-feather.png" ) ).exists(); - - app2 = apidocs.resolve( "resources/test2/App2.html" ); - assertThat( app2 ).exists(); - content = readFile( app2 ); - assertThat( content ).contains( "\"Maven\"" ); - assertThat( apidocs.resolve( "resources/test2/doc-files/maven-feather.png" ) ).exists(); + assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png")) + .exists(); + + app2 = apidocs.resolve("resources/test2/App2.html"); + assertThat(app2).exists(); + content = readFile(app2); + assertThat(content).contains("\"Maven\""); + assertThat(apidocs.resolve("resources/test2/doc-files/maven-feather.png")) + .exists(); } /** @@ -835,14 +774,13 @@ public void testJavadocResources() * * @throws Exception if any */ - public void testPom() - throws Exception - { - Path testPom = unit.resolve( "pom-test/pom-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testPom() throws Exception { + Path testPom = unit.resolve("pom-test/pom-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - assertThat( new File( getBasedir(), "target/test/unit/pom-test/target/site" )).doesNotExist(); + assertThat(new File(getBasedir(), "target/test/unit/pom-test/target/site")) + .doesNotExist(); } /** @@ -850,25 +788,22 @@ public void testPom() * * @throws Exception if any */ - public void testTag() - throws Exception - { - Path testPom = unit.resolve( "tag-test/tag-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + public void testTag() throws Exception { + Path testPom = unit.resolve("tag-test/tag-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path app = new File( getBasedir(), "target/test/unit/tag-test/target/site/apidocs/tag/test/App.html" ).toPath(); - assertThat( app ).exists(); - String readed = readFile( app ); - assertThat( readed ).contains( ">To do something:Generator Class:To do something:Generator Class:Version:" + LINE_SEPARATOR + "
1.0
" ) || readed.toLowerCase().contains( - "" + LINE_SEPARATOR + "
1.0
" /* JDK 8 */ ) ); + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) { + assertThat(readed).contains(">Version:" + LINE_SEPARATOR + "
1.0
") + || readed.toLowerCase().contains("" + LINE_SEPARATOR + "
1.0
" /* JDK 8 */)); } } @@ -877,21 +812,16 @@ public void testTag() * * @throws Exception if any */ - public void testHeaderFooter() - throws Exception - { - Path testPom = unit.resolve( "header-footer-test/header-footer-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); - try - { + public void testHeaderFooter() throws Exception { + Path testPom = unit.resolve("header-footer-test/header-footer-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); + try { mojo.execute(); - } - catch ( MojoExecutionException e ) - { - fail( "Doesnt handle correctly newline for header or footer parameter" ); + } catch (MojoExecutionException e) { + fail("Doesnt handle correctly newline for header or footer parameter"); } - assertTrue( true ); + assertTrue(true); } /** @@ -899,21 +829,16 @@ public void testHeaderFooter() * * @throws Exception if any */ - public void testNewline() - throws Exception - { - Path testPom = unit.resolve( "newline-test/newline-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); - try - { + public void testNewline() throws Exception { + Path testPom = unit.resolve("newline-test/newline-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); + try { mojo.execute(); - } - catch ( MojoExecutionException e ) - { - fail( "Doesn't handle correctly newline for string parameters. See options and packages files." ); + } catch (MojoExecutionException e) { + fail("Doesn't handle correctly newline for string parameters. See options and packages files."); } - assertTrue( true ); + assertTrue(true); } /** @@ -921,45 +846,41 @@ public void testNewline() * * @throws Exception if any */ - public void testJdk6() - throws Exception - { + public void testJdk6() throws Exception { // Should be an assumption, but not supported by TestCase // Java 6 not supported by Java 12 anymore - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "12" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("12")) { return; } - Path testPom = unit.resolve( "jdk6-test/jdk6-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("jdk6-test/jdk6-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); mojo.execute(); - Path apidocs = new File( getBasedir(), "target/test/unit/jdk6-test/target/site/apidocs" ).toPath(); - assertThat( apidocs.resolve( "index.html" ) ).exists(); + Path apidocs = new File(getBasedir(), "target/test/unit/jdk6-test/target/site/apidocs").toPath(); + assertThat(apidocs.resolve("index.html")).exists(); Path overview; - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore( "11" ) ) - { - overview = apidocs.resolve( "overview-summary.html" ); - } - else - { - overview = apidocs.resolve( "index.html" ); + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isBefore("11")) { + overview = apidocs.resolve("overview-summary.html"); + } else { + overview = apidocs.resolve("index.html"); } - assertThat( overview ).exists(); - String content = readFile( overview ); - assertThat( content ).contains( "Top - Copyright © All rights reserved." ) - .contains( "Header - Copyright © All rights reserved." ) - .contains( "Footer - Copyright © All rights reserved." ); - - Path packageSummary = apidocs.resolve( "jdk6/test/package-summary.html" ); - assertThat( packageSummary ).exists(); - content = readFile( packageSummary ); - assertThat( content ).contains( "Top - Copyright © All rights reserved." ) - .contains( "Header - Copyright © All rights reserved." ) - .contains( "Footer - Copyright © All rights reserved." ); + assertThat(overview).exists(); + String content = readFile(overview); + assertThat(content) + .contains("Top - Copyright © All rights reserved.") + .contains("Header - Copyright © All rights reserved.") + .contains("Footer - Copyright © All rights reserved."); + + Path packageSummary = apidocs.resolve("jdk6/test/package-summary.html"); + assertThat(packageSummary).exists(); + content = readFile(packageSummary); + assertThat(content) + .contains("Top - Copyright © All rights reserved.") + .contains("Header - Copyright © All rights reserved.") + .contains("Footer - Copyright © All rights reserved."); } /** @@ -967,87 +888,87 @@ public void testJdk6() * * @throws Exception if any */ - public void testProxy() - throws Exception - { + public void testProxy() throws Exception { Settings settings = new Settings(); Proxy proxy = new Proxy(); // dummy proxy - proxy.setActive( true ); - proxy.setHost( "127.0.0.1" ); - proxy.setPort( 80 ); - proxy.setProtocol( "http" ); - proxy.setUsername( "toto" ); - proxy.setPassword( "toto" ); - proxy.setNonProxyHosts( "www.google.com|*.somewhere.com" ); - settings.addProxy( proxy ); - - Path testPom = new File( getBasedir(), "src/test/resources/unit/proxy-test/proxy-test-plugin-config.xml" ).toPath(); - JavadocReport mojo = lookupMojo( testPom ); - - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + proxy.setActive(true); + proxy.setHost("127.0.0.1"); + proxy.setPort(80); + proxy.setProtocol("http"); + proxy.setUsername("toto"); + proxy.setPassword("toto"); + proxy.setNonProxyHosts("www.google.com|*.somewhere.com"); + settings.addProxy(proxy); + + Path testPom = + new File(getBasedir(), "src/test/resources/unit/proxy-test/proxy-test-plugin-config.xml").toPath(); + JavadocReport mojo = lookupMojo(testPom); + + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - - setVariableValueToObject( mojo, "settings", settings ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + + setVariableValueToObject(mojo, "settings", settings); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - Path commandLine = new File( getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/javadoc." + ( SystemUtils.IS_OS_WINDOWS ? "bat" : "sh" ) ).toPath(); - assertThat( commandLine ).exists(); - String readed = readFile( commandLine ); - assertThat( readed ).contains( "-J-Dhttp.proxyHost=127.0.0.1" ).contains( "-J-Dhttp.proxyPort=80" ); - if ( SystemUtils.IS_OS_WINDOWS ) - { - assertThat( readed ).contains( " -J-Dhttp.nonProxyHosts=\"www.google.com^|*.somewhere.com\" " ); - } - else - { - assertThat( readed ).contains( " \"-J-Dhttp.nonProxyHosts=\\\"www.google.com^|*.somewhere.com\\\"\" " ); + Path commandLine = new File( + getBasedir(), + "target/test/unit/proxy-test/target/site/apidocs/javadoc." + + (SystemUtils.IS_OS_WINDOWS ? "bat" : "sh")) + .toPath(); + assertThat(commandLine).exists(); + String readed = readFile(commandLine); + assertThat(readed).contains("-J-Dhttp.proxyHost=127.0.0.1").contains("-J-Dhttp.proxyPort=80"); + if (SystemUtils.IS_OS_WINDOWS) { + assertThat(readed).contains(" -J-Dhttp.nonProxyHosts=\"www.google.com^|*.somewhere.com\" "); + } else { + assertThat(readed).contains(" \"-J-Dhttp.nonProxyHosts=\\\"www.google.com^|*.somewhere.com\\\"\" "); } - Path options = new File( getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/options" ).toPath(); - assertThat( options ).exists(); - String optionsContent = readFile( options ); + Path options = new File(getBasedir(), "target/test/unit/proxy-test/target/site/apidocs/options").toPath(); + assertThat(options).exists(); + String optionsContent = readFile(options); // NO -link expected - assertThat( optionsContent ).doesNotContain( "-link" ); + assertThat(optionsContent).doesNotContain("-link"); // real proxy ProxyServer proxyServer = null; AuthAsyncProxyServlet proxyServlet; - try - { + try { proxyServlet = new AuthAsyncProxyServlet(); - proxyServer = new ProxyServer( proxyServlet ); + proxyServer = new ProxyServer(proxyServlet); proxyServer.start(); settings = new Settings(); proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - settings.addProxy( proxy ); - - mojo = lookupMojo( testPom ); - setVariableValueToObject( mojo, "settings", settings ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + settings.addProxy(proxy); + + mojo = lookupMojo(testPom); + setVariableValueToObject(mojo, "settings", settings); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - readed = readFile( commandLine ); - assertTrue( readed.contains( "-J-Dhttp.proxyHost=" + proxyServer.getHostName() ) ); - assertTrue( readed.contains( "-J-Dhttp.proxyPort=" + proxyServer.getPort() ) ); + readed = readFile(commandLine); + assertTrue(readed.contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName())); + assertTrue(readed.contains("-J-Dhttp.proxyPort=" + proxyServer.getPort())); - optionsContent = readFile( options ); + optionsContent = readFile(options); // -link expected // TODO: This got disabled for now! // This test fails since the last commit but I actually think it only ever worked by accident. @@ -1058,52 +979,46 @@ public void testProxy() // did go upstream. The remoteRepository list used is always empty!. // // assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) ); - } - finally - { - if ( proxyServer != null ) - { + } finally { + if (proxyServer != null) { proxyServer.stop(); } } // auth proxy Map authentications = new HashMap<>(); - authentications.put( "foo", "bar" ); - try - { - proxyServlet = new AuthAsyncProxyServlet( authentications ); - proxyServer = new ProxyServer( proxyServlet ); + authentications.put("foo", "bar"); + try { + proxyServlet = new AuthAsyncProxyServlet(authentications); + proxyServer = new ProxyServer(proxyServlet); proxyServer.start(); settings = new Settings(); proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - proxy.setUsername( "foo" ); - proxy.setPassword( "bar" ); - settings.addProxy( proxy ); - - mojo = lookupMojo( testPom ); - setVariableValueToObject( mojo, "settings", settings ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + proxy.setUsername("foo"); + proxy.setPassword("bar"); + settings.addProxy(proxy); + + mojo = lookupMojo(testPom); + setVariableValueToObject(mojo, "settings", settings); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - readed = readFile( commandLine ); - assertThat( readed ).contains( "-J-Dhttp.proxyHost=" + proxyServer.getHostName() ) - .contains( "-J-Dhttp.proxyPort=" + proxyServer.getPort() ); + readed = readFile(commandLine); + assertThat(readed) + .contains("-J-Dhttp.proxyHost=" + proxyServer.getHostName()) + .contains("-J-Dhttp.proxyPort=" + proxyServer.getPort()); - optionsContent = readFile( options ); + optionsContent = readFile(options); // -link expected // see comment above (line 829) // assertTrue( optionsContent.contains( "-link 'http://commons.apache.org/logging/apidocs'" ) ); - } - finally - { - if ( proxyServer != null ) - { + } finally { + if (proxyServer != null) { proxyServer.stop(); } } @@ -1114,72 +1029,55 @@ public void testProxy() * * @throws Exception if any */ - public void testValidateOptions() - throws Exception - { + public void testValidateOptions() throws Exception { // encoding - Path testPom = unit.resolve( "validate-options-test/wrong-encoding-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); - try - { + Path testPom = unit.resolve("validate-options-test/wrong-encoding-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); + try { mojo.execute(); - fail( "No wrong encoding catch" ); - } - catch ( MojoExecutionException e ) - { - assertTrue( "No wrong encoding catch", e.getMessage().contains( "Unsupported option " ) ); + fail("No wrong encoding catch"); + } catch (MojoExecutionException e) { + assertTrue("No wrong encoding catch", e.getMessage().contains("Unsupported option ")); } - testPom = unit.resolve( "validate-options-test/wrong-docencoding-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); - try - { + testPom = unit.resolve("validate-options-test/wrong-docencoding-test-plugin-config.xml"); + mojo = lookupMojo(testPom); + try { mojo.execute(); - fail( "No wrong docencoding catch" ); + fail("No wrong docencoding catch"); + } catch (MojoExecutionException e) { + assertTrue("No wrong docencoding catch", e.getMessage().contains("Unsupported option ")); } - catch ( MojoExecutionException e ) - { - assertTrue( "No wrong docencoding catch", e.getMessage().contains( "Unsupported option " ) ); - } - testPom = unit.resolve( "validate-options-test/wrong-charset-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); - try - { + testPom = unit.resolve("validate-options-test/wrong-charset-test-plugin-config.xml"); + mojo = lookupMojo(testPom); + try { mojo.execute(); - fail( "No wrong charset catch" ); - } - catch ( MojoExecutionException e ) - { - assertTrue( "No wrong charset catch", e.getMessage().contains( "Unsupported option " ) ); + fail("No wrong charset catch"); + } catch (MojoExecutionException e) { + assertTrue("No wrong charset catch", e.getMessage().contains("Unsupported option ")); } // locale - testPom = unit.resolve( "validate-options-test/wrong-locale-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); - try - { + testPom = unit.resolve("validate-options-test/wrong-locale-test-plugin-config.xml"); + mojo = lookupMojo(testPom); + try { mojo.execute(); - fail( "No wrong locale catch" ); + fail("No wrong locale catch"); + } catch (MojoExecutionException e) { + assertTrue("No wrong locale catch", e.getMessage().contains("Unsupported option ")); } - catch ( MojoExecutionException e ) - { - assertTrue( "No wrong locale catch", e.getMessage().contains( "Unsupported option " ) ); - } - testPom = unit.resolve( "validate-options-test/wrong-locale-with-variant-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); + testPom = unit.resolve("validate-options-test/wrong-locale-with-variant-test-plugin-config.xml"); + mojo = lookupMojo(testPom); mojo.execute(); - assertTrue( "No wrong locale catch", true ); + assertTrue("No wrong locale catch", true); // conflict options - testPom = unit.resolve( "validate-options-test/conflict-options-test-plugin-config.xml" ); - mojo = lookupMojo( testPom ); - try - { + testPom = unit.resolve("validate-options-test/conflict-options-test-plugin-config.xml"); + mojo = lookupMojo(testPom); + try { mojo.execute(); - fail( "No conflict catch" ); - } - catch ( MojoExecutionException e ) - { - assertTrue( "No conflict catch", e.getMessage().contains( "Option conflicts with " ) ); + fail("No conflict catch"); + } catch (MojoExecutionException e) { + assertTrue("No conflict catch", e.getMessage().contains("Option conflicts with ")); } } @@ -1188,42 +1086,41 @@ public void testValidateOptions() * * @throws Exception if any */ - public void testTagletArtifacts() - throws Exception - { + public void testTagletArtifacts() throws Exception { // Should be an assumption, but not supported by TestCase // com.sun.tools.doclets.Taglet not supported by Java 10 anymore - if ( JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast( "10" ) ) - { + if (JavaVersion.JAVA_SPECIFICATION_VERSION.isAtLeast("10")) { return; } - Path testPom = unit.resolve( "tagletArtifacts-test/tagletArtifacts-test-plugin-config.xml" ); - JavadocReport mojo = lookupMojo( testPom ); + Path testPom = unit.resolve("tagletArtifacts-test/tagletArtifacts-test-plugin-config.xml"); + JavadocReport mojo = lookupMojo(testPom); - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); mojo.execute(); - Path optionsFile = new File( mojo.getOutputDirectory(), "options" ).toPath(); - assertThat( optionsFile ).exists(); - String options = readFile( optionsFile ); + Path optionsFile = new File(mojo.getOutputDirectory(), "options").toPath(); + assertThat(optionsFile).exists(); + String options = readFile(optionsFile); // count -taglet - assertThat( StringUtils.countMatches( options, LINE_SEPARATOR + "-taglet" + LINE_SEPARATOR ) ).isEqualTo( 3 ); - assertThat( options ) - .contains( "org.codehaus.plexus.javadoc.PlexusConfigurationTaglet" ) - .contains( "org.codehaus.plexus.javadoc.PlexusRequirementTaglet" ) - .contains( "org.codehaus.plexus.javadoc.PlexusComponentTaglet" ); + assertThat(StringUtils.countMatches(options, LINE_SEPARATOR + "-taglet" + LINE_SEPARATOR)) + .isEqualTo(3); + assertThat(options) + .contains("org.codehaus.plexus.javadoc.PlexusConfigurationTaglet") + .contains("org.codehaus.plexus.javadoc.PlexusRequirementTaglet") + .contains("org.codehaus.plexus.javadoc.PlexusComponentTaglet"); } /** @@ -1231,110 +1128,98 @@ public void testTagletArtifacts() * * @throws Exception if any */ - public void testStylesheetfile() - throws Exception - { - Path testPom = unit.resolve( "stylesheetfile-test/pom.xml" ); - - JavadocReport mojo = lookupMojo( testPom ); - assertNotNull( mojo ); - - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + public void testStylesheetfile() throws Exception { + Path testPom = unit.resolve("stylesheetfile-test/pom.xml"); + + JavadocReport mojo = lookupMojo(testPom); + assertNotNull(mojo); + + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); - Path apidocs = new File( getBasedir(), "target/test/unit/stylesheetfile-test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/stylesheetfile-test/target/site/apidocs").toPath(); - Path stylesheetfile = apidocs.resolve( "stylesheet.css" ); - Path options = apidocs.resolve( "options" ); + Path stylesheetfile = apidocs.resolve("stylesheet.css"); + Path options = apidocs.resolve("options"); // stylesheet == maven OR java - setVariableValueToObject( mojo, "stylesheet", "javamaven" ); + setVariableValueToObject(mojo, "stylesheet", "javamaven"); - try - { + try { mojo.execute(); fail(); - } - catch ( Exception e ) - { - assertTrue( true ); + } catch (Exception e) { + assertTrue(true); } // stylesheet == java - setVariableValueToObject( mojo, "stylesheet", "java" ); + setVariableValueToObject(mojo, "stylesheet", "java"); mojo.execute(); - String content = readFile( stylesheetfile ); - if ( JavaVersion.JAVA_VERSION.isAtLeast( "13-ea" ) ) - { - assertTrue( content.contains( "/*" + LINE_SEPARATOR - + " * Javadoc style sheet" + LINE_SEPARATOR - + " */" ) ); - } - else if ( JavaVersion.JAVA_VERSION.isAtLeast( "10" ) ) - { - assertTrue( content.contains( "/* " + LINE_SEPARATOR - + " * Javadoc style sheet" + LINE_SEPARATOR - + " */" ) ); - } - else - { - assertTrue( content.contains( "/* Javadoc style sheet */" ) ); + String content = readFile(stylesheetfile); + if (JavaVersion.JAVA_VERSION.isAtLeast("13-ea")) { + assertTrue(content.contains("/*" + LINE_SEPARATOR + " * Javadoc style sheet" + LINE_SEPARATOR + " */")); + } else if (JavaVersion.JAVA_VERSION.isAtLeast("10")) { + assertTrue(content.contains("/* " + LINE_SEPARATOR + " * Javadoc style sheet" + LINE_SEPARATOR + " */")); + } else { + assertTrue(content.contains("/* Javadoc style sheet */")); } - String optionsContent = readFile( options ); - assertFalse( optionsContent.contains( "-stylesheetfile" ) ); + String optionsContent = readFile(options); + assertFalse(optionsContent.contains("-stylesheetfile")); // stylesheetfile defined as a project resource - setVariableValueToObject( mojo, "stylesheet", null ); - setVariableValueToObject( mojo, "stylesheetfile", "com/mycompany/app/javadoc/css/stylesheet.css" ); + setVariableValueToObject(mojo, "stylesheet", null); + setVariableValueToObject(mojo, "stylesheetfile", "com/mycompany/app/javadoc/css/stylesheet.css"); mojo.execute(); - content = readFile( stylesheetfile ); - assertTrue( content.contains( "/* Custom Javadoc style sheet in project */" ) ); + content = readFile(stylesheetfile); + assertTrue(content.contains("/* Custom Javadoc style sheet in project */")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-stylesheetfile" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-stylesheetfile")); Path stylesheetResource = - unit.resolve( "stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css/stylesheet.css" ); - assertTrue( optionsContent.contains( "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) - + "'" ) ); + unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css/stylesheet.css"); + assertTrue(optionsContent.contains( + "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); // stylesheetfile defined in a javadoc plugin dependency - setVariableValueToObject( mojo, "stylesheetfile", "com/mycompany/app/javadoc/css2/stylesheet.css" ); + setVariableValueToObject(mojo, "stylesheetfile", "com/mycompany/app/javadoc/css2/stylesheet.css"); mojo.execute(); - content = readFile( stylesheetfile ); - assertTrue( content.contains( "/* Custom Javadoc style sheet in artefact */" ) ); + content = readFile(stylesheetfile); + assertTrue(content.contains("/* Custom Javadoc style sheet in artefact */")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-stylesheetfile" ) ); - assertTrue( optionsContent.contains( "'" + stylesheetfile.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) + "'" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-stylesheetfile")); + assertTrue(optionsContent.contains( + "'" + stylesheetfile.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); // stylesheetfile defined as file - Path css = - unit.resolve( "stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css" ); - setVariableValueToObject( mojo, "stylesheetfile", css.toFile().getAbsolutePath() ); + Path css = unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css"); + setVariableValueToObject(mojo, "stylesheetfile", css.toFile().getAbsolutePath()); mojo.execute(); - content = readFile( stylesheetfile ); - assertTrue( content.contains( "/* Custom Javadoc style sheet as file */" ) ); + content = readFile(stylesheetfile); + assertTrue(content.contains("/* Custom Javadoc style sheet as file */")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-stylesheetfile" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-stylesheetfile")); stylesheetResource = - unit.resolve( "stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css" ); - assertTrue( optionsContent.contains( "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) + "'" ) ); + unit.resolve("stylesheetfile-test/src/main/resources/com/mycompany/app/javadoc/css3/stylesheet.css"); + assertTrue(optionsContent.contains( + "'" + stylesheetResource.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); } /** @@ -1342,79 +1227,78 @@ else if ( JavaVersion.JAVA_VERSION.isAtLeast( "10" ) ) * * @throws Exception if any */ - public void testHelpfile() - throws Exception - { - Path testPom = unit.resolve( "helpfile-test/pom.xml" ); - - JavadocReport mojo = lookupMojo( testPom ); - assertNotNull( mojo ); - - MavenSession session = spy( newMavenSession( mojo.project ) ); - ProjectBuildingRequest buildingRequest = mock( ProjectBuildingRequest.class ); - when( buildingRequest.getRemoteRepositories() ).thenReturn( mojo.project.getRemoteArtifactRepositories() ); - when( session.getProjectBuildingRequest() ).thenReturn( buildingRequest ); + public void testHelpfile() throws Exception { + Path testPom = unit.resolve("helpfile-test/pom.xml"); + + JavadocReport mojo = lookupMojo(testPom); + assertNotNull(mojo); + + MavenSession session = spy(newMavenSession(mojo.project)); + ProjectBuildingRequest buildingRequest = mock(ProjectBuildingRequest.class); + when(buildingRequest.getRemoteRepositories()).thenReturn(mojo.project.getRemoteArtifactRepositories()); + when(session.getProjectBuildingRequest()).thenReturn(buildingRequest); DefaultRepositorySystemSession repositorySession = new DefaultRepositorySystemSession(); - repositorySession.setLocalRepositoryManager( new SimpleLocalRepositoryManagerFactory().newInstance( repositorySession, new LocalRepository( localRepo ) ) ); - when( buildingRequest.getRepositorySession() ).thenReturn( repositorySession ); - when( session.getRepositorySession() ).thenReturn( repositorySession ); - LegacySupport legacySupport = lookup( LegacySupport.class ); - legacySupport.setSession( session ); - setVariableValueToObject( mojo, "session", session ); - setVariableValueToObject( mojo, "repoSession", repositorySession ); + repositorySession.setLocalRepositoryManager(new SimpleLocalRepositoryManagerFactory() + .newInstance(repositorySession, new LocalRepository(localRepo))); + when(buildingRequest.getRepositorySession()).thenReturn(repositorySession); + when(session.getRepositorySession()).thenReturn(repositorySession); + LegacySupport legacySupport = lookup(LegacySupport.class); + legacySupport.setSession(session); + setVariableValueToObject(mojo, "session", session); + setVariableValueToObject(mojo, "repoSession", repositorySession); - Path apidocs = new File( getBasedir(), "target/test/unit/helpfile-test/target/site/apidocs" ).toPath(); + Path apidocs = new File(getBasedir(), "target/test/unit/helpfile-test/target/site/apidocs").toPath(); - Path helpfile = apidocs.resolve( "help-doc.html" ); - Path options = apidocs.resolve( "options" ); + Path helpfile = apidocs.resolve("help-doc.html"); + Path options = apidocs.resolve("options"); // helpfile by default mojo.execute(); - String content = readFile( helpfile ); - assertTrue( content.contains( "" ) ); + content = readFile(helpfile); + assertTrue(content.contains("")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-helpfile" ) ); - Path help = apidocs.resolve( "help-doc.html" ); - assertTrue( optionsContent.contains( "'" + help.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) + "'" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-helpfile")); + Path help = apidocs.resolve("help-doc.html"); + assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); // helpfile defined as a project resource - setVariableValueToObject( mojo, "helpfile", "com/mycompany/app/javadoc/helpfile2/help-doc.html" ); + setVariableValueToObject(mojo, "helpfile", "com/mycompany/app/javadoc/helpfile2/help-doc.html"); mojo.execute(); - content = readFile( helpfile ); - assertTrue( content.contains( "" ) ); + content = readFile(helpfile); + assertTrue(content.contains("")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-helpfile" ) ); - help = unit.resolve( "helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html" ); - assertTrue( optionsContent.contains( "'" + help.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) + "'" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-helpfile")); + help = unit.resolve("helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html"); + assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); // helpfile defined as file - help = unit.resolve( "helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html" ); - setVariableValueToObject( mojo, "helpfile", help.toFile().getAbsolutePath() ); + help = unit.resolve("helpfile-test/src/main/resources/com/mycompany/app/javadoc/helpfile2/help-doc.html"); + setVariableValueToObject(mojo, "helpfile", help.toFile().getAbsolutePath()); mojo.execute(); - content = readFile( helpfile ); - assertTrue( content.contains( "" ) ); + content = readFile(helpfile); + assertTrue(content.contains("")); - optionsContent = readFile( options ); - assertTrue( optionsContent.contains( "-helpfile" ) ); - assertTrue( optionsContent.contains( "'" + help.toFile().getAbsolutePath().replaceAll( "\\\\", "/" ) + "'" ) ); + optionsContent = readFile(options); + assertTrue(optionsContent.contains("-helpfile")); + assertTrue(optionsContent.contains("'" + help.toFile().getAbsolutePath().replaceAll("\\\\", "/") + "'")); } } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/JavadocUtilTest.java b/src/test/java/org/apache/maven/plugins/javadoc/JavadocUtilTest.java index 3a7c93f14..c3168ba6d 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/JavadocUtilTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/JavadocUtilTest.java @@ -1,727 +1,649 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.OutputStream; -import java.net.SocketTimeoutException; -import java.net.URI; -import java.net.URL; -import java.nio.file.Path; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.regex.PatternSyntaxException; - -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.plugins.javadoc.ProxyServer.AuthAsyncProxyServlet; -import org.apache.maven.settings.Proxy; -import org.apache.maven.settings.Settings; -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.util.FileUtils; -import org.eclipse.jetty.server.Request; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.server.handler.AbstractHandler; -import org.eclipse.jetty.server.handler.MovedContextHandler; -import org.eclipse.jetty.util.ByteArrayISO8859Writer; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Vincent Siveton - */ -public class JavadocUtilTest - extends PlexusTestCase -{ - /** - * Method to test the javadoc version parsing. - * - */ - public void testParseJavadocVersion() - { - String version = null; - try - { - JavadocUtil.extractJavadocVersion( version ); - fail( "Not catch null" ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - - // Sun JDK 1.4 - version = "java full version \"1.4.2_12-b03\""; - assertEquals( "1.4.2", JavadocUtil.extractJavadocVersion( version ) ); - - // Sun JDK 1.5 - version = "java full version \"1.5.0_07-164\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // IBM JDK 1.4 - version = "java full version \"J2RE 1.4.2 IBM Windows 32 build cn1420-20040626\""; - assertEquals( "1.4.2", JavadocUtil.extractJavadocVersion( version ) ); - - // IBM JDK 1.5 - version = "javadoc version complète de \"J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // IBM JDK 1.5 - version = "J2RE 1.5.0 IBM Windows 32 build pwi32devifx-20070323 (ifix 117674: SR4 + 116644 + 114941 + 116110 + 114881)"; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // FreeBSD - version = "java full version \"diablo-1.5.0-b01\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // BEA - version = "java full version \"1.5.0_11-b03\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // Other tests - version = "java full version \"1.5.0_07-164\"" + System.getProperty( "line.separator" ); - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - version = System.getProperty( "line.separator" ) + "java full version \"1.5.0_07-164\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - version = System.getProperty( "line.separator" ) + "java full version \"1.5.0_07-164\"" - + System.getProperty( "line.separator" ); - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version )); - - version = "java full" + System.getProperty( "line.separator" ) + " version \"1.5.0_07-164\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"1.99.123-b01\""; - assertEquals( "1.99.123", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"1.5.0.07-164\""; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"1.4\""; - assertEquals( "1.4" , JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"1.A.B_07-164\""; - try - { - JavadocUtil.extractJavadocVersion( version ); - // does not fail since JEP 223 support addition - //assertTrue( "Not catch wrong pattern", false ); - } - catch ( PatternSyntaxException e ) - { - assertTrue( true ); - } - - version = "SCO-UNIX-J2SE-1.5.0_09*FCS-UW714-OSR6*_20061114"; - assertEquals( "1.5.0", JavadocUtil.extractJavadocVersion( version ) ); - - // Java 9 EA - version = "java full version \"9-ea+113\""; - assertEquals( "9", JavadocUtil.extractJavadocVersion( version ) ); - - // Java 9 EA Jigsaw - version = "java full version \"9-ea+113-2016-04-14-161743.javare.4852.nc\""; - assertEquals( "9", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java version \"9-ea\""; - assertEquals( "9", JavadocUtil.extractJavadocVersion( version ) ); - - // JEP 223 example for future versions - version = "java full version \"9+100\""; - assertEquals( "9", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"9.0.1+20\""; - assertEquals( "9.0.1", JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"10+100\""; - assertEquals( "10" , JavadocUtil.extractJavadocVersion( version ) ); - - version = "java full version \"10.0.1+20\""; - assertEquals( "10.0.1" , JavadocUtil.extractJavadocVersion( version ) ); - } - - /** - * Method to test the javadoc memory parsing. - * - */ - public void testParseJavadocMemory() - { - String memory = null; - try - { - JavadocUtil.parseJavadocMemory( memory ); - fail( "Not catch null" ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - - memory = "128"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - - memory = "128k"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128k" ); - memory = "128kb"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128k" ); - - memory = "128m"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - memory = "128mb"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - - memory = "1g"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "1024m" ); - memory = "1gb"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "1024m" ); - - memory = "1t"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "1048576m" ); - memory = "1tb"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "1048576m" ); - - memory = System.getProperty( "line.separator" ) + "128m"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - memory = System.getProperty( "line.separator" ) + "128m" + System.getProperty( "line.separator" ); - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - - memory = " 128m"; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - memory = " 128m "; - assertEquals( JavadocUtil.parseJavadocMemory( memory ), "128m" ); - - memory = "1m28m"; - try - { - JavadocUtil.parseJavadocMemory( memory ); - fail( "Not catch wrong pattern" ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - memory = "ABC128m"; - try - { - JavadocUtil.parseJavadocMemory( memory ); - fail( "Not catch wrong pattern" ); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - } - - /** - * Method to test the validate encoding parsing. - * - */ - public void testValidateEncoding() - { - assertFalse( "Not catch null", JavadocUtil.validateEncoding( null ) ); - assertTrue( "UTF-8 not supported on this plateform", JavadocUtil.validateEncoding( "UTF-8" ) ); - assertTrue( "ISO-8859-1 not supported on this plateform", JavadocUtil.validateEncoding( "ISO-8859-1" ) ); - assertFalse( "latin is supported on this plateform???", JavadocUtil.validateEncoding( "latin" ) ); - assertFalse( "WRONG is supported on this plateform???", JavadocUtil.validateEncoding( "WRONG" ) ); - } - - /** - * Method to test isValidPackageList() - * - * @throws Exception if any - */ - public void testIsValidPackageList() - throws Exception - { - Settings settings = null; - Proxy proxy; - - URL url = null; - URL wrongUrl; - try - { - JavadocUtil.isValidPackageList( url, settings, false ); - fail(); - } - catch ( IllegalArgumentException e ) - { - assertTrue( true ); - } - - url = new File( getBasedir(), "/pom.xml" ).toURI().toURL(); - assertTrue( JavadocUtil.isValidPackageList( url, settings, false ) ); - - try - { - assertFalse( JavadocUtil.isValidPackageList( url, settings, true ) ); - } - catch ( IOException e ) - { - assertTrue( true ); - } - - url = this.getClass().getResource( "/JavadocUtilTest-package-list.txt" ).toURI().toURL(); - assertTrue( JavadocUtil.isValidPackageList( url, settings, true ) ); - - url = new URL( "http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list" ); - assertTrue( JavadocUtil.isValidPackageList( url, settings, true ) ); - - wrongUrl = new URL( "http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list2" ); - try - { - JavadocUtil.isValidPackageList( wrongUrl, settings, false ); - fail(); - } - catch ( IOException e ) - { - assertTrue( true ); - } - - // real proxy - ProxyServer proxyServer = null; - AuthAsyncProxyServlet proxyServlet; - try - { - proxyServlet = new AuthAsyncProxyServlet(); - proxyServer = new ProxyServer( proxyServlet ); - proxyServer.start(); - - settings = new Settings(); - - assertTrue( JavadocUtil.isValidPackageList( url, settings, true ) ); - - try - { - JavadocUtil.isValidPackageList( wrongUrl, settings, false ); - fail(); - } - catch ( IOException e ) - { - assertTrue( true ); - } - } - finally - { - if ( proxyServer != null ) - { - proxyServer.stop(); - } - } - - Map authentications = new HashMap<>(); - authentications.put( "foo", "bar" ); - // wrong auth - try - { - proxyServlet = new AuthAsyncProxyServlet( authentications ); - proxyServer = new ProxyServer( proxyServlet ); - proxyServer.start(); - - settings = new Settings(); - proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - settings.addProxy( proxy ); - - JavadocUtil.isValidPackageList( url, settings, false ); - fail(); - } - catch ( FileNotFoundException e ) - { - assertTrue( true ); - } - finally - { - proxyServer.stop(); - } - - // auth proxy - try - { - proxyServlet = new AuthAsyncProxyServlet( authentications ); - proxyServer = new ProxyServer( proxyServlet ); - proxyServer.start(); - - settings = new Settings(); - proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - proxy.setUsername( "foo" ); - proxy.setPassword( "bar" ); - settings.addProxy( proxy ); - - assertTrue( JavadocUtil.isValidPackageList( url, settings, true ) ); - - try - { - JavadocUtil.isValidPackageList( wrongUrl, settings, false ); - fail(); - } - catch ( IOException e ) - { - assertTrue( true ); - } - } - finally - { - proxyServer.stop(); - } - - // timeout - try - { - proxyServlet = new AuthAsyncProxyServlet( authentications, 3000 ); // more than 2000, see fetchURL - proxyServer = new ProxyServer( proxyServlet ); - proxyServer.start(); - - settings = new Settings(); - proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - proxy.setUsername( "foo" ); - proxy.setPassword( "bar" ); - settings.addProxy( proxy ); - - JavadocUtil.isValidPackageList( url, settings, true ); - fail(); - } - catch ( SocketTimeoutException e ) - { - assertTrue( true ); - } - finally - { - proxyServer.stop(); - } - - // nonProxyHosts - try - { - proxyServlet = new AuthAsyncProxyServlet( authentications ); - proxyServer = new ProxyServer( proxyServlet ); - proxyServer.start(); - - settings = new Settings(); - proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( proxyServer.getHostName() ); - proxy.setPort( proxyServer.getPort() ); - proxy.setProtocol( "http" ); - proxy.setUsername( "foo" ); - proxy.setPassword( "bar" ); - proxy.setNonProxyHosts( "maven.apache.org" ); - settings.addProxy( proxy ); - - assertTrue( JavadocUtil.isValidPackageList( url, settings, true ) ); - } - finally - { - proxyServer.stop(); - } - } - - public void testGetRedirectUrlNotHttp() - throws Exception - { - URL url = new URI( "ftp://some.where" ).toURL(); - assertEquals( url.toString(), JavadocUtil.getRedirectUrl( url, new Settings() ).toString() ); - - url = new URI( "file://some/where" ).toURL(); - assertEquals( url.toString(), JavadocUtil.getRedirectUrl( url, new Settings() ).toString() ); - } - - /** - * Tests a redirect from localhost:port1 to localhost:port2 - */ - public void testGetRedirectUrl() - throws Exception - { - Server server = null, redirectServer = null; - try - { - redirectServer = new Server( 0 ); - redirectServer.setHandler( new AbstractHandler() - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException - { - response.setStatus( HttpServletResponse.SC_OK ); - ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer( 100 ); - writer.write( "Hello world" ); - writer.flush(); - response.setContentLength( writer.size() ); - OutputStream out = response.getOutputStream(); - writer.writeTo( out ); - out.close(); - writer.close(); - } - } ); - redirectServer.start(); - - server = new Server( 0 ); - MovedContextHandler handler = new MovedContextHandler(); - int redirectPort = ((ServerConnector)redirectServer.getConnectors()[0]).getLocalPort(); - handler.setNewContextURL( "http://localhost:" + redirectPort ); - server.setHandler( handler ); - server.start(); - - URL url = new URI( "http://localhost:" + ((ServerConnector)redirectServer.getConnectors()[0]).getLocalPort() ).toURL(); - URL redirectUrl = JavadocUtil.getRedirectUrl( url, new Settings() ); - - assertTrue( redirectUrl.toString().startsWith( "http://localhost:" + redirectPort ) ); - } - finally - { - stopSilently( server ); - stopSilently( redirectServer ); - } - } - - /** - * Tests that getRedirectUrl returns the same URL when there are no redirects. - */ - public void testGetRedirectUrlWithNoRedirects() - throws Exception - { - Server server = null; - try - { - server = new Server( 0 ); - server.setHandler( new AbstractHandler() - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException - { - response.setStatus( HttpServletResponse.SC_OK ); - ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer( 100 ); - writer.write( "Hello world" ); - writer.flush(); - response.setContentLength( writer.size() ); - OutputStream out = response.getOutputStream(); - writer.writeTo( out ); - out.close(); - writer.close(); - } - } ); - server.start(); - - URL url = new URI( "http://localhost:" + ((ServerConnector)server.getConnectors()[0]).getLocalPort() ).toURL(); - URL redirectUrl = JavadocUtil.getRedirectUrl( url, new Settings() ); - - assertEquals( url.toURI(), redirectUrl.toURI() ); - } - finally - { - stopSilently( server ); - } - } - - /** - * Tests that getRedirectUrl adds an Accept header in HTTP requests. Necessary because some sites like Cloudflare - * reject requests without an Accept header. - */ - public void testGetRedirectUrlVerifyHeaders() - throws Exception - { - Server server = null; - try - { - server = new Server( 0 ); - server.setHandler( new AbstractHandler() - { - @Override - public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) - throws IOException, ServletException - { - - if ( request.getHeader( "Accept" ) == null ) - { - response.setStatus( HttpServletResponse.SC_FORBIDDEN ); - } - else - { - response.setStatus( HttpServletResponse.SC_OK ); - } - response.getOutputStream().close(); - } - } ); - server.start(); - - URL url = new URI( "http://localhost:" + ((ServerConnector)server.getConnectors()[0]).getLocalPort() ).toURL(); - JavadocUtil.getRedirectUrl( url, new Settings() ); - } - finally - { - stopSilently( server ); - } - } - - /** - * Method to test copyJavadocResources() - * - * @throws Exception if any - */ - public void testCopyJavadocResources() - throws Exception - { - File input = new File( getBasedir(), "src/test/resources/unit/docfiles-test/docfiles/" ); - assertThat( input ).exists(); - - File output = new File( getBasedir(), "target/test/unit/docfiles-test/target/output" ); - if ( output.exists() ) - { - FileUtils.deleteDirectory( output ); - } - assertTrue( output.mkdirs() ); - - JavadocUtil.copyJavadocResources( output, input, null ); - - assertThat( FileUtils.getFiles( output, null, null, false ) ) - .containsExactlyInAnyOrder( - Paths.get( "test", "doc-files", "excluded-dir1", "sample-excluded1.gif" ).toFile(), - Paths.get( "test", "doc-files", "excluded-dir2", "sample-excluded2.gif" ).toFile(), - Paths.get( "test", "doc-files", "included-dir1", "sample-included1.gif" ).toFile(), - Paths.get( "test", "doc-files", "included-dir2", "sample-included2.gif" ).toFile() - ); - - assertThat( FileUtils.getDirectoryNames( new File( output, "test/doc-files" ), null, null, false ) ) - .containsExactlyInAnyOrder( "", "excluded-dir1", "excluded-dir2", "included-dir1", "included-dir2" ); - - input = new File( getBasedir(), "src/test/resources/unit/docfiles-test/docfiles/" ); - assertTrue( input.exists() ); - - output = new File( getBasedir(), "target/test/unit/docfiles-test/target/output" ); - if ( output.exists() ) - { - FileUtils.deleteDirectory( output ); - } - assertTrue( output.mkdirs() ); - - JavadocUtil.copyJavadocResources( output, input, "excluded-dir1:excluded-dir2" ); - - assertThat( FileUtils.getFiles( output, null, null, false ) ) - .containsExactlyInAnyOrder( - Paths.get( "test", "doc-files", "included-dir1", "sample-included1.gif" ).toFile(), - Paths.get( "test", "doc-files", "included-dir2", "sample-included2.gif" ).toFile() - ); - - assertThat( FileUtils.getDirectoryNames( new File( output, "test/doc-files" ), null, null, false ) ) - .containsExactlyInAnyOrder( "", "included-dir1", "included-dir2" ); - } - - /** - * Method to test pruneDirs() - * - */ - public void testPruneDirs() - { - List list = new ArrayList<>(); - list.add( getBasedir() + "/target/classes" ); - list.add( getBasedir() + "/target/classes" ); - list.add( getBasedir() + "/target/classes" ); - - Set expected = Collections.singleton( Paths.get( getBasedir(), "target/classes" ) ); - - MavenProjectStub project = new MavenProjectStub(); - project.setFile( new File( getBasedir(), "pom.xml" ) ); - - assertEquals( expected, JavadocUtil.pruneDirs( project, list ) ); - } - - /** - * Method to test unifyPathSeparator() - * - */ - public void testUnifyPathSeparator() - { - assertNull( JavadocUtil.unifyPathSeparator( null ) ); - - final String ps = File.pathSeparator; - - // Windows - String path1 = "C:\\maven-javadoc-plugin\\src\\main\\java"; - String path2 = "C:\\maven-javadoc-plugin\\src\\main\\javadoc"; - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ";" + path2 ) ); - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ":" + path2 ) ); - - path1 = "C:/maven-javadoc-plugin/src/main/java"; - path2 = "C:/maven-javadoc-plugin/src/main/javadoc"; - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ";" + path2 ) ); - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ":" + path2 ) ); - assertEquals( path1 + ps + path2 + ps + path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ";" - + path2 + ";" + path1 + ":" + path2 ) ); - - // Unix - path1 = "/tmp/maven-javadoc-plugin/src/main/java"; - path2 = "/tmp/maven-javadoc-plugin/src/main/javadoc"; - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ";" + path2 ) ); - assertEquals( path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ":" + path2 ) ); - assertEquals( path1 + ps + path2 + ps + path1 + ps + path2, JavadocUtil.unifyPathSeparator( path1 + ";" - + path2 + ":" + path1 + ":" + path2 ) ); - } - - - public void testGetIncludedFiles() - { - File sourceDirectory = new File("target/it").getAbsoluteFile(); - String[] fileList = new String[] { "Main.java" }; - Collection excludePackages = Collections.singleton( "*.it" ); - - List includedFiles = JavadocUtil.getIncludedFiles( sourceDirectory, fileList, excludePackages ); - - assertThat( includedFiles.toArray( new String[0] ) ).isEqualTo( fileList ); - } - - private void stopSilently( Server server ) - { - try - { - if ( server != null ) - { - server.stop(); - } - } - catch ( Exception e ) - { - // ignored - } - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.OutputStream; +import java.net.SocketTimeoutException; +import java.net.URI; +import java.net.URL; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.regex.PatternSyntaxException; + +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.plugins.javadoc.ProxyServer.AuthAsyncProxyServlet; +import org.apache.maven.settings.Proxy; +import org.apache.maven.settings.Settings; +import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.util.FileUtils; +import org.eclipse.jetty.server.Request; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.server.handler.AbstractHandler; +import org.eclipse.jetty.server.handler.MovedContextHandler; +import org.eclipse.jetty.util.ByteArrayISO8859Writer; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Vincent Siveton + */ +public class JavadocUtilTest extends PlexusTestCase { + /** + * Method to test the javadoc version parsing. + * + */ + public void testParseJavadocVersion() { + String version = null; + try { + JavadocUtil.extractJavadocVersion(version); + fail("Not catch null"); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + // Sun JDK 1.4 + version = "java full version \"1.4.2_12-b03\""; + assertEquals("1.4.2", JavadocUtil.extractJavadocVersion(version)); + + // Sun JDK 1.5 + version = "java full version \"1.5.0_07-164\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // IBM JDK 1.4 + version = "java full version \"J2RE 1.4.2 IBM Windows 32 build cn1420-20040626\""; + assertEquals("1.4.2", JavadocUtil.extractJavadocVersion(version)); + + // IBM JDK 1.5 + version = "javadoc version complète de \"J2RE 1.5.0 IBM Windows 32 build pwi32pdev-20070426a\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // IBM JDK 1.5 + version = + "J2RE 1.5.0 IBM Windows 32 build pwi32devifx-20070323 (ifix 117674: SR4 + 116644 + 114941 + 116110 + 114881)"; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // FreeBSD + version = "java full version \"diablo-1.5.0-b01\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // BEA + version = "java full version \"1.5.0_11-b03\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // Other tests + version = "java full version \"1.5.0_07-164\"" + System.getProperty("line.separator"); + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + version = System.getProperty("line.separator") + "java full version \"1.5.0_07-164\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + version = System.getProperty("line.separator") + "java full version \"1.5.0_07-164\"" + + System.getProperty("line.separator"); + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + version = "java full" + System.getProperty("line.separator") + " version \"1.5.0_07-164\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"1.99.123-b01\""; + assertEquals("1.99.123", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"1.5.0.07-164\""; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"1.4\""; + assertEquals("1.4", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"1.A.B_07-164\""; + try { + JavadocUtil.extractJavadocVersion(version); + // does not fail since JEP 223 support addition + // assertTrue( "Not catch wrong pattern", false ); + } catch (PatternSyntaxException e) { + assertTrue(true); + } + + version = "SCO-UNIX-J2SE-1.5.0_09*FCS-UW714-OSR6*_20061114"; + assertEquals("1.5.0", JavadocUtil.extractJavadocVersion(version)); + + // Java 9 EA + version = "java full version \"9-ea+113\""; + assertEquals("9", JavadocUtil.extractJavadocVersion(version)); + + // Java 9 EA Jigsaw + version = "java full version \"9-ea+113-2016-04-14-161743.javare.4852.nc\""; + assertEquals("9", JavadocUtil.extractJavadocVersion(version)); + + version = "java version \"9-ea\""; + assertEquals("9", JavadocUtil.extractJavadocVersion(version)); + + // JEP 223 example for future versions + version = "java full version \"9+100\""; + assertEquals("9", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"9.0.1+20\""; + assertEquals("9.0.1", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"10+100\""; + assertEquals("10", JavadocUtil.extractJavadocVersion(version)); + + version = "java full version \"10.0.1+20\""; + assertEquals("10.0.1", JavadocUtil.extractJavadocVersion(version)); + } + + /** + * Method to test the javadoc memory parsing. + * + */ + public void testParseJavadocMemory() { + String memory = null; + try { + JavadocUtil.parseJavadocMemory(memory); + fail("Not catch null"); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + memory = "128"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + + memory = "128k"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128k"); + memory = "128kb"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128k"); + + memory = "128m"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + memory = "128mb"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + + memory = "1g"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "1024m"); + memory = "1gb"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "1024m"); + + memory = "1t"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "1048576m"); + memory = "1tb"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "1048576m"); + + memory = System.getProperty("line.separator") + "128m"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + memory = System.getProperty("line.separator") + "128m" + System.getProperty("line.separator"); + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + + memory = " 128m"; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + memory = " 128m "; + assertEquals(JavadocUtil.parseJavadocMemory(memory), "128m"); + + memory = "1m28m"; + try { + JavadocUtil.parseJavadocMemory(memory); + fail("Not catch wrong pattern"); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + memory = "ABC128m"; + try { + JavadocUtil.parseJavadocMemory(memory); + fail("Not catch wrong pattern"); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + } + + /** + * Method to test the validate encoding parsing. + * + */ + public void testValidateEncoding() { + assertFalse("Not catch null", JavadocUtil.validateEncoding(null)); + assertTrue("UTF-8 not supported on this plateform", JavadocUtil.validateEncoding("UTF-8")); + assertTrue("ISO-8859-1 not supported on this plateform", JavadocUtil.validateEncoding("ISO-8859-1")); + assertFalse("latin is supported on this plateform???", JavadocUtil.validateEncoding("latin")); + assertFalse("WRONG is supported on this plateform???", JavadocUtil.validateEncoding("WRONG")); + } + + /** + * Method to test isValidPackageList() + * + * @throws Exception if any + */ + public void testIsValidPackageList() throws Exception { + Settings settings = null; + Proxy proxy; + + URL url = null; + URL wrongUrl; + try { + JavadocUtil.isValidPackageList(url, settings, false); + fail(); + } catch (IllegalArgumentException e) { + assertTrue(true); + } + + url = new File(getBasedir(), "/pom.xml").toURI().toURL(); + assertTrue(JavadocUtil.isValidPackageList(url, settings, false)); + + try { + assertFalse(JavadocUtil.isValidPackageList(url, settings, true)); + } catch (IOException e) { + assertTrue(true); + } + + url = this.getClass() + .getResource("/JavadocUtilTest-package-list.txt") + .toURI() + .toURL(); + assertTrue(JavadocUtil.isValidPackageList(url, settings, true)); + + url = new URL("http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list"); + assertTrue(JavadocUtil.isValidPackageList(url, settings, true)); + + wrongUrl = new URL("http://maven.apache.org/plugins/maven-javadoc-plugin/apidocs/package-list2"); + try { + JavadocUtil.isValidPackageList(wrongUrl, settings, false); + fail(); + } catch (IOException e) { + assertTrue(true); + } + + // real proxy + ProxyServer proxyServer = null; + AuthAsyncProxyServlet proxyServlet; + try { + proxyServlet = new AuthAsyncProxyServlet(); + proxyServer = new ProxyServer(proxyServlet); + proxyServer.start(); + + settings = new Settings(); + + assertTrue(JavadocUtil.isValidPackageList(url, settings, true)); + + try { + JavadocUtil.isValidPackageList(wrongUrl, settings, false); + fail(); + } catch (IOException e) { + assertTrue(true); + } + } finally { + if (proxyServer != null) { + proxyServer.stop(); + } + } + + Map authentications = new HashMap<>(); + authentications.put("foo", "bar"); + // wrong auth + try { + proxyServlet = new AuthAsyncProxyServlet(authentications); + proxyServer = new ProxyServer(proxyServlet); + proxyServer.start(); + + settings = new Settings(); + proxy = new Proxy(); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + settings.addProxy(proxy); + + JavadocUtil.isValidPackageList(url, settings, false); + fail(); + } catch (FileNotFoundException e) { + assertTrue(true); + } finally { + proxyServer.stop(); + } + + // auth proxy + try { + proxyServlet = new AuthAsyncProxyServlet(authentications); + proxyServer = new ProxyServer(proxyServlet); + proxyServer.start(); + + settings = new Settings(); + proxy = new Proxy(); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + proxy.setUsername("foo"); + proxy.setPassword("bar"); + settings.addProxy(proxy); + + assertTrue(JavadocUtil.isValidPackageList(url, settings, true)); + + try { + JavadocUtil.isValidPackageList(wrongUrl, settings, false); + fail(); + } catch (IOException e) { + assertTrue(true); + } + } finally { + proxyServer.stop(); + } + + // timeout + try { + proxyServlet = new AuthAsyncProxyServlet(authentications, 3000); // more than 2000, see fetchURL + proxyServer = new ProxyServer(proxyServlet); + proxyServer.start(); + + settings = new Settings(); + proxy = new Proxy(); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + proxy.setUsername("foo"); + proxy.setPassword("bar"); + settings.addProxy(proxy); + + JavadocUtil.isValidPackageList(url, settings, true); + fail(); + } catch (SocketTimeoutException e) { + assertTrue(true); + } finally { + proxyServer.stop(); + } + + // nonProxyHosts + try { + proxyServlet = new AuthAsyncProxyServlet(authentications); + proxyServer = new ProxyServer(proxyServlet); + proxyServer.start(); + + settings = new Settings(); + proxy = new Proxy(); + proxy.setActive(true); + proxy.setHost(proxyServer.getHostName()); + proxy.setPort(proxyServer.getPort()); + proxy.setProtocol("http"); + proxy.setUsername("foo"); + proxy.setPassword("bar"); + proxy.setNonProxyHosts("maven.apache.org"); + settings.addProxy(proxy); + + assertTrue(JavadocUtil.isValidPackageList(url, settings, true)); + } finally { + proxyServer.stop(); + } + } + + public void testGetRedirectUrlNotHttp() throws Exception { + URL url = new URI("ftp://some.where").toURL(); + assertEquals( + url.toString(), JavadocUtil.getRedirectUrl(url, new Settings()).toString()); + + url = new URI("file://some/where").toURL(); + assertEquals( + url.toString(), JavadocUtil.getRedirectUrl(url, new Settings()).toString()); + } + + /** + * Tests a redirect from localhost:port1 to localhost:port2 + */ + public void testGetRedirectUrl() throws Exception { + Server server = null, redirectServer = null; + try { + redirectServer = new Server(0); + redirectServer.setHandler(new AbstractHandler() { + @Override + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + response.setStatus(HttpServletResponse.SC_OK); + ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(100); + writer.write("Hello world"); + writer.flush(); + response.setContentLength(writer.size()); + OutputStream out = response.getOutputStream(); + writer.writeTo(out); + out.close(); + writer.close(); + } + }); + redirectServer.start(); + + server = new Server(0); + MovedContextHandler handler = new MovedContextHandler(); + int redirectPort = ((ServerConnector) redirectServer.getConnectors()[0]).getLocalPort(); + handler.setNewContextURL("http://localhost:" + redirectPort); + server.setHandler(handler); + server.start(); + + URL url = new URI("http://localhost:" + + ((ServerConnector) redirectServer.getConnectors()[0]).getLocalPort()) + .toURL(); + URL redirectUrl = JavadocUtil.getRedirectUrl(url, new Settings()); + + assertTrue(redirectUrl.toString().startsWith("http://localhost:" + redirectPort)); + } finally { + stopSilently(server); + stopSilently(redirectServer); + } + } + + /** + * Tests that getRedirectUrl returns the same URL when there are no redirects. + */ + public void testGetRedirectUrlWithNoRedirects() throws Exception { + Server server = null; + try { + server = new Server(0); + server.setHandler(new AbstractHandler() { + @Override + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + response.setStatus(HttpServletResponse.SC_OK); + ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(100); + writer.write("Hello world"); + writer.flush(); + response.setContentLength(writer.size()); + OutputStream out = response.getOutputStream(); + writer.writeTo(out); + out.close(); + writer.close(); + } + }); + server.start(); + + URL url = + new URI("http://localhost:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort()).toURL(); + URL redirectUrl = JavadocUtil.getRedirectUrl(url, new Settings()); + + assertEquals(url.toURI(), redirectUrl.toURI()); + } finally { + stopSilently(server); + } + } + + /** + * Tests that getRedirectUrl adds an Accept header in HTTP requests. Necessary because some sites like Cloudflare + * reject requests without an Accept header. + */ + public void testGetRedirectUrlVerifyHeaders() throws Exception { + Server server = null; + try { + server = new Server(0); + server.setHandler(new AbstractHandler() { + @Override + public void handle( + String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + if (request.getHeader("Accept") == null) { + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + } else { + response.setStatus(HttpServletResponse.SC_OK); + } + response.getOutputStream().close(); + } + }); + server.start(); + + URL url = + new URI("http://localhost:" + ((ServerConnector) server.getConnectors()[0]).getLocalPort()).toURL(); + JavadocUtil.getRedirectUrl(url, new Settings()); + } finally { + stopSilently(server); + } + } + + /** + * Method to test copyJavadocResources() + * + * @throws Exception if any + */ + public void testCopyJavadocResources() throws Exception { + File input = new File(getBasedir(), "src/test/resources/unit/docfiles-test/docfiles/"); + assertThat(input).exists(); + + File output = new File(getBasedir(), "target/test/unit/docfiles-test/target/output"); + if (output.exists()) { + FileUtils.deleteDirectory(output); + } + assertTrue(output.mkdirs()); + + JavadocUtil.copyJavadocResources(output, input, null); + + assertThat(FileUtils.getFiles(output, null, null, false)) + .containsExactlyInAnyOrder( + Paths.get("test", "doc-files", "excluded-dir1", "sample-excluded1.gif") + .toFile(), + Paths.get("test", "doc-files", "excluded-dir2", "sample-excluded2.gif") + .toFile(), + Paths.get("test", "doc-files", "included-dir1", "sample-included1.gif") + .toFile(), + Paths.get("test", "doc-files", "included-dir2", "sample-included2.gif") + .toFile()); + + assertThat(FileUtils.getDirectoryNames(new File(output, "test/doc-files"), null, null, false)) + .containsExactlyInAnyOrder("", "excluded-dir1", "excluded-dir2", "included-dir1", "included-dir2"); + + input = new File(getBasedir(), "src/test/resources/unit/docfiles-test/docfiles/"); + assertTrue(input.exists()); + + output = new File(getBasedir(), "target/test/unit/docfiles-test/target/output"); + if (output.exists()) { + FileUtils.deleteDirectory(output); + } + assertTrue(output.mkdirs()); + + JavadocUtil.copyJavadocResources(output, input, "excluded-dir1:excluded-dir2"); + + assertThat(FileUtils.getFiles(output, null, null, false)) + .containsExactlyInAnyOrder( + Paths.get("test", "doc-files", "included-dir1", "sample-included1.gif") + .toFile(), + Paths.get("test", "doc-files", "included-dir2", "sample-included2.gif") + .toFile()); + + assertThat(FileUtils.getDirectoryNames(new File(output, "test/doc-files"), null, null, false)) + .containsExactlyInAnyOrder("", "included-dir1", "included-dir2"); + } + + /** + * Method to test pruneDirs() + * + */ + public void testPruneDirs() { + List list = new ArrayList<>(); + list.add(getBasedir() + "/target/classes"); + list.add(getBasedir() + "/target/classes"); + list.add(getBasedir() + "/target/classes"); + + Set expected = Collections.singleton(Paths.get(getBasedir(), "target/classes")); + + MavenProjectStub project = new MavenProjectStub(); + project.setFile(new File(getBasedir(), "pom.xml")); + + assertEquals(expected, JavadocUtil.pruneDirs(project, list)); + } + + /** + * Method to test unifyPathSeparator() + * + */ + public void testUnifyPathSeparator() { + assertNull(JavadocUtil.unifyPathSeparator(null)); + + final String ps = File.pathSeparator; + + // Windows + String path1 = "C:\\maven-javadoc-plugin\\src\\main\\java"; + String path2 = "C:\\maven-javadoc-plugin\\src\\main\\javadoc"; + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ";" + path2)); + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ":" + path2)); + + path1 = "C:/maven-javadoc-plugin/src/main/java"; + path2 = "C:/maven-javadoc-plugin/src/main/javadoc"; + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ";" + path2)); + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ":" + path2)); + assertEquals( + path1 + ps + path2 + ps + path1 + ps + path2, + JavadocUtil.unifyPathSeparator(path1 + ";" + path2 + ";" + path1 + ":" + path2)); + + // Unix + path1 = "/tmp/maven-javadoc-plugin/src/main/java"; + path2 = "/tmp/maven-javadoc-plugin/src/main/javadoc"; + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ";" + path2)); + assertEquals(path1 + ps + path2, JavadocUtil.unifyPathSeparator(path1 + ":" + path2)); + assertEquals( + path1 + ps + path2 + ps + path1 + ps + path2, + JavadocUtil.unifyPathSeparator(path1 + ";" + path2 + ":" + path1 + ":" + path2)); + } + + public void testGetIncludedFiles() { + File sourceDirectory = new File("target/it").getAbsoluteFile(); + String[] fileList = new String[] {"Main.java"}; + Collection excludePackages = Collections.singleton("*.it"); + + List includedFiles = JavadocUtil.getIncludedFiles(sourceDirectory, fileList, excludePackages); + + assertThat(includedFiles.toArray(new String[0])).isEqualTo(fileList); + } + + private void stopSilently(Server server) { + try { + if (server != null) { + server.stop(); + } + } catch (Exception e) { + // ignored + } + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/JavadocVersionTest.java b/src/test/java/org/apache/maven/plugins/javadoc/JavadocVersionTest.java index 2aa6ff45f..b70547bbb 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/JavadocVersionTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/JavadocVersionTest.java @@ -1,68 +1,65 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -import org.junit.Test; - -import static org.assertj.core.api.Assertions.assertThat; - -public class JavadocVersionTest -{ - /** - * Parsing is lazy, only triggered when comparing - */ - @Test - @SuppressWarnings("deprecation") - public void testParse() - { - assertThat( JavadocVersion.parse( "1.4" ) ) - .isLessThan( JavadocVersion.parse( "1.4.2" ) ) - .isLessThan( JavadocVersion.parse( "1.5" ) ); - - assertThat( JavadocVersion.parse( "1.8" ) ).isLessThan( JavadocVersion.parse( "9" ) ); - - assertThat( JavadocVersion.parse( "1.4" ) ).isEqualByComparingTo( JavadocVersion.parse( "1.4" ) ); - assertThat( JavadocVersion.parse( "1.4.2" ) ).isEqualByComparingTo( JavadocVersion.parse( "1.4.2" ) ); - assertThat( JavadocVersion.parse( "9" ) ).isEqualByComparingTo( JavadocVersion.parse( "9" ) ); - - assertThat( JavadocVersion.parse( "1.4.2" ) ).isGreaterThan( JavadocVersion.parse( "1.4" ) ); - assertThat( JavadocVersion.parse( "1.5" ) ).isGreaterThan( JavadocVersion.parse( "1.4" ) ); - assertThat( JavadocVersion.parse( "9" ) ).isGreaterThan( JavadocVersion.parse( "1.8" ) ); - } - - @Test - public void testApiVersion() { - Pattern p = Pattern.compile( "(1\\.\\d|\\d\\d*)" ); - Matcher m = p.matcher( "9" ); - assertThat( m.find() ).isTrue(); - assertThat( m.group( 1 ) ).isEqualTo( "9" ); - - m = p.matcher( "1.4" ); - assertThat( m.find() ).isTrue(); - assertThat( m.group( 1 ) ).isEqualTo( "1.4" ); - - m = p.matcher( "1.4.2" ); - assertThat( m.find() ).isTrue(); - assertThat( m.group( 1 ) ).isEqualTo( "1.4" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +public class JavadocVersionTest { + /** + * Parsing is lazy, only triggered when comparing + */ + @Test + @SuppressWarnings("deprecation") + public void testParse() { + assertThat(JavadocVersion.parse("1.4")) + .isLessThan(JavadocVersion.parse("1.4.2")) + .isLessThan(JavadocVersion.parse("1.5")); + + assertThat(JavadocVersion.parse("1.8")).isLessThan(JavadocVersion.parse("9")); + + assertThat(JavadocVersion.parse("1.4")).isEqualByComparingTo(JavadocVersion.parse("1.4")); + assertThat(JavadocVersion.parse("1.4.2")).isEqualByComparingTo(JavadocVersion.parse("1.4.2")); + assertThat(JavadocVersion.parse("9")).isEqualByComparingTo(JavadocVersion.parse("9")); + + assertThat(JavadocVersion.parse("1.4.2")).isGreaterThan(JavadocVersion.parse("1.4")); + assertThat(JavadocVersion.parse("1.5")).isGreaterThan(JavadocVersion.parse("1.4")); + assertThat(JavadocVersion.parse("9")).isGreaterThan(JavadocVersion.parse("1.8")); + } + + @Test + public void testApiVersion() { + Pattern p = Pattern.compile("(1\\.\\d|\\d\\d*)"); + Matcher m = p.matcher("9"); + assertThat(m.find()).isTrue(); + assertThat(m.group(1)).isEqualTo("9"); + + m = p.matcher("1.4"); + assertThat(m.find()).isTrue(); + assertThat(m.group(1)).isEqualTo("1.4"); + + m = p.matcher("1.4.2"); + assertThat(m.find()).isTrue(); + assertThat(m.group(1)).isEqualTo("1.4"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/ProxyServer.java b/src/test/java/org/apache/maven/plugins/javadoc/ProxyServer.java index 6daa738e7..0425a6687 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/ProxyServer.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/ProxyServer.java @@ -1,228 +1,200 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.IOException; -import java.net.InetAddress; -import java.nio.charset.StandardCharsets; -import java.util.Base64; -import java.util.Map; - -import javax.servlet.ServletException; -import javax.servlet.ServletRequest; -import javax.servlet.ServletResponse; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -import org.eclipse.jetty.proxy.AsyncProxyServlet; -import org.eclipse.jetty.proxy.ConnectHandler; -import org.eclipse.jetty.server.Server; -import org.eclipse.jetty.server.ServerConnector; -import org.eclipse.jetty.servlet.ServletContextHandler; -import org.eclipse.jetty.servlet.ServletHolder; - -/** - * A Proxy server. - * - * @author Vincent Siveton - * @since 2.6 - */ -class ProxyServer -{ - private Server proxyServer; - - private ServerConnector serverConnector; - - /** - * @param proxyServlet the wanted auth proxy servlet - */ - public ProxyServer( AuthAsyncProxyServlet proxyServlet ) - { - this( null, 0, proxyServlet ); - } - - /** - * @param hostName the server name - * @param port the server port - * @param proxyServlet the wanted auth proxy servlet - */ - public ProxyServer( String hostName, int port, AuthAsyncProxyServlet proxyServlet ) - { - proxyServer = new Server( ); - - serverConnector = new ServerConnector( proxyServer ); - serverConnector.setHost( InetAddress.getLoopbackAddress().getHostName() ); - serverConnector.setReuseAddress( true ); - serverConnector.setPort( 0 ); - - proxyServer.addConnector( serverConnector ); - - // Setup proxy handler to handle CONNECT methods - ConnectHandler proxy = new ConnectHandler(); - proxyServer.setHandler(proxy); - - // Setup proxy servlet - ServletContextHandler context = new ServletContextHandler(proxy, "/", true, false); - ServletHolder appServletHolder = new ServletHolder(proxyServlet); - context.addServlet(appServletHolder, "/*"); - - } - - /** - * @return the host name - */ - public String getHostName() - { - return serverConnector.getHost() == null ? InetAddress.getLoopbackAddress().getHostName() : serverConnector.getHost(); - } - - /** - * @return the host port - */ - public int getPort() - { - return serverConnector.getLocalPort(); - } - - /** - * @throws Exception if any - */ - public void start() - throws Exception - { - if ( proxyServer != null ) - { - proxyServer.start(); - } - } - - /** - * @throws Exception if any - */ - public void stop() - throws Exception - { - if ( proxyServer != null ) - { - proxyServer.stop(); - } - proxyServer = null; - } - - - /** - * A proxy servlet with authentication support. - */ - static class AuthAsyncProxyServlet - extends AsyncProxyServlet - { - private Map authentications; - - private long sleepTime = 0; - - /** - * Constructor for non authentication servlet. - */ - public AuthAsyncProxyServlet() - { - super(); - } - - /** - * Constructor for authentication servlet. - * - * @param authentications a map of user/password - */ - public AuthAsyncProxyServlet( Map authentications ) - { - this(); - - this.authentications = authentications; - } - - /** - * Constructor for authentication servlet. - * - * @param authentications a map of user/password - * @param sleepTime a positive time to sleep the service thread (for timeout) - */ - public AuthAsyncProxyServlet( Map authentications, long sleepTime ) - { - this(); - this.authentications = authentications; - this.sleepTime = sleepTime; - } - - /** {@inheritDoc} */ - @Override - public void service( ServletRequest req, ServletResponse res ) - throws ServletException, IOException - { - final HttpServletRequest request = (HttpServletRequest) req; - final HttpServletResponse response = (HttpServletResponse) res; - - if ( this.authentications != null && !this.authentications.isEmpty() ) - { - String proxyAuthorization = request.getHeader( "Proxy-Authorization" ); - if ( proxyAuthorization != null && proxyAuthorization.startsWith( "Basic " ) ) - { - String proxyAuth = proxyAuthorization.substring("Basic ".length()); - String authorization = new String(Base64.getDecoder().decode(proxyAuth), StandardCharsets.UTF_8); - - - String[] authTokens = authorization.split( ":" ); - String user = authTokens[0]; - String password = authTokens[1]; - - if ( this.authentications.get( user ) == null ) - { - throw new IllegalArgumentException( user + " not found in the map!" ); - } - - if ( sleepTime > 0 ) - { - try - { - Thread.sleep( sleepTime ); - } - catch ( InterruptedException e ) - { - // nop - } - } - String authPass = this.authentications.get(user); - if ( password.equals( authPass ) ) - { - // could throw exceptions... - super.service( req, res ); - return; - } - } - - // Proxy-Authenticate Basic realm="CCProxy Authorization" - response.addHeader( "Proxy-Authenticate", "Basic realm=\"Jetty Proxy Authorization\"" ); - response.setStatus( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED ); - return; - } - - super.service( req, res ); - } - } -} \ No newline at end of file +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import javax.servlet.ServletException; +import javax.servlet.ServletRequest; +import javax.servlet.ServletResponse; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import java.io.IOException; +import java.net.InetAddress; +import java.nio.charset.StandardCharsets; +import java.util.Base64; +import java.util.Map; + +import org.eclipse.jetty.proxy.AsyncProxyServlet; +import org.eclipse.jetty.proxy.ConnectHandler; +import org.eclipse.jetty.server.Server; +import org.eclipse.jetty.server.ServerConnector; +import org.eclipse.jetty.servlet.ServletContextHandler; +import org.eclipse.jetty.servlet.ServletHolder; + +/** + * A Proxy server. + * + * @author Vincent Siveton + * @since 2.6 + */ +class ProxyServer { + private Server proxyServer; + + private ServerConnector serverConnector; + + /** + * @param proxyServlet the wanted auth proxy servlet + */ + public ProxyServer(AuthAsyncProxyServlet proxyServlet) { + this(null, 0, proxyServlet); + } + + /** + * @param hostName the server name + * @param port the server port + * @param proxyServlet the wanted auth proxy servlet + */ + public ProxyServer(String hostName, int port, AuthAsyncProxyServlet proxyServlet) { + proxyServer = new Server(); + + serverConnector = new ServerConnector(proxyServer); + serverConnector.setHost(InetAddress.getLoopbackAddress().getHostName()); + serverConnector.setReuseAddress(true); + serverConnector.setPort(0); + + proxyServer.addConnector(serverConnector); + + // Setup proxy handler to handle CONNECT methods + ConnectHandler proxy = new ConnectHandler(); + proxyServer.setHandler(proxy); + + // Setup proxy servlet + ServletContextHandler context = new ServletContextHandler(proxy, "/", true, false); + ServletHolder appServletHolder = new ServletHolder(proxyServlet); + context.addServlet(appServletHolder, "/*"); + } + + /** + * @return the host name + */ + public String getHostName() { + return serverConnector.getHost() == null + ? InetAddress.getLoopbackAddress().getHostName() + : serverConnector.getHost(); + } + + /** + * @return the host port + */ + public int getPort() { + return serverConnector.getLocalPort(); + } + + /** + * @throws Exception if any + */ + public void start() throws Exception { + if (proxyServer != null) { + proxyServer.start(); + } + } + + /** + * @throws Exception if any + */ + public void stop() throws Exception { + if (proxyServer != null) { + proxyServer.stop(); + } + proxyServer = null; + } + + /** + * A proxy servlet with authentication support. + */ + static class AuthAsyncProxyServlet extends AsyncProxyServlet { + private Map authentications; + + private long sleepTime = 0; + + /** + * Constructor for non authentication servlet. + */ + public AuthAsyncProxyServlet() { + super(); + } + + /** + * Constructor for authentication servlet. + * + * @param authentications a map of user/password + */ + public AuthAsyncProxyServlet(Map authentications) { + this(); + + this.authentications = authentications; + } + + /** + * Constructor for authentication servlet. + * + * @param authentications a map of user/password + * @param sleepTime a positive time to sleep the service thread (for timeout) + */ + public AuthAsyncProxyServlet(Map authentications, long sleepTime) { + this(); + this.authentications = authentications; + this.sleepTime = sleepTime; + } + + /** {@inheritDoc} */ + @Override + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { + final HttpServletRequest request = (HttpServletRequest) req; + final HttpServletResponse response = (HttpServletResponse) res; + + if (this.authentications != null && !this.authentications.isEmpty()) { + String proxyAuthorization = request.getHeader("Proxy-Authorization"); + if (proxyAuthorization != null && proxyAuthorization.startsWith("Basic ")) { + String proxyAuth = proxyAuthorization.substring("Basic ".length()); + String authorization = new String(Base64.getDecoder().decode(proxyAuth), StandardCharsets.UTF_8); + + String[] authTokens = authorization.split(":"); + String user = authTokens[0]; + String password = authTokens[1]; + + if (this.authentications.get(user) == null) { + throw new IllegalArgumentException(user + " not found in the map!"); + } + + if (sleepTime > 0) { + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { + // nop + } + } + String authPass = this.authentications.get(user); + if (password.equals(authPass)) { + // could throw exceptions... + super.service(req, res); + return; + } + } + + // Proxy-Authenticate Basic realm="CCProxy Authorization" + response.addHeader("Proxy-Authenticate", "Basic realm=\"Jetty Proxy Authorization\""); + response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); + return; + } + + super.service(req, res); + } + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/TestJavadocReportTest.java b/src/test/java/org/apache/maven/plugins/javadoc/TestJavadocReportTest.java index 450db3230..ad2cfa663 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/TestJavadocReportTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/TestJavadocReportTest.java @@ -1,71 +1,65 @@ -package org.apache.maven.plugins.javadoc; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.apache.maven.model.Plugin; -import org.apache.maven.plugin.MojoExecution; -import org.apache.maven.plugin.testing.AbstractMojoTestCase; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; -import org.codehaus.plexus.util.FileUtils; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author Vincent Siveton - */ -public class TestJavadocReportTest - extends AbstractMojoTestCase -{ - /** - * Test the test-javadoc configuration for the plugin - * - * @throws Exception if any - */ - public void testTestJavadoc() - throws Exception - { - File testPom = - new File( getBasedir(), - "src/test/resources/unit/test-javadoc-test/test-javadoc-test-plugin-config.xml" ); - TestJavadocReport mojo = (TestJavadocReport) lookupMojo( "test-javadoc", testPom ); - - MojoExecution mojoExec = new MojoExecution( new Plugin(), "test-javadoc", null ); - - setVariableValueToObject( mojo, "mojo", mojoExec ); - - MavenProject currentProject = new MavenProjectStub(); - currentProject.setGroupId( "GROUPID" ); - currentProject.setArtifactId( "ARTIFACTID" ); - - setVariableValueToObject( mojo, "session", newMavenSession( currentProject ) ); - - mojo.execute(); - - File generatedFile = - new File( getBasedir(), "target/test/unit/test-javadoc-test/target/site/apidocs/maven/AppTest.html" ); - assertThat( generatedFile ).exists(); - - File options = new File( getBasedir(), "target/test/unit/test-javadoc-test/target/site/apidocs/options"); - assertThat( FileUtils.fileRead( options ) ).contains( "junit-3.8.1.jar" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc; + +import java.io.File; + +import org.apache.maven.model.Plugin; +import org.apache.maven.plugin.MojoExecution; +import org.apache.maven.plugin.testing.AbstractMojoTestCase; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; +import org.codehaus.plexus.util.FileUtils; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Vincent Siveton + */ +public class TestJavadocReportTest extends AbstractMojoTestCase { + /** + * Test the test-javadoc configuration for the plugin + * + * @throws Exception if any + */ + public void testTestJavadoc() throws Exception { + File testPom = + new File(getBasedir(), "src/test/resources/unit/test-javadoc-test/test-javadoc-test-plugin-config.xml"); + TestJavadocReport mojo = (TestJavadocReport) lookupMojo("test-javadoc", testPom); + + MojoExecution mojoExec = new MojoExecution(new Plugin(), "test-javadoc", null); + + setVariableValueToObject(mojo, "mojo", mojoExec); + + MavenProject currentProject = new MavenProjectStub(); + currentProject.setGroupId("GROUPID"); + currentProject.setArtifactId("ARTIFACTID"); + + setVariableValueToObject(mojo, "session", newMavenSession(currentProject)); + + mojo.execute(); + + File generatedFile = + new File(getBasedir(), "target/test/unit/test-javadoc-test/target/site/apidocs/maven/AppTest.html"); + assertThat(generatedFile).exists(); + + File options = new File(getBasedir(), "target/test/unit/test-javadoc-test/target/site/apidocs/options"); + assertThat(FileUtils.fileRead(options)).contains("junit-3.8.1.jar"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/options/io/xpp3/JavadocOptionsXpp3ReaderTest.java b/src/test/java/org/apache/maven/plugins/javadoc/options/io/xpp3/JavadocOptionsXpp3ReaderTest.java index 118b26ad8..617a6d097 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/options/io/xpp3/JavadocOptionsXpp3ReaderTest.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/options/io/xpp3/JavadocOptionsXpp3ReaderTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc.options.io.xpp3; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,7 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc.options.io.xpp3; import java.io.StringReader; @@ -27,8 +26,7 @@ import static org.assertj.core.api.Assertions.assertThat; -public class JavadocOptionsXpp3ReaderTest -{ +public class JavadocOptionsXpp3ReaderTest { @Test public void testNameAndHead() throws Exception { @@ -37,23 +35,23 @@ public void testNameAndHead() throws Exception { StringReader reader = new StringReader(testString); JavadocOptions options = parser.read(reader); - assertThat( options.getTags().size() ).isEqualTo( 1 ); + assertThat(options.getTags().size()).isEqualTo(1); Tag tag = options.getTags().get(0); - assertThat( tag.getName() ).isEqualTo( "foo" ); - assertThat( tag.getHead() ).isEqualTo( "bar" ); + assertThat(tag.getName()).isEqualTo("foo"); + assertThat(tag.getHead()).isEqualTo("bar"); } - + @Test public void testPlacement() throws Exception { JavadocOptionsXpp3Reader parser = new JavadocOptionsXpp3Reader(); - String testString = "fooXaoptcmfbar"; + String testString = + "fooXaoptcmfbar"; StringReader reader = new StringReader(testString); JavadocOptions options = parser.read(reader); - assertThat( options.getTags().size() ).isEqualTo( 1 ); + assertThat(options.getTags().size()).isEqualTo(1); Tag tag = options.getTags().get(0); - assertThat( tag.getName() ).isEqualTo( "foo" ); - assertThat( tag.getPlacement() ).isEqualTo( "Xaoptcmf" ); + assertThat(tag.getName()).isEqualTo("foo"); + assertThat(tag.getPlacement()).isEqualTo("Xaoptcmf"); } - } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateChildMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateChildMavenProjectStub.java index d384294f4..e4ed95561 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateChildMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateChildMavenProjectStub.java @@ -1,82 +1,78 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Reto Weiss - */ -public class AbstractAggregateChildMavenProjectStub - extends MavenProjectStub -{ - private String baseDir; - - public AbstractAggregateChildMavenProjectStub(String baseDir, String pomFileName, String targetDirectory) - { - this.baseDir = baseDir; - readModel( new File( getBasedir(), pomFileName ) ); - - setGroupId( Objects.toString( getModel().getGroupId(), getModel().getParent().getGroupId() ) ); - setArtifactId( getModel().getArtifactId() ); - setVersion( Objects.toString( getModel().getVersion(), getModel().getParent().getVersion() ) ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - setExecutionRoot( true ); - - Artifact artifact = new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + targetDirectory ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + baseDir ); - } - - /** {@inheritDoc} */ - @Override - public MavenProject getExecutionProject() - { - return this; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Reto Weiss + */ +public class AbstractAggregateChildMavenProjectStub extends MavenProjectStub { + private String baseDir; + + public AbstractAggregateChildMavenProjectStub(String baseDir, String pomFileName, String targetDirectory) { + this.baseDir = baseDir; + readModel(new File(getBasedir(), pomFileName)); + + setGroupId( + Objects.toString(getModel().getGroupId(), getModel().getParent().getGroupId())); + setArtifactId(getModel().getArtifactId()); + setVersion( + Objects.toString(getModel().getVersion(), getModel().getParent().getVersion())); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + setExecutionRoot(true); + + Artifact artifact = new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + targetDirectory); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + baseDir); + } + + /** {@inheritDoc} */ + @Override + public MavenProject getExecutionProject() { + return this; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateMavenProjectStub.java index 759daabaa..ecef7a61b 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AbstractAggregateMavenProjectStub.java @@ -1,90 +1,84 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Reto Weiss - */ -public class AbstractAggregateMavenProjectStub - extends MavenProjectStub -{ - private final String baseDir; - private final String[] projects; - public AbstractAggregateMavenProjectStub(String baseDir, String pomFileName, String targetDirectory, String... projects) - { - this.baseDir = baseDir; - this.projects = projects; - readModel( new File( getBasedir(), pomFileName) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - setExecutionRoot( true ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + targetDirectory ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - setCompileSourceRoots( compileSourceRoots ); - } - - @Override - public File getBasedir() - { - return new File( super.getBasedir() + baseDir); - } - - @Override - public MavenProject getExecutionProject() - { - return this; - } - - @Override - public List getModules() - { - return Arrays.asList( projects ); - } - - @Override - public Set getDependencyArtifacts() - { - return Collections.emptySet(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Reto Weiss + */ +public class AbstractAggregateMavenProjectStub extends MavenProjectStub { + private final String baseDir; + private final String[] projects; + + public AbstractAggregateMavenProjectStub( + String baseDir, String pomFileName, String targetDirectory, String... projects) { + this.baseDir = baseDir; + this.projects = projects; + readModel(new File(getBasedir(), pomFileName)); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + setExecutionRoot(true); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + targetDirectory); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + setCompileSourceRoots(compileSourceRoots); + } + + @Override + public File getBasedir() { + return new File(super.getBasedir() + baseDir); + } + + @Override + public MavenProject getExecutionProject() { + return this; + } + + @Override + public List getModules() { + return Arrays.asList(projects); + } + + @Override + public Set getDependencyArtifacts() { + return Collections.emptySet(); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject1TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject1TestMavenProjectStub.java index 2c3be01b7..93613a184 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject1TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject1TestMavenProjectStub.java @@ -1,34 +1,31 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateNotInSubFolderProject1TestMavenProjectStub - extends AbstractAggregateChildMavenProjectStub -{ - public AggregateNotInSubFolderProject1TestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/project1", - "pom.xml", - "/target/test/unit/aggregate-modules-not-in-subfolders-test/project1/target" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateNotInSubFolderProject1TestMavenProjectStub extends AbstractAggregateChildMavenProjectStub { + public AggregateNotInSubFolderProject1TestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/project1", + "pom.xml", + "/target/test/unit/aggregate-modules-not-in-subfolders-test/project1/target"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject2TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject2TestMavenProjectStub.java index 4a47343c1..d596903e7 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject2TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderProject2TestMavenProjectStub.java @@ -1,34 +1,31 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateNotInSubFolderProject2TestMavenProjectStub - extends AbstractAggregateChildMavenProjectStub -{ - public AggregateNotInSubFolderProject2TestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/project2", - "pom.xml", - "/target/test/unit/aggregate-modules-not-in-subfolders-test/project2/target"); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateNotInSubFolderProject2TestMavenProjectStub extends AbstractAggregateChildMavenProjectStub { + public AggregateNotInSubFolderProject2TestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/project2", + "pom.xml", + "/target/test/unit/aggregate-modules-not-in-subfolders-test/project2/target"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderTestMavenProjectStub.java index 1ac9d9be9..f390f7e3d 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateNotInSubFolderTestMavenProjectStub.java @@ -1,36 +1,33 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateNotInSubFolderTestMavenProjectStub - extends AbstractAggregateMavenProjectStub -{ - public AggregateNotInSubFolderTestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/all", - "pom.xml", - "/target/test/unit/aggregate-modules-not-in-subfolders-test/target", - "../project1", - "../project2"); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateNotInSubFolderTestMavenProjectStub extends AbstractAggregateMavenProjectStub { + public AggregateNotInSubFolderTestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-modules-not-in-subfolders-test/all", + "pom.xml", + "/target/test/unit/aggregate-modules-not-in-subfolders-test/target", + "../project1", + "../project2"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject1TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject1TestMavenProjectStub.java index f2c11caeb..5e1454c64 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject1TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject1TestMavenProjectStub.java @@ -1,73 +1,67 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Maria Odea Ching - */ -public class AggregateProject1TestMavenProjectStub - extends MavenProjectStub -{ - public AggregateProject1TestMavenProjectStub() - { - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "aggregate-test-project1" ); - setVersion( "1.0-SNAPSHOT" ); - setPackaging( "jar" ); - setExecutionRoot( true ); - - Artifact artifact = new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); - - Build build = new Build(); - build.setFinalName( "aggregate-test-project1" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/aggregate-test/target" ); - setBuild( build ); - - String basedir = getBasedir().getAbsolutePath(); - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( basedir ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/aggregate-test/project1" ); - } - - /** {@inheritDoc} */ - @Override - public MavenProject getExecutionProject() - { - return this; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Maria Odea Ching + */ +public class AggregateProject1TestMavenProjectStub extends MavenProjectStub { + public AggregateProject1TestMavenProjectStub() { + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("aggregate-test-project1"); + setVersion("1.0-SNAPSHOT"); + setPackaging("jar"); + setExecutionRoot(true); + + Artifact artifact = new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); + + Build build = new Build(); + build.setFinalName("aggregate-test-project1"); + build.setDirectory(super.getBasedir() + "/target/test/unit/aggregate-test/target"); + setBuild(build); + + String basedir = getBasedir().getAbsolutePath(); + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(basedir); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/aggregate-test/project1"); + } + + /** {@inheritDoc} */ + @Override + public MavenProject getExecutionProject() { + return this; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject2TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject2TestMavenProjectStub.java index 8b0e04ebe..fb5064de2 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject2TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateProject2TestMavenProjectStub.java @@ -1,73 +1,67 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Maria Odea Ching - */ -public class AggregateProject2TestMavenProjectStub - extends MavenProjectStub -{ - public AggregateProject2TestMavenProjectStub() - { - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "aggregate-test-project2" ); - setVersion( "1.0-SNAPSHOT" ); - setPackaging( "jar" ); - setExecutionRoot( true ); - - Artifact artifact = new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); - - Build build = new Build(); - build.setFinalName( "aggregate-test-project2" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/aggregate-test/target" ); - setBuild( build ); - - String basedir = getBasedir().getAbsolutePath(); - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( basedir ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/aggregate-test/project2" ); - } - - /** {@inheritDoc} */ - @Override - public MavenProject getExecutionProject() - { - return this; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Maria Odea Ching + */ +public class AggregateProject2TestMavenProjectStub extends MavenProjectStub { + public AggregateProject2TestMavenProjectStub() { + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("aggregate-test-project2"); + setVersion("1.0-SNAPSHOT"); + setPackaging("jar"); + setExecutionRoot(true); + + Artifact artifact = new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); + + Build build = new Build(); + build.setFinalName("aggregate-test-project2"); + build.setDirectory(super.getBasedir() + "/target/test/unit/aggregate-test/target"); + setBuild(build); + + String basedir = getBasedir().getAbsolutePath(); + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(basedir); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/aggregate-test/project2"); + } + + /** {@inheritDoc} */ + @Override + public MavenProject getExecutionProject() { + return this; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject1TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject1TestMavenProjectStub.java index d1e9de72f..9557ad142 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject1TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject1TestMavenProjectStub.java @@ -1,34 +1,31 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateResourcesProject1TestMavenProjectStub - extends AbstractAggregateChildMavenProjectStub -{ - public AggregateResourcesProject1TestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-resources-test/project1", - "pom.xml", - "/target/test/unit/aggregate-resources-test/project1/target" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateResourcesProject1TestMavenProjectStub extends AbstractAggregateChildMavenProjectStub { + public AggregateResourcesProject1TestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-resources-test/project1", + "pom.xml", + "/target/test/unit/aggregate-resources-test/project1/target"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject2TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject2TestMavenProjectStub.java index ee45b9f70..f3d54302b 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject2TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesProject2TestMavenProjectStub.java @@ -1,34 +1,31 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateResourcesProject2TestMavenProjectStub - extends AbstractAggregateChildMavenProjectStub -{ - public AggregateResourcesProject2TestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-resources-test/project2", - "pom.xml", - "/target/test/unit/aggregate-resources-test/project2/target" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateResourcesProject2TestMavenProjectStub extends AbstractAggregateChildMavenProjectStub { + public AggregateResourcesProject2TestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-resources-test/project2", + "pom.xml", + "/target/test/unit/aggregate-resources-test/project2/target"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesTestMavenProjectStub.java index db7547a56..39a6789ef 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateResourcesTestMavenProjectStub.java @@ -1,36 +1,33 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -/** - * @author Reto Weiss - */ -public class AggregateResourcesTestMavenProjectStub - extends AbstractAggregateMavenProjectStub -{ - public AggregateResourcesTestMavenProjectStub() - { - super( "/src/test/resources/unit/aggregate-resources-test", - "aggregate-resources-test-plugin-config.xml", - "/target/test/unit/aggregate-resources-test/target", - "project1", - "project2" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +/** + * @author Reto Weiss + */ +public class AggregateResourcesTestMavenProjectStub extends AbstractAggregateMavenProjectStub { + public AggregateResourcesTestMavenProjectStub() { + super( + "/src/test/resources/unit/aggregate-resources-test", + "aggregate-resources-test-plugin-config.xml", + "/target/test/unit/aggregate-resources-test/target", + "project1", + "project2"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateTestMavenProjectStub.java index f4a45213e..14a614c0d 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/AggregateTestMavenProjectStub.java @@ -1,98 +1,88 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Maria Odea Ching - */ -public class AggregateTestMavenProjectStub - extends MavenProjectStub -{ - private Build build; - - public AggregateTestMavenProjectStub() - { - readModel( new File( getBasedir(), "aggregate-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - setExecutionRoot( true ); - - build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/aggregate-test/target" ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - @Override - public Build getBuild() - { - return build; - } - - @Override - public void setBuild( Build build ) - { - this.build = build; - } - - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/aggregate-test" ); - } - - @Override - public MavenProject getExecutionProject() - { - return this; - } - - @Override - public List getModules() - { - return Arrays.asList( "project1", "project2" ); - } - - @Override - public Set getDependencyArtifacts() - { - return Collections.emptySet(); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Maria Odea Ching + */ +public class AggregateTestMavenProjectStub extends MavenProjectStub { + private Build build; + + public AggregateTestMavenProjectStub() { + readModel(new File(getBasedir(), "aggregate-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + setExecutionRoot(true); + + build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/aggregate-test/target"); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + @Override + public Build getBuild() { + return build; + } + + @Override + public void setBuild(Build build) { + this.build = build; + } + + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/aggregate-test"); + } + + @Override + public MavenProject getExecutionProject() { + return this; + } + + @Override + public List getModules() { + return Arrays.asList("project1", "project2"); + } + + @Override + public Set getDependencyArtifacts() { + return Collections.emptySet(); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/CustomConfigurationMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/CustomConfigurationMavenProjectStub.java index c8d5ffe5a..25a0197e2 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/CustomConfigurationMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/CustomConfigurationMavenProjectStub.java @@ -1,107 +1,97 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class CustomConfigurationMavenProjectStub - extends MavenProjectStub -{ - - private Scm scm; - - private Build build; - - public CustomConfigurationMavenProjectStub() - { - readModel( new File( getBasedir(), "custom-configuration-plugin-config.xml" ) ); - - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "custom-configuration" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Custom configuration Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); - //setExecutionRoot( true ); - //setDescription( "Sample Maven Project" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( "default-configuration" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/custom-configuration/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - String temp = getBasedir().getAbsolutePath(); - if( !temp.startsWith( "/" ) ) - { - temp = temp.replace( '/', '\\' ); - } - compileSourceRoots.add( temp ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public Build getBuild() - { - return build; - } - - /** {@inheritDoc} */ - @Override - public void setBuild( Build build ) - { - this.build = build; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/custom-configuration/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class CustomConfigurationMavenProjectStub extends MavenProjectStub { + + private Scm scm; + + private Build build; + + public CustomConfigurationMavenProjectStub() { + readModel(new File(getBasedir(), "custom-configuration-plugin-config.xml")); + + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("custom-configuration"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Custom configuration Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); + // setExecutionRoot( true ); + // setDescription( "Sample Maven Project" ); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName("default-configuration"); + build.setDirectory(super.getBasedir() + "/target/test/unit/custom-configuration/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + String temp = getBasedir().getAbsolutePath(); + if (!temp.startsWith("/")) { + temp = temp.replace('/', '\\'); + } + compileSourceRoots.add(temp); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public Build getBuild() { + return build; + } + + /** {@inheritDoc} */ + @Override + public void setBuild(Build build) { + this.build = build; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/custom-configuration/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultArtifactHandlerStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultArtifactHandlerStub.java index 62a62a89f..a6bb52c99 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultArtifactHandlerStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultArtifactHandlerStub.java @@ -1,52 +1,46 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.handler.DefaultArtifactHandler; - -/** - * @author Maria Odea Ching - */ -public class DefaultArtifactHandlerStub - extends DefaultArtifactHandler -{ - private String language; - - /** {@inheritDoc} */ - @Override - public String getLanguage() - { - if ( language == null ) - { - language = "java"; - } - - return language; - } - - /** - * @param language - */ - @Override - public void setLanguage( String language ) - { - this.language = language; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import org.apache.maven.artifact.handler.DefaultArtifactHandler; + +/** + * @author Maria Odea Ching + */ +public class DefaultArtifactHandlerStub extends DefaultArtifactHandler { + private String language; + + /** {@inheritDoc} */ + @Override + public String getLanguage() { + if (language == null) { + language = "java"; + } + + return language; + } + + /** + * @param language + */ + @Override + public void setLanguage(String language) { + this.language = language; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultConfigurationMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultConfigurationMavenProjectStub.java index 4560611e2..4277b2159 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultConfigurationMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DefaultConfigurationMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class DefaultConfigurationMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public DefaultConfigurationMavenProjectStub() - { - readModel( new File( getBasedir(), "default-configuration-plugin-config.xml" ) ); - - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "default-configuration" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Default configuration Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( "default-configuration" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/default-configuration/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/default-configuration/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class DefaultConfigurationMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public DefaultConfigurationMavenProjectStub() { + readModel(new File(getBasedir(), "default-configuration-plugin-config.xml")); + + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("default-configuration"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Default configuration Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName("default-configuration"); + build.setDirectory(super.getBasedir() + "/target/test/unit/default-configuration/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/default-configuration/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesTestMavenProjectStub.java index 56fff0c04..28bb773d5 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesTestMavenProjectStub.java @@ -1,84 +1,77 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class DocfilesTestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public DocfilesTestMavenProjectStub() - { - readModel( new File( getBasedir(), "docfiles-test-plugin-config.xml" ) ); - - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "docfiles-test" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Docfiles Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); - //setDescription( "Sample Maven Project" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( "docfiles-test" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/docfiles-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/docfiles-test/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class DocfilesTestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public DocfilesTestMavenProjectStub() { + readModel(new File(getBasedir(), "docfiles-test-plugin-config.xml")); + + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("docfiles-test"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Docfiles Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); + // setDescription( "Sample Maven Project" ); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName("docfiles-test"); + build.setDirectory(super.getBasedir() + "/target/test/unit/docfiles-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/docfiles-test/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesWithJavaTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesWithJavaTestMavenProjectStub.java index 866758fc7..eb6a3f383 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesWithJavaTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocfilesWithJavaTestMavenProjectStub.java @@ -1,60 +1,55 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class DocfilesWithJavaTestMavenProjectStub - extends MavenProjectStub -{ - public DocfilesWithJavaTestMavenProjectStub() - { - readModel( new File( getBasedir(), "docfiles-with-java-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setPackaging( "jar" ); - - Build build = new Build(); - build.setFinalName( "docfiles-with-java-test" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/docfiles-with-java-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/docfiles-with-java-test/src/main" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir(), "/src/test/resources/unit/docfiles-with-java-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class DocfilesWithJavaTestMavenProjectStub extends MavenProjectStub { + public DocfilesWithJavaTestMavenProjectStub() { + readModel(new File(getBasedir(), "docfiles-with-java-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setPackaging("jar"); + + Build build = new Build(); + build.setFinalName("docfiles-with-java-test"); + build.setDirectory(super.getBasedir() + "/target/test/unit/docfiles-with-java-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/docfiles-with-java-test/src/main"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir(), "/src/test/resources/unit/docfiles-with-java-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletPathTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletPathTestMavenProjectStub.java index 39cbcabcb..5ef9d7171 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletPathTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletPathTestMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class DocletPathTestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public DocletPathTestMavenProjectStub() - { - readModel( new File( getBasedir(), "doclet-path-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/doclet-path-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/doclet/test" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/doclet-path-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class DocletPathTestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public DocletPathTestMavenProjectStub() { + readModel(new File(getBasedir(), "doclet-path-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/doclet-path-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/doclet/test"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/doclet-path-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletTestMavenProjectStub.java index 1a4ef3102..e0d0596f6 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/DocletTestMavenProjectStub.java @@ -1,84 +1,77 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class DocletTestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public DocletTestMavenProjectStub() - { - readModel( new File( getBasedir(), "doclet-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - //setDescription( "Sample Maven Project" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/doclet-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/doclet/test" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/doclet-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class DocletTestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public DocletTestMavenProjectStub() { + readModel(new File(getBasedir(), "doclet-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + // setDescription( "Sample Maven Project" ); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/doclet-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/doclet/test"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/doclet-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/FixMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/FixMavenProjectStub.java index 3d6abb7f5..7f741b183 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/FixMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/FixMavenProjectStub.java @@ -1,105 +1,93 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -/** - * @author Vincent Siveton - */ -public class FixMavenProjectStub - extends MavenProjectStub -{ - public FixMavenProjectStub() - { - readModel( new File( getBasedir(), "pom.xml" ) ); - - addCompileSourceRoot( getBasedir().getAbsolutePath() + "/target/classes" ); - addCompileSourceRoot( getBasedir().getAbsolutePath() + "/src/main/java" ); - - Build build = new Build(); - build.setDirectory( getBasedir().getAbsolutePath() + "/target" ); - build.setSourceDirectory( getBasedir().getAbsolutePath() + "/src/main/java" ); - build.setOutputDirectory( getBasedir().getAbsolutePath() + "/target/classes" ); - build.setTestSourceDirectory( getBasedir().getAbsolutePath() + "/src/test/java" ); - build.setTestOutputDirectory( getBasedir().getAbsolutePath() + "/target/test-classes" ); - setBuild( build ); - } - - /** {@inheritDoc} */ - @Override - public String getArtifactId() - { - return getModel().getArtifactId(); - } - - /** {@inheritDoc} */ - @Override - public String getGroupId() - { - String groupId = getModel().getGroupId(); - - if ( ( groupId == null ) && ( getModel().getParent() != null ) ) - { - groupId = getModel().getParent().getGroupId(); - } - - return groupId; - } - - /** {@inheritDoc} */ - @Override - public String getVersion() - { - String version = getModel().getVersion(); - - if ( ( version == null ) && ( getModel().getParent() != null ) ) - { - version = getModel().getParent().getVersion(); - } - - return version; - } - - /** {@inheritDoc} */ - @Override - public String getPackaging() - { - return getModel().getPackaging(); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - // Using unit test dir - return new File( super.getBasedir() + "/target/test/unit/fix-test/" ); - } - - /** {@inheritDoc} */ - @Override - public File getFile() - { - return new File( getBasedir(), "pom.xml" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class FixMavenProjectStub extends MavenProjectStub { + public FixMavenProjectStub() { + readModel(new File(getBasedir(), "pom.xml")); + + addCompileSourceRoot(getBasedir().getAbsolutePath() + "/target/classes"); + addCompileSourceRoot(getBasedir().getAbsolutePath() + "/src/main/java"); + + Build build = new Build(); + build.setDirectory(getBasedir().getAbsolutePath() + "/target"); + build.setSourceDirectory(getBasedir().getAbsolutePath() + "/src/main/java"); + build.setOutputDirectory(getBasedir().getAbsolutePath() + "/target/classes"); + build.setTestSourceDirectory(getBasedir().getAbsolutePath() + "/src/test/java"); + build.setTestOutputDirectory(getBasedir().getAbsolutePath() + "/target/test-classes"); + setBuild(build); + } + + /** {@inheritDoc} */ + @Override + public String getArtifactId() { + return getModel().getArtifactId(); + } + + /** {@inheritDoc} */ + @Override + public String getGroupId() { + String groupId = getModel().getGroupId(); + + if ((groupId == null) && (getModel().getParent() != null)) { + groupId = getModel().getParent().getGroupId(); + } + + return groupId; + } + + /** {@inheritDoc} */ + @Override + public String getVersion() { + String version = getModel().getVersion(); + + if ((version == null) && (getModel().getParent() != null)) { + version = getModel().getParent().getVersion(); + } + + return version; + } + + /** {@inheritDoc} */ + @Override + public String getPackaging() { + return getModel().getPackaging(); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + // Using unit test dir + return new File(super.getBasedir() + "/target/test/unit/fix-test/"); + } + + /** {@inheritDoc} */ + @Override + public File getFile() { + return new File(getBasedir(), "pom.xml"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/HeaderFooterTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/HeaderFooterTestMavenProjectStub.java index a9eedc16a..019f752a7 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/HeaderFooterTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/HeaderFooterTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class HeaderFooterTestMavenProjectStub extends MavenProjectStub -{ - public HeaderFooterTestMavenProjectStub() - { - readModel( new File( getBasedir(), "header-footer-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/header-footer-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/header-footer-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class HeaderFooterTestMavenProjectStub extends MavenProjectStub { + public HeaderFooterTestMavenProjectStub() { + readModel(new File(getBasedir(), "header-footer-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/header-footer-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/header-footer-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/HelpFileMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/HelpFileMavenProjectStub.java index 5fcebd720..2a9e566c8 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/HelpFileMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/HelpFileMavenProjectStub.java @@ -1,83 +1,77 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.DefaultArtifactRepository; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.apache.maven.model.Build; -import org.apache.maven.model.Resource; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class HelpFileMavenProjectStub extends MavenProjectStub -{ - public HelpFileMavenProjectStub() - { - readModel( new File( getBasedir(), "pom.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/helpfile-test/target" ); - Resource resource = new Resource(); - resource.setDirectory( getBasedir() + "/src/main/resources" ); - build.addResource( resource ); - - build.setPlugins( getModel().getBuild().getPlugins() ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/helpfile-test" ); - } - - /** {@inheritDoc} */ - @Override - public List getRemoteArtifactRepositories() - { - ArtifactRepository repository = - new DefaultArtifactRepository( "central", "http://repo.maven.apache.org/maven2", - new DefaultRepositoryLayout() ); - - return Collections.singletonList( repository ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.DefaultArtifactRepository; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.model.Build; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class HelpFileMavenProjectStub extends MavenProjectStub { + public HelpFileMavenProjectStub() { + readModel(new File(getBasedir(), "pom.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/helpfile-test/target"); + Resource resource = new Resource(); + resource.setDirectory(getBasedir() + "/src/main/resources"); + build.addResource(resource); + + build.setPlugins(getModel().getBuild().getPlugins()); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/helpfile-test"); + } + + /** {@inheritDoc} */ + @Override + public List getRemoteArtifactRepositories() { + ArtifactRepository repository = new DefaultArtifactRepository( + "central", "http://repo.maven.apache.org/maven2", new DefaultRepositoryLayout()); + + return Collections.singletonList(repository); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarArchiveConfigProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarArchiveConfigProjectStub.java index 95f1928fc..7c259e009 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarArchiveConfigProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarArchiveConfigProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,64 +16,61 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +package org.apache.maven.plugins.javadoc.stubs; import java.io.File; import java.util.ArrayList; import java.util.List; +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + /** * Project stub for testing archive configuration. */ -public class JavadocJarArchiveConfigProjectStub - extends MavenProjectStub -{ +public class JavadocJarArchiveConfigProjectStub extends MavenProjectStub { private Scm scm; - public JavadocJarArchiveConfigProjectStub() - { - File projectFile = new File( getBasedir(), "javadocjar-archive-config.xml" ); - readModel( new File( getBasedir(), "javadocjar-archive-config.xml" ) ); + public JavadocJarArchiveConfigProjectStub() { + File projectFile = new File(getBasedir(), "javadocjar-archive-config.xml"); + readModel(new File(getBasedir(), "javadocjar-archive-config.xml")); - setFile( projectFile ); + setFile(projectFile); - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); JavadocPluginArtifactStub artifact = - new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - artifact.setType( "jar" ); - artifact.setBaseVersion( "1.0-SNAPSHOT" ); - setArtifact( artifact ); + new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + artifact.setType("jar"); + artifact.setBaseVersion("1.0-SNAPSHOT"); + setArtifact(artifact); Build build = new Build(); - build.setFinalName( "javadocjar-archive-config" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/javadocjar-archive-config/target" ); - setBuild( build ); + build.setFinalName("javadocjar-archive-config"); + build.setDirectory(super.getBasedir() + "/target/test/unit/javadocjar-archive-config/target"); + setBuild(build); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); } /** * {@inheritDoc} */ @Override - public Scm getScm() - { + public Scm getScm() { return scm; } @@ -83,8 +78,7 @@ public Scm getScm() * {@inheritDoc} */ @Override - public void setScm(Scm scm) - { + public void setScm(Scm scm) { this.scm = scm; } @@ -92,8 +86,7 @@ public void setScm(Scm scm) * {@inheritDoc} */ @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/javadocjar-archive-config" ); + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/javadocjar-archive-config"); } } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarDefaultMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarDefaultMavenProjectStub.java index 92ccc50d6..b20e66e89 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarDefaultMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarDefaultMavenProjectStub.java @@ -1,90 +1,83 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class JavadocJarDefaultMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public JavadocJarDefaultMavenProjectStub() - { - readModel( new File( getBasedir(), "javadocjar-default-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - JavadocPluginArtifactStub artifact = - new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - artifact.setType( "jar" ); - artifact.setBaseVersion( "1.0-SNAPSHOT" ); - setArtifact( artifact ); - - Build build = new Build(); - build.setFinalName( "javadocjar-default" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/javadocjar-default/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/javadocjar-default" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class JavadocJarDefaultMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public JavadocJarDefaultMavenProjectStub() { + readModel(new File(getBasedir(), "javadocjar-default-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + JavadocPluginArtifactStub artifact = + new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + artifact.setType("jar"); + artifact.setBaseVersion("1.0-SNAPSHOT"); + setArtifact(artifact); + + Build build = new Build(); + build.setFinalName("javadocjar-default"); + build.setDirectory(super.getBasedir() + "/target/test/unit/javadocjar-default/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/javadocjar-default"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarFailOnErrorMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarFailOnErrorMavenProjectStub.java index 1cd717c06..09dc718a3 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarFailOnErrorMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarFailOnErrorMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,73 +16,68 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +package org.apache.maven.plugins.javadoc.stubs; import java.io.File; import java.util.ArrayList; import java.util.List; +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + /** * @author Maria Odea Ching */ -public class JavadocJarFailOnErrorMavenProjectStub - extends MavenProjectStub -{ +public class JavadocJarFailOnErrorMavenProjectStub extends MavenProjectStub { private Scm scm; - public JavadocJarFailOnErrorMavenProjectStub() - { - readModel( new File( getBasedir(), "javadocjar-failonerror-plugin-config.xml" ) ); + public JavadocJarFailOnErrorMavenProjectStub() { + readModel(new File(getBasedir(), "javadocjar-failonerror-plugin-config.xml")); - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); JavadocPluginArtifactStub artifact = - new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - artifact.setType( "jar" ); - artifact.setBaseVersion( "1.0-SNAPSHOT" ); - setArtifact( artifact ); + new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + artifact.setType("jar"); + artifact.setBaseVersion("1.0-SNAPSHOT"); + setArtifact(artifact); Build build = new Build(); - build.setFinalName( "javadocjar-failonerror" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/javadocjar-failonerror/target" ); - setBuild( build ); + build.setFinalName("javadocjar-failonerror"); + build.setDirectory(super.getBasedir() + "/target/test/unit/javadocjar-failonerror/target"); + setBuild(build); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); } /** {@inheritDoc} */ @Override - public Scm getScm() - { + public Scm getScm() { return scm; } /** {@inheritDoc} */ @Override - public void setScm( Scm scm ) - { + public void setScm(Scm scm) { this.scm = scm; } /** {@inheritDoc} */ @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/javadocjar-failonerror" ); + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/javadocjar-failonerror"); } } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarInvalidDestdirMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarInvalidDestdirMavenProjectStub.java index 71c0bc5af..a9ac06737 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarInvalidDestdirMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocJarInvalidDestdirMavenProjectStub.java @@ -1,89 +1,81 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class JavadocJarInvalidDestdirMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public JavadocJarInvalidDestdirMavenProjectStub() - { - readModel( new File( getBasedir(), "javadocjar-invalid-destdir-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Artifact artifact = - new JavadocPluginArtifactStub( getGroupId(), getArtifactId(), getVersion(), getPackaging() ); - artifact.setArtifactHandler( new DefaultArtifactHandlerStub() ); - setArtifact( artifact ); - - Build build = new Build(); - build.setFinalName( "javadocjar-invalid-destdir" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/javadocjar-invalid-destdir/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/javadocjar-invalid-destdir/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class JavadocJarInvalidDestdirMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public JavadocJarInvalidDestdirMavenProjectStub() { + readModel(new File(getBasedir(), "javadocjar-invalid-destdir-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Artifact artifact = new JavadocPluginArtifactStub(getGroupId(), getArtifactId(), getVersion(), getPackaging()); + artifact.setArtifactHandler(new DefaultArtifactHandlerStub()); + setArtifact(artifact); + + Build build = new Build(); + build.setFinalName("javadocjar-invalid-destdir"); + build.setDirectory(super.getBasedir() + "/target/test/unit/javadocjar-invalid-destdir/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/javadocjar-invalid-destdir/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocPluginArtifactStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocPluginArtifactStub.java index 340238237..5317068b4 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocPluginArtifactStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/JavadocPluginArtifactStub.java @@ -1,154 +1,136 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.handler.ArtifactHandler; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.plugin.testing.stubs.ArtifactStub; - -/** - * @author Maria Odea Ching - */ -public class JavadocPluginArtifactStub - extends ArtifactStub -{ - private String groupId; - - private String artifactId; - - private String version; - - private String packaging; - - private String baseVersion; - - private VersionRange versionRange; - - private ArtifactHandler handler; - - public JavadocPluginArtifactStub( String groupId, String artifactId, String version, String packaging ) - { - this.groupId = groupId; - this.artifactId = artifactId; - this.version = version; - this.packaging = packaging; - versionRange = VersionRange.createFromVersion( version ); - } - - /** {@inheritDoc} */ - @Override - public void setGroupId( String groupId ) - { - this.groupId = groupId; - } - - /** {@inheritDoc} */ - @Override - public String getGroupId() - { - return groupId; - } - - /** {@inheritDoc} */ - @Override - public void setArtifactId( String artifactId ) - { - this.artifactId = artifactId; - } - - /** {@inheritDoc} */ - @Override - public String getArtifactId() - { - return artifactId; - } - - /** {@inheritDoc} */ - @Override - public void setVersion( String version ) - { - this.version = version; - } - - /** {@inheritDoc} */ - @Override - public String getVersion() - { - return version; - } - - /** - * @param packaging - */ - public void setPackaging( String packaging ) - { - this.packaging = packaging; - } - - /** - * @return - */ - public String getPackaging() - { - return packaging; - } - - /** {@inheritDoc} */ - @Override - public VersionRange getVersionRange() - { - return versionRange; - } - - /** {@inheritDoc} */ - @Override - public void setVersionRange( VersionRange versionRange ) - { - this.versionRange = versionRange; - } - - /** {@inheritDoc} */ - @Override - public ArtifactHandler getArtifactHandler() - { - return handler; - } - - /** {@inheritDoc} */ - @Override - public void setArtifactHandler( ArtifactHandler handler ) - { - this.handler = handler; - } - - /** {@inheritDoc} */ - @Override - public String getBaseVersion() - { - return baseVersion; - } - - /** {@inheritDoc} */ - @Override - public void setBaseVersion( String string ) - { - this.baseVersion = string; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import org.apache.maven.artifact.handler.ArtifactHandler; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.plugin.testing.stubs.ArtifactStub; + +/** + * @author Maria Odea Ching + */ +public class JavadocPluginArtifactStub extends ArtifactStub { + private String groupId; + + private String artifactId; + + private String version; + + private String packaging; + + private String baseVersion; + + private VersionRange versionRange; + + private ArtifactHandler handler; + + public JavadocPluginArtifactStub(String groupId, String artifactId, String version, String packaging) { + this.groupId = groupId; + this.artifactId = artifactId; + this.version = version; + this.packaging = packaging; + versionRange = VersionRange.createFromVersion(version); + } + + /** {@inheritDoc} */ + @Override + public void setGroupId(String groupId) { + this.groupId = groupId; + } + + /** {@inheritDoc} */ + @Override + public String getGroupId() { + return groupId; + } + + /** {@inheritDoc} */ + @Override + public void setArtifactId(String artifactId) { + this.artifactId = artifactId; + } + + /** {@inheritDoc} */ + @Override + public String getArtifactId() { + return artifactId; + } + + /** {@inheritDoc} */ + @Override + public void setVersion(String version) { + this.version = version; + } + + /** {@inheritDoc} */ + @Override + public String getVersion() { + return version; + } + + /** + * @param packaging + */ + public void setPackaging(String packaging) { + this.packaging = packaging; + } + + /** + * @return + */ + public String getPackaging() { + return packaging; + } + + /** {@inheritDoc} */ + @Override + public VersionRange getVersionRange() { + return versionRange; + } + + /** {@inheritDoc} */ + @Override + public void setVersionRange(VersionRange versionRange) { + this.versionRange = versionRange; + } + + /** {@inheritDoc} */ + @Override + public ArtifactHandler getArtifactHandler() { + return handler; + } + + /** {@inheritDoc} */ + @Override + public void setArtifactHandler(ArtifactHandler handler) { + this.handler = handler; + } + + /** {@inheritDoc} */ + @Override + public String getBaseVersion() { + return baseVersion; + } + + /** {@inheritDoc} */ + @Override + public void setBaseVersion(String string) { + this.baseVersion = string; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk5TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk5TestMavenProjectStub.java index e7198e9fb..352ee3e1b 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk5TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk5TestMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class Jdk5TestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public Jdk5TestMavenProjectStub() - { - readModel( new File( getBasedir(), "jdk5-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/jdk5-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/jdk5-test/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class Jdk5TestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public Jdk5TestMavenProjectStub() { + readModel(new File(getBasedir(), "jdk5-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/jdk5-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/jdk5-test/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk6TestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk6TestMavenProjectStub.java index b6ec7f941..93ebc8d9f 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk6TestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/Jdk6TestMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class Jdk6TestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public Jdk6TestMavenProjectStub() - { - readModel( new File( getBasedir(), "jdk6-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/jdk6-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/jdk6-test/" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class Jdk6TestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public Jdk6TestMavenProjectStub() { + readModel(new File(getBasedir(), "jdk6-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/jdk6-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/jdk6-test/"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/NewlineTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/NewlineTestMavenProjectStub.java index 610460704..4fe51bd68 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/NewlineTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/NewlineTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class NewlineTestMavenProjectStub extends MavenProjectStub -{ - public NewlineTestMavenProjectStub() - { - readModel( new File( getBasedir(), "newline-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/newline-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/newline-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class NewlineTestMavenProjectStub extends MavenProjectStub { + public NewlineTestMavenProjectStub() { + readModel(new File(getBasedir(), "newline-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/newline-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/newline-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/OptionsUmlautEncodingMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/OptionsUmlautEncodingMavenProjectStub.java index f1db35cda..56d8a971e 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/OptionsUmlautEncodingMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/OptionsUmlautEncodingMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.javadoc.stubs; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -9,7 +7,7 @@ * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an @@ -18,63 +16,58 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.javadoc.stubs; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.model.Scm; -import org.apache.maven.model.Build; - -import java.util.List; -import java.util.ArrayList; import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -public class OptionsUmlautEncodingMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; +public class OptionsUmlautEncodingMavenProjectStub extends MavenProjectStub { + private Scm scm; - public OptionsUmlautEncodingMavenProjectStub() - { - readModel( new File( getBasedir(), "optionsumlautencoding-test-plugin-config.xml" ) ); + public OptionsUmlautEncodingMavenProjectStub() { + readModel(new File(getBasedir(), "optionsumlautencoding-test-plugin-config.xml")); - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "optionsumlautencoding-test" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Options Umlaut Encoding Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("optionsumlautencoding-test"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Options Umlaut Encoding Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); Build build = new Build(); - build.setFinalName( "optionsumlautencoding-test" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/optionsumlautencoding-test/target" ); - setBuild( build ); + build.setFinalName("optionsumlautencoding-test"); + build.setDirectory(super.getBasedir() + "/target/test/unit/optionsumlautencoding-test/target"); + setBuild(build); List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); } /** {@inheritDoc} */ @Override - public Scm getScm() - { + public Scm getScm() { return scm; } /** {@inheritDoc} */ @Override - public void setScm( Scm scm ) - { + public void setScm(Scm scm) { this.scm = scm; } /** {@inheritDoc} */ @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/optionsumlautencoding-test" ); + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/optionsumlautencoding-test"); } } diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/PomMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/PomMavenProjectStub.java index c72cd7ad0..6327d321f 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/PomMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/PomMavenProjectStub.java @@ -1,70 +1,65 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -/** - * @author Vincent Siveton - */ -public class PomMavenProjectStub - extends MavenProjectStub -{ - public PomMavenProjectStub() - { - readModel( new File( getBasedir(), "pom-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/pom-test/target" ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setOutputDirectory( super.getBasedir() + "/target/test/unit/pom-test/target/classes" ); - build.setTestSourceDirectory( getBasedir() + "/src/test/java" ); - build.setTestOutputDirectory( super.getBasedir() + "/target/test/unit/pom-test/target/test-classes" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - - List testCompileSourceRoots = new ArrayList<>(); - testCompileSourceRoots.add( getBasedir() + "/src/test/java" ); - setTestCompileSourceRoots( testCompileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/pom-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class PomMavenProjectStub extends MavenProjectStub { + public PomMavenProjectStub() { + readModel(new File(getBasedir(), "pom-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/pom-test/target"); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setOutputDirectory(super.getBasedir() + "/target/test/unit/pom-test/target/classes"); + build.setTestSourceDirectory(getBasedir() + "/src/test/java"); + build.setTestOutputDirectory(super.getBasedir() + "/target/test/unit/pom-test/target/test-classes"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + + List testCompileSourceRoots = new ArrayList<>(); + testCompileSourceRoots.add(getBasedir() + "/src/test/java"); + setTestCompileSourceRoots(testCompileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/pom-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ProxyTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ProxyTestMavenProjectStub.java index 2f9a9c086..d479a1a61 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ProxyTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ProxyTestMavenProjectStub.java @@ -1,91 +1,84 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * @author Vincent Siveton - */ -public class ProxyTestMavenProjectStub - extends MavenProjectStub -{ - private Set dependencyArtifacts = new HashSet<>(); - - public ProxyTestMavenProjectStub() - { - readModel( new File( getBasedir(), "proxy-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/proxy-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - - - Artifact artifact = mock( Artifact.class ); - when( artifact.getGroupId()).thenReturn( "commons-logging" ); - when( artifact.getArtifactId()).thenReturn( "commons-logging" ); - when( artifact.getVersion()).thenReturn( "1.1.1" ); - when( artifact.getScope()).thenReturn( Artifact.SCOPE_RUNTIME ); - when( artifact.getType()).thenReturn( "jar" ); - when( artifact.getFile()).thenReturn( getBasedir() ); - DefaultArtifactHandlerStub artifactHandler = new DefaultArtifactHandlerStub(); - artifactHandler.setExtension( "jar" ); - when( artifact.getArtifactHandler()).thenReturn( artifactHandler ); - - dependencyArtifacts.add( artifact ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/proxy-test" ); - } - - @Override - public Set getDependencyArtifacts() - { - return dependencyArtifacts; - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * @author Vincent Siveton + */ +public class ProxyTestMavenProjectStub extends MavenProjectStub { + private Set dependencyArtifacts = new HashSet<>(); + + public ProxyTestMavenProjectStub() { + readModel(new File(getBasedir(), "proxy-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/proxy-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + + Artifact artifact = mock(Artifact.class); + when(artifact.getGroupId()).thenReturn("commons-logging"); + when(artifact.getArtifactId()).thenReturn("commons-logging"); + when(artifact.getVersion()).thenReturn("1.1.1"); + when(artifact.getScope()).thenReturn(Artifact.SCOPE_RUNTIME); + when(artifact.getType()).thenReturn("jar"); + when(artifact.getFile()).thenReturn(getBasedir()); + DefaultArtifactHandlerStub artifactHandler = new DefaultArtifactHandlerStub(); + artifactHandler.setExtension("jar"); + when(artifact.getArtifactHandler()).thenReturn(artifactHandler); + + dependencyArtifacts.add(artifact); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/proxy-test"); + } + + @Override + public Set getDependencyArtifacts() { + return dependencyArtifacts; + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/QuotedPathMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/QuotedPathMavenProjectStub.java index 56e46036f..06e1d9ba5 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/QuotedPathMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/QuotedPathMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.model.Scm; -import org.apache.maven.model.Build; - -import java.util.List; -import java.util.ArrayList; -import java.io.File; - -/** - * @author Maria Odea Ching - */ -public class QuotedPathMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public QuotedPathMavenProjectStub() - { - readModel( new File( getBasedir(), "quotedpath-test-plugin-config.xml" ) ); - - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "quotedpath-test" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Quoted Path Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( "quotedpath-test" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/quotedpath'test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/quotedpath'test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class QuotedPathMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public QuotedPathMavenProjectStub() { + readModel(new File(getBasedir(), "quotedpath-test-plugin-config.xml")); + + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("quotedpath-test"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Quoted Path Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName("quotedpath-test"); + build.setDirectory(super.getBasedir() + "/target/test/unit/quotedpath'test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/quotedpath'test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesTestMavenProjectStub.java index e8141255d..673fa8094 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class ResourcesTestMavenProjectStub extends MavenProjectStub -{ - public ResourcesTestMavenProjectStub() - { - readModel( new File( getBasedir(), "resources-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/resources-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/resources-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class ResourcesTestMavenProjectStub extends MavenProjectStub { + public ResourcesTestMavenProjectStub() { + readModel(new File(getBasedir(), "resources-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/resources-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/resources-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesWithExcludesTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesWithExcludesTestMavenProjectStub.java index b1f4dfb01..919e60b7e 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesWithExcludesTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/ResourcesWithExcludesTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class ResourcesWithExcludesTestMavenProjectStub extends MavenProjectStub -{ - public ResourcesWithExcludesTestMavenProjectStub() - { - readModel( new File( getBasedir(), "resources-with-excludes-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/resources-with-excludes-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/resources-with-excludes-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class ResourcesWithExcludesTestMavenProjectStub extends MavenProjectStub { + public ResourcesWithExcludesTestMavenProjectStub() { + readModel(new File(getBasedir(), "resources-with-excludes-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/resources-with-excludes-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/resources-with-excludes-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/SettingsStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/SettingsStub.java index be9f0790e..147b0cb30 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/SettingsStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/SettingsStub.java @@ -1,55 +1,50 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.util.Collections; -import java.util.List; - -import org.apache.maven.settings.Proxy; -import org.apache.maven.settings.Settings; - -/** - * @author Vincent Siveton - */ -public class SettingsStub - extends Settings -{ - /** {@inheritDoc} */ - @Override - public synchronized Proxy getActiveProxy() - { - Proxy proxy = new Proxy(); - proxy.setActive( true ); - proxy.setHost( "http://localhost" ); - proxy.setPort( 80 ); - proxy.setUsername( "toto" ); - proxy.setPassword( "toto" ); - proxy.setNonProxyHosts( "www.google.com|*.somewhere.com" ); - - return proxy; - } - - /** {@inheritDoc} */ - @Override - public List getProxies() - { - return Collections.singletonList( getActiveProxy() ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.util.Collections; +import java.util.List; + +import org.apache.maven.settings.Proxy; +import org.apache.maven.settings.Settings; + +/** + * @author Vincent Siveton + */ +public class SettingsStub extends Settings { + /** {@inheritDoc} */ + @Override + public synchronized Proxy getActiveProxy() { + Proxy proxy = new Proxy(); + proxy.setActive(true); + proxy.setHost("http://localhost"); + proxy.setPort(80); + proxy.setUsername("toto"); + proxy.setPassword("toto"); + proxy.setNonProxyHosts("www.google.com|*.somewhere.com"); + + return proxy; + } + + /** {@inheritDoc} */ + @Override + public List getProxies() { + return Collections.singletonList(getActiveProxy()); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/StandardDocletConflictOptionsTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/StandardDocletConflictOptionsTestMavenProjectStub.java index 558e815b7..6fb5e21fc 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/StandardDocletConflictOptionsTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/StandardDocletConflictOptionsTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class StandardDocletConflictOptionsTestMavenProjectStub extends MavenProjectStub -{ - public StandardDocletConflictOptionsTestMavenProjectStub() - { - readModel( new File( getBasedir(), "conflict-options-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/validate-options-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/validate-options-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class StandardDocletConflictOptionsTestMavenProjectStub extends MavenProjectStub { + public StandardDocletConflictOptionsTestMavenProjectStub() { + readModel(new File(getBasedir(), "conflict-options-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/validate-options-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/validate-options-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/StylesheetFileMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/StylesheetFileMavenProjectStub.java index 227e65c58..45e7a5158 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/StylesheetFileMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/StylesheetFileMavenProjectStub.java @@ -1,83 +1,77 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.artifact.repository.ArtifactRepository; -import org.apache.maven.artifact.repository.DefaultArtifactRepository; -import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; -import org.apache.maven.model.Build; -import org.apache.maven.model.Resource; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class StylesheetFileMavenProjectStub extends MavenProjectStub -{ - public StylesheetFileMavenProjectStub() - { - readModel( new File( getBasedir(), "pom.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/stylesheetfile-test/target" ); - Resource resource = new Resource(); - resource.setDirectory( getBasedir() + "/src/main/resources" ); - build.addResource( resource ); - - build.setPlugins( getModel().getBuild().getPlugins() ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/stylesheetfile-test" ); - } - - /** {@inheritDoc} */ - @Override - public List getRemoteArtifactRepositories() - { - ArtifactRepository repository = - new DefaultArtifactRepository( "central", "http://repo.maven.apache.org/maven2", - new DefaultRepositoryLayout() ); - - return Collections.singletonList( repository ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.artifact.repository.ArtifactRepository; +import org.apache.maven.artifact.repository.DefaultArtifactRepository; +import org.apache.maven.artifact.repository.layout.DefaultRepositoryLayout; +import org.apache.maven.model.Build; +import org.apache.maven.model.Resource; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class StylesheetFileMavenProjectStub extends MavenProjectStub { + public StylesheetFileMavenProjectStub() { + readModel(new File(getBasedir(), "pom.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/stylesheetfile-test/target"); + Resource resource = new Resource(); + resource.setDirectory(getBasedir() + "/src/main/resources"); + build.addResource(resource); + + build.setPlugins(getModel().getBuild().getPlugins()); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/stylesheetfile-test"); + } + + /** {@inheritDoc} */ + @Override + public List getRemoteArtifactRepositories() { + ArtifactRepository repository = new DefaultArtifactRepository( + "central", "http://repo.maven.apache.org/maven2", new DefaultRepositoryLayout()); + + return Collections.singletonList(repository); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/SubpackagesTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/SubpackagesTestMavenProjectStub.java index a6b645e5b..8ce5d2cc0 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/SubpackagesTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/SubpackagesTestMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Maria Odea Ching - */ -public class SubpackagesTestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public SubpackagesTestMavenProjectStub() - { - readModel( new File( getBasedir(), "subpackages-test-plugin-config.xml" ) ); - - setGroupId( "org.apache.maven.plugins.maven-javadoc-plugin.unit" ); - setArtifactId( "subpackages-test" ); - setVersion( "1.0-SNAPSHOT" ); - setName( "Maven Javadoc Plugin Subpackages Test" ); - setUrl( "http://maven.apache.org" ); - setPackaging( "jar" ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( "subpackages-test" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/subpackages-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/subpackages-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Maria Odea Ching + */ +public class SubpackagesTestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public SubpackagesTestMavenProjectStub() { + readModel(new File(getBasedir(), "subpackages-test-plugin-config.xml")); + + setGroupId("org.apache.maven.plugins.maven-javadoc-plugin.unit"); + setArtifactId("subpackages-test"); + setVersion("1.0-SNAPSHOT"); + setName("Maven Javadoc Plugin Subpackages Test"); + setUrl("http://maven.apache.org"); + setPackaging("jar"); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName("subpackages-test"); + build.setDirectory(super.getBasedir() + "/target/test/unit/subpackages-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/subpackages-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagTestMavenProjectStub.java index db9d67c0e..12cf79eb6 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class TagTestMavenProjectStub extends MavenProjectStub -{ - public TagTestMavenProjectStub() - { - readModel( new File( getBasedir(), "tag-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/tag-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/tag-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class TagTestMavenProjectStub extends MavenProjectStub { + public TagTestMavenProjectStub() { + readModel(new File(getBasedir(), "tag-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/tag-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/tag-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletArtifactsMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletArtifactsMavenProjectStub.java index 72c59e698..93e9bab97 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletArtifactsMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletArtifactsMavenProjectStub.java @@ -1,79 +1,73 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.eclipse.aether.repository.RemoteRepository; - -/** - * @author Vincent Siveton - */ -public class TagletArtifactsMavenProjectStub - extends MavenProjectStub -{ - /** - * Default constructor. - */ - public TagletArtifactsMavenProjectStub() - { - readModel( new File( getBasedir(), "tagletArtifacts-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/tagletArtifacts-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /* - * Allow to retrieve some dependencies from Maven Central - */ - @Override - public List getRemoteProjectRepositories() - { - RemoteRepository.Builder builder = new RemoteRepository.Builder( "central", "default", - "https://repo.maven.apache.org/maven2" ); - return Collections.singletonList( builder.build() ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/tagletArtifacts-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.eclipse.aether.repository.RemoteRepository; + +/** + * @author Vincent Siveton + */ +public class TagletArtifactsMavenProjectStub extends MavenProjectStub { + /** + * Default constructor. + */ + public TagletArtifactsMavenProjectStub() { + readModel(new File(getBasedir(), "tagletArtifacts-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/tagletArtifacts-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /* + * Allow to retrieve some dependencies from Maven Central + */ + @Override + public List getRemoteProjectRepositories() { + RemoteRepository.Builder builder = + new RemoteRepository.Builder("central", "default", "https://repo.maven.apache.org/maven2"); + return Collections.singletonList(builder.build()); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/tagletArtifacts-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletTestMavenProjectStub.java index 3ec222ee5..10239d9f1 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TagletTestMavenProjectStub.java @@ -1,83 +1,76 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.model.Scm; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class TagletTestMavenProjectStub - extends MavenProjectStub -{ - private Scm scm; - - public TagletTestMavenProjectStub() - { - readModel( new File( getBasedir(), "taglet-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Scm scm = new Scm(); - scm.setConnection( "scm:svn:http://svn.apache.org/maven/sample/trunk" ); - setScm( scm ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/taglet-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir().getAbsolutePath() ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public Scm getScm() - { - return scm; - } - - /** {@inheritDoc} */ - @Override - public void setScm( Scm scm ) - { - this.scm = scm; - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/taglet-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.model.Scm; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class TagletTestMavenProjectStub extends MavenProjectStub { + private Scm scm; + + public TagletTestMavenProjectStub() { + readModel(new File(getBasedir(), "taglet-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Scm scm = new Scm(); + scm.setConnection("scm:svn:http://svn.apache.org/maven/sample/trunk"); + setScm(scm); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/taglet-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir().getAbsolutePath()); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public Scm getScm() { + return scm; + } + + /** {@inheritDoc} */ + @Override + public void setScm(Scm scm) { + this.scm = scm; + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/taglet-test"); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TestJavadocMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TestJavadocMavenProjectStub.java index 23586c1ba..946699b56 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/TestJavadocMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/TestJavadocMavenProjectStub.java @@ -1,94 +1,93 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import java.io.File; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import org.apache.maven.artifact.Artifact; -import org.apache.maven.artifact.DefaultArtifact; -import org.apache.maven.artifact.handler.DefaultArtifactHandler; -import org.apache.maven.artifact.versioning.VersionRange; -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; -import org.apache.maven.project.MavenProject; - -/** - * @author Vincent Siveton - */ -public class TestJavadocMavenProjectStub - extends MavenProjectStub -{ - public TestJavadocMavenProjectStub() - { - readModel( new File( getBasedir(), "test-javadoc-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setDirectory( super.getBasedir() + "/target/test/unit/test-javadoc-test/target" ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setOutputDirectory( super.getBasedir() + "/target/test/unit/test-javadoc-test/target/classes" ); - build.setTestSourceDirectory( getBasedir() + "/src/test/java" ); - build.setTestOutputDirectory( super.getBasedir() + "/target/test/unit/test-javadoc-test/target/test-classes" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - - List testCompileSourceRoots = new ArrayList<>(); - testCompileSourceRoots.add( getBasedir() + "/src/test/java" ); - setTestCompileSourceRoots( testCompileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/test-javadoc-test" ); - } - - /** {@inheritDoc} */ - @Override - public MavenProject getExecutionProject() - { - return this; - } - - @Override - public Set getArtifacts() - { - Artifact junit = new DefaultArtifact( "junit", "junit", VersionRange.createFromVersion( "3.8.1" ), - Artifact.SCOPE_TEST, "jar", null, new DefaultArtifactHandler( "jar" ), - false ); - junit.setFile( new File( getBasedir() + "/junit/junit/3.8.1/junit-3.8.1.jar" ) ); - return Collections.singleton( junit ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import org.apache.maven.artifact.Artifact; +import org.apache.maven.artifact.DefaultArtifact; +import org.apache.maven.artifact.handler.DefaultArtifactHandler; +import org.apache.maven.artifact.versioning.VersionRange; +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; +import org.apache.maven.project.MavenProject; + +/** + * @author Vincent Siveton + */ +public class TestJavadocMavenProjectStub extends MavenProjectStub { + public TestJavadocMavenProjectStub() { + readModel(new File(getBasedir(), "test-javadoc-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setDirectory(super.getBasedir() + "/target/test/unit/test-javadoc-test/target"); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setOutputDirectory(super.getBasedir() + "/target/test/unit/test-javadoc-test/target/classes"); + build.setTestSourceDirectory(getBasedir() + "/src/test/java"); + build.setTestOutputDirectory(super.getBasedir() + "/target/test/unit/test-javadoc-test/target/test-classes"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + + List testCompileSourceRoots = new ArrayList<>(); + testCompileSourceRoots.add(getBasedir() + "/src/test/java"); + setTestCompileSourceRoots(testCompileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/test-javadoc-test"); + } + + /** {@inheritDoc} */ + @Override + public MavenProject getExecutionProject() { + return this; + } + + @Override + public Set getArtifacts() { + Artifact junit = new DefaultArtifact( + "junit", + "junit", + VersionRange.createFromVersion("3.8.1"), + Artifact.SCOPE_TEST, + "jar", + null, + new DefaultArtifactHandler("jar"), + false); + junit.setFile(new File(getBasedir() + "/junit/junit/3.8.1/junit-3.8.1.jar")); + return Collections.singleton(junit); + } +} diff --git a/src/test/java/org/apache/maven/plugins/javadoc/stubs/WrongEncodingOptionsTestMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/javadoc/stubs/WrongEncodingOptionsTestMavenProjectStub.java index 742ae589c..aa608eca7 100644 --- a/src/test/java/org/apache/maven/plugins/javadoc/stubs/WrongEncodingOptionsTestMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/javadoc/stubs/WrongEncodingOptionsTestMavenProjectStub.java @@ -1,62 +1,58 @@ -package org.apache.maven.plugins.javadoc.stubs; - -/* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, - * software distributed under the License is distributed on an - * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY - * KIND, either express or implied. See the License for the - * specific language governing permissions and limitations - * under the License. - */ - -import org.apache.maven.model.Build; -import org.apache.maven.plugin.testing.stubs.MavenProjectStub; - -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * @author Vincent Siveton - */ -public class WrongEncodingOptionsTestMavenProjectStub extends MavenProjectStub -{ - public WrongEncodingOptionsTestMavenProjectStub() - { - readModel( new File( getBasedir(), "wrong-encoding-test-plugin-config.xml" ) ); - - setGroupId( getModel().getGroupId() ); - setArtifactId( getModel().getArtifactId() ); - setVersion( getModel().getVersion() ); - setName( getModel().getName() ); - setUrl( getModel().getUrl() ); - setPackaging( getModel().getPackaging() ); - - Build build = new Build(); - build.setFinalName( getModel().getArtifactId() ); - build.setSourceDirectory( getBasedir() + "/src/main/java" ); - build.setDirectory( super.getBasedir() + "/target/test/unit/validate-options-test/target" ); - setBuild( build ); - - List compileSourceRoots = new ArrayList<>(); - compileSourceRoots.add( getBasedir() + "/src/main/java" ); - setCompileSourceRoots( compileSourceRoots ); - } - - /** {@inheritDoc} */ - @Override - public File getBasedir() - { - return new File( super.getBasedir() + "/src/test/resources/unit/validate-options-test" ); - } -} +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.maven.plugins.javadoc.stubs; + +import java.io.File; +import java.util.ArrayList; +import java.util.List; + +import org.apache.maven.model.Build; +import org.apache.maven.plugin.testing.stubs.MavenProjectStub; + +/** + * @author Vincent Siveton + */ +public class WrongEncodingOptionsTestMavenProjectStub extends MavenProjectStub { + public WrongEncodingOptionsTestMavenProjectStub() { + readModel(new File(getBasedir(), "wrong-encoding-test-plugin-config.xml")); + + setGroupId(getModel().getGroupId()); + setArtifactId(getModel().getArtifactId()); + setVersion(getModel().getVersion()); + setName(getModel().getName()); + setUrl(getModel().getUrl()); + setPackaging(getModel().getPackaging()); + + Build build = new Build(); + build.setFinalName(getModel().getArtifactId()); + build.setSourceDirectory(getBasedir() + "/src/main/java"); + build.setDirectory(super.getBasedir() + "/target/test/unit/validate-options-test/target"); + setBuild(build); + + List compileSourceRoots = new ArrayList<>(); + compileSourceRoots.add(getBasedir() + "/src/main/java"); + setCompileSourceRoots(compileSourceRoots); + } + + /** {@inheritDoc} */ + @Override + public File getBasedir() { + return new File(super.getBasedir() + "/src/test/resources/unit/validate-options-test"); + } +}