This is an automated email from the ASF dual-hosted git repository. slachiewicz pushed a commit to branch master in repository https://gitbox.apache.org/repos/asf/maven-doxia-sitetools.git
commit 6c87186608ecd2fbc846e7b6540d6aea1e75a93d Author: Sylwester Lachiewicz <[email protected]> AuthorDate: Sat Nov 21 23:59:21 2026 +0100 Drop the direct plexus-utils dependency Rebased onto current master; the static endsWithIgnoreCase import added there is kept. --- doxia-integration-tools/pom.xml | 4 - .../apache/maven/doxia/tools/DefaultSiteTool.java | 20 +- .../org/apache/maven/doxia/tools/SiteToolTest.java | 11 +- doxia-site-model/pom.xml | 4 - .../java/org/apache/maven/doxia/site/PathTool.java | 342 +++++++++++++++++++++ .../org/apache/maven/doxia/site/SiteUtils.java | 4 +- .../doxia/site/inheritance/URIPathDescriptor.java | 2 +- .../org/apache/maven/doxia/site/PathToolTest.java | 86 ++++++ .../SiteModelInheritanceAssemblerTest.java | 7 +- doxia-site-renderer/pom.xml | 5 - .../doxia/siterenderer/DefaultSiteRenderer.java | 192 +++++++++--- .../siterenderer/DocumentRenderingContext.java | 2 +- .../siterenderer/DefaultSiteRendererTest.java | 65 ++-- 13 files changed, 644 insertions(+), 100 deletions(-) diff --git a/doxia-integration-tools/pom.xml b/doxia-integration-tools/pom.xml index 44dc960..bf5778e 100644 --- a/doxia-integration-tools/pom.xml +++ b/doxia-integration-tools/pom.xml @@ -119,10 +119,6 @@ </exclusion> </exclusions> </dependency> - <dependency> - <groupId>org.codehaus.plexus</groupId> - <artifactId>plexus-utils</artifactId> - </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-xml</artifactId> diff --git a/doxia-integration-tools/src/main/java/org/apache/maven/doxia/tools/DefaultSiteTool.java b/doxia-integration-tools/src/main/java/org/apache/maven/doxia/tools/DefaultSiteTool.java index 96efcd8..a67c709 100644 --- a/doxia-integration-tools/src/main/java/org/apache/maven/doxia/tools/DefaultSiteTool.java +++ b/doxia-integration-tools/src/main/java/org/apache/maven/doxia/tools/DefaultSiteTool.java @@ -42,6 +42,7 @@ import java.util.Properties; import java.util.StringTokenizer; import org.apache.commons.io.FilenameUtils; +import org.apache.commons.io.IOUtils; import org.apache.maven.RepositoryUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.doxia.site.Banner; @@ -76,8 +77,6 @@ import org.codehaus.plexus.interpolation.MapBasedValueSource; import org.codehaus.plexus.interpolation.PrefixedObjectValueSource; import org.codehaus.plexus.interpolation.PrefixedPropertiesValueSource; import org.codehaus.plexus.interpolation.RegexBasedInterpolator; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.Xpp3Dom; import org.codehaus.plexus.util.xml.pull.MXParser; @@ -741,7 +740,9 @@ public class DefaultSiteTool implements SiteTool { return Collections.singletonList(DEFAULT_LOCALE); } - String[] localesArray = StringUtils.split(locales, ","); + String[] localesArray = Arrays.stream(locales.split(",")) + .filter(locale -> !locale.isEmpty()) + .toArray(String[]::new); List<Locale> localesList = new ArrayList<>(localesArray.length); List<Locale> availableLocales = Arrays.asList(Locale.getAvailableLocales()); @@ -1043,7 +1044,7 @@ public class DefaultSiteTool implements SiteTool { siteDescriptorReader = new XmlStreamReader(siteDescriptor); - String siteDescriptorContent = IOUtil.toString(siteDescriptorReader); + String siteDescriptorContent = IOUtils.toString(siteDescriptorReader); // interpolate ${this.*} = early interpolation siteDescriptorContent = @@ -1058,7 +1059,7 @@ public class DefaultSiteTool implements SiteTool { throw new SiteToolException( "The site descriptor for '" + project.getId() + "' cannot be read from " + siteDescriptor, e); } finally { - IOUtil.close(siteDescriptorReader); + IOUtils.closeQuietly(siteDescriptorReader); } // 3. look for parent project @@ -1353,11 +1354,11 @@ public class DefaultSiteTool implements SiteTool { Reader reader = null; try { reader = new XmlStreamReader(getClass().getResourceAsStream("/default-site.xml")); - siteDescriptorContent = IOUtil.toString(reader); + siteDescriptorContent = IOUtils.toString(reader); } catch (IOException e) { throw new SiteToolException("Error reading default site descriptor", e); } finally { - IOUtil.close(reader); + IOUtils.closeQuietly(reader); } return readSiteModel(siteDescriptorContent, null, SiteTool.DEFAULT_LOCALE); @@ -1372,7 +1373,7 @@ public class DefaultSiteTool implements SiteTool { } catch (IOException e) { throw new SiteToolException("Error reading site descriptor", e); } finally { - IOUtil.close(writer); + IOUtils.closeQuietly(writer); } } @@ -1571,7 +1572,8 @@ public class DefaultSiteTool implements SiteTool { Xpp3Dom xpp3Dom = (Xpp3Dom) plugin.getConfiguration(); if (xpp3Dom != null && xpp3Dom.getChild(param) != null - && StringUtils.isNotEmpty(xpp3Dom.getChild(param).getValue())) { + && xpp3Dom.getChild(param).getValue() != null + && !xpp3Dom.getChild(param).getValue().isEmpty()) { return xpp3Dom.getChild(param).getValue(); } } diff --git a/doxia-integration-tools/src/test/java/org/apache/maven/doxia/tools/SiteToolTest.java b/doxia-integration-tools/src/test/java/org/apache/maven/doxia/tools/SiteToolTest.java index e180b4a..24b7ba4 100644 --- a/doxia-integration-tools/src/test/java/org/apache/maven/doxia/tools/SiteToolTest.java +++ b/doxia-integration-tools/src/test/java/org/apache/maven/doxia/tools/SiteToolTest.java @@ -23,6 +23,7 @@ import javax.inject.Inject; import java.io.File; import java.io.StringReader; import java.io.Writer; +import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; @@ -37,6 +38,8 @@ import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.stream.Stream; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; import org.apache.maven.doxia.site.LinkItem; import org.apache.maven.doxia.site.SiteModel; import org.apache.maven.doxia.site.Skin; @@ -48,8 +51,6 @@ import org.apache.maven.execution.MavenExecutionRequest; import org.apache.maven.project.MavenProject; import org.apache.maven.repository.internal.MavenRepositorySystemUtils; import org.codehaus.plexus.testing.PlexusTest; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.XmlStreamWriter; import org.eclipse.aether.DefaultRepositorySystemSession; import org.eclipse.aether.RepositorySystemSession; @@ -544,7 +545,7 @@ class SiteToolTest { assertNotNull(descriptorFile); assertTrue(descriptorFile.exists()); - String siteDescriptorContent = FileUtils.fileRead(descriptorFile); + String siteDescriptorContent = FileUtils.readFileToString(descriptorFile, Charset.defaultCharset()); assertNotNull(siteDescriptorContent); assertTrue(siteDescriptorContent.contains("${project.name}")); assertFalse(siteDescriptorContent.contains( @@ -682,7 +683,7 @@ class SiteToolTest { assertNotNull(descriptorFile); assertTrue(descriptorFile.exists()); - String siteDescriptorContent = FileUtils.fileRead(descriptorFile); + String siteDescriptorContent = FileUtils.readFileToString(descriptorFile, Charset.defaultCharset()); SiteModel newModel = new SiteXpp3Reader().read(new StringReader(siteDescriptorContent)); assertNotNull(newModel); assertEquals(newModel, model); @@ -741,7 +742,7 @@ class SiteToolTest { try { new SiteXpp3Writer().write(writer, model); } finally { - IOUtil.close(writer); + IOUtils.closeQuietly(writer); } } } diff --git a/doxia-site-model/pom.xml b/doxia-site-model/pom.xml index 74dcf7f..a41d69f 100644 --- a/doxia-site-model/pom.xml +++ b/doxia-site-model/pom.xml @@ -41,10 +41,6 @@ under the License. <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> </dependency> - <dependency> - <groupId>org.codehaus.plexus</groupId> - <artifactId>plexus-utils</artifactId> - </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-xml</artifactId> diff --git a/doxia-site-model/src/main/java/org/apache/maven/doxia/site/PathTool.java b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/PathTool.java new file mode 100644 index 0000000..de3ea73 --- /dev/null +++ b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/PathTool.java @@ -0,0 +1,342 @@ +/* + * 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.doxia.site; + +import java.io.File; +import java.util.StringTokenizer; + +/** + * Path calculations used by site descriptors and by the site renderer. + * + * <p>This is a trimmed copy of the methods used from {@code org.codehaus.plexus.util.PathTool} + * (Apache License 2.0), kept here so that Doxia Sitetools no longer needs a dependency on + * plexus-utils. The behavior is intentionally identical, including the handling of Windows + * drive letters, trailing separators and the historical {@code /site/} and {@code /absolute/} + * link prefixes.</p> + */ +public class PathTool { + + /** + * Determines the relative path of a filename, using the separator found in the filename. + * + * @param filename the filename to be parsed + * @return the relative path, not terminated with a separator + */ + public static String getRelativePath(String filename) { + filename = uppercaseDrive(filename); + + if (isEmpty(filename)) { + return ""; + } + + String separator = determineSeparator(filename); + filename = chompLast(filename, separator); + if (!filename.startsWith(separator)) { + filename = separator + filename; + } + + return determineRelativePath(filename, separator); + } + + /** + * Determines the relative path of a filename with respect to a base directory. + * + * @param basedir the base directory + * @param filename the filename that is relative to the base directory + * @return the relative path, or an empty string when the filename is not below the base directory + */ + public static String getRelativePath(String basedir, String filename) { + basedir = uppercaseDrive(basedir); + filename = uppercaseDrive(filename); + + if (isEmpty(basedir) || isEmpty(filename) || !filename.startsWith(basedir)) { + return ""; + } + + String separator = determineSeparator(filename); + basedir = chompLast(basedir, separator); + filename = chompLast(filename, separator); + + String relativeFilename = filename.substring(basedir.length()); + + return determineRelativePath(relativeFilename, separator); + } + + /** + * Determines the directory component of a filename. + * + * @param filename the filename to be parsed + * @return the directory portion, or {@code .} when there is no directory component + */ + public static String getDirectoryComponent(String filename) { + if (isEmpty(filename)) { + return ""; + } + + String separator = determineSeparator(filename); + int index = filename.lastIndexOf(separator); + String directory = index != -1 ? filename.substring(0, index) : filename; + if (filename.equals(directory)) { + return "."; + } + return directory; + } + + /** + * Calculates the appropriate link given the preferred link and the relative path of the document. + * + * @param link the preferred link + * @param relativePath the relative path of the current document + * @return the link relative to the current document + */ + public static String calculateLink(String link, String relativePath) { + if (link == null) { + link = ""; + } + if (relativePath == null) { + relativePath = ""; + } + + // Historical site and absolute link prefixes. + if (link.startsWith("/site/")) { + return link.substring(5); + } + if (link.startsWith("/absolute/")) { + return link.substring(10); + } + + // Allows absolute links in nav-bars etc. + if (link.contains(":")) { + return link; + } + + if (equals(relativePath, ".")) { + if (link.startsWith("/")) { + return link.substring(1); + } + return link; + } + + // Avoid a double slash in "../" + "/page.html". + if (relativePath.endsWith("/") && link.startsWith("/")) { + return relativePath + "." + link.substring(1); + } + + if (relativePath.endsWith("/") || link.startsWith("/")) { + return relativePath + link; + } + + return relativePath + "/" + link; + } + + /** + * Calculates the relative path between two paths on a web site. + * + * @param oldPath the path of the referring page + * @param newPath the path of the target + * @return a relative web path from {@code oldPath} + */ + public static String getRelativeWebPath(String oldPath, String newPath) { + if (isEmpty(oldPath) || isEmpty(newPath)) { + return ""; + } + + String resultPath = buildRelativePath(newPath, oldPath, '/'); + + if (newPath.endsWith("/") && !resultPath.endsWith("/")) { + return resultPath + "/"; + } + + return resultPath; + } + + /** + * Calculates the relative path between two paths on the file system. + * + * @param oldPath the path of the referring file + * @param newPath the path of the target + * @return a relative file path from {@code oldPath}, or {@code null} when the paths are on different drives + */ + public static String getRelativeFilePath(String oldPath, String newPath) { + if (isEmpty(oldPath) || isEmpty(newPath)) { + return ""; + } + + String fromPath = new File(oldPath).getPath(); + String toPath = new File(newPath).getPath(); + + // strip any leading slashes if it is a Windows path + if (toPath.matches("^\\[a-zA-Z]:")) { + toPath = toPath.substring(1); + } + if (fromPath.matches("^\\[a-zA-Z]:")) { + fromPath = fromPath.substring(1); + } + + // lowercase Windows drive letters + if (fromPath.startsWith(":", 1)) { + fromPath = Character.toLowerCase(fromPath.charAt(0)) + fromPath.substring(1); + } + if (toPath.startsWith(":", 1)) { + toPath = Character.toLowerCase(toPath.charAt(0)) + toPath.substring(1); + } + + boolean fromHasDrive = fromPath.startsWith(":", 1); + boolean toHasDrive = toPath.startsWith(":", 1); + + if ((toHasDrive && fromHasDrive) && !toPath.substring(0, 1).equals(fromPath.substring(0, 1))) { + return null; + } + if (toHasDrive != fromHasDrive) { + return null; + } + + String resultPath = buildRelativePath(toPath, fromPath, File.separatorChar); + + if (newPath.endsWith(File.separator) && !resultPath.endsWith(File.separator)) { + return resultPath + File.separator; + } + + return resultPath; + } + + /** + * For each separator within the filename (except a leading one), appends a {@code ../}. + */ + private static String determineRelativePath(String filename, String separator) { + if (filename.isEmpty()) { + return ""; + } + + int slashCount = countMatches(filename, separator.charAt(0)) - 1; + if (slashCount <= 0) { + return "."; + } + + StringBuilder sb = new StringBuilder(); + for (int i = 0; i < slashCount; i++) { + sb.append("../"); + } + + return chop(sb.toString()); + } + + /** + * Returns the separator which occurs more often in the filename. + */ + private static String determineSeparator(String filename) { + int forwardCount = countMatches(filename, '/'); + int backwardCount = countMatches(filename, '\\'); + + return forwardCount >= backwardCount ? "/" : "\\"; + } + + /** + * Cygwin prefers lowercase drive letters, but other parts of Maven use uppercase. + */ + private static String uppercaseDrive(String path) { + if (path == null) { + return null; + } + if (path.length() >= 2 && path.charAt(1) == ':') { + path = Character.toUpperCase(path.charAt(0)) + path.substring(1); + } + return path; + } + + private static String buildRelativePath(String toPath, String fromPath, char separatorChar) { + String separator = String.valueOf(separatorChar); + + StringTokenizer toTokeniser = new StringTokenizer(toPath, separator); + StringTokenizer fromTokeniser = new StringTokenizer(fromPath, separator); + + int count = 0; + + // Walk along the to path looking for divergence from the from path. + while (toTokeniser.hasMoreTokens() && fromTokeniser.hasMoreTokens()) { + if (separatorChar == '\\') { + if (!fromTokeniser.nextToken().equalsIgnoreCase(toTokeniser.nextToken())) { + break; + } + } else if (!fromTokeniser.nextToken().equals(toTokeniser.nextToken())) { + break; + } + count++; + } + + toTokeniser = new StringTokenizer(toPath, separator); + fromTokeniser = new StringTokenizer(fromPath, separator); + + while (count-- > 0) { + fromTokeniser.nextToken(); + toTokeniser.nextToken(); + } + + StringBuilder relativePath = new StringBuilder(); + + // Add back references for the rest of the from location. + while (fromTokeniser.hasMoreTokens()) { + fromTokeniser.nextToken(); + relativePath.append(".."); + if (fromTokeniser.hasMoreTokens()) { + relativePath.append(separatorChar); + } + } + + if (relativePath.length() != 0 && toTokeniser.hasMoreTokens()) { + relativePath.append(separatorChar); + } + + // Add forward fills for whatever is left of the new path. + while (toTokeniser.hasMoreTokens()) { + relativePath.append(toTokeniser.nextToken()); + if (toTokeniser.hasMoreTokens()) { + relativePath.append(separatorChar); + } + } + + return relativePath.toString(); + } + + private static boolean isEmpty(String value) { + return value == null || value.isEmpty(); + } + + private static boolean equals(String left, String right) { + return left == null ? right == null : left.equals(right); + } + + private static String chompLast(String value, String suffix) { + return value.endsWith(suffix) ? value.substring(0, value.length() - suffix.length()) : value; + } + + private static String chop(String value) { + return value.substring(0, value.length() - 1); + } + + private static int countMatches(String value, char character) { + int count = 0; + for (int i = 0; i < value.length(); i++) { + if (value.charAt(i) == character) { + count++; + } + } + return count; + } +} diff --git a/doxia-site-model/src/main/java/org/apache/maven/doxia/site/SiteUtils.java b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/SiteUtils.java index 0464ab1..8e7ff3a 100644 --- a/doxia-site-model/src/main/java/org/apache/maven/doxia/site/SiteUtils.java +++ b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/SiteUtils.java @@ -18,7 +18,6 @@ */ package org.apache.maven.doxia.site; -import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.Xpp3Dom; /** @@ -28,7 +27,8 @@ import org.codehaus.plexus.util.xml.Xpp3Dom; */ public class SiteUtils { public static boolean isLink(String href) { - return StringUtils.isNotBlank(href) + return href != null + && !href.trim().isEmpty() && (startsWithAnyIgnoreCase(href, "http:/", "https:/", "ftp:/", "mailto:", "file:/") || href.contains("://")); } diff --git a/doxia-site-model/src/main/java/org/apache/maven/doxia/site/inheritance/URIPathDescriptor.java b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/inheritance/URIPathDescriptor.java index ba99289..8c3b702 100644 --- a/doxia-site-model/src/main/java/org/apache/maven/doxia/site/inheritance/URIPathDescriptor.java +++ b/doxia-site-model/src/main/java/org/apache/maven/doxia/site/inheritance/URIPathDescriptor.java @@ -21,7 +21,7 @@ package org.apache.maven.doxia.site.inheritance; import java.net.URI; import java.net.URISyntaxException; -import org.codehaus.plexus.util.PathTool; +import org.apache.maven.doxia.site.PathTool; /** * Describes a link that may be absolute or relative, and that is anchored to an absolute URI. diff --git a/doxia-site-model/src/test/java/org/apache/maven/doxia/site/PathToolTest.java b/doxia-site-model/src/test/java/org/apache/maven/doxia/site/PathToolTest.java new file mode 100644 index 0000000..63a1893 --- /dev/null +++ b/doxia-site-model/src/test/java/org/apache/maven/doxia/site/PathToolTest.java @@ -0,0 +1,86 @@ +/* + * 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.doxia.site; + +import java.io.File; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * Checks that {@link PathTool} keeps the behavior of the plexus-utils implementation it replaces. + * The expected values are taken from that implementation's API documentation. + */ +class PathToolTest { + @Test + void relativePathFromBaseDirectory() { + assertEquals("..", PathTool.getRelativePath("/usr/local/", "/usr/local/java/bin")); + assertEquals("../..", PathTool.getRelativePath("/usr/local/", "/usr/local/java/bin/java.sh")); + assertEquals("", PathTool.getRelativePath("/usr/local/java/bin/java.sh", "/usr/local/")); + } + + @Test + void relativePathWithinFilename() { + assertEquals("../../../..", PathTool.getRelativePath("/usr/local/java/bin/java.sh")); + assertEquals(".", PathTool.getRelativePath("java.sh")); + } + + @Test + void directoryComponent() { + assertEquals("/usr/local/java", PathTool.getDirectoryComponent("/usr/local/java/bin")); + assertEquals(".", PathTool.getDirectoryComponent("java.sh")); + assertEquals("", PathTool.getDirectoryComponent(null)); + } + + @Test + void relativeWebPath() { + assertEquals( + "plexus-utils/index.html", + PathTool.getRelativeWebPath( + "http://plexus.codehaus.org/", "http://plexus.codehaus.org/plexus-utils/index.html")); + assertEquals( + "../../", + PathTool.getRelativeWebPath( + "http://plexus.codehaus.org/plexus-utils/index.html", "http://plexus.codehaus.org/")); + assertEquals("", PathTool.getRelativeWebPath(null, "http://plexus.codehaus.org/")); + } + + @Test + void relativeFilePath() { + assertEquals( + "java" + File.separator + "bin", PathTool.getRelativeFilePath("/usr/local", "/usr/local/java/bin")); + assertEquals( + ".." + File.separator + ".." + File.separator, + PathTool.getRelativeFilePath("/usr/local/java/bin", "/usr/local/")); + assertEquals("", PathTool.getRelativeFilePath(null, "/usr/local")); + } + + @Test + void calculateLink() { + assertEquals("../../index.html", PathTool.calculateLink("/index.html", "../..")); + assertEquals( + "http://plexus.codehaus.org/plexus-utils/index.html", + PathTool.calculateLink("http://plexus.codehaus.org/plexus-utils/index.html", "../..")); + assertEquals( + "/usr/local/java/bin/../index.html", PathTool.calculateLink("../index.html", "/usr/local/java/bin")); + assertEquals("index.html", PathTool.calculateLink("/index.html", ".")); + assertEquals("sub/index.html", PathTool.calculateLink("index.html", "sub")); + } +} diff --git a/doxia-site-model/src/test/java/org/apache/maven/doxia/site/inheritance/SiteModelInheritanceAssemblerTest.java b/doxia-site-model/src/test/java/org/apache/maven/doxia/site/inheritance/SiteModelInheritanceAssemblerTest.java index 3ed9d09..eeb7a4f 100644 --- a/doxia-site-model/src/test/java/org/apache/maven/doxia/site/inheritance/SiteModelInheritanceAssemblerTest.java +++ b/doxia-site-model/src/test/java/org/apache/maven/doxia/site/inheritance/SiteModelInheritanceAssemblerTest.java @@ -31,7 +31,6 @@ import org.apache.maven.doxia.site.Logo; import org.apache.maven.doxia.site.Menu; import org.apache.maven.doxia.site.SiteModel; import org.apache.maven.doxia.site.io.xpp3.SiteXpp3Reader; -import org.codehaus.plexus.util.IOUtil; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.junit.jupiter.api.Test; @@ -921,12 +920,8 @@ class SiteModelInheritanceAssemblerTest { } private SiteModel readModel(String name) throws IOException, XmlPullParserException { - Reader reader = null; - try { - reader = new XmlStreamReader(getClass().getResourceAsStream("/" + name)); + try (Reader reader = new XmlStreamReader(getClass().getResourceAsStream("/" + name))) { return new SiteXpp3Reader().read(reader); - } finally { - IOUtil.close(reader); } } } diff --git a/doxia-site-renderer/pom.xml b/doxia-site-renderer/pom.xml index 45c3e8d..8168401 100644 --- a/doxia-site-renderer/pom.xml +++ b/doxia-site-renderer/pom.xml @@ -121,10 +121,6 @@ under the License. <artifactId>plexus-velocity</artifactId> <version>2.4.0</version> </dependency> - <dependency> - <groupId>org.codehaus.plexus</groupId> - <artifactId>plexus-utils</artifactId> - </dependency> <dependency> <groupId>org.codehaus.plexus</groupId> <artifactId>plexus-xml</artifactId> @@ -193,7 +189,6 @@ under the License. <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> - <scope>test</scope> </dependency> <dependency> <groupId>org.apache.maven.doxia</groupId> diff --git a/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DefaultSiteRenderer.java b/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DefaultSiteRenderer.java index 01dcf33..e1bb669 100644 --- a/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DefaultSiteRenderer.java +++ b/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DefaultSiteRenderer.java @@ -37,9 +37,12 @@ import java.io.StringWriter; import java.io.Writer; import java.net.URL; import java.net.URLClassLoader; +import java.nio.charset.Charset; import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardCopyOption; +import java.nio.file.StandardOpenOption; import java.util.ArrayList; -import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Enumeration; @@ -54,11 +57,16 @@ import java.util.Map.Entry; import java.util.Properties; import java.util.TimeZone; import java.util.function.Function; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; +import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.SystemUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.doxia.Doxia; @@ -69,6 +77,7 @@ import org.apache.maven.doxia.parser.module.ParserModule; import org.apache.maven.doxia.parser.module.ParserModuleManager; import org.apache.maven.doxia.site.LinkItem; import org.apache.maven.doxia.site.ModelNamespace; +import org.apache.maven.doxia.site.PathTool; import org.apache.maven.doxia.site.SiteModel; import org.apache.maven.doxia.site.skin.ResourceCondition; import org.apache.maven.doxia.site.skin.SkinModel; @@ -100,12 +109,6 @@ import org.apache.velocity.tools.generic.ResourceTool; import org.apache.velocity.tools.generic.SortTool; import org.apache.velocity.tools.generic.XmlTool; import org.codehaus.plexus.PlexusContainer; -import org.codehaus.plexus.util.DirectoryScanner; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.Os; -import org.codehaus.plexus.util.PathTool; -import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.codehaus.plexus.util.xml.pull.XmlPullParserException; import org.codehaus.plexus.velocity.VelocityComponent; @@ -270,7 +273,7 @@ public class DefaultSiteRenderer implements Renderer { return; } - List<String> allFiles = FileUtils.getFileNames(moduleBasedir, "**/*", excludes, false); + List<String> allFiles = getFileNames(moduleBasedir, "**/*", excludes, false); for (String extension : module.getExtensions()) { String fullExtension = "." + extension; @@ -340,7 +343,7 @@ public class DefaultSiteRenderer implements Renderer { }; DuplicateCallback caseInsensitiveDuplicateCallback = message -> { - if (Os.isFamily(Os.FAMILY_WINDOWS)) { + if (SystemUtils.IS_OS_WINDOWS) { return duplicateCallback.onDuplicate(message); } else { if (LOGGER.isWarnEnabled()) { @@ -430,7 +433,7 @@ public class DefaultSiteRenderer implements Renderer { docRenderer.renderDocument(writer, this, siteRenderingContext); rendered = true; } finally { - IOUtil.close(writer); + IOUtils.closeQuietly(writer); // a partly written page is newer than its source and would be skipped as unchanged next time if (!rendered && writer != null) { Files.deleteIfExists(outputFile.toPath()); @@ -531,7 +534,7 @@ public class DefaultSiteRenderer implements Renderer { sink.close(); - IOUtil.close(reader); + IOUtils.closeQuietly(reader); } mergeDocumentIntoSite(writer, (DocumentContent) sink, siteContext); @@ -554,7 +557,11 @@ public class DefaultSiteRenderer implements Renderer { outputParent.mkdirs(); } - FileUtils.fileWrite(outputFile, siteContext.getInputEncoding(), doxiaContent); + Files.write( + outputFile.toPath(), + doxiaContent.getBytes(Charset.forName(siteContext.getInputEncoding())), + StandardOpenOption.CREATE, + StandardOpenOption.TRUNCATE_EXISTING); } /** @@ -814,7 +821,7 @@ public class DefaultSiteRenderer implements Renderer { throw new RendererException("IO exception while merging site template.", ioe); } } finally { - IOUtil.close(writer); + IOUtils.closeQuietly(writer); if (old != null) { Thread.currentThread().setContextClassLoader(old); @@ -874,9 +881,9 @@ public class DefaultSiteRenderer implements Renderer { ZipEntry skinDescriptorEntry = zipFile.getEntry(SkinModel.SKIN_DESCRIPTOR_LOCATION); if (skinDescriptorEntry != null) { in = zipFile.getInputStream(skinDescriptorEntry); - byte[] skinDescriptor = IOUtil.toByteArray(in); + byte[] skinDescriptor = IOUtils.toByteArray(in); String skinDescriptorContent = - IOUtil.toString(new XmlStreamReader(new ByteArrayInputStream(skinDescriptor))); + IOUtils.toString(new XmlStreamReader(new ByteArrayInputStream(skinDescriptor))); if (ModelNamespace.isNewerThan(skinDescriptorContent, "SKIN", ModelNamespace.SKIN_MODEL_VERSION)) { LOGGER.warn("Skin " + skinId + " declares the skin model " + ModelNamespace.declaredVersion(skinDescriptorContent, "SKIN") @@ -911,7 +918,7 @@ public class DefaultSiteRenderer implements Renderer { + " skin", e); } finally { - IOUtil.close(in); + IOUtils.closeQuietly(in); closeZipFile(zipFile); } @@ -1007,7 +1014,7 @@ public class DefaultSiteRenderer implements Renderer { // DOXIA-290...the file should not be 0 bytes. writer.write("/* You can override this file with your own styles */"); } finally { - IOUtil.close(writer); + IOUtils.closeQuietly(writer); } } @@ -1032,7 +1039,7 @@ public class DefaultSiteRenderer implements Renderer { throw new IllegalArgumentException("Could not find the resource with name " + name); } else { try (OutputStream out = new FileOutputStream(destFile)) { - IOUtil.copy(in, out); + IOUtils.copy(in, out); } } } @@ -1094,9 +1101,9 @@ public class DefaultSiteRenderer implements Renderer { FileOutputStream fos = new FileOutputStream(destFile); try { - IOUtil.copy(file.getInputStream(entry), fos); + IOUtils.copy(file.getInputStream(entry), fos); } finally { - IOUtil.close(fos); + IOUtils.closeQuietly(fos); } } @@ -1109,26 +1116,15 @@ public class DefaultSiteRenderer implements Renderer { */ protected void copyDirectory(File source, File destination) throws IOException { if (source.exists()) { - DirectoryScanner scanner = new DirectoryScanner(); - - String[] includedResources = {"**/*"}; - - scanner.setIncludes(includedResources); - - scanner.addDefaultExcludes(); - - scanner.setBasedir(source); - - scanner.scan(); - - List<String> includedFiles = Arrays.asList(scanner.getIncludedFiles()); - - for (String name : includedFiles) { + for (String name : getFileNames(source, "**/*", null, true)) { File sourceFile = new File(source, name); - File destinationFile = new File(destination, name); - FileUtils.copyFile(sourceFile, destinationFile); + if (sourceFile.getCanonicalPath().equals(destinationFile.getCanonicalPath())) { + continue; + } + Files.createDirectories(destinationFile.getParentFile().toPath()); + Files.copy(sourceFile.toPath(), destinationFile.toPath(), StandardCopyOption.REPLACE_EXISTING); } } } @@ -1137,13 +1133,13 @@ public class DefaultSiteRenderer implements Renderer { LOGGER.debug("Validating: " + resource); try { - String content = IOUtil.toString(new BufferedReader(source)); + String content = IOUtils.toString(new BufferedReader(source)); new XmlValidator().validate(content); return new StringReader(content); } finally { - IOUtil.close(source); + IOUtils.closeQuietly(source); } } @@ -1185,8 +1181,124 @@ public class DefaultSiteRenderer implements Renderer { } } + /** + * Scans a directory with the same Ant-style pattern semantics as the plexus-utils scanner. + * When requested, the scanner's default excludes (VCS metadata, editor backups, and so on) + * are applied in addition to the caller's excludes. + */ + static List<String> getFileNames(File basedir, String includes, String excludes, boolean addDefaultExcludes) + throws IOException { + List<Pattern> includePatterns = compilePatterns(includes); + List<Pattern> excludePatterns = compilePatterns(excludes); + if (addDefaultExcludes) { + for (String pattern : DEFAULT_EXCLUDES) { + excludePatterns.add(toRegexPattern(pattern)); + } + } + + Path basePath = basedir.toPath(); + try (Stream<Path> paths = Files.walk(basePath)) { + return paths.filter(Files::isRegularFile) + .map(path -> basePath.relativize(path).toString().replace(File.separatorChar, '/')) + .filter(name -> matchesAny(name, includePatterns)) + .filter(name -> !matchesAny(name, excludePatterns)) + .sorted() + .collect(Collectors.toList()); + } + } + + private static List<Pattern> compilePatterns(String patterns) { + List<Pattern> result = new ArrayList<>(); + if (patterns != null) { + for (String pattern : StringUtils.split(patterns, ",")) { + result.add(toRegexPattern(pattern)); + } + } + return result; + } + + private static boolean matchesAny(String name, List<Pattern> patterns) { + for (Pattern pattern : patterns) { + if (pattern.matcher(name).matches()) { + return true; + } + } + return false; + } + + /** + * Converts an Ant-style path pattern into a regular expression. {@code **} matches across + * directory boundaries, {@code *} and {@code ?} match within a single segment. + */ + private static Pattern toRegexPattern(String antPattern) { + StringBuilder regex = new StringBuilder(); + for (int i = 0; i < antPattern.length(); i++) { + char c = antPattern.charAt(i); + if (c == '*') { + if (i + 1 < antPattern.length() && antPattern.charAt(i + 1) == '*') { + i++; + if (i + 1 < antPattern.length() && antPattern.charAt(i + 1) == '/') { + i++; + regex.append("(?:.*/)?"); + } else { + regex.append(".*"); + } + } else { + regex.append("[^/]*"); + } + } else if (c == '?') { + regex.append("[^/]"); + } else { + if ("\\.[]{}()+-^$|".indexOf(c) >= 0) { + regex.append('\\'); + } + regex.append(c); + } + } + return Pattern.compile(regex.toString()); + } + + private static final String[] DEFAULT_EXCLUDES = { + "**/*~", + "**/#*#", + "**/.#*", + "**/%*%", + "**/._*", + "**/CVS", + "**/CVS/**", + "**/RCS", + "**/RCS/**", + "**/SCCS", + "**/SCCS/**", + "**/vssver.scc", + "**/project.pj", + "**/.svn", + "**/.svn/**", + "**/.arch-ids", + "**/.arch-ids/**", + "**/.bzr", + "**/.bzr/**", + "**/.MySCMServerInfo", + "**/.DS_Store", + "**/.metadata", + "**/.metadata/**", + "**/.hg", + "**/.hg/**", + "**/.git", + "**/.git/**", + "**/BitKeeper", + "**/BitKeeper/**", + "**/ChangeSet", + "**/ChangeSet/**", + "**/_darcs", + "**/_darcs/**", + "**/.darcsrepo", + "**/.darcsrepo/**", + "**/-darcs-backup*", + "**/.darcs-temp-mail" + }; + private static void closeZipFile(ZipFile zipFile) { - // TODO: move to plexus utils try { zipFile.close(); } catch (IOException e) { diff --git a/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DocumentRenderingContext.java b/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DocumentRenderingContext.java index 62a9673..7313c59 100644 --- a/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DocumentRenderingContext.java +++ b/doxia-site-renderer/src/main/java/org/apache/maven/doxia/siterenderer/DocumentRenderingContext.java @@ -25,7 +25,7 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; -import org.codehaus.plexus.util.PathTool; +import org.apache.maven.doxia.site.PathTool; /** * The rendering context of a document. diff --git a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/DefaultSiteRendererTest.java b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/DefaultSiteRendererTest.java index 9aabaa4..dbe898c 100644 --- a/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/DefaultSiteRendererTest.java +++ b/doxia-site-renderer/src/test/java/org/apache/maven/doxia/siterenderer/DefaultSiteRendererTest.java @@ -44,10 +44,14 @@ import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.jar.JarOutputStream; +import java.util.regex.Matcher; +import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.reflect.FieldUtils; import org.apache.maven.artifact.Artifact; import org.apache.maven.artifact.DefaultArtifact; import org.apache.maven.artifact.versioning.VersionRange; @@ -61,10 +65,6 @@ import org.apache.maven.doxia.siterenderer.sink.SiteRendererSink; import org.apache.maven.doxia.xsd.AbstractXmlValidator; import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.testing.PlexusTest; -import org.codehaus.plexus.util.FileUtils; -import org.codehaus.plexus.util.IOUtil; -import org.codehaus.plexus.util.ReflectionUtils; -import org.codehaus.plexus.util.StringUtils; import org.codehaus.plexus.util.xml.XmlStreamReader; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeAll; @@ -181,7 +181,7 @@ public class DefaultSiteRendererTest { .when(doxiaSpy) .parse(Mockito.<Reader>any(), Mockito.anyString(), Mockito.<Sink>any(), Mockito.nullable(String.class)); SiteRenderer siteRenderer = container.lookup(SiteRenderer.class); - ReflectionUtils.setVariableValueInObject(siteRenderer, "doxia", doxiaSpy); + FieldUtils.writeField(siteRenderer, "doxia", doxiaSpy, true); DocumentRenderingContext docRenderingContext = new DocumentRenderingContext( testBasedir, "src/test/resources/site/xdoc", testDocument, "xdoc", "", false); @@ -212,7 +212,7 @@ public class DefaultSiteRendererTest { .when(doxiaSpy) .parse(Mockito.<Reader>any(), Mockito.anyString(), Mockito.<Sink>any(), Mockito.nullable(String.class)); SiteRenderer siteRenderer = container.lookup(SiteRenderer.class); - ReflectionUtils.setVariableValueInObject(siteRenderer, "doxia", doxiaSpy); + FieldUtils.writeField(siteRenderer, "doxia", doxiaSpy, true); DocumentRenderingContext docRenderingContext = new DocumentRenderingContext( testBasedir, "src/test/resources/site/xdoc", testDocumentName, "xdoc", "", false); @@ -344,7 +344,7 @@ public class DefaultSiteRendererTest { String renderResult = writer.toString(); String expectedResult = IOUtils.toString( getClass().getResourceAsStream("velocity-toolmanager.expected.txt"), StandardCharsets.UTF_8); - expectedResult = StringUtils.unifyLineSeparators(expectedResult); + expectedResult = unifyLineSeparators(expectedResult); assertEquals(expectedResult, renderResult); } @@ -357,7 +357,7 @@ public class DefaultSiteRendererTest { try (InputStream skinIS = getClass().getResourceAsStream("velocity-toolmanager.vm"); JarOutputStream jarOS = new JarOutputStream(new FileOutputStream(skinFile))) { jarOS.putNextEntry(new ZipEntry("META-INF/maven/site.vm")); - IOUtil.copy(skinIS, jarOS); + IOUtils.copy(skinIS, jarOS); jarOS.closeEntry(); } @@ -381,7 +381,7 @@ public class DefaultSiteRendererTest { SiteRendererSink sink = new SiteRendererSink(context); siteRenderer.mergeDocumentIntoSite(writer, sink, siteRenderingContext); String renderResult = writer.toString(); - String expectedResult = StringUtils.unifyLineSeparators(IOUtils.toString( + String expectedResult = unifyLineSeparators(IOUtils.toString( getClass().getResourceAsStream("velocity-toolmanager.expected.txt"), StandardCharsets.UTF_8)); assertEquals(expectedResult, renderResult); } @@ -614,10 +614,10 @@ public class DefaultSiteRendererTest { Reader reader = null; try { reader = new XmlStreamReader(macro); - String content = IOUtil.toString(reader); + String content = IOUtils.toString(reader); assertEquals(-1, content.indexOf("</macro>")); } finally { - IOUtil.close(reader); + IOUtils.closeQuietly(reader); } } @@ -683,16 +683,34 @@ public class DefaultSiteRendererTest { */ public void verifyNewlines() throws Exception { /* apt */ - checkNewlines(FileUtils.fileRead(getTestFile("target/output/apt.html"), "ISO-8859-1")); - checkNewlines(FileUtils.fileRead(getTestFile("target/output/cdc.html"), "ISO-8859-1")); - checkNewlines(FileUtils.fileRead(getTestFile("target/output/interpolation.html"), "ISO-8859-1")); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/apt.html").toPath()), StandardCharsets.ISO_8859_1)); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/cdc.html").toPath()), StandardCharsets.ISO_8859_1)); + checkNewlines(new String( + Files.readAllBytes( + getTestFile("target/output/interpolation.html").toPath()), + StandardCharsets.ISO_8859_1)); /* fml */ - checkNewlines(FileUtils.fileRead(getTestFile("target/output/faq.html"), "ISO-8859-1")); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/faq.html").toPath()), StandardCharsets.ISO_8859_1)); /* xdoc */ - checkNewlines(FileUtils.fileRead(getTestFile("target/output/attributes.html"), "ISO-8859-1")); - checkNewlines(FileUtils.fileRead(getTestFile("target/output/javascript.html"), "ISO-8859-1")); - checkNewlines(FileUtils.fileRead(getTestFile("target/output/head.html"), "ISO-8859-1")); - checkNewlines(FileUtils.fileRead(getTestFile("target/output/macro.html"), "ISO-8859-1")); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/attributes.html").toPath()), + StandardCharsets.ISO_8859_1)); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/javascript.html").toPath()), + StandardCharsets.ISO_8859_1)); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/head.html").toPath()), StandardCharsets.ISO_8859_1)); + checkNewlines(new String( + Files.readAllBytes(getTestFile("target/output/macro.html").toPath()), StandardCharsets.ISO_8859_1)); + } + + private static String unifyLineSeparators(String content) { + return content == null + ? null + : content.replaceAll("\\r\\n|\\r|\\n", Matcher.quoteReplacement(System.lineSeparator())); } private void checkNewlines(String content) { @@ -749,17 +767,18 @@ public class DefaultSiteRendererTest { File dir = new File(getBasedir(), "target/output"); - List<String> l = - FileUtils.getFileNames(dir, getIncludes()[0], FileUtils.getDefaultExcludesAsString(), true); + List<String> l = DefaultSiteRenderer.getFileNames(dir, getIncludes()[0], null, true).stream() + .map(name -> new File(dir, name).getPath()) + .collect(Collectors.toList()); for (String file : l) { file = file == null || file.isEmpty() ? file : file.replace("\\", "/"); Reader reader = new XmlStreamReader(new File(file)); try { - testDocs.put(file, IOUtil.toString(reader)); + testDocs.put(file, IOUtils.toString(reader)); } finally { - IOUtil.close(reader); + IOUtils.closeQuietly(reader); } }
