From 476c44f36ac1b9e1f3d03372c77bcc99c5a213f0 Mon Sep 17 00:00:00 2001 From: Michael Osipov Date: Sat, 11 Feb 2023 13:09:58 +0100 Subject: [PATCH] [MSITE-927] Upgrade Parent to 39 --- pom.xml | 22 +- src/it/projects/effective-site/pom.xml | 2 +- .../projects/site-sd-lang/src/site/site.xml | 30 +- .../site-sd-lang/src/site/site_fr.xml | 30 +- .../maven/plugins/site/AbstractSiteMojo.java | 31 +- .../site/deploy/AbstractDeployMojo.java | 528 +++++++----------- .../site/deploy/AbstractStagingMojo.java | 28 +- .../plugins/site/deploy/SiteDeployMojo.java | 22 +- .../site/deploy/SiteStageDeployMojo.java | 119 ++-- .../plugins/site/deploy/SiteStageMojo.java | 83 +-- .../AbstractSiteDescriptorMojo.java | 55 +- .../site/descriptor/EffectiveSiteMojo.java | 139 ++--- .../SiteDescriptorArtifactMetadata.java | 72 +-- .../descriptor/SiteDescriptorAttachMojo.java | 76 +-- .../render/AbstractSiteRenderingMojo.java | 418 ++++++-------- .../CategorySummaryDocumentRenderer.java | 91 ++- .../site/render/ReportDocumentRenderer.java | 221 +++----- .../plugins/site/render/SiteJarMojo.java | 107 ++-- .../maven/plugins/site/render/SiteMap.java | 81 +-- .../maven/plugins/site/render/SiteMojo.java | 211 +++---- .../maven/plugins/site/run/DoxiaBean.java | 31 +- .../maven/plugins/site/run/DoxiaFilter.java | 154 ++--- .../maven/plugins/site/run/SiteRunMojo.java | 177 +++--- .../deploy/AbstractSiteDeployWebDavTest.java | 268 ++++----- .../site/deploy/AuthAsyncProxyServlet.java | 106 ++-- .../plugins/site/deploy/HttpRequest.java | 24 +- .../site/deploy/SimpleDavServerHandler.java | 99 ++-- .../site/deploy/SiteDeployMojoTest.java | 25 +- .../site/deploy/SiteDeployWebDavTest.java | 18 +- .../maven/plugins/site/run/WebXmlTest.java | 122 ++-- .../site/stubs/SiteMavenProjectStub.java | 52 +- 31 files changed, 1419 insertions(+), 2023 deletions(-) diff --git a/pom.xml b/pom.xml index a4b2d4bf..715bbf6b 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - - 4.0.0 org.apache.maven.plugins maven-plugins - 36 + 39 @@ -176,8 +174,8 @@ under the License. scm:git:https://gitbox.apache.org/repos/asf/maven-site-plugin.git scm:git:https://gitbox.apache.org/repos/asf/maven-site-plugin.git - https://github.com/apache/maven-site-plugin/tree/${project.scm.tag} HEAD + https://github.com/apache/maven-site-plugin/tree/${project.scm.tag} JIRA @@ -526,14 +524,6 @@ under the License. org.codehaus.mojo mrm-maven-plugin 1.4.1 - - - - start - stop - - - @@ -542,6 +532,14 @@ under the License. + + + + start + stop + + + diff --git a/src/it/projects/effective-site/pom.xml b/src/it/projects/effective-site/pom.xml index 27685e1f..64258f84 100644 --- a/src/it/projects/effective-site/pom.xml +++ b/src/it/projects/effective-site/pom.xml @@ -27,7 +27,7 @@ under the License. org.apache.maven.plugins maven-plugins - 31 + 39 org.apache.maven.plugins.site.its diff --git a/src/it/projects/site-sd-lang/src/site/site.xml b/src/it/projects/site-sd-lang/src/site/site.xml index d8327fc5..8dd66a1e 100644 --- a/src/it/projects/site-sd-lang/src/site/site.xml +++ b/src/it/projects/site-sd-lang/src/site/site.xml @@ -25,19 +25,19 @@ under the License. maven-fluido-skin ${fluidoSkinVersion} - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/it/projects/site-sd-lang/src/site/site_fr.xml b/src/it/projects/site-sd-lang/src/site/site_fr.xml index e7233270..f24d2b3e 100644 --- a/src/it/projects/site-sd-lang/src/site/site_fr.xml +++ b/src/it/projects/site-sd-lang/src/site/site_fr.xml @@ -26,19 +26,19 @@ under the License. ${fluidoSkinVersion} - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + diff --git a/src/main/java/org/apache/maven/plugins/site/AbstractSiteMojo.java b/src/main/java/org/apache/maven/plugins/site/AbstractSiteMojo.java index 72f91dba..6f6c153b 100644 --- a/src/main/java/org/apache/maven/plugins/site/AbstractSiteMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/AbstractSiteMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site; + +import java.util.List; +import java.util.Locale; import org.apache.maven.artifact.repository.ArtifactRepository; import org.apache.maven.doxia.tools.SiteTool; @@ -28,24 +30,19 @@ import org.apache.maven.rtinfo.RuntimeInformation; import org.codehaus.plexus.i18n.I18N; -import java.util.List; -import java.util.Locale; - /** * Base class for site mojos. * * @author Brett Porter */ -public abstract class AbstractSiteMojo - extends AbstractMojo -{ +public abstract class AbstractSiteMojo extends AbstractMojo { /** * A comma separated list of locales to render. The first valid token will be the default Locale * for this site. * * @since 2.3 */ - @Parameter( property = "locales", defaultValue = "default" ) + @Parameter(property = "locales", defaultValue = "default") private String locales; /** @@ -53,7 +50,7 @@ public abstract class AbstractSiteMojo * * @since 3.0 */ - @Parameter( property = "maven.site.skip", defaultValue = "false" ) + @Parameter(property = "maven.site.skip", defaultValue = "false") protected boolean skip; /** @@ -71,32 +68,30 @@ public abstract class AbstractSiteMojo /** * The Maven project. */ - @Parameter( defaultValue = "${project}", readonly = true ) + @Parameter(defaultValue = "${project}", readonly = true) protected MavenProject project; /** * The local repository. */ - @Parameter( defaultValue = "${localRepository}", readonly = true ) + @Parameter(defaultValue = "${localRepository}", readonly = true) protected ArtifactRepository localRepository; /** * The reactor projects. */ - @Parameter( defaultValue = "${reactorProjects}", required = true, readonly = true ) + @Parameter(defaultValue = "${reactorProjects}", required = true, readonly = true) protected List reactorProjects; @Component protected RuntimeInformation runtimeInformation; @Deprecated - protected String getMavenVersion() - { + protected String getMavenVersion() { return runtimeInformation.getMavenVersion(); } - protected List getLocales() - { - return siteTool.getSiteLocales( locales ); + protected List getLocales() { + return siteTool.getSiteLocales(locales); } } diff --git a/src/main/java/org/apache/maven/plugins/site/deploy/AbstractDeployMojo.java b/src/main/java/org/apache/maven/plugins/site/deploy/AbstractDeployMojo.java index 50647564..b7019d54 100644 --- a/src/main/java/org/apache/maven/plugins/site/deploy/AbstractDeployMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/deploy/AbstractDeployMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,14 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.List; +import java.util.Locale; +import java.util.Set; import org.apache.maven.artifact.manager.WagonManager; import org.apache.maven.doxia.site.decoration.inheritance.URIPathDescriptor; @@ -56,13 +62,6 @@ import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable; import org.codehaus.plexus.util.StringUtils; -import java.io.File; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.List; -import java.util.Locale; -import java.util.Set; - /** * Abstract base class for deploy mojos. * Since 2.3 this includes {@link SiteStageMojo} and {@link SiteStageDeployMojo}. @@ -70,16 +69,13 @@ * @author ltheussl * @since 2.3 */ -public abstract class AbstractDeployMojo - extends AbstractSiteMojo - implements Contextualizable -{ +public abstract class AbstractDeployMojo extends AbstractSiteMojo implements Contextualizable { /** * Directory containing the generated project sites and report distributions. * * @since 2.3 */ - @Parameter( alias = "outputDirectory", defaultValue = "${project.reporting.outputDirectory}", required = true ) + @Parameter(alias = "outputDirectory", defaultValue = "${project.reporting.outputDirectory}", required = true) private File inputDirectory; /** @@ -88,7 +84,7 @@ public abstract class AbstractDeployMojo * * @since 2.1 */ - @Parameter( property = "maven.site.chmod", defaultValue = "true" ) + @Parameter(property = "maven.site.chmod", defaultValue = "true") private boolean chmod; /** @@ -97,7 +93,7 @@ public abstract class AbstractDeployMojo * * @since 2.1 */ - @Parameter( property = "maven.site.chmod.mode", defaultValue = "g+w,a+rX" ) + @Parameter(property = "maven.site.chmod.mode", defaultValue = "g+w,a+rX") private String chmodMode; /** @@ -106,7 +102,7 @@ public abstract class AbstractDeployMojo * * @since 2.1 */ - @Parameter( property = "maven.site.chmod.options", defaultValue = "-Rf" ) + @Parameter(property = "maven.site.chmod.options", defaultValue = "-Rf") private String chmodOptions; /** @@ -114,7 +110,7 @@ public abstract class AbstractDeployMojo * * @since 3.0 */ - @Parameter( property = "maven.site.deploy.skip", defaultValue = "false" ) + @Parameter(property = "maven.site.deploy.skip", defaultValue = "false") private boolean skipDeploy; /** @@ -125,13 +121,13 @@ public abstract class AbstractDeployMojo /** * The current user system settings for use in Maven. */ - @Parameter( defaultValue = "${settings}", readonly = true ) + @Parameter(defaultValue = "${settings}", readonly = true) private Settings settings; /** * @since 3.0-beta-2 */ - @Parameter( defaultValue = "${session}", readonly = true ) + @Parameter(defaultValue = "${session}", readonly = true) protected MavenSession mavenSession; private String topDistributionManagementSiteUrl; @@ -143,22 +139,18 @@ public abstract class AbstractDeployMojo /** * {@inheritDoc} */ - public void execute() - throws MojoExecutionException - { - if ( skip && isDeploy() ) - { - getLog().info( "maven.site.skip = true: Skipping site deployment" ); + public void execute() throws MojoExecutionException { + if (skip && isDeploy()) { + getLog().info("maven.site.skip = true: Skipping site deployment"); return; } - if ( skipDeploy && isDeploy() ) - { - getLog().info( "maven.site.deploy.skip = true: Skipping site deployment" ); + if (skipDeploy && isDeploy()) { + getLog().info("maven.site.deploy.skip = true: Skipping site deployment"); return; } - deployTo( new Repository( getDeploySite().getId(), getDeploySite().getUrl() ) ); + deployTo(new Repository(getDeploySite().getId(), getDeploySite().getUrl())); } /** @@ -168,19 +160,14 @@ public void execute() * @return if url already ends with '/' it is returned unchanged. * Otherwise a '/' character is appended. */ - protected static String appendSlash( final String url ) - { - if ( url.endsWith( "/" ) ) - { + protected static String appendSlash(final String url) { + if (url.endsWith("/")) { return url; - } - else - { + } else { return url + "/"; } } - /** * Detect if the mojo is staging or deploying. * @@ -197,23 +184,18 @@ protected static String appendSlash( final String url ) * @throws MojoExecutionException in case of issue * @see #determineTopDistributionManagementSiteUrl() */ - protected String getTopDistributionManagementSiteUrl() - throws MojoExecutionException - { - if ( topDistributionManagementSiteUrl == null ) - { + protected String getTopDistributionManagementSiteUrl() throws MojoExecutionException { + if (topDistributionManagementSiteUrl == null) { topDistributionManagementSiteUrl = determineTopDistributionManagementSiteUrl(); - if ( !isDeploy() ) - { - getLog().debug( "distributionManagement.site.url relative path: " + getDeployModuleDirectory() ); + if (!isDeploy()) { + getLog().debug("distributionManagement.site.url relative path: " + getDeployModuleDirectory()); } } return topDistributionManagementSiteUrl; } - protected abstract String determineTopDistributionManagementSiteUrl() - throws MojoExecutionException; + protected abstract String determineTopDistributionManagementSiteUrl() throws MojoExecutionException; /** * Get the site used for deployment, with its id to look up credential settings and the target URL for the deploy. @@ -224,18 +206,14 @@ protected abstract String determineTopDistributionManagementSiteUrl() * @throws MojoExecutionException in case of issue * @see #determineDeploySite() */ - protected Site getDeploySite() - throws MojoExecutionException - { - if ( deploySite == null ) - { + protected Site getDeploySite() throws MojoExecutionException { + if (deploySite == null) { deploySite = determineDeploySite(); } return deploySite; } - protected abstract Site determineDeploySite() - throws MojoExecutionException; + protected abstract Site determineDeploySite() throws MojoExecutionException; /** * Find the relative path between the distribution URLs of the top site and the current project. @@ -243,21 +221,19 @@ protected abstract Site determineDeploySite() * @return the relative path or "./" if the two URLs are the same. * @throws MojoExecutionException in case of issue */ - protected String getDeployModuleDirectory() - throws MojoExecutionException - { - String to = getSite( project ).getUrl(); + protected String getDeployModuleDirectory() throws MojoExecutionException { + String to = getSite(project).getUrl(); - getLog().debug( "Mapping url source calculation: " ); + getLog().debug("Mapping url source calculation: "); String from = getTopDistributionManagementSiteUrl(); - String relative = siteTool.getRelativePath( to, from ); + String relative = siteTool.getRelativePath(to, from); // SiteTool.getRelativePath() uses File.separatorChar, // so we need to convert '\' to '/' in order for the URL to be valid for Windows users - relative = relative.replace( '\\', '/' ); + relative = relative.replace('\\', '/'); - return ( "".equals( relative ) ) ? "./" : relative; + return ("".equals(relative)) ? "./" : relative; } /** @@ -269,194 +245,154 @@ protected String getDeployModuleDirectory() * {@link Repository#getUrl() scm url} to deploy to. * @throws MojoExecutionException if the deploy fails. */ - private void deployTo( final Repository repository ) - throws MojoExecutionException - { - if ( !inputDirectory.exists() ) - { - throw new MojoExecutionException( "The site does not exist, please run site:site first" ); + private void deployTo(final Repository repository) throws MojoExecutionException { + if (!inputDirectory.exists()) { + throw new MojoExecutionException("The site does not exist, please run site:site first"); } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "Deploying to '" + repository.getUrl() + "',\n Using credentials from server id '" - + repository.getId() + "'" ); + if (getLog().isDebugEnabled()) { + getLog().debug("Deploying to '" + repository.getUrl() + "',\n Using credentials from server id '" + + repository.getId() + "'"); } - deploy( inputDirectory, repository ); + deploy(inputDirectory, repository); } - private void deploy( final File directory, final Repository repository ) - throws MojoExecutionException - { + private void deploy(final File directory, final Repository repository) throws MojoExecutionException { // TODO: work on moving this into the deployer like the other deploy methods - final Wagon wagon = getWagon( repository, wagonManager ); + final Wagon wagon = getWagon(repository, wagonManager); - try - { - SettingsDecrypter settingsDecrypter = container.lookup( SettingsDecrypter.class ); + try { + SettingsDecrypter settingsDecrypter = container.lookup(SettingsDecrypter.class); - ProxyInfo proxyInfo = getProxy( repository, settingsDecrypter ); + ProxyInfo proxyInfo = getProxy(repository, settingsDecrypter); - push( directory, repository, wagon, proxyInfo, getLocales(), getDeployModuleDirectory() ); + push(directory, repository, wagon, proxyInfo, getLocales(), getDeployModuleDirectory()); - if ( chmod ) - { - chmod( wagon, repository, chmodOptions, chmodMode ); + if (chmod) { + chmod(wagon, repository, chmodOptions, chmodMode); } - } - catch ( ComponentLookupException cle ) - { - throw new MojoExecutionException( "Unable to lookup SettingsDecrypter: " + cle.getMessage(), cle ); - } - finally - { - try - { + } catch (ComponentLookupException cle) { + throw new MojoExecutionException("Unable to lookup SettingsDecrypter: " + cle.getMessage(), cle); + } finally { + try { wagon.disconnect(); - } - catch ( ConnectionException e ) - { - getLog().error( "Error disconnecting wagon - ignored", e ); + } catch (ConnectionException e) { + getLog().error("Error disconnecting wagon - ignored", e); } } } - private Wagon getWagon( final Repository repository, final WagonManager manager ) - throws MojoExecutionException - { + private Wagon getWagon(final Repository repository, final WagonManager manager) throws MojoExecutionException { final Wagon wagon; - try - { - wagon = manager.getWagon( repository ); - } - catch ( UnsupportedProtocolException e ) - { + try { + wagon = manager.getWagon(repository); + } catch (UnsupportedProtocolException e) { String shortMessage = "Unsupported protocol: '" + repository.getProtocol() + "' for site deployment to " - + "distributionManagement.site.url=" + repository.getUrl() + "."; + + "distributionManagement.site.url=" + repository.getUrl() + "."; String longMessage = - "\n" + shortMessage + "\n" + "Currently supported protocols are: " + getSupportedProtocols() + ".\n" - + " Protocols may be added through wagon providers.\n" + " For more information, see " - + "https://maven.apache.org/plugins/maven-site-plugin/examples/adding-deploy-protocol.html"; + "\n" + shortMessage + "\n" + "Currently supported protocols are: " + getSupportedProtocols() + ".\n" + + " Protocols may be added through wagon providers.\n" + " For more information, see " + + "https://maven.apache.org/plugins/maven-site-plugin/examples/adding-deploy-protocol.html"; - getLog().error( longMessage ); + getLog().error(longMessage); - throw new MojoExecutionException( shortMessage ); - } - catch ( TransferFailedException e ) - { - throw new MojoExecutionException( "Unable to configure Wagon: '" + repository.getProtocol() + "'", e ); + throw new MojoExecutionException(shortMessage); + } catch (TransferFailedException e) { + throw new MojoExecutionException("Unable to configure Wagon: '" + repository.getProtocol() + "'", e); } - if ( !wagon.supportsDirectoryCopy() ) - { + if (!wagon.supportsDirectoryCopy()) { throw new MojoExecutionException( - "Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying" ); + "Wagon protocol '" + repository.getProtocol() + "' doesn't support directory copying"); } return wagon; } - private String getSupportedProtocols() - { - try - { - Set protocols = container.lookupMap( Wagon.class ).keySet(); + private String getSupportedProtocols() { + try { + Set protocols = container.lookupMap(Wagon.class).keySet(); - return StringUtils.join( protocols.iterator(), ", " ); - } - catch ( ComponentLookupException e ) - { + return StringUtils.join(protocols.iterator(), ", "); + } catch (ComponentLookupException e) { // in the unexpected case there is a problem when instantiating a wagon provider - getLog().error( e ); + getLog().error(e); } return ""; } - private void push( final File inputDirectory, final Repository repository, final Wagon wagon, - final ProxyInfo proxyInfo, final List localesList, final String relativeDir ) - throws MojoExecutionException - { - AuthenticationInfo authenticationInfo = wagonManager.getAuthenticationInfo( repository.getId() ); - getLog().debug( "authenticationInfo with id '" + repository.getId() + "': " - + ( ( authenticationInfo == null ) ? "-" : authenticationInfo.getUserName() ) ); - - try - { - if ( getLog().isDebugEnabled() ) - { + private void push( + final File inputDirectory, + final Repository repository, + final Wagon wagon, + final ProxyInfo proxyInfo, + final List localesList, + final String relativeDir) + throws MojoExecutionException { + AuthenticationInfo authenticationInfo = wagonManager.getAuthenticationInfo(repository.getId()); + getLog().debug("authenticationInfo with id '" + repository.getId() + "': " + + ((authenticationInfo == null) ? "-" : authenticationInfo.getUserName())); + + try { + if (getLog().isDebugEnabled()) { Debug debug = new Debug(); - wagon.addSessionListener( debug ); + wagon.addSessionListener(debug); - wagon.addTransferListener( debug ); + wagon.addTransferListener(debug); } - if ( proxyInfo != null ) - { - getLog().debug( "connect with proxyInfo" ); - wagon.connect( repository, authenticationInfo, proxyInfo ); - } - else if ( proxyInfo == null && authenticationInfo != null ) - { - getLog().debug( "connect with authenticationInfo and without proxyInfo" ); - wagon.connect( repository, authenticationInfo ); - } - else - { - getLog().debug( "connect without authenticationInfo and without proxyInfo" ); - wagon.connect( repository ); + if (proxyInfo != null) { + getLog().debug("connect with proxyInfo"); + wagon.connect(repository, authenticationInfo, proxyInfo); + } else if (proxyInfo == null && authenticationInfo != null) { + getLog().debug("connect with authenticationInfo and without proxyInfo"); + wagon.connect(repository, authenticationInfo); + } else { + getLog().debug("connect without authenticationInfo and without proxyInfo"); + wagon.connect(repository); } - getLog().info( "Pushing " + inputDirectory ); + getLog().info("Pushing " + inputDirectory); // Default is first in the list - final Locale defaultLocale = localesList.get( 0 ); + final Locale defaultLocale = localesList.get(0); - for ( Locale locale : localesList ) - { - if ( locale.equals( defaultLocale ) ) - { + for (Locale locale : localesList) { + if (locale.equals(defaultLocale)) { // TODO: this also uploads the non-default locales, // is there a way to exclude directories in wagon? - getLog().info( " >>> to " + appendSlash( repository.getUrl() ) + relativeDir ); + getLog().info(" >>> to " + appendSlash(repository.getUrl()) + relativeDir); - wagon.putDirectory( inputDirectory, relativeDir ); - } - else - { - getLog().info( " >>> to " + appendSlash( repository.getUrl() ) + locale + "/" - + relativeDir ); + wagon.putDirectory(inputDirectory, relativeDir); + } else { + getLog().info(" >>> to " + appendSlash(repository.getUrl()) + locale + "/" + relativeDir); - wagon.putDirectory( new File( inputDirectory, locale.toString() ), - locale + "/" + relativeDir ); + wagon.putDirectory(new File(inputDirectory, locale.toString()), locale + "/" + relativeDir); } } - } - catch ( ResourceDoesNotExistException | TransferFailedException | AuthorizationException | ConnectionException - | AuthenticationException e ) - { - throw new MojoExecutionException( "Error uploading site", e ); + } catch (ResourceDoesNotExistException + | TransferFailedException + | AuthorizationException + | ConnectionException + | AuthenticationException e) { + throw new MojoExecutionException("Error uploading site", e); } } - private static void chmod( final Wagon wagon, final Repository repository, final String chmodOptions, - final String chmodMode ) - throws MojoExecutionException - { - try - { - if ( wagon instanceof CommandExecutor ) - { + private static void chmod( + final Wagon wagon, final Repository repository, final String chmodOptions, final String chmodMode) + throws MojoExecutionException { + try { + if (wagon instanceof CommandExecutor) { CommandExecutor exec = (CommandExecutor) wagon; - exec.executeCommand( "chmod " + chmodOptions + " " + chmodMode + " " + repository.getBasedir() ); + exec.executeCommand("chmod " + chmodOptions + " " + chmodMode + " " + repository.getBasedir()); } // else ? silently ignore, FileWagon is not a CommandExecutor! - } - catch ( CommandExecutionException e ) - { - throw new MojoExecutionException( "Error uploading site", e ); + } catch (CommandExecutionException e) { + throw new MojoExecutionException("Error uploading site", e); } } @@ -479,46 +415,41 @@ private static void chmod( final Wagon wagon, final Repository repository, final * @param wagonManager the WagonManager used to connect to the Repository * @return a ProxyInfo object instantiated or null if no matching proxy is found */ - public static ProxyInfo getProxyInfo( Repository repository, WagonManager wagonManager ) - { - ProxyInfo proxyInfo = wagonManager.getProxy( repository.getProtocol() ); + public static ProxyInfo getProxyInfo(Repository repository, WagonManager wagonManager) { + ProxyInfo proxyInfo = wagonManager.getProxy(repository.getProtocol()); - if ( proxyInfo == null ) - { + if (proxyInfo == null) { return null; } String host = repository.getHost(); String nonProxyHostsAsString = proxyInfo.getNonProxyHosts(); - for ( String nonProxyHost : StringUtils.split( nonProxyHostsAsString, ",;|" ) ) - { - if ( StringUtils.contains( nonProxyHost, "*" ) ) - { + for (String nonProxyHost : StringUtils.split(nonProxyHostsAsString, ",;|")) { + if (StringUtils.contains(nonProxyHost, "*")) { // Handle wildcard at the end, beginning or middle of the nonProxyHost - final int pos = nonProxyHost.indexOf( '*' ); - String nonProxyHostPrefix = nonProxyHost.substring( 0, pos ); - String nonProxyHostSuffix = nonProxyHost.substring( pos + 1 ); + final int pos = nonProxyHost.indexOf('*'); + String nonProxyHostPrefix = nonProxyHost.substring(0, pos); + String nonProxyHostSuffix = nonProxyHost.substring(pos + 1); // prefix* - if ( StringUtils.isNotEmpty( nonProxyHostPrefix ) && host.startsWith( nonProxyHostPrefix ) - && StringUtils.isEmpty( nonProxyHostSuffix ) ) - { + if (StringUtils.isNotEmpty(nonProxyHostPrefix) + && host.startsWith(nonProxyHostPrefix) + && StringUtils.isEmpty(nonProxyHostSuffix)) { return null; } // *suffix - if ( StringUtils.isEmpty( nonProxyHostPrefix ) && StringUtils.isNotEmpty( nonProxyHostSuffix ) - && host.endsWith( nonProxyHostSuffix ) ) - { + if (StringUtils.isEmpty(nonProxyHostPrefix) + && StringUtils.isNotEmpty(nonProxyHostSuffix) + && host.endsWith(nonProxyHostSuffix)) { return null; } // prefix*suffix - if ( StringUtils.isNotEmpty( nonProxyHostPrefix ) && host.startsWith( nonProxyHostPrefix ) - && StringUtils.isNotEmpty( nonProxyHostSuffix ) && host.endsWith( nonProxyHostSuffix ) ) - { + if (StringUtils.isNotEmpty(nonProxyHostPrefix) + && host.startsWith(nonProxyHostPrefix) + && StringUtils.isNotEmpty(nonProxyHostSuffix) + && host.endsWith(nonProxyHostSuffix)) { return null; } - } - else if ( host.equals( nonProxyHost ) ) - { + } else if (host.equals(nonProxyHost)) { return null; } } @@ -532,72 +463,60 @@ else if ( host.equals( nonProxyHost ) ) * @param settingsDecrypter settings password decrypter * @return a ProxyInfo object instantiated or null if no matching proxy is found. */ - private ProxyInfo getProxy( Repository repository, SettingsDecrypter settingsDecrypter ) - { + private ProxyInfo getProxy(Repository repository, SettingsDecrypter settingsDecrypter) { String protocol = repository.getProtocol(); String url = repository.getUrl(); - getLog().debug( "repository protocol " + protocol ); + getLog().debug("repository protocol " + protocol); String originalProtocol = protocol; // olamy: hackish here protocol (wagon hint in fact !) is dav // but the real protocol (transport layer) is http(s) // and it's the one use in wagon to find the proxy arghhh // so we will check both - if ( StringUtils.equalsIgnoreCase( "dav", protocol ) && url.startsWith( "dav:" ) ) - { - url = url.substring( 4 ); - if ( url.startsWith( "http" ) ) - { - try - { - URL urlSite = new URL( url ); + if (StringUtils.equalsIgnoreCase("dav", protocol) && url.startsWith("dav:")) { + url = url.substring(4); + if (url.startsWith("http")) { + try { + URL urlSite = new URL(url); protocol = urlSite.getProtocol(); - getLog().debug( "found dav protocol so transform to real transport protocol " + protocol ); - } - catch ( MalformedURLException e ) - { - getLog().warn( "fail to build URL with " + url ); + getLog().debug("found dav protocol so transform to real transport protocol " + protocol); + } catch (MalformedURLException e) { + getLog().warn("fail to build URL with " + url); } } - } - else - { - getLog().debug( "getProxy 'protocol': " + protocol ); + } else { + getLog().debug("getProxy 'protocol': " + protocol); } - if ( mavenSession != null && protocol != null ) - { + if (mavenSession != null && protocol != null) { MavenExecutionRequest request = mavenSession.getRequest(); - if ( request != null ) - { + if (request != null) { List proxies = request.getProxies(); - if ( proxies != null ) - { - for ( Proxy proxy : proxies ) - { - if ( proxy.isActive() && ( protocol.equalsIgnoreCase( proxy.getProtocol() ) - || originalProtocol.equalsIgnoreCase( proxy.getProtocol() ) ) ) - { + if (proxies != null) { + for (Proxy proxy : proxies) { + if (proxy.isActive() + && (protocol.equalsIgnoreCase(proxy.getProtocol()) + || originalProtocol.equalsIgnoreCase(proxy.getProtocol()))) { SettingsDecryptionResult result = - settingsDecrypter.decrypt( new DefaultSettingsDecryptionRequest( proxy ) ); + settingsDecrypter.decrypt(new DefaultSettingsDecryptionRequest(proxy)); proxy = result.getProxy(); ProxyInfo proxyInfo = new ProxyInfo(); - proxyInfo.setHost( proxy.getHost() ); + proxyInfo.setHost(proxy.getHost()); // so hackish for wagon the protocol is https for site dav: // dav:https://dav.codehaus.org/mojo/ - proxyInfo.setType( protocol ); //proxy.getProtocol() ); - proxyInfo.setPort( proxy.getPort() ); - proxyInfo.setNonProxyHosts( proxy.getNonProxyHosts() ); - proxyInfo.setUserName( proxy.getUsername() ); - proxyInfo.setPassword( proxy.getPassword() ); + proxyInfo.setType(protocol); // proxy.getProtocol() ); + proxyInfo.setPort(proxy.getPort()); + proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts()); + proxyInfo.setUserName(proxy.getUsername()); + proxyInfo.setPassword(proxy.getPassword()); - getLog().debug( "found proxyInfo " - + ( "host:port " + proxyInfo.getHost() + ":" + proxyInfo.getPort() - + ", " + proxyInfo.getUserName() ) ); + getLog().debug("found proxyInfo " + + ("host:port " + proxyInfo.getHost() + ":" + proxyInfo.getPort() + ", " + + proxyInfo.getUserName())); return proxyInfo; } @@ -605,17 +524,15 @@ private ProxyInfo getProxy( Repository repository, SettingsDecrypter settingsDec } } } - getLog().debug( "getProxy 'protocol': " + protocol + " no ProxyInfo found" ); + getLog().debug("getProxy 'protocol': " + protocol + " no ProxyInfo found"); return null; } /** * {@inheritDoc} */ - public void contextualize( Context context ) - throws ContextException - { - container = (PlexusContainer) context.get( PlexusConstants.PLEXUS_KEY ); + public void contextualize(Context context) throws ContextException { + container = (PlexusContainer) context.get(PlexusConstants.PLEXUS_KEY); } /** @@ -626,37 +543,31 @@ public void contextualize( Context context ) * Also site.getUrl() and site.getId() are guaranteed to be not null. * @throws MojoExecutionException if any of the site info is missing. */ - protected static Site getSite( final MavenProject project ) - throws MojoExecutionException - { + protected static Site getSite(final MavenProject project) throws MojoExecutionException { final DistributionManagement distributionManagement = project.getDistributionManagement(); - if ( distributionManagement == null ) - { - throw new MojoExecutionException( "Missing distribution management in project " + getFullName( project ) ); + if (distributionManagement == null) { + throw new MojoExecutionException("Missing distribution management in project " + getFullName(project)); } final Site site = distributionManagement.getSite(); - if ( site == null ) - { - throw new MojoExecutionException( "Missing site information in the distribution management of the project " - + getFullName( project ) ); + if (site == null) { + throw new MojoExecutionException( + "Missing site information in the distribution management of the project " + getFullName(project)); } - if ( site.getUrl() == null || site.getId() == null ) - { - throw new MojoExecutionException( "Missing site data: specify url and id for project " - + getFullName( project ) ); + if (site.getUrl() == null || site.getId() == null) { + throw new MojoExecutionException( + "Missing site data: specify url and id for project " + getFullName(project)); } return site; } - private static String getFullName( MavenProject project ) - { + private static String getFullName(MavenProject project) { return project.getName() + " (" + project.getGroupId() + ':' + project.getArtifactId() + ':' - + project.getVersion() + ')'; + + project.getVersion() + ')'; } /** @@ -671,36 +582,29 @@ private static String getFullName( MavenProject project ) * @throws MojoExecutionException if no site info is found in the tree. * @see URIPathDescriptor#sameSite(java.net.URI) */ - protected MavenProject getTopLevelProject( MavenProject project ) - throws MojoExecutionException - { - Site site = getSite( project ); + protected MavenProject getTopLevelProject(MavenProject project) throws MojoExecutionException { + Site site = getSite(project); MavenProject parent = project; - while ( parent.getParent() != null ) - { + while (parent.getParent() != null) { MavenProject oldProject = parent; // MSITE-585, MNG-1943 - parent = siteTool.getParentProject( parent, reactorProjects, localRepository ); + parent = siteTool.getParentProject(parent, reactorProjects, localRepository); Site oldSite = site; - try - { - site = getSite( parent ); - } - catch ( MojoExecutionException e ) - { + try { + site = getSite(parent); + } catch (MojoExecutionException e) { return oldProject; } // MSITE-600 - URIPathDescriptor siteURI = new URIPathDescriptor( URIEncoder.encodeURI( site.getUrl() ), "" ); - URIPathDescriptor oldSiteURI = new URIPathDescriptor( URIEncoder.encodeURI( oldSite.getUrl() ), "" ); + URIPathDescriptor siteURI = new URIPathDescriptor(URIEncoder.encodeURI(site.getUrl()), ""); + URIPathDescriptor oldSiteURI = new URIPathDescriptor(URIEncoder.encodeURI(oldSite.getUrl()), ""); - if ( !siteURI.sameSite( oldSiteURI.getBaseURI() ) ) - { + if (!siteURI.sameSite(oldSiteURI.getBaseURI())) { return oldProject; } } @@ -708,34 +612,30 @@ protected MavenProject getTopLevelProject( MavenProject project ) return parent; } - private static class URIEncoder - { + private static class URIEncoder { private static final String MARK = "-_.!~*'()"; private static final String RESERVED = ";/?:@&=+$,"; - private static String encodeURI( final String uriString ) - { + private static String encodeURI(final String uriString) { final char[] chars = uriString.toCharArray(); - final StringBuilder uri = new StringBuilder( chars.length ); + final StringBuilder uri = new StringBuilder(chars.length); // MSITE-750: wagon dav: pseudo-protocol - if ( uriString.startsWith( "dav:http" ) ) - { + if (uriString.startsWith("dav:http")) { // transform dav:http to dav-http chars[3] = '-'; } - for ( char c : chars ) - { - if ( ( c >= '0' && c <= '9' ) || ( c >= 'a' && c <= 'z' ) || ( c >= 'A' && c <= 'Z' ) - || MARK.indexOf( c ) != -1 || RESERVED.indexOf( c ) != -1 ) - { - uri.append( c ); - } - else - { - uri.append( '%' ); - uri.append( Integer.toHexString( (int) c ) ); + for (char c : chars) { + if ((c >= '0' && c <= '9') + || (c >= 'a' && c <= 'z') + || (c >= 'A' && c <= 'Z') + || MARK.indexOf(c) != -1 + || RESERVED.indexOf(c) != -1) { + uri.append(c); + } else { + uri.append('%'); + uri.append(Integer.toHexString((int) c)); } } return uri.toString(); diff --git a/src/main/java/org/apache/maven/plugins/site/deploy/AbstractStagingMojo.java b/src/main/java/org/apache/maven/plugins/site/deploy/AbstractStagingMojo.java index 7070b530..565f19aa 100644 --- a/src/main/java/org/apache/maven/plugins/site/deploy/AbstractStagingMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/deploy/AbstractStagingMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * 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.site.deploy; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.Parameter; @@ -30,16 +29,14 @@ * @author hboutemy * @since 3.3 */ -public abstract class AbstractStagingMojo - extends AbstractDeployMojo -{ +public abstract class AbstractStagingMojo extends AbstractDeployMojo { /** * Top distribution management site url, for manual configuration when auto-calculated value * doesn't match expectations. Relative module directory will be calculated from this url. * * @since 3.3 */ - @Parameter( property = "topSiteURL" ) + @Parameter(property = "topSiteURL") protected String topSiteURL; /** @@ -53,22 +50,19 @@ public abstract class AbstractStagingMojo * expectations, topSiteURL can be configured: it will be used instead. */ @Override - protected String determineTopDistributionManagementSiteUrl() - throws MojoExecutionException - { - if ( StringUtils.isEmpty( topSiteURL ) ) - { - MavenProject topProject = getTopLevelProject( project ); - String url = getSite( topProject ).getUrl(); + protected String determineTopDistributionManagementSiteUrl() throws MojoExecutionException { + if (StringUtils.isEmpty(topSiteURL)) { + MavenProject topProject = getTopLevelProject(project); + String url = getSite(topProject).getUrl(); - getLog().debug( "staging top distributionManagement.site.url found in " + topProject.getId() - + " with value: " + url ); + getLog().debug("staging top distributionManagement.site.url found in " + topProject.getId() + + " with value: " + url); return url; } - getLog().debug( "staging top distributionManagement.site.url configured with topSiteURL parameter: " - + topSiteURL ); + getLog().debug("staging top distributionManagement.site.url configured with topSiteURL parameter: " + + topSiteURL); return topSiteURL; } } diff --git a/src/main/java/org/apache/maven/plugins/site/deploy/SiteDeployMojo.java b/src/main/java/org/apache/maven/plugins/site/deploy/SiteDeployMojo.java index 93dca930..7e82fed4 100644 --- a/src/main/java/org/apache/maven/plugins/site/deploy/SiteDeployMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/deploy/SiteDeployMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * 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.site.deploy; import org.apache.maven.model.Site; import org.apache.maven.plugin.MojoExecutionException; @@ -37,13 +36,10 @@ * * @since 2.0 */ -@Mojo( name = "deploy" ) -public class SiteDeployMojo - extends AbstractDeployMojo -{ +@Mojo(name = "deploy") +public class SiteDeployMojo extends AbstractDeployMojo { @Override - protected boolean isDeploy() - { + protected boolean isDeploy() { return true; } @@ -51,9 +47,7 @@ protected boolean isDeploy() * Deploy distribution site url is directly the current project value. */ @Override - protected String determineTopDistributionManagementSiteUrl() - throws MojoExecutionException - { + protected String determineTopDistributionManagementSiteUrl() throws MojoExecutionException { return getDeploySite().getUrl(); } @@ -61,9 +55,7 @@ protected String determineTopDistributionManagementSiteUrl() * Deploy directly to the current project's distribution management site. */ @Override - protected Site determineDeploySite() - throws MojoExecutionException - { - return getSite( getTopLevelProject( project ) ); + protected Site determineDeploySite() throws MojoExecutionException { + return getSite(getTopLevelProject(project)); } } diff --git a/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageDeployMojo.java b/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageDeployMojo.java index e31c7513..13cd5e46 100644 --- a/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageDeployMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageDeployMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,8 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; import java.util.Map; + import org.apache.maven.model.Build; import org.apache.maven.model.Plugin; import org.apache.maven.model.PluginManagement; @@ -41,10 +41,8 @@ * * @since 2.0 */ -@Mojo( name = "stage-deploy", requiresDependencyResolution = ResolutionScope.TEST ) -public class SiteStageDeployMojo - extends AbstractStagingMojo -{ +@Mojo(name = "stage-deploy", requiresDependencyResolution = ResolutionScope.TEST) +public class SiteStageDeployMojo extends AbstractStagingMojo { /** * The staged site will be deployed to this URL. *

@@ -62,7 +60,7 @@ public class SiteStageDeployMojo * * @since 2.3 */ - @Parameter( property = "stagingSiteURL" ) + @Parameter(property = "stagingSiteURL") private String stagingSiteURL; /** @@ -77,12 +75,11 @@ public class SiteStageDeployMojo * * @since 2.0.1 */ - @Parameter( property = "stagingRepositoryId" ) + @Parameter(property = "stagingRepositoryId") private String stagingRepositoryId; @Override - protected boolean isDeploy() - { + protected boolean isDeploy() { return true; } @@ -91,22 +88,18 @@ protected boolean isDeploy() * will be used. */ @Override - protected String determineTopDistributionManagementSiteUrl() - throws MojoExecutionException - { - if ( StringUtils.isNotEmpty( topSiteURL ) ) - { - getLog().debug( "stage-deploy top distributionManagement.site.url configured with topSiteURL parameter: " - + topSiteURL ); + protected String determineTopDistributionManagementSiteUrl() throws MojoExecutionException { + if (StringUtils.isNotEmpty(topSiteURL)) { + getLog().debug("stage-deploy top distributionManagement.site.url configured with topSiteURL parameter: " + + topSiteURL); return topSiteURL; } - if ( StringUtils.isNotEmpty( stagingSiteURL ) ) - { + if (StringUtils.isNotEmpty(stagingSiteURL)) { // We need to calculate the first project that supplied same stagingSiteURL MavenProject topProject = getTopMostParentWithSameStagingSiteURL(); - String url = getSite( topProject ).getUrl(); - getLog().debug( "stage-deploy top stagingSiteURL found in " + topProject.getId() + " with value: " + url ); + String url = getSite(topProject).getUrl(); + getLog().debug("stage-deploy top stagingSiteURL found in " + topProject.getId() + " with value: " + url); return url; } @@ -114,18 +107,16 @@ protected String determineTopDistributionManagementSiteUrl() } @Override - protected Site determineDeploySite() - throws MojoExecutionException - { + protected Site determineDeploySite() throws MojoExecutionException { Site top = new Site(); - top.setId( stagingRepoId() ); - getLog().info( "Using this server ID for stage deploy: " + top.getId() ); + top.setId(stagingRepoId()); + getLog().info("Using this server ID for stage deploy: " + top.getId()); String stagingURL = determineStageDeploySiteURL(); - getLog().info( "Using this base URL for stage deploy: " + stagingURL ); + getLog().info("Using this base URL for stage deploy: " + stagingURL); - top.setUrl( stagingURL ); + top.setUrl(stagingURL); return top; } @@ -141,16 +132,14 @@ protected Site determineDeploySite() * * @return the site for the top most project that has a stagingSiteURL. Not null. */ - private MavenProject getTopMostParentWithSameStagingSiteURL() - { + private MavenProject getTopMostParentWithSameStagingSiteURL() { MavenProject current = project; MavenProject parent; // CHECKSTYLE_OFF: InnerAssignment - while ( // MSITE-585, MNG-1943 - ( parent = siteTool.getParentProject( current, reactorProjects, localRepository ) ) != null - && stagingSiteURL.equals( getStagingSiteURL( parent ) ) ) - { + while ( // MSITE-585, MNG-1943 + (parent = siteTool.getParentProject(current, reactorProjects, localRepository)) != null + && stagingSiteURL.equals(getStagingSiteURL(parent))) { current = parent; } // CHECKSTYLE_ON: InnerAssignment @@ -165,54 +154,44 @@ private MavenProject getTopMostParentWithSameStagingSiteURL() * @param project The MavenProject, not null * @return The stagingSiteURL for the project, or null if it doesn't have one */ - private String getStagingSiteURL( MavenProject project ) - { + private String getStagingSiteURL(MavenProject project) { final String sitePluginKey = "org.apache.maven.plugins:maven-site-plugin"; - if ( project == null ) - { + if (project == null) { return null; } final Build build = project.getBuild(); - if ( build == null ) - { + if (build == null) { return null; } Map plugins = build.getPluginsAsMap(); - Plugin sitePlugin = plugins.get( sitePluginKey ); - if ( sitePlugin == null ) - { + Plugin sitePlugin = plugins.get(sitePluginKey); + if (sitePlugin == null) { final PluginManagement buildPluginManagement = build.getPluginManagement(); - if ( buildPluginManagement == null ) - { + if (buildPluginManagement == null) { return null; } plugins = buildPluginManagement.getPluginsAsMap(); - sitePlugin = plugins.get( sitePluginKey ); + sitePlugin = plugins.get(sitePluginKey); } - if ( sitePlugin == null ) - { + if (sitePlugin == null) { return null; } final Xpp3Dom sitePluginConfiguration = (Xpp3Dom) sitePlugin.getConfiguration(); - if ( sitePluginConfiguration == null ) - { + if (sitePluginConfiguration == null) { return null; } - final Xpp3Dom child = sitePluginConfiguration.getChild( "stagingSiteURL" ); - if ( child == null ) - { + final Xpp3Dom child = sitePluginConfiguration.getChild("stagingSiteURL"); + if (child == null) { return null; - } - else - { + } else { return child.getValue(); } } @@ -222,36 +201,28 @@ private String getStagingSiteURL( MavenProject project ) * * @return the site URL for staging */ - private String determineStageDeploySiteURL() - throws MojoExecutionException - { - if ( stagingSiteURL != null ) - { + private String determineStageDeploySiteURL() throws MojoExecutionException { + if (stagingSiteURL != null) { // the user has specified a stagingSiteURL - use it - getLog().debug( "stagingSiteURL specified by the user: " + stagingSiteURL ); + getLog().debug("stagingSiteURL specified by the user: " + stagingSiteURL); return stagingSiteURL; } // The user didn't specify a URL, use the top level site distribution URL and add "[/]staging/" to it - String defaultStagingSiteURL = appendSlash( getTopDistributionManagementSiteUrl() ) + DEFAULT_STAGING_DIRECTORY; - getLog().debug( "stagingSiteURL NOT specified, using the top level project: " + defaultStagingSiteURL ); + String defaultStagingSiteURL = appendSlash(getTopDistributionManagementSiteUrl()) + DEFAULT_STAGING_DIRECTORY; + getLog().debug("stagingSiteURL NOT specified, using the top level project: " + defaultStagingSiteURL); return defaultStagingSiteURL; } - private String stagingRepoId() - { - if ( stagingRepositoryId != null ) - { + private String stagingRepoId() { + if (stagingRepositoryId != null) { return stagingRepositoryId; } - try - { - return getSite( project ).getId(); - } - catch ( MojoExecutionException ex ) - { + try { + return getSite(project).getId(); + } catch (MojoExecutionException ex) { return "stagingSite"; } } diff --git a/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageMojo.java b/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageMojo.java index a9b88489..f096d31e 100644 --- a/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/deploy/SiteStageMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * 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.site.deploy; import java.io.File; import java.util.List; @@ -43,10 +42,8 @@ * * @since 2.0 */ -@Mojo( name = "stage", requiresDependencyResolution = ResolutionScope.TEST ) -public class SiteStageMojo - extends AbstractStagingMojo -{ +@Mojo(name = "stage", requiresDependencyResolution = ResolutionScope.TEST) +public class SiteStageMojo extends AbstractStagingMojo { /** * Staging directory location. This needs to be an absolute path, like * C:\stagingArea\myProject\ on Windows or @@ -55,16 +52,13 @@ public class SiteStageMojo * * @since 2.3 */ - @Parameter( property = "stagingDirectory" ) + @Parameter(property = "stagingDirectory") private File stagingDirectory; @Override - public void execute() - throws MojoExecutionException - { - if ( skip ) - { - getLog().info( "maven.site.skip = true: Skipping site staging" ); + public void execute() throws MojoExecutionException { + if (skip) { + getLog().info("maven.site.skip = true: Skipping site staging"); return; } @@ -72,28 +66,24 @@ public void execute() } @Override - protected boolean isDeploy() - { + protected boolean isDeploy() { return false; } @Override - protected Site determineDeploySite() - throws MojoExecutionException - { + protected Site determineDeploySite() throws MojoExecutionException { Site staging = new Site(); - staging.setId( "stagingLocal" ); + staging.setId("stagingLocal"); final File outputDirectory = determineStagingDirectory(); - getLog().info( "Using this base directory for staging: " + outputDirectory ); + getLog().info("Using this base directory for staging: " + outputDirectory); // Safety - if ( !outputDirectory.exists() ) - { + if (!outputDirectory.exists()) { outputDirectory.mkdirs(); } - staging.setUrl( "file://" + outputDirectory.getAbsolutePath() ); + staging.setUrl("file://" + outputDirectory.getAbsolutePath()); return staging; } @@ -103,19 +93,16 @@ protected Site determineDeploySite() * * @return the directory for staging */ - private File determineStagingDirectory() - { - if ( stagingDirectory != null ) - { + private File determineStagingDirectory() { + if (stagingDirectory != null) { // the user has specified a stagingDirectory - use it - getLog().debug( "stagingDirectory specified by the user: " + stagingDirectory ); + getLog().debug("stagingDirectory specified by the user: " + stagingDirectory); return stagingDirectory; } // The user didn't specify a URL: calculate default in the execution root target dir - File defaultStagingDirectory = new File( getExecutionRootBuildDirectory(), DEFAULT_STAGING_DIRECTORY ); - getLog().debug( "stagingDirectory NOT specified, using the execution root project: " - + defaultStagingDirectory ); + File defaultStagingDirectory = new File(getExecutionRootBuildDirectory(), DEFAULT_STAGING_DIRECTORY); + getLog().debug("stagingDirectory NOT specified, using the execution root project: " + defaultStagingDirectory); return defaultStagingDirectory; } @@ -125,26 +112,22 @@ private File determineStagingDirectory() * * @return the build directory of the execution root project. */ - protected File getExecutionRootBuildDirectory() - { + protected File getExecutionRootBuildDirectory() { // Find the top level project in the reactor - final MavenProject executionRootProject = getExecutionRootProject( reactorProjects ); + final MavenProject executionRootProject = getExecutionRootProject(reactorProjects); // Use the top level project's build directory if there is one, otherwise use this project's build directory final File buildDirectory; - if ( executionRootProject == null ) - { - getLog().debug( "No execution root project found in the reactor, using the current project." ); + if (executionRootProject == null) { + getLog().debug("No execution root project found in the reactor, using the current project."); - buildDirectory = new File( project.getBuild().getDirectory() ); - } - else - { - getLog().debug( "Using the execution root project found in the reactor: " - + executionRootProject.getArtifactId() ); + buildDirectory = new File(project.getBuild().getDirectory()); + } else { + getLog().debug("Using the execution root project found in the reactor: " + + executionRootProject.getArtifactId()); - buildDirectory = new File( executionRootProject.getBuild().getDirectory() ); + buildDirectory = new File(executionRootProject.getBuild().getDirectory()); } return buildDirectory; @@ -157,18 +140,14 @@ protected File getExecutionRootBuildDirectory() * returned. * @return The execution root project in the reactor, or null if none can be found */ - private static MavenProject getExecutionRootProject( List reactorProjects ) - { - if ( reactorProjects == null ) - { + private static MavenProject getExecutionRootProject(List reactorProjects) { + if (reactorProjects == null) { return null; } // todo Lambda Java 1.8 - for ( MavenProject reactorProject : reactorProjects ) - { - if ( reactorProject.isExecutionRoot() ) - { + for (MavenProject reactorProject : reactorProjects) { + if (reactorProject.isExecutionRoot()) { return reactorProject; } } diff --git a/src/main/java/org/apache/maven/plugins/site/descriptor/AbstractSiteDescriptorMojo.java b/src/main/java/org/apache/maven/plugins/site/descriptor/AbstractSiteDescriptorMojo.java index 9635dac6..7695ba44 100644 --- a/src/main/java/org/apache/maven/plugins/site/descriptor/AbstractSiteDescriptorMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/descriptor/AbstractSiteDescriptorMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.descriptor; - /* * 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.site.descriptor; import java.io.File; import java.util.List; @@ -37,9 +36,7 @@ * * @since 3.5 */ -public abstract class AbstractSiteDescriptorMojo - extends AbstractSiteMojo -{ +public abstract class AbstractSiteDescriptorMojo extends AbstractSiteMojo { /** * The component for assembling site decoration model inheritance. */ @@ -52,7 +49,7 @@ public abstract class AbstractSiteDescriptorMojo * todo this is used for site descriptor resolution - it should relate to the actual project but for some reason * they are not always filled in */ - @Parameter( defaultValue = "${project.remoteArtifactRepositories}", readonly = true ) + @Parameter(defaultValue = "${project.remoteArtifactRepositories}", readonly = true) protected List repositories; /** @@ -62,7 +59,7 @@ public abstract class AbstractSiteDescriptorMojo * * @since 2.3 */ - @Parameter( defaultValue = "${basedir}/src/site" ) + @Parameter(defaultValue = "${basedir}/src/site") protected File siteDirectory; /** @@ -74,50 +71,40 @@ public abstract class AbstractSiteDescriptorMojo * * @since 2.3 */ - @Parameter( property = "relativizeDecorationLinks", defaultValue = "true" ) + @Parameter(property = "relativizeDecorationLinks", defaultValue = "true") private boolean relativizeDecorationLinks; - protected DecorationModel prepareDecorationModel( Locale locale ) - throws MojoExecutionException - { + protected DecorationModel prepareDecorationModel(Locale locale) throws MojoExecutionException { DecorationModel decorationModel; - try - { - decorationModel = siteTool.getDecorationModel( siteDirectory, locale, project, reactorProjects, - localRepository, repositories ); - } - catch ( SiteToolException e ) - { - throw new MojoExecutionException( "SiteToolException: " + e.getMessage(), e ); + try { + decorationModel = siteTool.getDecorationModel( + siteDirectory, locale, project, reactorProjects, localRepository, repositories); + } catch (SiteToolException e) { + throw new MojoExecutionException("SiteToolException: " + e.getMessage(), e); } - if ( relativizeDecorationLinks ) - { + if (relativizeDecorationLinks) { final String url = project.getUrl(); - if ( url == null ) - { - getLog().warn( "No project URL defined - decoration links will not be relativized!" ); - } - else - { + if (url == null) { + getLog().warn("No project URL defined - decoration links will not be relativized!"); + } else { List localesList = getLocales(); // Default is first in the list - Locale defaultLocale = localesList.get( 0 ); + Locale defaultLocale = localesList.get(0); // MSITE-658 - final String localeUrl = locale.equals( defaultLocale ) ? url : append( url, locale.toString() ); + final String localeUrl = locale.equals(defaultLocale) ? url : append(url, locale.toString()); - getLog().info( "Relativizing decoration links with respect to localized project URL: " + localeUrl ); - assembler.resolvePaths( decorationModel, localeUrl ); + getLog().info("Relativizing decoration links with respect to localized project URL: " + localeUrl); + assembler.resolvePaths(decorationModel, localeUrl); } } return decorationModel; } - private String append( String url, String path ) - { - return url.endsWith( "/" ) ? ( url + path ) : ( url + '/' + path ); + private String append(String url, String path) { + return url.endsWith("/") ? (url + path) : (url + '/' + path); } } diff --git a/src/main/java/org/apache/maven/plugins/site/descriptor/EffectiveSiteMojo.java b/src/main/java/org/apache/maven/plugins/site/descriptor/EffectiveSiteMojo.java index 556f6bfb..b847a781 100644 --- a/src/main/java/org/apache/maven/plugins/site/descriptor/EffectiveSiteMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/descriptor/EffectiveSiteMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.descriptor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.descriptor; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; import org.apache.maven.doxia.site.decoration.DecorationModel; import org.apache.maven.doxia.site.decoration.io.xpp3.DecorationXpp3Writer; @@ -31,11 +35,6 @@ import org.codehaus.plexus.util.xml.XMLWriter; import org.codehaus.plexus.util.xml.XmlWriterUtil; -import java.io.File; -import java.io.IOException; -import java.io.StringWriter; -import java.io.Writer; - /** * Displays the effective site descriptor as an XML for this build, after inheritance and interpolation of * site.xml, for the first locale. @@ -44,65 +43,55 @@ * * @since 2.2 */ -@Mojo( name = "effective-site", requiresReports = true ) -public class EffectiveSiteMojo - extends AbstractSiteDescriptorMojo -{ +@Mojo(name = "effective-site", requiresReports = true) +public class EffectiveSiteMojo extends AbstractSiteDescriptorMojo { /** * Optional parameter to write the output of this help in a given file, instead of writing to the console. *

* Note: Could be a relative path. *

*/ - @Parameter( property = "output" ) + @Parameter(property = "output") protected File output; /** * {@inheritDoc} */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - DecorationModel decorationModel = prepareDecorationModel( getLocales().get( 0 ) ); + public void execute() throws MojoExecutionException, MojoFailureException { + DecorationModel decorationModel = prepareDecorationModel(getLocales().get(0)); StringWriter w = new StringWriter(); - XMLWriter writer = - new PrettyPrintXMLWriter( w, StringUtils.repeat( " ", XmlWriterUtil.DEFAULT_INDENTATION_SIZE ), - decorationModel.getModelEncoding(), null ); + XMLWriter writer = new PrettyPrintXMLWriter( + w, + StringUtils.repeat(" ", XmlWriterUtil.DEFAULT_INDENTATION_SIZE), + decorationModel.getModelEncoding(), + null); - writeHeader( writer ); + writeHeader(writer); - writeEffectiveSite( decorationModel, writer ); + writeEffectiveSite(decorationModel, writer); String effectiveSite = w.toString(); - if ( output != null ) - { - try - { - writeXmlFile( output, effectiveSite ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Cannot write effective site descriptor to output: " + output, e ); + if (output != null) { + try { + writeXmlFile(output, effectiveSite); + } catch (IOException e) { + throw new MojoExecutionException("Cannot write effective site descriptor to output: " + output, e); } - if ( getLog().isInfoEnabled() ) - { - getLog().info( "Effective site descriptor written to: " + output ); + if (getLog().isInfoEnabled()) { + getLog().info("Effective site descriptor written to: " + output); } - } - else - { + } else { StringBuilder message = new StringBuilder(); - message.append( "\nEffective site descriptor, after inheritance and interpolation:\n\n" ); - message.append( effectiveSite ); - message.append( "\n" ); + message.append("\nEffective site descriptor, after inheritance and interpolation:\n\n"); + message.append(effectiveSite); + message.append("\n"); - if ( getLog().isInfoEnabled() ) - { - getLog().info( message.toString() ); + if (getLog().isInfoEnabled()) { + getLog().info(message.toString()); } } } @@ -112,16 +101,15 @@ public void execute() * * @param writer not null */ - protected static void writeHeader( XMLWriter writer ) - { - XmlWriterUtil.writeCommentLineBreak( writer ); - XmlWriterUtil.writeComment( writer, " " ); - XmlWriterUtil.writeComment( writer, "Generated by Maven Site Plugin" ); - XmlWriterUtil.writeComment( writer, "See: http://maven.apache.org/plugins/maven-site-plugin/" ); - XmlWriterUtil.writeComment( writer, " " ); - XmlWriterUtil.writeCommentLineBreak( writer ); - - XmlWriterUtil.writeLineBreak( writer ); + protected static void writeHeader(XMLWriter writer) { + XmlWriterUtil.writeCommentLineBreak(writer); + XmlWriterUtil.writeComment(writer, " "); + XmlWriterUtil.writeComment(writer, "Generated by Maven Site Plugin"); + XmlWriterUtil.writeComment(writer, "See: https://maven.apache.org/plugins/maven-site-plugin/"); + XmlWriterUtil.writeComment(writer, " "); + XmlWriterUtil.writeCommentLineBreak(writer); + + XmlWriterUtil.writeLineBreak(writer); } /** @@ -130,49 +118,40 @@ protected static void writeHeader( XMLWriter writer ) * @param writer not null * @param comment not null */ - protected static void writeComment( XMLWriter writer, String comment ) - { - XmlWriterUtil.writeCommentLineBreak( writer ); - XmlWriterUtil.writeComment( writer, " " ); - XmlWriterUtil.writeComment( writer, comment ); - XmlWriterUtil.writeComment( writer, " " ); - XmlWriterUtil.writeCommentLineBreak( writer ); - - XmlWriterUtil.writeLineBreak( writer ); + protected static void writeComment(XMLWriter writer, String comment) { + XmlWriterUtil.writeCommentLineBreak(writer); + XmlWriterUtil.writeComment(writer, " "); + XmlWriterUtil.writeComment(writer, comment); + XmlWriterUtil.writeComment(writer, " "); + XmlWriterUtil.writeCommentLineBreak(writer); + + XmlWriterUtil.writeLineBreak(writer); } - private void writeEffectiveSite( DecorationModel decorationModel, XMLWriter writer ) - throws MojoExecutionException - { + private void writeEffectiveSite(DecorationModel decorationModel, XMLWriter writer) throws MojoExecutionException { String effectiveSite; StringWriter sWriter = new StringWriter(); DecorationXpp3Writer siteWriter = new DecorationXpp3Writer(); - try - { - siteWriter.write( sWriter, decorationModel ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Cannot serialize site descriptor to XML.", e ); + try { + siteWriter.write(sWriter, decorationModel); + } catch (IOException e) { + throw new MojoExecutionException("Cannot serialize site descriptor to XML.", e); } effectiveSite = sWriter.toString(); - effectiveSite = effectiveSite.substring( effectiveSite.indexOf( "Brett Porter * */ -public class SiteDescriptorArtifactMetadata - extends AbstractArtifactMetadata -{ +public class SiteDescriptorArtifactMetadata extends AbstractArtifactMetadata { private final DecorationModel decoration; private final File file; - public SiteDescriptorArtifactMetadata( Artifact artifact, DecorationModel decoration, File file ) - { - super( artifact ); + public SiteDescriptorArtifactMetadata(Artifact artifact, DecorationModel decoration, File file) { + super(artifact); this.file = file; this.decoration = decoration; } - public String getRemoteFilename() - { + public String getRemoteFilename() { return getFilename(); } - public String getLocalFilename( ArtifactRepository repository ) - { + public String getLocalFilename(ArtifactRepository repository) { return getFilename(); } - private String getFilename() - { + private String getFilename() { return getArtifactId() + "-" + artifact.getVersion() + "-" + file.getName(); } - public void storeInLocalRepository( ArtifactRepository localRepository, ArtifactRepository remoteRepository ) - throws RepositoryMetadataStoreException - { - File destination = new File( localRepository.getBasedir(), - localRepository.pathOfLocalRepositoryMetadata( this, remoteRepository ) ); + public void storeInLocalRepository(ArtifactRepository localRepository, ArtifactRepository remoteRepository) + throws RepositoryMetadataStoreException { + File destination = new File( + localRepository.getBasedir(), localRepository.pathOfLocalRepositoryMetadata(this, remoteRepository)); destination.getParentFile().mkdirs(); - try ( Writer writer = WriterFactory.newXmlWriter( destination ) ) - { - new DecorationXpp3Writer().write( writer, decoration ); - } - catch ( IOException e ) - { - throw new RepositoryMetadataStoreException( "Error saving in local repository", e ); + try (Writer writer = WriterFactory.newXmlWriter(destination)) { + new DecorationXpp3Writer().write(writer, decoration); + } catch (IOException e) { + throw new RepositoryMetadataStoreException("Error saving in local repository", e); } } - public String toString() - { + public String toString() { return "site descriptor for " + artifact.getArtifactId() + " " + artifact.getVersion() + " " + file.getName(); } - public boolean storedInArtifactVersionDirectory() - { + public boolean storedInArtifactVersionDirectory() { return true; } - public String getBaseVersion() - { + public String getBaseVersion() { return artifact.getBaseVersion(); } - public Object getKey() - { + public Object getKey() { return "site descriptor " + artifact.getGroupId() + ":" + artifact.getArtifactId() + " " + file.getName(); } - public void merge( ArtifactMetadata metadata ) - { + public void merge(ArtifactMetadata metadata) { SiteDescriptorArtifactMetadata m = (SiteDescriptorArtifactMetadata) metadata; - if ( !m.file.equals( file ) ) - { - throw new IllegalStateException( "Cannot add two different pieces of metadata for: " + getKey() ); + if (!m.file.equals(file)) { + throw new IllegalStateException("Cannot add two different pieces of metadata for: " + getKey()); } } - public void merge( org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata ) - { + public void merge(org.apache.maven.repository.legacy.metadata.ArtifactMetadata metadata) { // FIXME what todo here ? } } diff --git a/src/main/java/org/apache/maven/plugins/site/descriptor/SiteDescriptorAttachMojo.java b/src/main/java/org/apache/maven/plugins/site/descriptor/SiteDescriptorAttachMojo.java index 6e46c7d0..9459567b 100644 --- a/src/main/java/org/apache/maven/plugins/site/descriptor/SiteDescriptorAttachMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/descriptor/SiteDescriptorAttachMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.descriptor; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.descriptor; import java.io.File; import java.io.IOException; - import java.util.Locale; import org.apache.maven.plugin.MojoExecutionException; @@ -45,13 +43,11 @@ * * @since 2.0 */ -@Mojo( name = "attach-descriptor", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true ) -public class SiteDescriptorAttachMojo - extends AbstractSiteDescriptorMojo -{ +@Mojo(name = "attach-descriptor", defaultPhase = LifecyclePhase.PACKAGE, threadSafe = true) +public class SiteDescriptorAttachMojo extends AbstractSiteDescriptorMojo { /** */ - @Parameter( property = "basedir", required = true, readonly = true ) + @Parameter(property = "basedir", required = true, readonly = true) private File basedir; /** @@ -66,69 +62,55 @@ public class SiteDescriptorAttachMojo * Attach site descriptor only if packaging is pom. * @since 3.0 */ - @Parameter( defaultValue = "true" ) + @Parameter(defaultValue = "true") private boolean pomPackagingOnly; - public void execute() - throws MojoExecutionException - { - if ( pomPackagingOnly && !"pom".equals( project.getPackaging() ) ) - { + public void execute() throws MojoExecutionException { + if (pomPackagingOnly && !"pom".equals(project.getPackaging())) { // https://issues.apache.org/jira/browse/MSITE-597 - getLog().info( "Skipping because packaging '" + project.getPackaging() + "' is not pom." ); + getLog().info("Skipping because packaging '" + project.getPackaging() + "' is not pom."); return; } boolean attachedSiteDescriptor = false; - for ( Locale locale : getLocales() ) - { - File descriptorFile = siteTool.getSiteDescriptor( siteDirectory, locale ); + for (Locale locale : getLocales()) { + File descriptorFile = siteTool.getSiteDescriptor(siteDirectory, locale); - if ( descriptorFile.exists() ) - { + if (descriptorFile.exists()) { attachedSiteDescriptor = true; // Calculate the classifier to use - String classifier = getClassifier( descriptorFile ); + String classifier = getClassifier(descriptorFile); // Prepare a file for the interpolated site descriptor String filename = project.getArtifactId() + "-" + project.getVersion() + "-" + descriptorFile.getName(); - File targetDescriptorFile = new File( project.getBuild().getDirectory(), filename ); + File targetDescriptorFile = new File(project.getBuild().getDirectory(), filename); - try - { + try { // Copy the site descriptor to a file - FileUtils.copyFile( descriptorFile, targetDescriptorFile ); + FileUtils.copyFile(descriptorFile, targetDescriptorFile); // Attach the site descriptor - getLog().info( "Attaching '" - + PathTool.getRelativeFilePath( basedir.getAbsolutePath(), descriptorFile.getAbsolutePath() ) - + "' site descriptor with classifier '" + classifier + "'." ); - projectHelper.attachArtifact( project, "xml", classifier, targetDescriptorFile ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to copy site descriptor", e ); + getLog().info("Attaching '" + + PathTool.getRelativeFilePath(basedir.getAbsolutePath(), descriptorFile.getAbsolutePath()) + + "' site descriptor with classifier '" + classifier + "'."); + projectHelper.attachArtifact(project, "xml", classifier, targetDescriptorFile); + } catch (IOException e) { + throw new MojoExecutionException("Unable to copy site descriptor", e); } } } - if ( !attachedSiteDescriptor ) - { - getLog().info( "No site descriptor found: nothing to attach." ); + if (!attachedSiteDescriptor) { + getLog().info("No site descriptor found: nothing to attach."); } } - private static String getClassifier( final File descriptorFile ) - throws MojoExecutionException - { - final int index = descriptorFile.getName().lastIndexOf( '.' ); + private static String getClassifier(final File descriptorFile) throws MojoExecutionException { + final int index = descriptorFile.getName().lastIndexOf('.'); - if ( index > 0 ) - { - return descriptorFile.getName().substring( 0, index ); - } - else - { - throw new MojoExecutionException( "Unable to determine the classifier to use" ); + if (index > 0) { + return descriptorFile.getName().substring(0, index); + } else { + throw new MojoExecutionException("Unable to determine the classifier to use"); } } } diff --git a/src/main/java/org/apache/maven/plugins/site/render/AbstractSiteRenderingMojo.java b/src/main/java/org/apache/maven/plugins/site/render/AbstractSiteRenderingMojo.java index bb02ffe3..1d1041e9 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/AbstractSiteRenderingMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/render/AbstractSiteRenderingMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,19 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.render; + +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import org.apache.maven.archiver.MavenArchiver; import org.apache.maven.artifact.Artifact; @@ -48,18 +59,6 @@ import org.codehaus.plexus.util.ReaderFactory; import org.codehaus.plexus.util.StringUtils; -import java.io.File; -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.HashMap; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; /** @@ -68,8 +67,7 @@ * @author Brett Porter * */ -public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMojo -{ +public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMojo { /** * Module type exclusion mappings * ex: fml -> **/*-m1.fml (excludes fml files ending in '-m1.fml' recursively) @@ -105,7 +103,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo /** * Reports (Maven 2). */ - @Parameter( defaultValue = "${reports}", required = true, readonly = true ) + @Parameter(defaultValue = "${reports}", required = true, readonly = true) protected List reports; /** @@ -113,7 +111,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @deprecated use the standard m2 directory layout */ - @Parameter( defaultValue = "${basedir}/xdocs" ) + @Parameter(defaultValue = "${basedir}/xdocs") private File xdocDirectory; /** @@ -126,13 +124,13 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * todo should we deprecate in favour of reports directly using Doxia Sink API, without this Doxia source * intermediate step? */ - @Parameter( alias = "workingDirectory", defaultValue = "${project.build.directory}/generated-site" ) + @Parameter(alias = "workingDirectory", defaultValue = "${project.build.directory}/generated-site") protected File generatedSiteDirectory; /** * The current Maven session. */ - @Parameter( defaultValue = "${session}", readonly = true, required = true ) + @Parameter(defaultValue = "${session}", readonly = true, required = true) protected MavenSession mavenSession; /** @@ -141,7 +139,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @since 3.7.1 */ - @Parameter( defaultValue = "${project.reporting}", readonly = true ) + @Parameter(defaultValue = "${project.reporting}", readonly = true) private Reporting reporting; /** @@ -149,7 +147,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @since 2.3 */ - @Parameter( property = "generateProjectInfo", defaultValue = "true" ) + @Parameter(property = "generateProjectInfo", defaultValue = "true") private boolean generateProjectInfo; /** @@ -157,7 +155,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @since 2.3 */ - @Parameter( property = "encoding", defaultValue = "${project.build.sourceEncoding}" ) + @Parameter(property = "encoding", defaultValue = "${project.build.sourceEncoding}") private String inputEncoding; /** @@ -165,7 +163,7 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @since 2.3 */ - @Parameter( property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}" ) + @Parameter(property = "outputEncoding", defaultValue = "${project.reporting.outputEncoding}") private String outputEncoding; @Component @@ -176,9 +174,8 @@ public abstract class AbstractSiteRenderingMojo extends AbstractSiteDescriptorMo * * @return The input files encoding, never null. */ - protected String getInputEncoding() - { - return ( StringUtils.isEmpty( inputEncoding ) ) ? ReaderFactory.FILE_ENCODING : inputEncoding; + protected String getInputEncoding() { + return (StringUtils.isEmpty(inputEncoding)) ? ReaderFactory.FILE_ENCODING : inputEncoding; } /** @@ -186,9 +183,8 @@ protected String getInputEncoding() * * @return The effective reporting output file encoding, never null. */ - protected String getOutputEncoding() - { - return ( outputEncoding == null ) ? ReaderFactory.UTF_8 : outputEncoding; + protected String getOutputEncoding() { + return (outputEncoding == null) ? ReaderFactory.UTF_8 : outputEncoding; } /** @@ -200,33 +196,27 @@ protected String getOutputEncoding() @Parameter private boolean saveProcessedContent; - protected void checkInputEncoding() - { - if ( StringUtils.isEmpty( inputEncoding ) ) - { - getLog().warn( "Input file encoding has not been set, using platform encoding " - + ReaderFactory.FILE_ENCODING + ", i.e. build is platform dependent!" ); + protected void checkInputEncoding() { + if (StringUtils.isEmpty(inputEncoding)) { + getLog().warn("Input file encoding has not been set, using platform encoding " + ReaderFactory.FILE_ENCODING + + ", i.e. build is platform dependent!"); } } - protected List getReports() - throws MojoExecutionException - { + protected List getReports() throws MojoExecutionException { MavenReportExecutorRequest mavenReportExecutorRequest = new MavenReportExecutorRequest(); - mavenReportExecutorRequest.setLocalRepository( localRepository ); - mavenReportExecutorRequest.setMavenSession( mavenSession ); - mavenReportExecutorRequest.setProject( project ); - mavenReportExecutorRequest.setReportPlugins( getReportingPlugins() ); + mavenReportExecutorRequest.setLocalRepository(localRepository); + mavenReportExecutorRequest.setMavenSession(mavenSession); + mavenReportExecutorRequest.setProject(project); + mavenReportExecutorRequest.setReportPlugins(getReportingPlugins()); - List allReports = mavenReportExecutor.buildMavenReports( mavenReportExecutorRequest ); + List allReports = mavenReportExecutor.buildMavenReports(mavenReportExecutorRequest); // filter out reports that can't be generated - List reportExecutions = new ArrayList<>( allReports.size() ); - for ( MavenReportExecution exec : allReports ) - { - if ( exec.canGenerateReport() ) - { - reportExecutions.add( exec ); + List reportExecutions = new ArrayList<>(allReports.size()); + for (MavenReportExecution exec : allReports) { + if (exec.canGenerateReport()) { + reportExecutions.add(exec); } } return reportExecutions; @@ -239,115 +229,95 @@ protected List getReports() * @return the effective list of reports * @since 3.7.1 */ - private ReportPlugin[] getReportingPlugins() - { + private ReportPlugin[] getReportingPlugins() { List reportingPlugins = reporting.getPlugins(); // MSITE-806: add default report plugin like done in maven-model-builder DefaultReportingConverter boolean hasMavenProjectInfoReportsPlugin = false; - for ( ReportPlugin plugin : reportingPlugins ) - { - if ( "org.apache.maven.plugins".equals( plugin.getGroupId() ) - && "maven-project-info-reports-plugin".equals( plugin.getArtifactId() ) ) - { + for (ReportPlugin plugin : reportingPlugins) { + if ("org.apache.maven.plugins".equals(plugin.getGroupId()) + && "maven-project-info-reports-plugin".equals(plugin.getArtifactId())) { hasMavenProjectInfoReportsPlugin = true; break; } } - if ( !reporting.isExcludeDefaults() && !hasMavenProjectInfoReportsPlugin ) - { + if (!reporting.isExcludeDefaults() && !hasMavenProjectInfoReportsPlugin) { ReportPlugin mpir = new ReportPlugin(); - mpir.setArtifactId( "maven-project-info-reports-plugin" ); - reportingPlugins.add( mpir ); + mpir.setArtifactId("maven-project-info-reports-plugin"); + reportingPlugins.add(mpir); } - return reportingPlugins.toArray( new ReportPlugin[reportingPlugins.size()] ); + return reportingPlugins.toArray(new ReportPlugin[reportingPlugins.size()]); } - protected SiteRenderingContext createSiteRenderingContext( Locale locale ) - throws MojoExecutionException, IOException, MojoFailureException - { - DecorationModel decorationModel = prepareDecorationModel( locale ); - if ( attributes == null ) - { + protected SiteRenderingContext createSiteRenderingContext(Locale locale) + throws MojoExecutionException, IOException, MojoFailureException { + DecorationModel decorationModel = prepareDecorationModel(locale); + if (attributes == null) { attributes = new HashMap<>(); } - if ( attributes.get( "project" ) == null ) - { - attributes.put( "project", project ); + if (attributes.get("project") == null) { + attributes.put("project", project); } - if ( attributes.get( "inputEncoding" ) == null ) - { - attributes.put( "inputEncoding", getInputEncoding() ); + if (attributes.get("inputEncoding") == null) { + attributes.put("inputEncoding", getInputEncoding()); } - if ( attributes.get( "outputEncoding" ) == null ) - { - attributes.put( "outputEncoding", getOutputEncoding() ); + if (attributes.get("outputEncoding") == null) { + attributes.put("outputEncoding", getOutputEncoding()); } // Put any of the properties in directly into the Velocity context - for ( Map.Entry entry : project.getProperties().entrySet() ) - { - attributes.put( (String) entry.getKey(), entry.getValue() ); + for (Map.Entry entry : project.getProperties().entrySet()) { + attributes.put((String) entry.getKey(), entry.getValue()); } SiteRenderingContext context; - try - { - Artifact skinArtifact = - siteTool.getSkinArtifactFromRepository( localRepository, repositories, decorationModel ); - - getLog().info( buffer().a( "Rendering content with " ).strong( skinArtifact.getId() - + " skin" ).a( '.' ).toString() ); - - context = siteRenderer.createContextForSkin( skinArtifact, attributes, decorationModel, - project.getName(), locale ); - } - catch ( SiteToolException e ) - { - throw new MojoExecutionException( "SiteToolException while preparing skin: " + e.getMessage(), e ); - } - catch ( RendererException e ) - { - throw new MojoExecutionException( "RendererException while preparing context for skin: " - + e.getMessage(), e ); + try { + Artifact skinArtifact = + siteTool.getSkinArtifactFromRepository(localRepository, repositories, decorationModel); + + getLog().info(buffer().a("Rendering content with ") + .strong(skinArtifact.getId() + " skin") + .a('.') + .toString()); + + context = siteRenderer.createContextForSkin( + skinArtifact, attributes, decorationModel, project.getName(), locale); + } catch (SiteToolException e) { + throw new MojoExecutionException("SiteToolException while preparing skin: " + e.getMessage(), e); + } catch (RendererException e) { + throw new MojoExecutionException( + "RendererException while preparing context for skin: " + e.getMessage(), e); } // Add publish date - MavenProject p = attributes.get( "project" ) != null ? (MavenProject) attributes.get( "project" ) : project; - String outputTimestamp = p.getProperties().getProperty( "project.build.outputTimestamp" ); - MavenArchiver.parseBuildOutputTimestamp( outputTimestamp ).ifPresent( v -> - { - context.setPublishDate( Date.from( v ) ); - } - ); + MavenProject p = attributes.get("project") != null ? (MavenProject) attributes.get("project") : project; + String outputTimestamp = p.getProperties().getProperty("project.build.outputTimestamp"); + MavenArchiver.parseBuildOutputTimestamp(outputTimestamp).ifPresent(v -> { + context.setPublishDate(Date.from(v)); + }); // Generate static site - context.setRootDirectory( project.getBasedir() ); - if ( !locale.equals( SiteTool.DEFAULT_LOCALE ) ) - { - context.addSiteDirectory( new File( siteDirectory, locale.toString() ) ); - context.addModuleDirectory( new File( xdocDirectory, locale.toString() ), "xdoc" ); - context.addModuleDirectory( new File( xdocDirectory, locale.toString() ), "fml" ); - } - else - { - context.addSiteDirectory( siteDirectory ); - context.addModuleDirectory( xdocDirectory, "xdoc" ); - context.addModuleDirectory( xdocDirectory, "fml" ); + context.setRootDirectory(project.getBasedir()); + if (!locale.equals(SiteTool.DEFAULT_LOCALE)) { + context.addSiteDirectory(new File(siteDirectory, locale.toString())); + context.addModuleDirectory(new File(xdocDirectory, locale.toString()), "xdoc"); + context.addModuleDirectory(new File(xdocDirectory, locale.toString()), "fml"); + } else { + context.addSiteDirectory(siteDirectory); + context.addModuleDirectory(xdocDirectory, "xdoc"); + context.addModuleDirectory(xdocDirectory, "fml"); } - if ( moduleExcludes != null ) - { - context.setModuleExcludes( moduleExcludes ); + if (moduleExcludes != null) { + context.setModuleExcludes(moduleExcludes); } - if ( saveProcessedContent ) - { - context.setProcessedContentOutput( new File( generatedSiteDirectory, "processed" ) ); + if (saveProcessedContent) { + context.setProcessedContentOutput(new File(generatedSiteDirectory, "processed")); } return context; @@ -366,38 +336,39 @@ protected SiteRenderingContext createSiteRenderingContext( Locale locale ) * @return A map with all reports keyed by filename having the report itself as value. * The map will be used to populate a menu. */ - protected Map locateReports( List reports, - Map documents, Locale locale ) - { + protected Map locateReports( + List reports, Map documents, Locale locale) { Map reportsByOutputName = new LinkedHashMap<>(); - for ( MavenReportExecution mavenReportExecution : reports ) - { + for (MavenReportExecution mavenReportExecution : reports) { MavenReport report = mavenReportExecution.getMavenReport(); String outputName = report.getOutputName() + ".html"; // Always add the report to the menu, see MSITE-150 - reportsByOutputName.put( report.getOutputName(), report ); - - if ( documents.containsKey( outputName ) ) - { - String reportMojoInfo = - ( mavenReportExecution.getGoal() == null ) ? "" : ( " (" - + mavenReportExecution.getPlugin().getArtifactId() + ':' - + mavenReportExecution.getPlugin().getVersion() + ':' + mavenReportExecution.getGoal() + ')' ); - - getLog().info( "Skipped \"" + report.getName( locale ) + "\" report" + reportMojoInfo + ", file \"" - + outputName + "\" already exists." ); - } - else - { - String reportMojoInfo = mavenReportExecution.getPlugin().getGroupId() + ':' - + mavenReportExecution.getPlugin().getArtifactId() + ':' - + mavenReportExecution.getPlugin().getVersion() + ':' + mavenReportExecution.getGoal(); - RenderingContext renderingContext = new RenderingContext( siteDirectory, outputName, reportMojoInfo ); + reportsByOutputName.put(report.getOutputName(), report); + + if (documents.containsKey(outputName)) { + String reportMojoInfo = (mavenReportExecution.getGoal() == null) + ? "" + : (" (" + + mavenReportExecution.getPlugin().getArtifactId() + ':' + + mavenReportExecution.getPlugin().getVersion() + ':' + mavenReportExecution.getGoal() + + ')'); + + getLog().info("Skipped \"" + report.getName(locale) + "\" report" + reportMojoInfo + ", file \"" + + outputName + "\" already exists."); + } else { + String reportMojoInfo = mavenReportExecution.getPlugin().getGroupId() + + ':' + + mavenReportExecution.getPlugin().getArtifactId() + + ':' + + mavenReportExecution.getPlugin().getVersion() + + ':' + + mavenReportExecution.getGoal(); + RenderingContext renderingContext = new RenderingContext(siteDirectory, outputName, reportMojoInfo); DocumentRenderer renderer = - new ReportDocumentRenderer( mavenReportExecution, renderingContext, getLog() ); - documents.put( outputName, renderer ); + new ReportDocumentRenderer(mavenReportExecution, renderingContext, getLog()); + documents.put(outputName, renderer); } } return reportsByOutputName; @@ -410,18 +381,15 @@ protected Map locateReports( List rep * @param reports A Collection of MavenReports * @return A map keyed category having the report itself as value */ - protected Map> categoriseReports( Collection reports ) - { + protected Map> categoriseReports(Collection reports) { Map> categories = new LinkedHashMap<>(); - for ( MavenReport report : reports ) - { - List categoryReports = categories.get( report.getCategoryName() ); - if ( categoryReports == null ) - { + for (MavenReport report : reports) { + List categoryReports = categories.get(report.getCategoryName()); + if (categoryReports == null) { categoryReports = new ArrayList<>(); - categories.put( report.getCategoryName(), categoryReports ); + categories.put(report.getCategoryName(), categoryReports); } - categoryReports.add( report ); + categoryReports.add(report); } return categories; } @@ -441,113 +409,93 @@ protected Map> categoriseReports( Collection locateDocuments( SiteRenderingContext context, - List reports, Locale locale ) - throws IOException, RendererException - { - Map documents = siteRenderer.locateDocumentFiles( context, true ); + protected Map locateDocuments( + SiteRenderingContext context, List reports, Locale locale) + throws IOException, RendererException { + Map documents = siteRenderer.locateDocumentFiles(context, true); - Map reportsByOutputName = locateReports( reports, documents, locale ); + Map reportsByOutputName = locateReports(reports, documents, locale); // TODO: I want to get rid of categories eventually. There's no way to add your own in a fully i18n manner - Map> categories = categoriseReports( reportsByOutputName.values() ); + Map> categories = categoriseReports(reportsByOutputName.values()); - siteTool.populateReportsMenu( context.getDecoration(), locale, categories ); - populateReportItems( context.getDecoration(), locale, reportsByOutputName ); + siteTool.populateReportsMenu(context.getDecoration(), locale, categories); + populateReportItems(context.getDecoration(), locale, reportsByOutputName); - if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_INFORMATION ) && generateProjectInfo ) - { + if (categories.containsKey(MavenReport.CATEGORY_PROJECT_INFORMATION) && generateProjectInfo) { // add "Project Information" category summary document - List categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_INFORMATION ); - - RenderingContext renderingContext = - new RenderingContext( siteDirectory, "project-info.html", - getSitePluginInfo() + ":CategorySummaryDocumentRenderer" ); - String title = i18n.getString( "site-plugin", locale, "report.information.title" ); - String desc1 = i18n.getString( "site-plugin", locale, "report.information.description1" ); - String desc2 = i18n.getString( "site-plugin", locale, "report.information.description2" ); - DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2, - i18n, categoryReports, getLog() ); - - if ( !documents.containsKey( renderer.getOutputName() ) ) - { - documents.put( renderer.getOutputName(), renderer ); - } - else - { - getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" ); + List categoryReports = categories.get(MavenReport.CATEGORY_PROJECT_INFORMATION); + + RenderingContext renderingContext = new RenderingContext( + siteDirectory, "project-info.html", getSitePluginInfo() + ":CategorySummaryDocumentRenderer"); + String title = i18n.getString("site-plugin", locale, "report.information.title"); + String desc1 = i18n.getString("site-plugin", locale, "report.information.description1"); + String desc2 = i18n.getString("site-plugin", locale, "report.information.description2"); + DocumentRenderer renderer = new CategorySummaryDocumentRenderer( + renderingContext, title, desc1, desc2, i18n, categoryReports, getLog()); + + if (!documents.containsKey(renderer.getOutputName())) { + documents.put(renderer.getOutputName(), renderer); + } else { + getLog().info("Category summary '" + renderer.getOutputName() + "' skipped; already exists"); } } - if ( categories.containsKey( MavenReport.CATEGORY_PROJECT_REPORTS ) ) - { + if (categories.containsKey(MavenReport.CATEGORY_PROJECT_REPORTS)) { // add "Project Reports" category summary document - List categoryReports = categories.get( MavenReport.CATEGORY_PROJECT_REPORTS ); - RenderingContext renderingContext = - new RenderingContext( siteDirectory, "project-reports.html", - getSitePluginInfo() + ":CategorySummaryDocumentRenderer" ); - String title = i18n.getString( "site-plugin", locale, "report.project.title" ); - String desc1 = i18n.getString( "site-plugin", locale, "report.project.description1" ); - String desc2 = i18n.getString( "site-plugin", locale, "report.project.description2" ); - DocumentRenderer renderer = new CategorySummaryDocumentRenderer( renderingContext, title, desc1, desc2, - i18n, categoryReports, getLog() ); - - if ( !documents.containsKey( renderer.getOutputName() ) ) - { - documents.put( renderer.getOutputName(), renderer ); - } - else - { - getLog().info( "Category summary '" + renderer.getOutputName() + "' skipped; already exists" ); + List categoryReports = categories.get(MavenReport.CATEGORY_PROJECT_REPORTS); + RenderingContext renderingContext = new RenderingContext( + siteDirectory, "project-reports.html", getSitePluginInfo() + ":CategorySummaryDocumentRenderer"); + String title = i18n.getString("site-plugin", locale, "report.project.title"); + String desc1 = i18n.getString("site-plugin", locale, "report.project.description1"); + String desc2 = i18n.getString("site-plugin", locale, "report.project.description2"); + DocumentRenderer renderer = new CategorySummaryDocumentRenderer( + renderingContext, title, desc1, desc2, i18n, categoryReports, getLog()); + + if (!documents.containsKey(renderer.getOutputName())) { + documents.put(renderer.getOutputName(), renderer); + } else { + getLog().info("Category summary '" + renderer.getOutputName() + "' skipped; already exists"); } } return documents; } - private String getSitePluginInfo() - { - PluginDescriptor pluginDescriptor = (PluginDescriptor) getPluginContext().get( "pluginDescriptor" ); + private String getSitePluginInfo() { + PluginDescriptor pluginDescriptor = + (PluginDescriptor) getPluginContext().get("pluginDescriptor"); return pluginDescriptor.getId(); } - protected void populateReportItems( DecorationModel decorationModel, Locale locale, - Map reportsByOutputName ) - { - for ( Menu menu : decorationModel.getMenus() ) - { - populateItemRefs( menu.getItems(), locale, reportsByOutputName ); + + protected void populateReportItems( + DecorationModel decorationModel, Locale locale, Map reportsByOutputName) { + for (Menu menu : decorationModel.getMenus()) { + populateItemRefs(menu.getItems(), locale, reportsByOutputName); } } - private void populateItemRefs( List items, Locale locale, Map reportsByOutputName ) - { - for ( Iterator i = items.iterator(); i.hasNext(); ) - { + private void populateItemRefs(List items, Locale locale, Map reportsByOutputName) { + for (Iterator i = items.iterator(); i.hasNext(); ) { MenuItem item = i.next(); - if ( item.getRef() != null ) - { - MavenReport report = reportsByOutputName.get( item.getRef() ); + if (item.getRef() != null) { + MavenReport report = reportsByOutputName.get(item.getRef()); - if ( report != null ) - { - if ( item.getName() == null ) - { - item.setName( report.getName( locale ) ); + if (report != null) { + if (item.getName() == null) { + item.setName(report.getName(locale)); } - if ( item.getHref() == null || item.getHref().length() == 0 ) - { - item.setHref( report.getOutputName() + ".html" ); + if (item.getHref() == null || item.getHref().length() == 0) { + item.setHref(report.getOutputName() + ".html"); } - } - else - { - getLog().warn( "Unrecognised reference: '" + item.getRef() + "'" ); + } else { + getLog().warn("Unrecognised reference: '" + item.getRef() + "'"); i.remove(); } } - populateItemRefs( item.getItems(), locale, reportsByOutputName ); + populateItemRefs(item.getItems(), locale, reportsByOutputName); } } } diff --git a/src/main/java/org/apache/maven/plugins/site/render/CategorySummaryDocumentRenderer.java b/src/main/java/org/apache/maven/plugins/site/render/CategorySummaryDocumentRenderer.java index 9c295a10..32777d67 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/CategorySummaryDocumentRenderer.java +++ b/src/main/java/org/apache/maven/plugins/site/render/CategorySummaryDocumentRenderer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * 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.site.render; import java.io.FileNotFoundException; import java.io.Writer; @@ -41,9 +40,7 @@ * * @author Brett Porter */ -public class CategorySummaryDocumentRenderer - implements DocumentRenderer -{ +public class CategorySummaryDocumentRenderer implements DocumentRenderer { private RenderingContext renderingContext; private String title; @@ -58,34 +55,42 @@ public class CategorySummaryDocumentRenderer private final Log log; - public CategorySummaryDocumentRenderer( RenderingContext renderingContext, String title, String desc1, String desc2, - I18N i18n, List categoryReports ) - { - this( renderingContext, title, desc1, desc2, i18n, categoryReports, null ); + public CategorySummaryDocumentRenderer( + RenderingContext renderingContext, + String title, + String desc1, + String desc2, + I18N i18n, + List categoryReports) { + this(renderingContext, title, desc1, desc2, i18n, categoryReports, null); } - public CategorySummaryDocumentRenderer( RenderingContext renderingContext, String title, String desc1, String desc2, - I18N i18n, List categoryReports, Log log ) - { + public CategorySummaryDocumentRenderer( + RenderingContext renderingContext, + String title, + String desc1, + String desc2, + I18N i18n, + List categoryReports, + Log log) { this.renderingContext = renderingContext; this.title = title; this.desc1 = desc1; this.desc2 = desc2; this.i18n = i18n; - this.categoryReports = Collections.unmodifiableList( categoryReports ); + this.categoryReports = Collections.unmodifiableList(categoryReports); this.log = log; } - public void renderDocument( Writer writer, Renderer renderer, SiteRenderingContext siteRenderingContext ) - throws RendererException, FileNotFoundException - { - SiteRendererSink sink = new SiteRendererSink( renderingContext ); + public void renderDocument(Writer writer, Renderer renderer, SiteRenderingContext siteRenderingContext) + throws RendererException, FileNotFoundException { + SiteRendererSink sink = new SiteRendererSink(renderingContext); sink.head(); sink.title(); - sink.text( title ); + sink.text(title); sink.title_(); @@ -95,58 +100,56 @@ public void renderDocument( Writer writer, Renderer renderer, SiteRenderingConte sink.section1(); sink.sectionTitle1(); - sink.text( title ); + sink.text(title); sink.sectionTitle1_(); sink.paragraph(); - sink.text( desc1 + " " ); - sink.link( "http://maven.apache.org" ); - sink.text( "Maven" ); + sink.text(desc1 + " "); + sink.link("http://maven.apache.org"); + sink.text("Maven"); sink.link_(); - sink.text( " " + desc2 ); + sink.text(" " + desc2); sink.paragraph_(); sink.section2(); sink.sectionTitle2(); Locale locale = siteRenderingContext.getLocale(); - sink.text( i18n.getString( "site-plugin", locale, "report.category.sectionTitle" ) ); + sink.text(i18n.getString("site-plugin", locale, "report.category.sectionTitle")); sink.sectionTitle2_(); sink.table(); - sink.tableRows( new int[] {Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT}, false ); + sink.tableRows(new int[] {Sink.JUSTIFY_LEFT, Sink.JUSTIFY_LEFT}, false); - String name = i18n.getString( "site-plugin", locale, "report.category.column.document" ); - String description = i18n.getString( "site-plugin", locale, "report.category.column.description" ); + String name = i18n.getString("site-plugin", locale, "report.category.column.document"); + String description = i18n.getString("site-plugin", locale, "report.category.column.description"); sink.tableRow(); sink.tableHeaderCell(); - sink.text( name ); + sink.text(name); sink.tableHeaderCell_(); sink.tableHeaderCell(); - sink.text( description ); + sink.text(description); sink.tableHeaderCell_(); sink.tableRow_(); - if ( categoryReports != null ) - { - for ( MavenReport report : categoryReports ) - { + if (categoryReports != null) { + for (MavenReport report : categoryReports) { sink.tableRow(); sink.tableCell(); - sink.link( report.getOutputName() + ".html" ); - sink.text( report.getName( locale ) ); + sink.link(report.getOutputName() + ".html"); + sink.text(report.getName(locale)); sink.link_(); sink.tableCell_(); sink.tableCell(); - sink.text( report.getDescription( locale ) ); + sink.text(report.getDescription(locale)); sink.tableCell_(); sink.tableRow_(); } @@ -166,26 +169,22 @@ public void renderDocument( Writer writer, Renderer renderer, SiteRenderingConte sink.close(); - renderer.mergeDocumentIntoSite( writer, sink, siteRenderingContext ); + renderer.mergeDocumentIntoSite(writer, sink, siteRenderingContext); } - public String getOutputName() - { + public String getOutputName() { return renderingContext.getOutputName(); } - public RenderingContext getRenderingContext() - { + public RenderingContext getRenderingContext() { return renderingContext; } - public boolean isOverwrite() - { + public boolean isOverwrite() { return true; } - - public boolean isExternalReport() - { + + public boolean isExternalReport() { return false; } } diff --git a/src/main/java/org/apache/maven/plugins/site/render/ReportDocumentRenderer.java b/src/main/java/org/apache/maven/plugins/site/render/ReportDocumentRenderer.java index 83dfe9a2..147789b5 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/ReportDocumentRenderer.java +++ b/src/main/java/org/apache/maven/plugins/site/render/ReportDocumentRenderer.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,17 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.render; -import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; - +import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; -import java.io.File; import java.util.ArrayList; -import java.util.Locale; import java.util.List; +import java.util.Locale; import org.apache.maven.doxia.sink.Sink; import org.apache.maven.doxia.sink.SinkFactory; @@ -47,15 +44,15 @@ import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.WriterFactory; +import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; + /** * Renders a Maven report in a Doxia site. * * @author Brett Porter * @see org.apache.maven.doxia.siterenderer.DoxiaDocumentRenderer */ -public class ReportDocumentRenderer - implements DocumentRenderer -{ +public class ReportDocumentRenderer implements DocumentRenderer { private final MavenReport report; private final RenderingContext renderingContext; @@ -66,52 +63,45 @@ public class ReportDocumentRenderer private final Log log; - public ReportDocumentRenderer( MavenReportExecution mavenReportExecution, RenderingContext renderingContext, - Log log ) - { + public ReportDocumentRenderer( + MavenReportExecution mavenReportExecution, RenderingContext renderingContext, Log log) { this.report = mavenReportExecution.getMavenReport(); this.renderingContext = renderingContext; // full MavenReportExecution prepared by maven-reporting-impl - this.reportMojoInfo = - mavenReportExecution.getPlugin().getArtifactId() + ':' + mavenReportExecution.getPlugin().getVersion() - + ':' + mavenReportExecution.getGoal(); + this.reportMojoInfo = mavenReportExecution.getPlugin().getArtifactId() + + ':' + + mavenReportExecution.getPlugin().getVersion() + + ':' + + mavenReportExecution.getGoal(); this.classLoader = mavenReportExecution.getClassLoader(); this.log = log; } - private static class MultiPageSubSink - extends SiteRendererSink - { + private static class MultiPageSubSink extends SiteRendererSink { private File outputDir; private String outputName; - MultiPageSubSink( File outputDir, String outputName, RenderingContext context ) - { - super( context ); + MultiPageSubSink(File outputDir, String outputName, RenderingContext context) { + super(context); this.outputName = outputName; this.outputDir = outputDir; } - public String getOutputName() - { + public String getOutputName() { return outputName; } - public File getOutputDir() - { + public File getOutputDir() { return outputDir; } - } - private static class MultiPageSinkFactory - implements SinkFactory - { + private static class MultiPageSinkFactory implements SinkFactory { /** * The report that is (maybe) generating multiple pages */ @@ -127,199 +117,164 @@ private static class MultiPageSinkFactory */ private List sinks = new ArrayList(); - MultiPageSinkFactory( MavenReport report, RenderingContext context ) - { + MultiPageSinkFactory(MavenReport report, RenderingContext context) { this.report = report; this.context = context; } @Override - public Sink createSink( File outputDir, String outputName ) - { + public Sink createSink(File outputDir, String outputName) { // Create a new context, similar to the main one, but with a different output name String outputRelativeToTargetSite = PathTool.getRelativeFilePath( - report.getReportOutputDirectory().getPath(), - new File( outputDir, outputName ).getPath() - ); + report.getReportOutputDirectory().getPath(), new File(outputDir, outputName).getPath()); RenderingContext subSinkContext = new RenderingContext( - context.getBasedir(), - context.getBasedirRelativePath(), - outputRelativeToTargetSite, - context.getParserId(), - context.getExtension(), - context.isEditable(), - context.getGenerator() - ); + context.getBasedir(), + context.getBasedirRelativePath(), + outputRelativeToTargetSite, + context.getParserId(), + context.getExtension(), + context.isEditable(), + context.getGenerator()); // Create a sink for this subpage, based on this new context - MultiPageSubSink sink = new MultiPageSubSink( outputDir, outputName, subSinkContext ); + MultiPageSubSink sink = new MultiPageSubSink(outputDir, outputName, subSinkContext); // Add it to the list of sinks associated to this report - sinks.add( sink ); + sinks.add(sink); return sink; } @Override - public Sink createSink( File arg0, String arg1, String arg2 ) - throws IOException - { + public Sink createSink(File arg0, String arg1, String arg2) throws IOException { // Not used return null; } @Override - public Sink createSink( OutputStream arg0 ) - throws IOException - { + public Sink createSink(OutputStream arg0) throws IOException { // Not used return null; } @Override - public Sink createSink( OutputStream arg0, String arg1 ) - throws IOException - { + public Sink createSink(OutputStream arg0, String arg1) throws IOException { // Not used return null; } - public List sinks() - { + public List sinks() { return sinks; } } @Override - public void renderDocument( Writer writer, Renderer renderer, SiteRenderingContext siteRenderingContext ) - throws RendererException, FileNotFoundException - { + public void renderDocument(Writer writer, Renderer renderer, SiteRenderingContext siteRenderingContext) + throws RendererException, FileNotFoundException { Locale locale = siteRenderingContext.getLocale(); - String localReportName = report.getName( locale ); + String localReportName = report.getName(locale); - String msg = "Generating \"" + buffer().strong( localReportName ) + "\" report"; + String msg = "Generating \"" + buffer().strong(localReportName) + "\" report"; // CHECKSTYLE_OFF: MagicNumber - log.info( reportMojoInfo == null ? ( msg + '.' ) - : ( StringUtils.rightPad( msg, 40 ) + buffer().strong( " --- " ).mojo( reportMojoInfo ) ) ); + log.info( + reportMojoInfo == null + ? (msg + '.') + : (StringUtils.rightPad(msg, 40) + + buffer().strong(" --- ").mojo(reportMojoInfo))); // CHECKSTYLE_ON: MagicNumber // main sink - SiteRendererSink mainSink = new SiteRendererSink( renderingContext ); + SiteRendererSink mainSink = new SiteRendererSink(renderingContext); // sink factory, for multi-page reports that need sub-sinks - MultiPageSinkFactory multiPageSinkFactory = new MultiPageSinkFactory( report, renderingContext ); + MultiPageSinkFactory multiPageSinkFactory = new MultiPageSinkFactory(report, renderingContext); ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); - try - { - if ( classLoader != null ) - { - Thread.currentThread().setContextClassLoader( classLoader ); + try { + if (classLoader != null) { + Thread.currentThread().setContextClassLoader(classLoader); } - if ( report instanceof MavenMultiPageReport ) - { + if (report instanceof MavenMultiPageReport) { // extended multi-page API - ( (MavenMultiPageReport) report ).generate( mainSink, multiPageSinkFactory, locale ); - } - else - { + ((MavenMultiPageReport) report).generate(mainSink, multiPageSinkFactory, locale); + } else { // old single-page-only API - report.generate( mainSink, locale ); + report.generate(mainSink, locale); } - } - catch ( MavenReportException e ) - { - String report = ( reportMojoInfo == null ) ? ( '"' + localReportName + '"' ) : reportMojoInfo; - throw new RendererException( "Error generating " + report + " report", e ); - } - catch ( RuntimeException re ) - { + } catch (MavenReportException e) { + String report = (reportMojoInfo == null) ? ('"' + localReportName + '"') : reportMojoInfo; + throw new RendererException("Error generating " + report + " report", e); + } catch (RuntimeException re) { // MSITE-836: if report generation throws a RuntimeException, transform to RendererException - String report = ( reportMojoInfo == null ) ? ( '"' + localReportName + '"' ) : reportMojoInfo; - throw new RendererException( "Error generating " + report + " report", re ); - } - catch ( LinkageError e ) - { - String report = ( reportMojoInfo == null ) ? ( '"' + localReportName + '"' ) : reportMojoInfo; - log.warn( "An issue has occurred with " + report + " report, skipping LinkageError " - + e.getMessage() + ", please report an issue to Maven dev team.", e ); - } - finally - { - if ( classLoader != null ) - { - Thread.currentThread().setContextClassLoader( originalClassLoader ); + String report = (reportMojoInfo == null) ? ('"' + localReportName + '"') : reportMojoInfo; + throw new RendererException("Error generating " + report + " report", re); + } catch (LinkageError e) { + String report = (reportMojoInfo == null) ? ('"' + localReportName + '"') : reportMojoInfo; + log.warn( + "An issue has occurred with " + report + " report, skipping LinkageError " + e.getMessage() + + ", please report an issue to Maven dev team.", + e); + } finally { + if (classLoader != null) { + Thread.currentThread().setContextClassLoader(originalClassLoader); } mainSink.close(); } - if ( report.isExternalReport() ) - { + if (report.isExternalReport()) { // external reports are rendered from their own: no Doxia site rendering needed return; } // render main sink document content - renderer.mergeDocumentIntoSite( writer, mainSink, siteRenderingContext ); + renderer.mergeDocumentIntoSite(writer, mainSink, siteRenderingContext); // render sub-sinks, eventually created by multi-page reports String outputName = ""; - try - { + try { List sinks = multiPageSinkFactory.sinks(); - log.debug( "Multipage report: " + sinks.size() + " subreports" ); + log.debug("Multipage report: " + sinks.size() + " subreports"); - for ( MultiPageSubSink mySink : sinks ) - { + for (MultiPageSubSink mySink : sinks) { outputName = mySink.getOutputName(); - log.debug( " Rendering " + outputName ); + log.debug(" Rendering " + outputName); // Create directories if necessary - if ( !mySink.getOutputDir().exists() ) - { + if (!mySink.getOutputDir().exists()) { mySink.getOutputDir().mkdirs(); } - File outputFile = new File( mySink.getOutputDir(), outputName ); + File outputFile = new File(mySink.getOutputDir(), outputName); - try ( Writer out = WriterFactory.newWriter( outputFile, siteRenderingContext.getOutputEncoding() ) ) - { - renderer.mergeDocumentIntoSite( out, mySink, siteRenderingContext ); + try (Writer out = WriterFactory.newWriter(outputFile, siteRenderingContext.getOutputEncoding())) { + renderer.mergeDocumentIntoSite(out, mySink, siteRenderingContext); mySink.close(); mySink = null; - } - finally - { - if ( mySink != null ) - { + } finally { + if (mySink != null) { mySink.close(); } } } - } - catch ( IOException e ) - { - throw new RendererException( "Cannot create writer to " + outputName, e ); + } catch (IOException e) { + throw new RendererException("Cannot create writer to " + outputName, e); } } @Override - public String getOutputName() - { + public String getOutputName() { return renderingContext.getOutputName(); } @Override - public RenderingContext getRenderingContext() - { + public RenderingContext getRenderingContext() { return renderingContext; } @Override - public boolean isOverwrite() - { + public boolean isOverwrite() { // TODO: would be nice to query the report to see if it is modified return true; } @@ -328,13 +283,11 @@ public boolean isOverwrite() * @return true if the current report is external, false otherwise */ @Override - public boolean isExternalReport() - { + public boolean isExternalReport() { return report.isExternalReport(); } - public String getReportMojoInfo() - { + public String getReportMojoInfo() { return reportMojoInfo; } } diff --git a/src/main/java/org/apache/maven/plugins/site/render/SiteJarMojo.java b/src/main/java/org/apache/maven/plugins/site/render/SiteJarMojo.java index 8880052d..130a2d06 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/SiteJarMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/render/SiteJarMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * 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.site.render; import java.io.File; import java.io.IOException; @@ -46,26 +45,27 @@ * @since 2.0-beta-6 */ // MSITE-665: requiresDependencyResolution workaround for MPLUGIN-253 -@Mojo( name = "jar", defaultPhase = LifecyclePhase.PACKAGE, requiresDependencyResolution = ResolutionScope.TEST, - requiresReports = true ) -public class SiteJarMojo - extends SiteMojo -{ - private static final String[] DEFAULT_ARCHIVE_EXCLUDES = new String[]{ }; +@Mojo( + name = "jar", + defaultPhase = LifecyclePhase.PACKAGE, + requiresDependencyResolution = ResolutionScope.TEST, + requiresReports = true) +public class SiteJarMojo extends SiteMojo { + private static final String[] DEFAULT_ARCHIVE_EXCLUDES = new String[] {}; - private static final String[] DEFAULT_ARCHIVE_INCLUDES = new String[]{ "**/**" }; + private static final String[] DEFAULT_ARCHIVE_INCLUDES = new String[] {"**/**"}; /** * Specifies the directory where the generated jar file will be put. */ - @Parameter( property = "project.build.directory", required = true ) + @Parameter(property = "project.build.directory", required = true) private String jarOutputDirectory; /** * Specifies the filename that will be used for the generated jar file. * Please note that "-site" will be appended to the file name. */ - @Parameter( property = "project.build.finalName", required = true ) + @Parameter(property = "project.build.finalName", required = true) private String finalName; /** @@ -77,7 +77,7 @@ public class SiteJarMojo /** * Specifies whether to attach the generated artifact to the project. */ - @Parameter( property = "site.attach", defaultValue = "true" ) + @Parameter(property = "site.attach", defaultValue = "true") private boolean attach; /** @@ -85,7 +85,7 @@ public class SiteJarMojo * * @since 3.1 */ - @Component( role = Archiver.class, hint = "jar" ) + @Component(role = Archiver.class, hint = "jar") private JarArchiver jarArchiver; /** @@ -122,50 +122,39 @@ public class SiteJarMojo * * @since 3.9.0 */ - @Parameter( defaultValue = "${project.build.outputTimestamp}" ) + @Parameter(defaultValue = "${project.build.outputTimestamp}") private String outputTimestamp; /** * @see org.apache.maven.plugin.Mojo#execute() */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "maven.site.skip = true: Skipping jar generation" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("maven.site.skip = true: Skipping jar generation"); return; } super.execute(); - try - { - File outputFile = createArchive( outputDirectory, - finalName + "-" + getClassifier() + "." + getArtifactType() ); + try { + File outputFile = + createArchive(outputDirectory, finalName + "-" + getClassifier() + "." + getArtifactType()); - if ( attach ) - { - projectHelper.attachArtifact( project, getArtifactType(), getClassifier(), outputFile ); + if (attach) { + projectHelper.attachArtifact(project, getArtifactType(), getClassifier(), outputFile); + } else { + getLog().info("NOT adding site jar to the list of attached artifacts."); } - else - { - getLog().info( "NOT adding site jar to the list of attached artifacts." ); - } - } - catch ( ArchiverException | IOException | ManifestException | DependencyResolutionRequiredException e ) - { - throw new MojoExecutionException( "Error while creating archive.", e ); + } catch (ArchiverException | IOException | ManifestException | DependencyResolutionRequiredException e) { + throw new MojoExecutionException("Error while creating archive.", e); } } - protected String getArtifactType() - { + protected String getArtifactType() { return "jar"; } - protected String getClassifier() - { + protected String getClassifier() { return "site"; } @@ -180,49 +169,41 @@ protected String getClassifier() * @throws ManifestException * @throws DependencyResolutionRequiredException */ - private File createArchive( File siteDirectory, String jarFilename ) - throws ArchiverException, IOException, ManifestException, DependencyResolutionRequiredException - { - File siteJar = new File( jarOutputDirectory, jarFilename ); + private File createArchive(File siteDirectory, String jarFilename) + throws ArchiverException, IOException, ManifestException, DependencyResolutionRequiredException { + File siteJar = new File(jarOutputDirectory, jarFilename); MavenArchiver archiver = new MavenArchiver(); - archiver.setCreatedBy( "Maven Site Plugin", "org.apache.maven.plugins", "maven-site-plugin" ); + archiver.setCreatedBy("Maven Site Plugin", "org.apache.maven.plugins", "maven-site-plugin"); - archiver.setArchiver( this.jarArchiver ); + archiver.setArchiver(this.jarArchiver); - archiver.setOutputFile( siteJar ); + archiver.setOutputFile(siteJar); // configure for Reproducible Builds based on outputTimestamp value - archiver.configureReproducibleBuild( outputTimestamp ); + archiver.configureReproducibleBuild(outputTimestamp); - if ( !siteDirectory.isDirectory() ) - { - getLog().warn( "JAR will be empty - no content was marked for inclusion!" ); - } - else - { - archiver.getArchiver().addDirectory( siteDirectory, getArchiveIncludes(), getArchiveExcludes() ); + if (!siteDirectory.isDirectory()) { + getLog().warn("JAR will be empty - no content was marked for inclusion!"); + } else { + archiver.getArchiver().addDirectory(siteDirectory, getArchiveIncludes(), getArchiveExcludes()); } - archiver.createArchive( getSession(), getProject(), archive ); + archiver.createArchive(getSession(), getProject(), archive); return siteJar; } - private String[] getArchiveIncludes() - { - if ( this.archiveIncludes != null && this.archiveIncludes.length > 0 ) - { + private String[] getArchiveIncludes() { + if (this.archiveIncludes != null && this.archiveIncludes.length > 0) { return this.archiveIncludes; } return DEFAULT_ARCHIVE_INCLUDES; } - private String[] getArchiveExcludes() - { - if ( this.archiveExcludes != null && this.archiveExcludes.length > 0 ) - { + private String[] getArchiveExcludes() { + if (this.archiveExcludes != null && this.archiveExcludes.length > 0) { return this.archiveExcludes; } return DEFAULT_ARCHIVE_EXCLUDES; diff --git a/src/main/java/org/apache/maven/plugins/site/render/SiteMap.java b/src/main/java/org/apache/maven/plugins/site/render/SiteMap.java index d454170d..890273a6 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/SiteMap.java +++ b/src/main/java/org/apache/maven/plugins/site/render/SiteMap.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,10 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.render; import java.io.File; import java.io.IOException; - import java.util.List; import java.util.Locale; @@ -30,7 +28,6 @@ import org.apache.maven.doxia.site.decoration.DecorationModel; import org.apache.maven.doxia.site.decoration.Menu; import org.apache.maven.doxia.site.decoration.MenuItem; - import org.codehaus.plexus.i18n.I18N; /** @@ -40,8 +37,7 @@ * * @since 2.1 */ -public class SiteMap -{ +public class SiteMap { private String encoding; private I18N i18n; @@ -52,8 +48,7 @@ public class SiteMap * @param encoding the default encoding to use when writing the output file. * @param i18n the default I18N for translations. */ - public SiteMap( String encoding, I18N i18n ) - { + public SiteMap(String encoding, I18N i18n) { this.encoding = encoding; this.i18n = i18n; } @@ -63,8 +58,7 @@ public SiteMap( String encoding, I18N i18n ) * * @return the value of i18n. */ - public I18N getI18n() - { + public I18N getI18n() { return i18n; } @@ -73,8 +67,7 @@ public I18N getI18n() * * @param i18n new value of i18n. */ - public void setI18n( I18N i18n ) - { + public void setI18n(I18N i18n) { this.i18n = i18n; } @@ -83,8 +76,7 @@ public void setI18n( I18N i18n ) * * @return the value of encoding. */ - public String getEncoding() - { + public String getEncoding() { return encoding; } @@ -93,8 +85,7 @@ public String getEncoding() * * @param enc new value of encoding. */ - public void setEncoding( String enc ) - { + public void setEncoding(String enc) { this.encoding = enc; } @@ -109,49 +100,42 @@ public void setEncoding( String enc ) * * @throws IOException if the file cannot be ceated. */ - public void generate( DecorationModel model, File targetDir, Locale locale ) - throws IOException - { - File outputDir = new File( targetDir, "xdoc" ); - Sink sink = new XdocSinkFactory().createSink( outputDir, "sitemap.xml", encoding ); - - try - { - extract( model, sink, locale ); - } - finally - { + public void generate(DecorationModel model, File targetDir, Locale locale) throws IOException { + File outputDir = new File(targetDir, "xdoc"); + Sink sink = new XdocSinkFactory().createSink(outputDir, "sitemap.xml", encoding); + + try { + extract(model, sink, locale); + } finally { sink.close(); } } - private void extract( DecorationModel decoration, Sink sink, Locale locale ) - { + private void extract(DecorationModel decoration, Sink sink, Locale locale) { sink.head(); sink.title(); - sink.text( i18n.getString( "site-plugin", locale, "site.sitemap.title" ) ); + sink.text(i18n.getString("site-plugin", locale, "site.sitemap.title")); sink.title_(); sink.head_(); sink.body(); sink.section1(); sink.sectionTitle1(); - sink.text( i18n.getString( "site-plugin", locale, "site.sitemap.section.title" ) ); + sink.text(i18n.getString("site-plugin", locale, "site.sitemap.section.title")); sink.sectionTitle1_(); sink.paragraph(); - sink.text( i18n.getString( "site-plugin", locale, "site.sitemap.description" ) ); + sink.text(i18n.getString("site-plugin", locale, "site.sitemap.description")); sink.paragraph_(); - for ( Menu menu : decoration.getMenus() ) - { + for (Menu menu : decoration.getMenus()) { sink.section3(); sink.sectionTitle3(); - sink.text( menu.getName() ); + sink.text(menu.getName()); sink.sectionTitle3_(); sink.horizontalRule(); - extractItems( menu.getItems(), sink ); + extractItems(menu.getItems(), sink); sink.section3_(); } @@ -160,26 +144,22 @@ private void extract( DecorationModel decoration, Sink sink, Locale locale ) sink.body_(); } - private static void extractItems( List items, Sink sink ) - { - if ( items == null || items.isEmpty() ) - { + private static void extractItems(List items, Sink sink) { + if (items == null || items.isEmpty()) { return; } sink.list(); - for ( MenuItem item : items ) - { + for (MenuItem item : items) { sink.listItem(); - if ( item.getHref() != null ) - { - sink.link( relativePath( item.getHref() ) ); - sink.text( item.getName() ); + if (item.getHref() != null) { + sink.link(relativePath(item.getHref())); + sink.text(item.getName()); sink.link_(); } - extractItems( item.getItems(), sink ); + extractItems(item.getItems(), sink); sink.listItem_(); } @@ -187,8 +167,7 @@ private static void extractItems( List items, Sink sink ) } // sitemap.html gets generated into top-level so we only have to check leading slashes - private static String relativePath( String href ) - { - return href.startsWith( "/" ) ? "." + href : href; + private static String relativePath(String href) { + return href.startsWith("/") ? "." + href : href; } } diff --git a/src/main/java/org/apache/maven/plugins/site/render/SiteMojo.java b/src/main/java/org/apache/maven/plugins/site/render/SiteMojo.java index e0537517..c8b1880d 100644 --- a/src/main/java/org/apache/maven/plugins/site/render/SiteMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/render/SiteMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.render; - /* * 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.site.render; import java.io.File; import java.io.IOException; @@ -58,20 +57,18 @@ * @author Vincent Siveton * */ -@Mojo( name = "site", requiresDependencyResolution = ResolutionScope.TEST, requiresReports = true ) -public class SiteMojo - extends AbstractSiteRenderingMojo -{ +@Mojo(name = "site", requiresDependencyResolution = ResolutionScope.TEST, requiresReports = true) +public class SiteMojo extends AbstractSiteRenderingMojo { /** * Directory where the project sites and report distributions will be generated (as html/css/...). */ - @Parameter( property = "siteOutputDirectory", defaultValue = "${project.reporting.outputDirectory}" ) + @Parameter(property = "siteOutputDirectory", defaultValue = "${project.reporting.outputDirectory}") protected File outputDirectory; /** * Convenience parameter that allows you to disable report generation. */ - @Parameter( property = "generateReports", defaultValue = "true" ) + @Parameter(property = "generateReports", defaultValue = "true") private boolean generateReports; /** @@ -79,7 +76,7 @@ public class SiteMojo * * @since 2.1 */ - @Parameter( property = "generateSitemap", defaultValue = "false" ) + @Parameter(property = "generateSitemap", defaultValue = "false") private boolean generateSitemap; /** @@ -88,123 +85,104 @@ public class SiteMojo * * @since 2.1.1 */ - @Parameter( property = "validate", defaultValue = "false" ) + @Parameter(property = "validate", defaultValue = "false") private boolean validate; /** * {@inheritDoc} */ - public void execute() - throws MojoExecutionException, MojoFailureException - { - if ( skip ) - { - getLog().info( "maven.site.skip = true: Skipping site generation" ); + public void execute() throws MojoExecutionException, MojoFailureException { + if (skip) { + getLog().info("maven.site.skip = true: Skipping site generation"); return; } - if ( getLog().isDebugEnabled() ) - { - getLog().debug( "executing Site Mojo" ); + if (getLog().isDebugEnabled()) { + getLog().debug("executing Site Mojo"); } checkInputEncoding(); List reports; - if ( generateReports ) - { + if (generateReports) { reports = getReports(); - } - else - { + } else { reports = Collections.emptyList(); } - try - { + try { List localesList = getLocales(); // Default is first in the list - Locale defaultLocale = localesList.get( 0 ); - - for ( Locale locale : localesList ) - { - getLog().info( "Rendering site for " - + buffer().strong( ( locale.equals( defaultLocale ) - ? "default locale" : "locale '" + locale + "'" ) ).toString() ); - renderLocale( locale, reports, localesList ); + Locale defaultLocale = localesList.get(0); + + for (Locale locale : localesList) { + getLog().info("Rendering site for " + + buffer().strong((locale.equals(defaultLocale) ? "default locale" : "locale '" + locale + "'")) + .toString()); + renderLocale(locale, reports, localesList); } - } - catch ( RendererException e ) - { - if ( e.getCause() instanceof MavenReportException ) - { + } catch (RendererException e) { + if (e.getCause() instanceof MavenReportException) { // issue caused by report, not really by Doxia Site Renderer - throw new MojoExecutionException( e.getMessage(), e.getCause() ); + throw new MojoExecutionException(e.getMessage(), e.getCause()); } - throw new MojoExecutionException( e.getMessage(), e ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Error during site generation", e ); + throw new MojoExecutionException(e.getMessage(), e); + } catch (IOException e) { + throw new MojoExecutionException("Error during site generation", e); } } - private void renderLocale( Locale locale, List reports, List supportedLocales ) - throws IOException, RendererException, MojoFailureException, MojoExecutionException - { - SiteRenderingContext context = createSiteRenderingContext( locale ); - context.addSiteLocales( supportedLocales ); + private void renderLocale(Locale locale, List reports, List supportedLocales) + throws IOException, RendererException, MojoFailureException, MojoExecutionException { + SiteRenderingContext context = createSiteRenderingContext(locale); + context.addSiteLocales(supportedLocales); // MSITE-723 add generated site directory, in case some content has been put in pre-site phase - context.addSiteDirectory( generatedSiteDirectory ); - - context.setInputEncoding( getInputEncoding() ); - context.setOutputEncoding( getOutputEncoding() ); - context.setValidate( validate ); - if ( validate ) - { - getLog().info( "Validation is switched on, xml input documents will be validated!" ); + context.addSiteDirectory(generatedSiteDirectory); + + context.setInputEncoding(getInputEncoding()); + context.setOutputEncoding(getOutputEncoding()); + context.setValidate(validate); + if (validate) { + getLog().info("Validation is switched on, xml input documents will be validated!"); } - File outputDir = getOutputDirectory( locale ); + File outputDir = getOutputDirectory(locale); - Map documents = locateDocuments( context, reports, locale ); + Map documents = locateDocuments(context, reports, locale); // copy resources - siteRenderer.copyResources( context, outputDir ); + siteRenderer.copyResources(context, outputDir); // 1. render Doxia documents first - List reportDocuments = renderDoxiaDocuments( documents, context, outputDir, false ); + List reportDocuments = renderDoxiaDocuments(documents, context, outputDir, false); // 2. then reports // prepare external reports - for ( MavenReportExecution mavenReportExecution : reports ) - { + for (MavenReportExecution mavenReportExecution : reports) { MavenReport report = mavenReportExecution.getMavenReport(); - report.setReportOutputDirectory( outputDir ); + report.setReportOutputDirectory(outputDir); } - siteRenderer.render( reportDocuments, context, outputDir ); + siteRenderer.render(reportDocuments, context, outputDir); - if ( generateSitemap ) - { - getLog().info( "Generating Sitemap." ); + if (generateSitemap) { + getLog().info("Generating Sitemap."); - new SiteMap( getOutputEncoding(), i18n ).generate( context.getDecoration(), generatedSiteDirectory, - locale ); + new SiteMap(getOutputEncoding(), i18n).generate(context.getDecoration(), generatedSiteDirectory, locale); } // 3. Generated docs must be (re-)done afterwards as they are often generated by reports context.getSiteDirectories().clear(); - context.addSiteDirectory( generatedSiteDirectory ); + context.addSiteDirectory(generatedSiteDirectory); Map generatedDocuments = - siteRenderer.locateDocumentFiles( context, false /* not editable */ ); + siteRenderer.locateDocumentFiles(context, false /* not editable */); - renderDoxiaDocuments( generatedDocuments, context, outputDir, true ); + renderDoxiaDocuments(generatedDocuments, context, outputDir, true); // copy generated resources also - siteRenderer.copyResources( context, outputDir ); + siteRenderer.copyResources(context, outputDir); } /** @@ -213,103 +191,82 @@ private void renderLocale( Locale locale, List reports, Li * @param documents a collection of documents containing both Doxia source files and reports * @return the sublist of documents that are not Doxia source files */ - private List renderDoxiaDocuments( Map documents, - SiteRenderingContext context, File outputDir, - boolean generated ) - throws RendererException, IOException - { + private List renderDoxiaDocuments( + Map documents, SiteRenderingContext context, File outputDir, boolean generated) + throws RendererException, IOException { Map doxiaDocuments = new TreeMap<>(); List nonDoxiaDocuments = new ArrayList<>(); Map counts = new TreeMap<>(); - for ( Map.Entry entry : documents.entrySet() ) - { + for (Map.Entry entry : documents.entrySet()) { DocumentRenderer doc = entry.getValue(); - if ( doc instanceof DoxiaDocumentRenderer ) - { - doxiaDocuments.put( entry.getKey(), doc ); + if (doc instanceof DoxiaDocumentRenderer) { + doxiaDocuments.put(entry.getKey(), doc); DoxiaDocumentRenderer doxia = (DoxiaDocumentRenderer) doc; // count documents per parserId String parserId = doxia.getRenderingContext().getParserId(); - Integer count = counts.get( parserId ); - if ( count == null ) - { + Integer count = counts.get(parserId); + if (count == null) { count = 1; - } - else - { + } else { count++; } - counts.put( parserId, count ); - } - else - { - nonDoxiaDocuments.add( doc ); + counts.put(parserId, count); + } else { + nonDoxiaDocuments.add(doc); } } - if ( doxiaDocuments.size() > 0 ) - { + if (doxiaDocuments.size() > 0) { MessageBuilder mb = buffer(); - mb.a( "Rendering " ); - mb.strong( doxiaDocuments.size() + ( generated ? " generated" : "" ) + " Doxia document" - + ( doxiaDocuments.size() > 1 ? "s" : "" ) ); - mb.a( ": " ); + mb.a("Rendering "); + mb.strong(doxiaDocuments.size() + (generated ? " generated" : "") + " Doxia document" + + (doxiaDocuments.size() > 1 ? "s" : "")); + mb.a(": "); boolean first = true; - for ( Map.Entry entry : counts.entrySet() ) - { - if ( first ) - { + for (Map.Entry entry : counts.entrySet()) { + if (first) { first = false; + } else { + mb.a(", "); } - else - { - mb.a( ", " ); - } - mb.strong( entry.getValue() + " " + entry.getKey() ); + mb.strong(entry.getValue() + " " + entry.getKey()); } - getLog().info( mb.toString() ); + getLog().info(mb.toString()); - siteRenderer.render( doxiaDocuments.values(), context, outputDir ); + siteRenderer.render(doxiaDocuments.values(), context, outputDir); } return nonDoxiaDocuments; } - private File getOutputDirectory( Locale locale ) - { + private File getOutputDirectory(Locale locale) { File file; - if ( locale.equals( SiteTool.DEFAULT_LOCALE ) ) - { + if (locale.equals(SiteTool.DEFAULT_LOCALE)) { file = outputDirectory; - } - else - { - file = new File( outputDirectory, locale.toString() ); + } else { + file = new File(outputDirectory, locale.toString()); } // Safety - if ( !file.exists() ) - { + if (!file.exists()) { file.mkdirs(); } return file; } - public MavenProject getProject() - { + public MavenProject getProject() { return project; } - public MavenSession getSession() - { + public MavenSession getSession() { return mavenSession; } } diff --git a/src/main/java/org/apache/maven/plugins/site/run/DoxiaBean.java b/src/main/java/org/apache/maven/plugins/site/run/DoxiaBean.java index 792452e3..34f97a9f 100644 --- a/src/main/java/org/apache/maven/plugins/site/run/DoxiaBean.java +++ b/src/main/java/org/apache/maven/plugins/site/run/DoxiaBean.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.run; - /* * 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.site.run; import java.util.Map; @@ -30,8 +29,7 @@ * @author Vincent Siveton * */ -public class DoxiaBean -{ +public class DoxiaBean { private SiteRenderingContext context; private Map documents; @@ -43,41 +41,36 @@ public class DoxiaBean * @param documents documents * @param generatedSiteContext context of generated content */ - public DoxiaBean( SiteRenderingContext context, Map documents, - SiteRenderingContext generatedSiteContext ) - { + public DoxiaBean( + SiteRenderingContext context, + Map documents, + SiteRenderingContext generatedSiteContext) { this.context = context; this.documents = documents; this.generatedSiteContext = generatedSiteContext; } - public SiteRenderingContext getContext() - { + public SiteRenderingContext getContext() { return context; } - public void setContext( SiteRenderingContext context ) - { + public void setContext(SiteRenderingContext context) { this.context = context; } - public Map getDocuments() - { + public Map getDocuments() { return documents; } - public void setDocuments( Map documents ) - { + public void setDocuments(Map documents) { this.documents = documents; } - public SiteRenderingContext getGeneratedSiteContext() - { + public SiteRenderingContext getGeneratedSiteContext() { return generatedSiteContext; } - public void setGeneratedSiteContext( SiteRenderingContext generatedSiteContext ) - { + public void setGeneratedSiteContext(SiteRenderingContext generatedSiteContext) { this.generatedSiteContext = generatedSiteContext; } } diff --git a/src/main/java/org/apache/maven/plugins/site/run/DoxiaFilter.java b/src/main/java/org/apache/maven/plugins/site/run/DoxiaFilter.java index 8853984e..96725bf6 100644 --- a/src/main/java/org/apache/maven/plugins/site/run/DoxiaFilter.java +++ b/src/main/java/org/apache/maven/plugins/site/run/DoxiaFilter.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.run; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,15 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import org.apache.maven.doxia.siterenderer.DocumentRenderer; -import org.apache.maven.doxia.siterenderer.DoxiaDocumentRenderer; -import org.apache.maven.doxia.siterenderer.Renderer; -import org.apache.maven.doxia.siterenderer.RendererException; -import org.apache.maven.doxia.siterenderer.SiteRenderingContext; -import org.apache.maven.plugins.site.render.ReportDocumentRenderer; - -import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; +package org.apache.maven.plugins.site.run; import javax.servlet.Filter; import javax.servlet.FilterChain; @@ -45,14 +35,21 @@ import java.util.Locale; import java.util.Map; +import org.apache.maven.doxia.siterenderer.DocumentRenderer; +import org.apache.maven.doxia.siterenderer.DoxiaDocumentRenderer; +import org.apache.maven.doxia.siterenderer.Renderer; +import org.apache.maven.doxia.siterenderer.RendererException; +import org.apache.maven.doxia.siterenderer.SiteRenderingContext; +import org.apache.maven.plugins.site.render.ReportDocumentRenderer; + +import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; + /** * Render a page as requested. * * @author Brett Porter */ -public class DoxiaFilter - implements Filter -{ +public class DoxiaFilter implements Filter { public static final String OUTPUT_DIRECTORY_KEY = "outputDirectory"; public static final String SITE_RENDERER_KEY = "siteRenderer"; @@ -74,26 +71,23 @@ public class DoxiaFilter /** * @see javax.servlet.Filter#init(javax.servlet.FilterConfig) */ - public void init( FilterConfig filterConfig ) - throws ServletException - { + public void init(FilterConfig filterConfig) throws ServletException { servletContext = filterConfig.getServletContext(); - outputDirectory = (File) servletContext.getAttribute( OUTPUT_DIRECTORY_KEY ); + outputDirectory = (File) servletContext.getAttribute(OUTPUT_DIRECTORY_KEY); - siteRenderer = (Renderer) servletContext.getAttribute( SITE_RENDERER_KEY ); + siteRenderer = (Renderer) servletContext.getAttribute(SITE_RENDERER_KEY); - i18nDoxiaContexts = (Map) servletContext.getAttribute( I18N_DOXIA_CONTEXTS_KEY ); + i18nDoxiaContexts = (Map) servletContext.getAttribute(I18N_DOXIA_CONTEXTS_KEY); - localesList = (List) servletContext.getAttribute( LOCALES_LIST_KEY ); + localesList = (List) servletContext.getAttribute(LOCALES_LIST_KEY); } /** * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain) */ - public void doFilter( ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain ) - throws IOException, ServletException - { + public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) + throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) servletRequest; // ---------------------------------------------------------------------- @@ -101,13 +95,12 @@ public void doFilter( ServletRequest servletRequest, ServletResponse servletResp // ---------------------------------------------------------------------- String path = req.getServletPath(); // welcome file - if ( path.endsWith( "/" ) ) - { + if (path.endsWith("/")) { path += "index.html"; } // Remove the / - path = path.substring( 1 ); + path = path.substring(1); // Handle locale request SiteRenderingContext context; @@ -115,32 +108,25 @@ public void doFilter( ServletRequest servletRequest, ServletResponse servletResp SiteRenderingContext generatedSiteContext; String localeWanted = null; - for ( Locale locale : localesList ) - { - if ( path.startsWith( locale + "/" ) ) - { + for (Locale locale : localesList) { + if (path.startsWith(locale + "/")) { localeWanted = locale.toString(); - path = path.substring( localeWanted.length() + 1 ); + path = path.substring(localeWanted.length() + 1); } } - if ( localeWanted == null ) - { - DoxiaBean defaultDoxiaBean = i18nDoxiaContexts.get( "default" ); - if ( defaultDoxiaBean == null ) - { - throw new ServletException( "No doxia bean found for the default locale" ); + if (localeWanted == null) { + DoxiaBean defaultDoxiaBean = i18nDoxiaContexts.get("default"); + if (defaultDoxiaBean == null) { + throw new ServletException("No doxia bean found for the default locale"); } context = defaultDoxiaBean.getContext(); documents = defaultDoxiaBean.getDocuments(); generatedSiteContext = defaultDoxiaBean.getGeneratedSiteContext(); - } - else - { - DoxiaBean i18nDoxiaBean = i18nDoxiaContexts.get( localeWanted ); - if ( i18nDoxiaBean == null ) - { - throw new ServletException( "No doxia bean found for locale '" + localeWanted + "'" ); + } else { + DoxiaBean i18nDoxiaBean = i18nDoxiaContexts.get(localeWanted); + if (i18nDoxiaBean == null) { + throw new ServletException("No doxia bean found for locale '" + localeWanted + "'"); } context = i18nDoxiaBean.getContext(); documents = i18nDoxiaBean.getDocuments(); @@ -150,83 +136,63 @@ public void doFilter( ServletRequest servletRequest, ServletResponse servletResp // ---------------------------------------------------------------------- // Handle report and documents // ---------------------------------------------------------------------- - if ( documents.containsKey( path ) ) - { - try - { - DocumentRenderer renderer = documents.get( path ); - logDocumentRenderer( path, renderer ); - renderer.renderDocument( servletResponse.getWriter(), siteRenderer, context ); - - if ( renderer instanceof ReportDocumentRenderer ) - { + if (documents.containsKey(path)) { + try { + DocumentRenderer renderer = documents.get(path); + logDocumentRenderer(path, renderer); + renderer.renderDocument(servletResponse.getWriter(), siteRenderer, context); + + if (renderer instanceof ReportDocumentRenderer) { ReportDocumentRenderer reportDocumentRenderer = (ReportDocumentRenderer) renderer; - if ( reportDocumentRenderer.isExternalReport() ) - { - Path externalReportFile = outputDirectory.toPath().resolve( renderer.getOutputName() ); + if (reportDocumentRenderer.isExternalReport()) { + Path externalReportFile = outputDirectory.toPath().resolve(renderer.getOutputName()); servletResponse.reset(); - Files.copy( externalReportFile, servletResponse.getOutputStream() ); + Files.copy(externalReportFile, servletResponse.getOutputStream()); } } return; + } catch (RendererException e) { + throw new ServletException(e); } - catch ( RendererException e ) - { - throw new ServletException( e ); - } - } - else if ( generatedSiteContext != null ) - { - try - { + } else if (generatedSiteContext != null) { + try { Map locateDocuments = - siteRenderer.locateDocumentFiles( generatedSiteContext, false ); + siteRenderer.locateDocumentFiles(generatedSiteContext, false); - if ( locateDocuments.containsKey( path ) ) - { - DocumentRenderer renderer = locateDocuments.get( path ); - logDocumentRenderer( path, renderer ); - renderer.renderDocument( servletResponse.getWriter(), siteRenderer, generatedSiteContext ); + if (locateDocuments.containsKey(path)) { + DocumentRenderer renderer = locateDocuments.get(path); + logDocumentRenderer(path, renderer); + renderer.renderDocument(servletResponse.getWriter(), siteRenderer, generatedSiteContext); return; } - } - catch ( RendererException e ) - { - throw new ServletException( e ); + } catch (RendererException e) { + throw new ServletException(e); } } - filterChain.doFilter( servletRequest, servletResponse ); + filterChain.doFilter(servletRequest, servletResponse); - servletContext.log( path ); + servletContext.log(path); } - private void logDocumentRenderer( String path, DocumentRenderer renderer ) - { + private void logDocumentRenderer(String path, DocumentRenderer renderer) { String source; - if ( renderer instanceof DoxiaDocumentRenderer ) - { + if (renderer instanceof DoxiaDocumentRenderer) { DoxiaDocumentRenderer doxiaDocumentRenderer = (DoxiaDocumentRenderer) renderer; source = doxiaDocumentRenderer.getRenderingContext().getInputName(); - } - else if ( renderer instanceof ReportDocumentRenderer ) - { + } else if (renderer instanceof ReportDocumentRenderer) { ReportDocumentRenderer reportDocumentRenderer = (ReportDocumentRenderer) renderer; source = reportDocumentRenderer.getReportMojoInfo(); - } - else - { + } else { source = renderer.getClass().getName(); } - servletContext.log( path + " -> " + buffer().strong( source ) ); + servletContext.log(path + " -> " + buffer().strong(source)); } /** * @see javax.servlet.Filter#destroy() */ - public void destroy() - { - } + public void destroy() {} } diff --git a/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java b/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java index e324a2fd..fded9a79 100644 --- a/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java +++ b/src/main/java/org/apache/maven/plugins/site/run/SiteRunMojo.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.run; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,16 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.run; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; import org.apache.maven.doxia.siterenderer.DocumentRenderer; import org.apache.maven.doxia.siterenderer.SiteRenderingContext; @@ -34,15 +42,6 @@ import static org.apache.maven.shared.utils.logging.MessageUtils.buffer; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; - /** * Starts the site up, rendering documents as requested for faster editing. * It uses Jetty as the web server. @@ -50,159 +49,131 @@ * @author Brett Porter * */ -@Mojo( name = "run", requiresDependencyResolution = ResolutionScope.TEST, requiresReports = true ) -public class SiteRunMojo - extends AbstractSiteRenderingMojo -{ +@Mojo(name = "run", requiresDependencyResolution = ResolutionScope.TEST, requiresReports = true) +public class SiteRunMojo extends AbstractSiteRenderingMojo { /** * Where to create the dummy web application. */ - @Parameter( defaultValue = "${project.build.directory}/site-webapp" ) + @Parameter(defaultValue = "${project.build.directory}/site-webapp") private File tempWebappDirectory; /** * The port to execute the HTTP server on. */ - @Parameter( property = "port", defaultValue = "8080" ) + @Parameter(property = "port", defaultValue = "8080") private int port; /** * @see org.apache.maven.plugin.AbstractMojo#execute() */ - public void execute() - throws MojoExecutionException, MojoFailureException - { + public void execute() throws MojoExecutionException, MojoFailureException { checkInputEncoding(); - Server server = new Server( port ); - server.setStopAtShutdown( true ); + Server server = new Server(port); + server.setStopAtShutdown(true); WebAppContext webapp = createWebApplication(); - webapp.setServer( server ); + webapp.setServer(server); - server.setHandler( webapp ); + server.setHandler(webapp); - getLog().info( buffer().a( "Starting Jetty on " ).strong( "http://localhost:" + port + "/" ).toString() ); - try - { + getLog().info(buffer().a("Starting Jetty on ") + .strong("http://localhost:" + port + "/") + .toString()); + try { server.start(); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Error executing Jetty: " + e.getMessage(), e ); + } catch (Exception e) { + throw new MojoExecutionException("Error executing Jetty: " + e.getMessage(), e); } // Watch it - try - { + try { server.getThreadPool().join(); - } - catch ( InterruptedException e ) - { - getLog().warn( "Jetty was interrupted", e ); + } catch (InterruptedException e) { + getLog().warn("Jetty was interrupted", e); } } - private WebAppContext createWebApplication() - throws MojoExecutionException - { - File webXml = new File( tempWebappDirectory, "WEB-INF/web.xml" ); + private WebAppContext createWebApplication() throws MojoExecutionException { + File webXml = new File(tempWebappDirectory, "WEB-INF/web.xml"); webXml.getParentFile().mkdirs(); - - try ( InputStream inStream = getClass().getResourceAsStream( "/run/web.xml" ); // - FileOutputStream outStream = new FileOutputStream( webXml ) ) - { - IOUtil.copy( inStream, outStream ); - } - catch ( IOException e ) - { - throw new MojoExecutionException( "Unable to construct temporary webapp for running site", e ); + try (InputStream inStream = getClass().getResourceAsStream("/run/web.xml"); // + FileOutputStream outStream = new FileOutputStream(webXml)) { + IOUtil.copy(inStream, outStream); + } catch (IOException e) { + throw new MojoExecutionException("Unable to construct temporary webapp for running site", e); } WebAppContext webapp = new WebAppContext(); - webapp.setContextPath( "/" ); - webapp.setResourceBase( tempWebappDirectory.getAbsolutePath() ); - webapp.setAttribute( DoxiaFilter.OUTPUT_DIRECTORY_KEY, tempWebappDirectory ); - webapp.setAttribute( DoxiaFilter.SITE_RENDERER_KEY, siteRenderer ); - webapp.getInitParams().put( "org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false" ); + webapp.setContextPath("/"); + webapp.setResourceBase(tempWebappDirectory.getAbsolutePath()); + webapp.setAttribute(DoxiaFilter.OUTPUT_DIRECTORY_KEY, tempWebappDirectory); + webapp.setAttribute(DoxiaFilter.SITE_RENDERER_KEY, siteRenderer); + webapp.getInitParams().put("org.mortbay.jetty.servlet.Default.useFileMappedBuffer", "false"); // For external reports - project.getReporting().setOutputDirectory( tempWebappDirectory.getAbsolutePath() ); - for ( MavenReportExecution mavenReportExecution : getReports() ) - { - mavenReportExecution.getMavenReport().setReportOutputDirectory( tempWebappDirectory ); + project.getReporting().setOutputDirectory(tempWebappDirectory.getAbsolutePath()); + for (MavenReportExecution mavenReportExecution : getReports()) { + mavenReportExecution.getMavenReport().setReportOutputDirectory(tempWebappDirectory); } - List reports = getReports(); // TODO: is it sane to call getReports() method a second time? + List reports = + getReports(); // TODO: is it sane to call getReports() method a second time? List localesList = getLocales(); - webapp.setAttribute( DoxiaFilter.LOCALES_LIST_KEY, localesList ); + webapp.setAttribute(DoxiaFilter.LOCALES_LIST_KEY, localesList); // Default is first in the list - Locale defaultLocale = localesList.get( 0 ); + Locale defaultLocale = localesList.get(0); - try - { + try { Map i18nDoxiaContexts = new HashMap<>(); - for ( Locale locale : localesList ) - { - SiteRenderingContext i18nContext = createSiteRenderingContext( locale ); - i18nContext.setInputEncoding( getInputEncoding() ); - i18nContext.setOutputEncoding( getOutputEncoding() ); + for (Locale locale : localesList) { + SiteRenderingContext i18nContext = createSiteRenderingContext(locale); + i18nContext.setInputEncoding(getInputEncoding()); + i18nContext.setOutputEncoding(getOutputEncoding()); - SiteRenderingContext i18nGeneratedSiteContext = createSiteRenderingContext( locale ); - i18nGeneratedSiteContext.setInputEncoding( getInputEncoding() ); - i18nGeneratedSiteContext.setOutputEncoding( getOutputEncoding() ); + SiteRenderingContext i18nGeneratedSiteContext = createSiteRenderingContext(locale); + i18nGeneratedSiteContext.setInputEncoding(getInputEncoding()); + i18nGeneratedSiteContext.setOutputEncoding(getOutputEncoding()); i18nGeneratedSiteContext.getSiteDirectories().clear(); - Map i18nDocuments = locateDocuments( i18nContext, reports, locale ); + Map i18nDocuments = locateDocuments(i18nContext, reports, locale); DoxiaBean doxiaBean; - if ( defaultLocale.equals( locale ) ) - { - i18nGeneratedSiteContext.addSiteDirectory( generatedSiteDirectory ); - doxiaBean = new DoxiaBean( i18nContext, i18nDocuments, i18nGeneratedSiteContext ); - } - else - { - i18nGeneratedSiteContext.addSiteDirectory( new File( generatedSiteDirectory, - locale.toString() ) ); - doxiaBean = new DoxiaBean( i18nContext, i18nDocuments, i18nGeneratedSiteContext ); + if (defaultLocale.equals(locale)) { + i18nGeneratedSiteContext.addSiteDirectory(generatedSiteDirectory); + doxiaBean = new DoxiaBean(i18nContext, i18nDocuments, i18nGeneratedSiteContext); + } else { + i18nGeneratedSiteContext.addSiteDirectory(new File(generatedSiteDirectory, locale.toString())); + doxiaBean = new DoxiaBean(i18nContext, i18nDocuments, i18nGeneratedSiteContext); } - i18nDoxiaContexts.put( locale.toString(), doxiaBean ); - if ( defaultLocale.equals( locale ) ) - { - i18nDoxiaContexts.put( "default", doxiaBean ); + i18nDoxiaContexts.put(locale.toString(), doxiaBean); + if (defaultLocale.equals(locale)) { + i18nDoxiaContexts.put("default", doxiaBean); } - if ( defaultLocale.equals( locale ) ) - { - siteRenderer.copyResources( i18nContext, tempWebappDirectory ); - } - else - { - siteRenderer.copyResources( i18nContext, new File( tempWebappDirectory, locale.toString() ) ); + if (defaultLocale.equals(locale)) { + siteRenderer.copyResources(i18nContext, tempWebappDirectory); + } else { + siteRenderer.copyResources(i18nContext, new File(tempWebappDirectory, locale.toString())); } } - webapp.setAttribute( DoxiaFilter.I18N_DOXIA_CONTEXTS_KEY, i18nDoxiaContexts ); - } - catch ( Exception e ) - { - throw new MojoExecutionException( "Unable to set up webapp", e ); + webapp.setAttribute(DoxiaFilter.I18N_DOXIA_CONTEXTS_KEY, i18nDoxiaContexts); + } catch (Exception e) { + throw new MojoExecutionException("Unable to set up webapp", e); } return webapp; } - public void setTempWebappDirectory( File tempWebappDirectory ) - { + public void setTempWebappDirectory(File tempWebappDirectory) { this.tempWebappDirectory = tempWebappDirectory; } - public void setPort( int port ) - { + public void setPort(int port) { this.port = port; } } diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/AbstractSiteDeployWebDavTest.java b/src/test/java/org/apache/maven/plugins/site/deploy/AbstractSiteDeployWebDavTest.java index 7e22aa2d..cfa25f9f 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/AbstractSiteDeployWebDavTest.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/AbstractSiteDeployWebDavTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * 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.site.deploy; import java.io.File; import java.util.Arrays; @@ -34,7 +33,6 @@ import org.apache.maven.execution.MavenSession; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.testing.AbstractMojoTestCase; - import org.apache.maven.plugins.site.stubs.SiteMavenProjectStub; import org.apache.maven.settings.Proxy; import org.apache.maven.settings.Settings; @@ -48,227 +46,201 @@ * @author Olivier Lamy * */ -@RunWith( JUnit4.class ) -public abstract class AbstractSiteDeployWebDavTest - extends AbstractMojoTestCase -{ +@RunWith(JUnit4.class) +public abstract class AbstractSiteDeployWebDavTest extends AbstractMojoTestCase { - File siteTargetPath = new File( getBasedir() + File.separator + "target" + File.separator + "siteTargetDeploy" ); + File siteTargetPath = new File(getBasedir() + File.separator + "target" + File.separator + "siteTargetDeploy"); @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - if ( !siteTargetPath.exists() ) - { + if (!siteTargetPath.exists()) { siteTargetPath.mkdirs(); - FileUtils.cleanDirectory( siteTargetPath ); + FileUtils.cleanDirectory(siteTargetPath); } } abstract String getMojoName(); - abstract AbstractMojo getMojo( File pomFile ) - throws Exception; + abstract AbstractMojo getMojo(File pomFile) throws Exception; @Test - public void noAuthzDavDeploy() - throws Exception - { - FileUtils.cleanDirectory( siteTargetPath ); - SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler( siteTargetPath ); - - try - { - File pomFile = getTestFile( "src/test/resources/unit/deploy-dav/pom.xml" ); - AbstractMojo mojo = getMojo( pomFile ); - assertNotNull( mojo ); - SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub( "deploy-dav" ); - - assertTrue( "dav server port not available: " + simpleDavServerHandler.getPort(), - simpleDavServerHandler.getPort() > 0 ); - - siteMavenProjectStub.getDistributionManagement().getSite() - .setUrl( "dav:http://localhost:" + simpleDavServerHandler.getPort() + "/site/" ); - - setVariableValueToObject( mojo, "project", siteMavenProjectStub ); + public void noAuthzDavDeploy() throws Exception { + FileUtils.cleanDirectory(siteTargetPath); + SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler(siteTargetPath); + + try { + File pomFile = getTestFile("src/test/resources/unit/deploy-dav/pom.xml"); + AbstractMojo mojo = getMojo(pomFile); + assertNotNull(mojo); + SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub("deploy-dav"); + + assertTrue( + "dav server port not available: " + simpleDavServerHandler.getPort(), + simpleDavServerHandler.getPort() > 0); + + siteMavenProjectStub + .getDistributionManagement() + .getSite() + .setUrl("dav:http://localhost:" + simpleDavServerHandler.getPort() + "/site/"); + + setVariableValueToObject(mojo, "project", siteMavenProjectStub); Settings settings = new Settings(); - setVariableValueToObject( mojo, "settings", settings ); - File inputDirectory = new File( "src/test/resources/unit/deploy-dav/target/site" ); + setVariableValueToObject(mojo, "settings", settings); + File inputDirectory = new File("src/test/resources/unit/deploy-dav/target/site"); - setVariableValueToObject( mojo, "inputDirectory", inputDirectory ); + setVariableValueToObject(mojo, "inputDirectory", inputDirectory); mojo.execute(); assertContentInFiles(); - assertFalse( requestsContainsProxyUse( simpleDavServerHandler.httpRequests ) ); - } - finally - { + assertFalse(requestsContainsProxyUse(simpleDavServerHandler.httpRequests)); + } finally { simpleDavServerHandler.stop(); } } @Test - public void davDeployThruProxyWithoutAuthzInProxy() - throws Exception - { - - FileUtils.cleanDirectory( siteTargetPath ); - SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler( siteTargetPath ); - try - { - File pluginXmlFile = getTestFile( "src/test/resources/unit/deploy-dav/pom.xml" ); - AbstractMojo mojo = getMojo( pluginXmlFile ); - assertNotNull( mojo ); - SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub( "deploy-dav" ); + public void davDeployThruProxyWithoutAuthzInProxy() throws Exception { + + FileUtils.cleanDirectory(siteTargetPath); + SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler(siteTargetPath); + try { + File pluginXmlFile = getTestFile("src/test/resources/unit/deploy-dav/pom.xml"); + AbstractMojo mojo = getMojo(pluginXmlFile); + assertNotNull(mojo); + SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub("deploy-dav"); // olamy, Note : toto is something like foo or bar for french folks :-) String siteUrl = "dav:http://toto.com/site/"; - siteMavenProjectStub.getDistributionManagement().getSite().setUrl( siteUrl ); + siteMavenProjectStub.getDistributionManagement().getSite().setUrl(siteUrl); - setVariableValueToObject( mojo, "project", siteMavenProjectStub ); + setVariableValueToObject(mojo, "project", siteMavenProjectStub); Settings settings = new Settings(); Proxy proxy = new Proxy(); - //dummy proxy - proxy.setActive( true ); - proxy.setHost( "localhost" ); - proxy.setPort( simpleDavServerHandler.getPort() ); - proxy.setProtocol( "http" ); - proxy.setNonProxyHosts( "www.google.com|*.somewhere.com" ); - settings.addProxy( proxy ); + // dummy proxy + proxy.setActive(true); + proxy.setHost("localhost"); + proxy.setPort(simpleDavServerHandler.getPort()); + proxy.setProtocol("http"); + proxy.setNonProxyHosts("www.google.com|*.somewhere.com"); + settings.addProxy(proxy); - setVariableValueToObject( mojo, "settings", settings ); + setVariableValueToObject(mojo, "settings", settings); MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setProxies( Arrays.asList( proxy ) ); - MavenSession mavenSession = new MavenSession( getContainer(), null, request, null ); + request.setProxies(Arrays.asList(proxy)); + MavenSession mavenSession = new MavenSession(getContainer(), null, request, null); - setVariableValueToObject( mojo, "mavenSession", mavenSession ); + setVariableValueToObject(mojo, "mavenSession", mavenSession); - File inputDirectory = new File( "src/test/resources/unit/deploy-dav/target/site" ); + File inputDirectory = new File("src/test/resources/unit/deploy-dav/target/site"); - setVariableValueToObject( mojo, "inputDirectory", inputDirectory ); + setVariableValueToObject(mojo, "inputDirectory", inputDirectory); mojo.execute(); assertContentInFiles(); - assertTrue( requestsContainsProxyUse( simpleDavServerHandler.httpRequests ) ); - } - finally - { + assertTrue(requestsContainsProxyUse(simpleDavServerHandler.httpRequests)); + } finally { simpleDavServerHandler.stop(); } - } @Test - public void davDeployThruProxyWitAuthzInProxy() throws Exception - { + public void davDeployThruProxyWitAuthzInProxy() throws Exception { - FileUtils.cleanDirectory( siteTargetPath ); - //SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler( siteTargetPath ); + FileUtils.cleanDirectory(siteTargetPath); + // SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler( siteTargetPath ); Map authentications = new HashMap(); - authentications.put( "foo", "titi" ); + authentications.put("foo", "titi"); - AuthAsyncProxyServlet servlet = new AuthAsyncProxyServlet( authentications, siteTargetPath ); + AuthAsyncProxyServlet servlet = new AuthAsyncProxyServlet(authentications, siteTargetPath); - SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler( servlet ); - try - { - File pluginXmlFile = getTestFile( "src/test/resources/unit/deploy-dav/pom.xml" ); - AbstractMojo mojo = getMojo( pluginXmlFile ); - assertNotNull( mojo ); - SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub( "deploy-dav" ); + SimpleDavServerHandler simpleDavServerHandler = new SimpleDavServerHandler(servlet); + try { + File pluginXmlFile = getTestFile("src/test/resources/unit/deploy-dav/pom.xml"); + AbstractMojo mojo = getMojo(pluginXmlFile); + assertNotNull(mojo); + SiteMavenProjectStub siteMavenProjectStub = new SiteMavenProjectStub("deploy-dav"); - siteMavenProjectStub.getDistributionManagement().getSite() - .setUrl( "dav:http://toto.com/site/" ); + siteMavenProjectStub.getDistributionManagement().getSite().setUrl("dav:http://toto.com/site/"); - setVariableValueToObject( mojo, "project", siteMavenProjectStub ); + setVariableValueToObject(mojo, "project", siteMavenProjectStub); Settings settings = new Settings(); Proxy proxy = new Proxy(); - //dummy proxy - proxy.setActive( true ); - proxy.setHost( "localhost" ); - proxy.setPort( simpleDavServerHandler.getPort() ); - proxy.setProtocol( "dav" ); - proxy.setUsername( "foo" ); - proxy.setPassword( "titi" ); - proxy.setNonProxyHosts( "www.google.com|*.somewhere.com" ); - settings.addProxy( proxy ); + // dummy proxy + proxy.setActive(true); + proxy.setHost("localhost"); + proxy.setPort(simpleDavServerHandler.getPort()); + proxy.setProtocol("dav"); + proxy.setUsername("foo"); + proxy.setPassword("titi"); + proxy.setNonProxyHosts("www.google.com|*.somewhere.com"); + settings.addProxy(proxy); - setVariableValueToObject( mojo, "settings", settings ); + setVariableValueToObject(mojo, "settings", settings); MavenExecutionRequest request = new DefaultMavenExecutionRequest(); - request.setProxies( Arrays.asList( proxy ) ); - MavenSession mavenSession = new MavenSession( getContainer(), null, request, null ); + request.setProxies(Arrays.asList(proxy)); + MavenSession mavenSession = new MavenSession(getContainer(), null, request, null); - setVariableValueToObject( mojo, "mavenSession", mavenSession ); + setVariableValueToObject(mojo, "mavenSession", mavenSession); - File inputDirectory = new File( "src/test/resources/unit/deploy-dav/target/site" ); + File inputDirectory = new File("src/test/resources/unit/deploy-dav/target/site"); // test which mojo we are using - if ( ReflectionUtils.getFieldByNameIncludingSuperclasses( "inputDirectory", mojo.getClass() ) != null ) - { - setVariableValueToObject( mojo, "inputDirectory", inputDirectory ); - } - else - { - ArtifactRepositoryFactory artifactRepositoryFactory = getContainer().lookup( ArtifactRepositoryFactory.class ); - - setVariableValueToObject( mojo, "stagingDirectory", inputDirectory ); - setVariableValueToObject( mojo, "reactorProjects", Collections.emptyList() ); - setVariableValueToObject( mojo, "localRepository", - artifactRepositoryFactory.createArtifactRepository( "local", "foo", "default", - null, null ) ); - setVariableValueToObject( mojo, "siteTool", getContainer().lookup( SiteTool.class ) ); - setVariableValueToObject( mojo, "siteDirectory", new File("foo") ); - setVariableValueToObject( mojo, "repositories", Collections.emptyList() ); + if (ReflectionUtils.getFieldByNameIncludingSuperclasses("inputDirectory", mojo.getClass()) != null) { + setVariableValueToObject(mojo, "inputDirectory", inputDirectory); + } else { + ArtifactRepositoryFactory artifactRepositoryFactory = + getContainer().lookup(ArtifactRepositoryFactory.class); + + setVariableValueToObject(mojo, "stagingDirectory", inputDirectory); + setVariableValueToObject(mojo, "reactorProjects", Collections.emptyList()); + setVariableValueToObject( + mojo, + "localRepository", + artifactRepositoryFactory.createArtifactRepository("local", "foo", "default", null, null)); + setVariableValueToObject(mojo, "siteTool", getContainer().lookup(SiteTool.class)); + setVariableValueToObject(mojo, "siteDirectory", new File("foo")); + setVariableValueToObject(mojo, "repositories", Collections.emptyList()); } mojo.execute(); assertContentInFiles(); - assertTrue( requestsContainsProxyUse( servlet.httpRequests ) ); - assertAtLeastOneRequestContainsHeader( servlet.httpRequests, "Proxy-Authorization" ); - } - finally - { + assertTrue(requestsContainsProxyUse(servlet.httpRequests)); + assertAtLeastOneRequestContainsHeader(servlet.httpRequests, "Proxy-Authorization"); + } finally { simpleDavServerHandler.stop(); } } - private void assertContentInFiles() - throws Exception - { - File fileToTest = new File( siteTargetPath, "site" + File.separator + "index.html" ); - assertTrue( fileToTest.exists() ); - String fileContent = FileUtils.readFileToString( fileToTest ); - assertTrue( fileContent.contains( "Welcome to Apache Maven" ) ); - - fileToTest = new File( siteTargetPath, "site" + File.separator + "css" + File.separator + "maven-base.css" ); - assertTrue( fileToTest.exists() ); - fileContent = FileUtils.readFileToString( fileToTest ); - assertTrue( fileContent.contains( "background-image: url(../images/collapsed.gif);" ) ); + private void assertContentInFiles() throws Exception { + File fileToTest = new File(siteTargetPath, "site" + File.separator + "index.html"); + assertTrue(fileToTest.exists()); + String fileContent = FileUtils.readFileToString(fileToTest); + assertTrue(fileContent.contains("Welcome to Apache Maven")); + + fileToTest = new File(siteTargetPath, "site" + File.separator + "css" + File.separator + "maven-base.css"); + assertTrue(fileToTest.exists()); + fileContent = FileUtils.readFileToString(fileToTest); + assertTrue(fileContent.contains("background-image: url(../images/collapsed.gif);")); } /** * @param requests * @return true if at least on request use proxy http header Proxy-Connection : Keep-Alive */ - private boolean requestsContainsProxyUse( List requests ) - { - return assertAtLeastOneRequestContainsHeader( requests, "Proxy-Connection" ); + private boolean requestsContainsProxyUse(List requests) { + return assertAtLeastOneRequestContainsHeader(requests, "Proxy-Connection"); } - private boolean assertAtLeastOneRequestContainsHeader( List requests, String headerName ) - { - for ( HttpRequest rq : requests ) - { - boolean containsProxyHeader = rq.headers.containsKey( headerName ); - if ( containsProxyHeader ) - { + private boolean assertAtLeastOneRequestContainsHeader(List requests, String headerName) { + for (HttpRequest rq : requests) { + boolean containsProxyHeader = rq.headers.containsKey(headerName); + if (containsProxyHeader) { return true; } } diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/AuthAsyncProxyServlet.java b/src/test/java/org/apache/maven/plugins/site/deploy/AuthAsyncProxyServlet.java index be161469..0276630b 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/AuthAsyncProxyServlet.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/AuthAsyncProxyServlet.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,10 +16,7 @@ * specific language governing permissions and limitations * under the License. */ - -import java.io.File; -import java.io.IOException; -import java.util.*; +package org.apache.maven.plugins.site.deploy; import javax.servlet.ServletException; import javax.servlet.ServletRequest; @@ -29,26 +24,26 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import java.io.File; +import java.io.IOException; +import java.util.*; + import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; -import org.eclipse.jetty.util.B64Code; import org.eclipse.jetty.proxy.AsyncProxyServlet; +import org.eclipse.jetty.util.B64Code; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.apache.maven.plugins.site.deploy.HttpRequest; - /** * @author Olivier Lamy */ -public class AuthAsyncProxyServlet - extends AsyncProxyServlet -{ +public class AuthAsyncProxyServlet extends AsyncProxyServlet { private Map authentications; private long sleepTime = 0; - private Logger log = LoggerFactory.getLogger( getClass() ); + private Logger log = LoggerFactory.getLogger(getClass()); List httpRequests = new ArrayList(); @@ -57,111 +52,96 @@ public class AuthAsyncProxyServlet /** * Constructor for non authentication servlet. */ - public AuthAsyncProxyServlet( File siteTargetPath ) - { + public AuthAsyncProxyServlet(File siteTargetPath) { super(); this.siteTargetPath = siteTargetPath; } /** * Constructor for authentication servlet. - * + * * @param authentications a map of user/password */ - public AuthAsyncProxyServlet( Map authentications, File siteTargetPath ) - { - this( siteTargetPath ); + public AuthAsyncProxyServlet(Map authentications, File siteTargetPath) { + this(siteTargetPath); 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, File siteTargetPath ) - { - this( siteTargetPath ); + public AuthAsyncProxyServlet(Map authentications, long sleepTime, File siteTargetPath) { + this(siteTargetPath); this.authentications = authentications; this.sleepTime = sleepTime; } /** {@inheritDoc} */ - public void service( ServletRequest req, ServletResponse res ) - throws ServletException, IOException - { + public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { final HttpServletRequest request = (HttpServletRequest) req; final HttpServletResponse response = (HttpServletResponse) res; - log.info( "handle " ); + log.info("handle "); - if ( this.authentications != null && !this.authentications.isEmpty() ) - { - String proxyAuthorization = request.getHeader( "Proxy-Authorization" ); - if ( proxyAuthorization != null && proxyAuthorization.startsWith( "Basic " ) ) - { - String proxyAuth = proxyAuthorization.substring( 6 ); - String authorization = new String(B64Code.decode( proxyAuth )); - String[] authTokens = authorization.split( ":" ); + if (this.authentications != null && !this.authentications.isEmpty()) { + String proxyAuthorization = request.getHeader("Proxy-Authorization"); + if (proxyAuthorization != null && proxyAuthorization.startsWith("Basic ")) { + String proxyAuth = proxyAuthorization.substring(6); + String authorization = new String(B64Code.decode(proxyAuth)); + 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 (this.authentications.get(user) == null) { + throw new IllegalArgumentException(user + " not found in the map!"); } - if ( sleepTime > 0 ) - { - try - { - Thread.sleep( sleepTime ); - } - catch ( InterruptedException e ) - { + if (sleepTime > 0) { + try { + Thread.sleep(sleepTime); + } catch (InterruptedException e) { // nop } } - String authPass = this.authentications.get( user ); - if ( password.equals( authPass ) ) - { + String authPass = this.authentications.get(user); + if (password.equals(authPass)) { String targetPath = request.getServletPath(); HttpRequest rq = new HttpRequest(); rq.method = request.getMethod(); rq.path = targetPath; - @SuppressWarnings( "rawtypes" ) + @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); - while ( headerNames.hasMoreElements() ) - { + while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); - rq.headers.put( name, request.getHeader( name ) ); + rq.headers.put(name, request.getHeader(name)); } - httpRequests.add( rq ); + httpRequests.add(rq); - if ( request.getMethod().equalsIgnoreCase( "PUT" ) && targetPath != null ) - { - File targetFile = new File( siteTargetPath, targetPath ); - log.info( "writing file " + targetFile.getPath() ); - FileUtils.writeByteArrayToFile( targetFile, IOUtils.toByteArray( request.getInputStream() ) ); + if (request.getMethod().equalsIgnoreCase("PUT") && targetPath != null) { + File targetFile = new File(siteTargetPath, targetPath); + log.info("writing file " + targetFile.getPath()); + FileUtils.writeByteArrayToFile(targetFile, IOUtils.toByteArray(request.getInputStream())); } - response.setStatus( HttpServletResponse.SC_OK ); + response.setStatus(HttpServletResponse.SC_OK); return; } } // Proxy-Authenticate Basic realm="CCProxy Authorization" - response.addHeader( "Proxy-Authenticate", "Basic realm=\"Jetty Proxy Authorization\"" ); - response.setStatus( HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED ); + response.addHeader("Proxy-Authenticate", "Basic realm=\"Jetty Proxy Authorization\""); + response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED); return; } - super.service( req, res ); + super.service(req, res); } } diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/HttpRequest.java b/src/test/java/org/apache/maven/plugins/site/deploy/HttpRequest.java index b7d5cd8f..8cef7850 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/HttpRequest.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/HttpRequest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,32 +16,28 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; import java.util.HashMap; import java.util.Map; -class HttpRequest -{ - Map headers = new HashMap(); +class HttpRequest { + Map headers = new HashMap(); String method; String path; - HttpRequest() - { + HttpRequest() { // nop } @Override - public String toString() - { - StringBuilder sb = new StringBuilder( method ).append( " path " ).append( path ) - .append( System.lineSeparator() ); - for ( Map.Entry entry : headers.entrySet() ) - { - sb.append( entry.getKey() ).append( " : " ).append( entry.getValue() ) - .append( System.lineSeparator() ); + public String toString() { + StringBuilder sb = + new StringBuilder(method).append(" path ").append(path).append(System.lineSeparator()); + for (Map.Entry entry : headers.entrySet()) { + sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append(System.lineSeparator()); } return sb.toString(); } diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/SimpleDavServerHandler.java b/src/test/java/org/apache/maven/plugins/site/deploy/SimpleDavServerHandler.java index 445886e1..5e81dff7 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/SimpleDavServerHandler.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/SimpleDavServerHandler.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,6 +16,12 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; + +import javax.servlet.Servlet; +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; @@ -25,11 +29,6 @@ import java.util.Enumeration; import java.util.List; -import javax.servlet.Servlet; -import javax.servlet.ServletException; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.eclipse.jetty.server.Handler; @@ -38,7 +37,6 @@ import org.eclipse.jetty.server.handler.AbstractHandler; import org.eclipse.jetty.servlet.ServletContextHandler; import org.eclipse.jetty.servlet.ServletHolder; -import org.apache.maven.plugins.site.deploy.HttpRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -47,87 +45,70 @@ * @since 3.0-beta-2 * */ -public class SimpleDavServerHandler -{ - - private Logger log = LoggerFactory.getLogger( getClass() ); - +public class SimpleDavServerHandler { + + private Logger log = LoggerFactory.getLogger(getClass()); + private Server server; - + private File siteTargetPath; - + List httpRequests = new ArrayList(); - - public SimpleDavServerHandler(final File targetPath ) - throws Exception - { + + public SimpleDavServerHandler(final File targetPath) throws Exception { this.siteTargetPath = targetPath; - Handler repoHandler = new AbstractHandler() - { - public void handle( String target, Request r, HttpServletRequest request, HttpServletResponse response ) - throws IOException, ServletException - { + Handler repoHandler = new AbstractHandler() { + public void handle(String target, Request r, HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { String targetPath = request.getPathInfo(); - + HttpRequest rq = new HttpRequest(); rq.method = request.getMethod(); rq.path = targetPath; - @SuppressWarnings( "rawtypes" ) + @SuppressWarnings("rawtypes") Enumeration headerNames = request.getHeaderNames(); - while ( headerNames.hasMoreElements() ) - { + while (headerNames.hasMoreElements()) { String name = (String) headerNames.nextElement(); - rq.headers.put( name, request.getHeader( name ) ); + rq.headers.put(name, request.getHeader(name)); } - - httpRequests.add( rq ); - - - if ( request.getMethod().equalsIgnoreCase( "PUT" ) ) - { - File targetFile = new File( siteTargetPath, targetPath ); - log.info( "writing file " + targetFile.getPath() ); - FileUtils.writeByteArrayToFile( targetFile, IOUtils.toByteArray( request.getInputStream() ) ); + + httpRequests.add(rq); + + if (request.getMethod().equalsIgnoreCase("PUT")) { + File targetFile = new File(siteTargetPath, targetPath); + log.info("writing file " + targetFile.getPath()); + FileUtils.writeByteArrayToFile(targetFile, IOUtils.toByteArray(request.getInputStream())); } - - //PrintWriter writer = response.getWriter(); - response.setStatus( HttpServletResponse.SC_OK ); + // PrintWriter writer = response.getWriter(); + + response.setStatus(HttpServletResponse.SC_OK); - ( (Request) request ).setHandled( true ); + ((Request) request).setHandled(true); } }; - server = new Server( 0 ); - server.setHandler( repoHandler ); + server = new Server(0); + server.setHandler(repoHandler); server.start(); - } - public SimpleDavServerHandler( Servlet servlet ) - throws Exception - { + public SimpleDavServerHandler(Servlet servlet) throws Exception { siteTargetPath = null; - server = new Server( 0 ); + server = new Server(0); ServletContextHandler context = new ServletContextHandler(ServletContextHandler.NO_SESSIONS); context.setContextPath("/"); server.setHandler(context); - context.addServlet( new ServletHolder( servlet ), "/" ); + context.addServlet(new ServletHolder(servlet), "/"); server.start(); } - - public int getPort() - { + + public int getPort() { return server.getURI().getPort(); } - public void stop() - throws Exception - { + public void stop() throws Exception { server.stop(); } - - - } diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployMojoTest.java b/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployMojoTest.java index c512ef03..8f092461 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployMojoTest.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployMojoTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,9 +16,9 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; import org.apache.maven.artifact.manager.WagonManager; -//import org.apache.maven.wagon.repository.Repository; import org.apache.maven.plugin.testing.AbstractMojoTestCase; import org.junit.Before; import org.junit.Test; @@ -30,28 +28,23 @@ /** * @author Cyrille Le Clerc */ -@RunWith( JUnit4.class ) -public class SiteDeployMojoTest - extends AbstractMojoTestCase -{ +@RunWith(JUnit4.class) +public class SiteDeployMojoTest extends AbstractMojoTestCase { private WagonManager wagonManager; - //private Repository repository; + // private Repository repository; @Before - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - wagonManager = getContainer().lookup( WagonManager.class ); - //repository = new Repository( "my-repository", "scp://repository-host/var/maven2" ); + wagonManager = getContainer().lookup(WagonManager.class); + // repository = new Repository( "my-repository", "scp://repository-host/var/maven2" ); } @Test - public void testFoo() - { + public void testFoo() { // should not fail ;-) - assertTrue( true ); + assertTrue(true); } /** diff --git a/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployWebDavTest.java b/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployWebDavTest.java index 53af294d..5ccaec5e 100644 --- a/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployWebDavTest.java +++ b/src/test/java/org/apache/maven/plugins/site/deploy/SiteDeployWebDavTest.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.deploy; - /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file @@ -18,32 +16,26 @@ * specific language governing permissions and limitations * under the License. */ +package org.apache.maven.plugins.site.deploy; import java.io.File; import org.apache.maven.plugin.AbstractMojo; -import org.apache.maven.plugins.site.deploy.SiteDeployMojo; /** * @author Olivier Lamy * @since 3.0-beta-2 * */ -public class SiteDeployWebDavTest - extends AbstractSiteDeployWebDavTest -{ +public class SiteDeployWebDavTest extends AbstractSiteDeployWebDavTest { @Override - String getMojoName() - { + String getMojoName() { return "deploy"; } @Override - AbstractMojo getMojo( File pomXmlFile ) - throws Exception - { - return (SiteDeployMojo) lookupMojo( getMojoName(), pomXmlFile ); + AbstractMojo getMojo(File pomXmlFile) throws Exception { + return (SiteDeployMojo) lookupMojo(getMojoName(), pomXmlFile); } - } diff --git a/src/test/java/org/apache/maven/plugins/site/run/WebXmlTest.java b/src/test/java/org/apache/maven/plugins/site/run/WebXmlTest.java index e7a044b3..342c2838 100644 --- a/src/test/java/org/apache/maven/plugins/site/run/WebXmlTest.java +++ b/src/test/java/org/apache/maven/plugins/site/run/WebXmlTest.java @@ -1,65 +1,57 @@ -package org.apache.maven.plugins.site.run; - -/* - * 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.junit.Assert.assertTrue; -import static org.junit.Assert.fail; - -import javax.xml.parsers.DocumentBuilder; -import javax.xml.parsers.DocumentBuilderFactory; -import javax.xml.xpath.XPath; -import javax.xml.xpath.XPathConstants; -import javax.xml.xpath.XPathFactory; - -import org.junit.Test; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; - -public class WebXmlTest -{ - - @Test - public void testFilters() - throws Exception - { - DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); - Document doc = docBuilder.parse( SiteRunMojo.class.getResourceAsStream( "/run/web.xml" ) ); - XPath xPath = XPathFactory.newInstance().newXPath(); - - NodeList filterClasses = - (NodeList) xPath.compile( "/web-app/filter/filter-class" ).evaluate( doc, XPathConstants.NODESET ); - - assertTrue( "Expected at least one filter", filterClasses.getLength() > 0 ); - for ( int index = 0; index < filterClasses.getLength(); index++ ) - { - Node filterClass = filterClasses.item( index ).getFirstChild(); - try - { - Class.forName( filterClass.getNodeValue() ); - } - catch ( ClassNotFoundException cnfe ) - { - fail( "/web-app/filter[" + index + "]/filter-class refers to " + filterClass.getNodeValue() - + ", which doesn't exist" ); - } - } - } -} +/* + * 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.site.run; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathFactory; + +import org.junit.Test; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class WebXmlTest { + + @Test + public void testFilters() throws Exception { + DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); + Document doc = docBuilder.parse(SiteRunMojo.class.getResourceAsStream("/run/web.xml")); + XPath xPath = XPathFactory.newInstance().newXPath(); + + NodeList filterClasses = + (NodeList) xPath.compile("/web-app/filter/filter-class").evaluate(doc, XPathConstants.NODESET); + + assertTrue("Expected at least one filter", filterClasses.getLength() > 0); + for (int index = 0; index < filterClasses.getLength(); index++) { + Node filterClass = filterClasses.item(index).getFirstChild(); + try { + Class.forName(filterClass.getNodeValue()); + } catch (ClassNotFoundException cnfe) { + fail("/web-app/filter[" + index + "]/filter-class refers to " + filterClass.getNodeValue() + + ", which doesn't exist"); + } + } + } +} diff --git a/src/test/java/org/apache/maven/plugins/site/stubs/SiteMavenProjectStub.java b/src/test/java/org/apache/maven/plugins/site/stubs/SiteMavenProjectStub.java index 901d5595..f624b2ce 100644 --- a/src/test/java/org/apache/maven/plugins/site/stubs/SiteMavenProjectStub.java +++ b/src/test/java/org/apache/maven/plugins/site/stubs/SiteMavenProjectStub.java @@ -1,5 +1,3 @@ -package org.apache.maven.plugins.site.stubs; - /* * 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.site.stubs; import java.io.File; import java.util.Properties; @@ -34,67 +33,54 @@ * @author Vincent Siveton * */ -public class SiteMavenProjectStub - extends MavenProjectStub -{ +public class SiteMavenProjectStub extends MavenProjectStub { private File basedir; DistributionManagement distributionManagement = new DistributionManagement(); - - public SiteMavenProjectStub( String projectName ) - { - basedir = new File( super.getBasedir() + "/src/test/resources/unit/" + projectName ); + + public SiteMavenProjectStub(String projectName) { + basedir = new File(super.getBasedir() + "/src/test/resources/unit/" + projectName); XmlStreamReader reader = null; - try - { - reader = ReaderFactory.newXmlReader( new File( getBasedir(), "pom.xml" ) ); - setModel( new MavenXpp3Reader().read( reader ) ); + try { + reader = ReaderFactory.newXmlReader(new File(getBasedir(), "pom.xml")); + setModel(new MavenXpp3Reader().read(reader)); reader.close(); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); - } - finally - { - IOUtil.close( reader); + } catch (Exception e) { + throw new RuntimeException(e); + } finally { + IOUtil.close(reader); } Site site = new Site(); - site.setId( "localhost" ); - distributionManagement.setSite( site ); + site.setId("localhost"); + distributionManagement.setSite(site); } /** * @see org.apache.maven.project.MavenProject#getName() */ - public String getName() - { + public String getName() { return getModel().getName(); } /** * @see org.apache.maven.project.MavenProject#getProperties() */ - public Properties getProperties() - { + public Properties getProperties() { return new Properties(); } @Override - public DistributionManagement getDistributionManagement() - { + public DistributionManagement getDistributionManagement() { return distributionManagement; } /** {@inheritDoc} */ - public File getBasedir() - { + public File getBasedir() { return basedir; } - public void setBasedir( File basedir ) - { + public void setBasedir(File basedir) { this.basedir = basedir; } }