diff --git a/.github/workflows/codeql-analysis.yml b/.github/workflows/codeql-analysis.yml deleted file mode 100644 index 7d1e5b90..00000000 --- a/.github/workflows/codeql-analysis.yml +++ /dev/null @@ -1,67 +0,0 @@ -# For most projects, this workflow file will not need changing; you simply need -# to commit it to your repository. -# -# You may wish to alter this file to override the set of languages analyzed, -# or to provide custom queries or build logic. -# -# ******** NOTE ******** -# We have attempted to detect the languages in your repository. Please check -# the `language` matrix defined below to confirm you have the correct set of -# supported CodeQL languages. -# -name: "CodeQL" - -on: - push: - branches: [ master ] - pull_request: - # The branches below must be a subset of the branches above - branches: [ master ] - schedule: - - cron: '24 19 * * 0' - -jobs: - analyze: - name: Analyze - runs-on: ubuntu-latest - - strategy: - fail-fast: false - matrix: - language: [ 'java' ] - # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ] - # Learn more: - # https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed - - steps: - - name: Checkout repository - uses: actions/checkout@v2.4.0 - - # Initializes the CodeQL tools for scanning. - - name: Initialize CodeQL - uses: github/codeql-action/init@v1 - with: - languages: ${{ matrix.language }} - # If you wish to specify custom queries, you can do so here or in a config file. - # By default, queries listed here will override any specified in a config file. - # Prefix the list here with "+" to use these queries and those in the config file. - # queries: ./path/to/local/query, your-org/your-repo/queries@main - - # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). - # If this step fails, then you should remove it and run the build manually (see below) - - name: Autobuild - uses: github/codeql-action/autobuild@v1 - - # â„šī¸ Command-line programs to run using the OS shell. - # 📚 https://git.io/JvXDl - - # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines - # and modify them (or add more) to build your code if your project - # uses a compiled language - - #- run: | - # make bootstrap - # make release - - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@v1 diff --git a/.github/workflows/maven.yml b/.github/workflows/maven.yml index ff4a45d1..fb8795b4 100644 --- a/.github/workflows/maven.yml +++ b/.github/workflows/maven.yml @@ -21,22 +21,11 @@ on: [push, pull_request] jobs: build: + name: Build it + uses: codehaus-plexus/.github/.github/workflows/maven.yml@master - strategy: - matrix: - os: [ubuntu-latest,windows-latest, macOS-latest] - java: [8, 11, 17] - fail-fast: false - - runs-on: ${{ matrix.os }} - - steps: - - uses: actions/checkout@v2.4.0 - - uses: actions/setup-java@v2 - with: - java-version: ${{ matrix.java }} - distribution: 'temurin' - cache: 'maven' - - - name: Build with Maven - run: mvn install javadoc:javadoc site -e -B -V -Pno-tests-if-not-on-osx +# deploy: +# name: Deploy +# needs: build +# uses: codehaus-plexus/.github/.github/workflows/maven-deploy.yml@master +# secrets: inherit diff --git a/.github/workflows/release-drafter.yml b/.github/workflows/release-drafter.yml index 96f54b5d..02e42b3d 100644 --- a/.github/workflows/release-drafter.yml +++ b/.github/workflows/release-drafter.yml @@ -1,3 +1,20 @@ +# 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. + name: Release Drafter on: push: @@ -5,8 +22,5 @@ on: - master jobs: update_release_draft: - runs-on: ubuntu-latest - steps: - - uses: release-drafter/release-drafter@v5.19.0 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + name: Update Release Notes Draft + uses: codehaus-plexus/.github/.github/workflows/release-drafter.yml@v0.0.5 diff --git a/README.md b/README.md index 28c4a0b1..421dc5a7 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,9 @@ Plexus-IO ========= -[![Build Status](https://travis-ci.org/codehaus-plexus/plexus-io.svg?branch=master)](https://travis-ci.org/codehaus-plexus/plexus-io) +[![Build Status](https://github.com/codehaus-plexus/plexus-io/actions/workflows/maven.yml/badge.svg)](https://github.com/codehaus-plexus/plexus-io/actions/workflows/maven.yml) [![Maven Central](https://img.shields.io/maven-central/v/org.codehaus.plexus/plexus-io.svg?label=Maven%20Central)](https://search.maven.org/artifact/org.codehaus.plexus/plexus-io) +[![Reproducible Builds](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/jvm-repo-rebuild/reproducible-central/master/content/org/codehaus/plexus/plexus-io/badge.json)](https://github.com/jvm-repo-rebuild/reproducible-central/blob/master/content/org/codehaus/plexus/plexus-io/README.md) The current master is now at https://github.com/codehaus-plexus/plexus-io @@ -12,13 +13,4 @@ For publishing [the site](https://codehaus-plexus.github.io/plexus-io/) do the f mvn -Preporting verify site-deploy ``` -## Release Notes - -You can find details about the different releases in the -[Release Notes](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md). - - * [Release 3.2.0](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md#plexus-io-320). - * [Release 3.1.1](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md#plexus-io-311). - * [Release 3.1.0](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md#plexus-io-310). - * [Release 3.0.1](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md#plexus-io-301). - * [Release 3.0.0](https://github.com/codehaus-plexus/plexus-io/blob/master/ReleaseNotes.md#plexus-io-300). +Enjoy! diff --git a/ReleaseNotes.md b/ReleaseNotes.md deleted file mode 100644 index 70c00952..00000000 --- a/ReleaseNotes.md +++ /dev/null @@ -1,243 +0,0 @@ -Plexus-IO Release Notes -======================================================================== - -Plexus IO 3.2.0 ---------------- - -Plexus IO 3.2.0 requires Java 7. - -### New Features - - * [Issue #18][issue-18] - Add an option to sort the entries of PlexusIoFileResourceCollection - -Plexus IO 3.1.1 ---------------- - -Plexus IO 3.1.1 requires Java 7. - -### Improvements - - * [Issue #16][issue-16], [Pull Request #17][pr-17] - Improve performance - on systems which have high time penalty when fetching owner and group name. - Thanks to Classe. - -Plexus IO 3.1.0 ---------------- - -Plexus IO 3.1.0 requires Java 7. - -### New Features - - * [Pull Request #14][pr-14] - Add new FileMapper for giving a suffix to filename: - `SuffixFileMapper`. Thanks to Thomas Collignon. - -Plexus IO 3.0.1 ---------------- - -Plexus IO 3.0.1 requires Java 7. - -### Tasks - - * [Issue #9][issue-9], [Issue #10][issue-10] - Updated dependencies: - `plexus-utils` to 3.1.0 and `commons-io` to 2.6 - -Plexus IO 3.0.0 ---------------- - -Plexus IO 3.0.0 requires Java 7 and introduces backward incompatible changes: - - * `Java7FileAttributes` is renamed to `FileAttributes`, replacing - the old `FileAttributes` implementation - * `Java7AttributeUtils` is renamed to `AttributeUtils` - * `PlexusIoResourceAttributeUtils#getFileAttributesByPath( File, boolean, boolean )` - is deleted - -### Improvements - - * [Pull Request #5][pr-5] - The required Java version is upgraded to 7. - Classes that use native tools like `ls` are removed and the pure Java - implementations are used instead. - -### Tasks - - * [Issue #8][issue-8] - Update of `plexus-utils` to 3.0.24 and - `commons-io` to 2.5 - -Plexus IO 2.7.1 ---------------- - -### Improvements - - * [Pull Request #3][pr-3] - Introduce new constant to indicate uknown - octal mode for resources - `PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE` - -### Bugs - - * [Issue #2][issue-2] - JAR entry not found when JAR is updated inline and - cached by URLConnection - -Plexus IO 2.7 ---------------- - -### Improvements - - * Added TIME_STYLE=long-iso to ls screen scrape - * [Pull Request #1][pr-1] - Add concurrent access flag - to the PlexusIoProxyResourceCollection - - `PlexusIoResourceCollection#isConcurrentAccessSupported()` - -Plexus IO 2.6.1 ---------------- - -### Improvement - - * Performance improvement affecting mac/linux users - with lots of small files in large archives. - -Plexus IO 2.5 -------------- - - * Proper support for closeable on zip archives. - * Removed zip supporting PlexusIoZipFileResourceCollection; which now exists in plexus-archiver. (Drop in replacement, - just change/add jar file). - -Plexus IO 2.4.1 ---------------- - -### Bugs - - * PLXCOMP-279 - PlexusIoProxyResourceCollection does not provide Closeable iterator - * Fixed PLXCOMP-280 - SimpleResourceAttributes has incorrect value for - default file mode - -Plexus IO 2.4 -------------- - -### Improvements - - * PLXCOMP-274 - Simplify use of proxies - * PLXCOMP-275 - Avoid leaky abstractions - * PLXCOMP-276 - Reduce number of ways to create a PlexusIoResource - -Plexus IO 2.3.5 ---------------- - -### Bugs - - * PLXCOMP-278 - Symlink attribute was not preserved through merged/overridden attributes - -Plexus IO 2.3.4 ---------------- - -### Bugs - - * PLXCOMP-270 - Escaping algoritghm leaks through to system classloader - * PLXCOMP-272 - Overriding dirmode/filemode breaks symlinks - -Plexus IO 2.3.3 ---------------- - -### Bugs - - * PLXCOMP-267 - StreamTransformers are consistently applied to all collections - -Plexus IO 2.3.2 ---------------- - -### Bugs - - * PLXCOMP-265 - Locale in shell influences "ls" parsing for screenscraper - -Plexus IO 2.3.1 ---------------- - -### Bugs - - * PLXCOMP-264 - Thread safety issue in streamconsumer - -Plexus IO 2.3 -------------- - -### New Features - - * PLXCOMP-261 - Make plexus io collections support on-the-fly filtering - -### Improvements - - * PLXCOMP-260 - Make plexus io collections iterable - -Plexus IO 2.2 -------------- - -### Bugs - - * PLXCOMP-251 - Date parsing in "ls" screenscraping has locale dependencies - * PLXCOMP-254 - Fix File.separatorChar normalization when prefixes are used - -Plexus IO 2.1.4 ---------------- - -### Improvements - - * PLXCOMP-250 - Upgrade maven-enforcer-plugin to 1.3.1 - -### Bugs - - * PLXCOMP-107 - Fail to unzip archive, which contains file with name - 'How_can_I_annotate_a_part_in_the_AAM%3F.Help' - -Plexus IO 2.1.3 ---------------- - -### Bugs - - * PLXCOMP-247 - Bug with windows AND java5 - -Plexus IO 2.1.2 ---------------- - -### Bugs - - * PLXCOMP-244 - Don't try to set attributes of symbolic links - * PLXCOMP-245 - Archives created on windows get zero permissions, - creates malformed permissions on linux - -Plexus IO 2.1.1 ---------------- - -### Bugs - - * PLXCOMP-243 - Restore JDK1.5 compatibility - -Plexus IO 2.1 -------------- - -### Improvements - - * PLXCOMP-64 - add symlink support to tar unarchiver - * PLXCOMP-117 - add symbolic links managment - -### Bugs - - * PLXCOMP-113 - zip unarchiver doesn't support symlinks (and trivial to fix) - * PLXCOMP-241 - ResourcesTest.compare test failure - * PLXCOMP-248 - Use java7 setAttributes and ignore useJvmChmod flag when applicable - -Plexus IO 2.0.12 ----------------- - -### Bugs - - * PLXCOMP-249 - Add support for java7 chmod - -[issue-2]: https://github.com/codehaus-plexus/plexus-io/issues/2 -[issue-8]: https://github.com/codehaus-plexus/plexus-io/issues/8 -[issue-9]: https://github.com/codehaus-plexus/plexus-io/issues/9 -[issue-10]: https://github.com/codehaus-plexus/plexus-io/issues/10 -[issue-16]: https://github.com/codehaus-plexus/plexus-io/issues/16 -[issue-18]: https://github.com/codehaus-plexus/plexus-io/issues/18 -[pr-1]: https://github.com/codehaus-plexus/plexus-io/pull/1 -[pr-3]: https://github.com/codehaus-plexus/plexus-io/pull/3 -[pr-5]: https://github.com/codehaus-plexus/plexus-io/pull/5 -[pr-14]: https://github.com/codehaus-plexus/plexus-io/pull/14 -[pr-17]: https://github.com/codehaus-plexus/plexus-io/pull/17 diff --git a/pom.xml b/pom.xml index 798f119a..517106bc 100644 --- a/pom.xml +++ b/pom.xml @@ -1,22 +1,23 @@ + 4.0.0 org.codehaus.plexus plexus - 8 + 23 plexus-io - 3.3.0 + 3.5.2-SNAPSHOT Plexus IO Components scm:git:git@github.com:codehaus-plexus/plexus-io.git scm:git:git@github.com:codehaus-plexus/plexus-io.git + HEAD http://github.com/codehaus-plexus/plexus-io - plexus-io-3.3.0 jira @@ -30,22 +31,37 @@ - true - 8 - 2022-03-27T07:31:26Z + 0.9.0.M4 + 1.7.36 + 2024-09-09T12:59:25Z + + + + org.eclipse.sisu + org.eclipse.sisu.inject + ${eclipseSisuVersion} + + + org.eclipse.sisu + org.eclipse.sisu.plexus + ${eclipseSisuVersion} + + + + - org.codehaus.plexus - plexus-utils - 3.4.1 + javax.inject + javax.inject + 1 + org.codehaus.plexus - plexus-container-default - test - 2.1.1 + plexus-utils + 3.6.0 com.google.code.findbugs @@ -56,93 +72,59 @@ commons-io commons-io - 2.11.0 + 2.20.0 + + + + + org.junit.jupiter + junit-jupiter-api + test - junit - junit - 4.13.2 + org.slf4j + slf4j-simple + ${slf4jVersion} + test + + + org.codehaus.plexus + plexus-testing + 1.6.0 + test + + + + org.eclipse.sisu + org.eclipse.sisu.inject test - + + org.eclipse.sisu + sisu-maven-plugin + org.apache.maven.plugins maven-scm-publish-plugin - ${project.reporting.outputDirectory} + ${project.reporting.outputDirectory} + scm-publish - site-deploy + publish-scm + site-deploy - - org.apache.maven.plugins - maven-surefire-plugin - - never - - - - org.apache.maven.plugins - maven-enforcer-plugin - - - enforce-java - validate - - enforce - - - - - 1.7.0 - - - - - - - - org.codehaus.mojo - animal-sniffer-maven-plugin - 1.21 - - - sniff - test - - check - - - - - - org.codehaus.mojo.signature - java17 - 1.0 - - - - - org.apache.maven.plugins - maven-resources-plugin - - 2.7 - diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeConstants.java b/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeConstants.java index 95c26f22..fb87b569 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeConstants.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeConstants.java @@ -16,8 +16,8 @@ * limitations under the License. */ -public final class AttributeConstants -{ +@SuppressWarnings("OctalInteger") +public final class AttributeConstants { public static final int OCTAL_OWNER_READ = 0400; @@ -37,8 +37,5 @@ public final class AttributeConstants public static final int OCTAL_WORLD_EXECUTE = 01; - private AttributeConstants() - { - } - -} \ No newline at end of file + private AttributeConstants() {} +} diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeUtils.java b/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeUtils.java index 03e7944a..be00c0a5 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeUtils.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/AttributeUtils.java @@ -15,6 +15,9 @@ */ package org.codehaus.plexus.components.io.attributes; +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -27,134 +30,96 @@ import java.util.HashSet; import java.util.Set; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - /** * @author Kristian Rosenvold */ -public class AttributeUtils -{ +@SuppressWarnings("OctalInteger") +public class AttributeUtils { /* Reads last-modified with proper failure handling if something goes wrong. */ - public static long getLastModified( @Nonnull File file ) - { - try - { - BasicFileAttributes basicFileAttributes = Files.readAttributes( file.toPath(), BasicFileAttributes.class ); + public static long getLastModified(@Nonnull File file) { + try { + BasicFileAttributes basicFileAttributes = Files.readAttributes(file.toPath(), BasicFileAttributes.class); return basicFileAttributes.lastModifiedTime().toMillis(); + } catch (IOException e) { + throw new RuntimeException(e); } - catch ( IOException e ) - { - throw new RuntimeException( e ); - } - } - public static void chmod( @Nonnull File file, int mode ) - throws IOException - { + public static void chmod(@Nonnull File file, int mode) throws IOException { final Path path = file.toPath(); - if ( !Files.isSymbolicLink( path ) ) - { - Files.setPosixFilePermissions( path, getPermissions( mode ) ); + if (!Files.isSymbolicLink(path)) { + Files.setPosixFilePermissions(path, getPermissions(mode)); } } @Nonnull - public static Set getPermissions( int mode ) - { + public static Set getPermissions(int mode) { Set perms = new HashSet<>(); // add owners permission - if ( ( mode & 0400 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_READ ); + if ((mode & 0400) > 0) { + perms.add(PosixFilePermission.OWNER_READ); } - if ( ( mode & 0200 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_WRITE ); + if ((mode & 0200) > 0) { + perms.add(PosixFilePermission.OWNER_WRITE); } - if ( ( mode & 0100 ) > 0 ) - { - perms.add( PosixFilePermission.OWNER_EXECUTE ); + if ((mode & 0100) > 0) { + perms.add(PosixFilePermission.OWNER_EXECUTE); } // add group permissions - if ( ( mode & 0040 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_READ ); + if ((mode & 0040) > 0) { + perms.add(PosixFilePermission.GROUP_READ); } - if ( ( mode & 0020 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_WRITE ); + if ((mode & 0020) > 0) { + perms.add(PosixFilePermission.GROUP_WRITE); } - if ( ( mode & 0010 ) > 0 ) - { - perms.add( PosixFilePermission.GROUP_EXECUTE ); + if ((mode & 0010) > 0) { + perms.add(PosixFilePermission.GROUP_EXECUTE); } // add others permissions - if ( ( mode & 0004 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_READ ); + if ((mode & 0004) > 0) { + perms.add(PosixFilePermission.OTHERS_READ); } - if ( ( mode & 0002 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_WRITE ); + if ((mode & 0002) > 0) { + perms.add(PosixFilePermission.OTHERS_WRITE); } - if ( ( mode & 0001 ) > 0 ) - { - perms.add( PosixFilePermission.OTHERS_EXECUTE ); + if ((mode & 0001) > 0) { + perms.add(PosixFilePermission.OTHERS_EXECUTE); } return perms; } @Nonnull - public static PosixFileAttributes getPosixFileAttributes( @Nonnull File file ) - throws IOException - { - return Files.readAttributes( file.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS ); + public static PosixFileAttributes getPosixFileAttributes(@Nonnull File file) throws IOException { + return Files.readAttributes(file.toPath(), PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); } @Nonnull - public static BasicFileAttributes getFileAttributes( @Nonnull File file ) - throws IOException - { - return getFileAttributes( file.toPath() ); + public static BasicFileAttributes getFileAttributes(@Nonnull File file) throws IOException { + return getFileAttributes(file.toPath()); } - public static BasicFileAttributes getFileAttributes( Path path ) - throws IOException - { - if ( isUnix( path ) ) - { - - try - { - return Files.readAttributes( path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS ); - } - catch ( UnsupportedOperationException ignore ) - { + public static BasicFileAttributes getFileAttributes(Path path) throws IOException { + if (isUnix(path)) { + try { + return Files.readAttributes(path, PosixFileAttributes.class, LinkOption.NOFOLLOW_LINKS); + } catch (UnsupportedOperationException ignore) { // Maybe ignoring is dramatic. Maybe not. But we do get the basic attrs anyway } } - return Files.readAttributes( path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS ); + return Files.readAttributes(path, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS); } - public static boolean isUnix( Path path ) - { - return path.getFileSystem().supportedFileAttributeViews().contains( "unix" ); + public static boolean isUnix(Path path) { + return path.getFileSystem().supportedFileAttributeViews().contains("unix"); } @Nullable - public static FileOwnerAttributeView getFileOwnershipInfo( @Nonnull File file ) - throws IOException - { - try - { - return Files.getFileAttributeView( file.toPath(), FileOwnerAttributeView.class, LinkOption.NOFOLLOW_LINKS ); - } - catch ( UnsupportedOperationException e ) - { + public static FileOwnerAttributeView getFileOwnershipInfo(@Nonnull File file) throws IOException { + try { + return Files.getFileAttributeView(file.toPath(), FileOwnerAttributeView.class, LinkOption.NOFOLLOW_LINKS); + } catch (UnsupportedOperationException e) { return null; } } diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/FileAttributes.java b/src/main/java/org/codehaus/plexus/components/io/attributes/FileAttributes.java index 6b90fdff..d530790c 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/FileAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/FileAttributes.java @@ -16,30 +16,33 @@ * limitations under the License. */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; + import java.io.File; import java.io.IOException; +import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; -import java.nio.file.attribute.FileOwnerAttributeView; import java.nio.file.attribute.FileTime; import java.nio.file.attribute.PosixFilePermission; import java.security.Principal; import java.util.Collections; -import java.util.HashMap; import java.util.Map; import java.util.Set; - -import javax.annotation.Nonnull; -import javax.annotation.Nullable; +import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; /* * File attributes * Immutable */ -public class FileAttributes - implements PlexusIoResourceAttributes -{ +public class FileAttributes implements PlexusIoResourceAttributes { + public static final LinkOption[] FOLLOW_LINK_OPTIONS = new LinkOption[] {}; + + public static final LinkOption[] NOFOLLOW_LINK_OPTIONS = new LinkOption[] {LinkOption.NOFOLLOW_LINKS}; + @Nullable private final Integer groupId; @@ -67,51 +70,114 @@ public class FileAttributes private final FileTime lastModifiedTime; - public FileAttributes( @Nonnull File file, @Nonnull Map userCache, - @Nonnull Map groupCache ) - throws IOException - { + private static final Map> UIDS_CACHE = + Collections.synchronizedMap(new WeakHashMap<>()); + + private static final Map> GIDS_CACHE = + Collections.synchronizedMap(new WeakHashMap<>()); + + /** + * @deprecated use {@link #FileAttributes(File)} and remove the unused userCache and groupCache parameters + */ + @Deprecated + public FileAttributes( + @Nonnull File file, @Nonnull Map userCache, @Nonnull Map groupCache) + throws IOException { + this(file); + } - Path path = file.toPath(); + public FileAttributes(@Nonnull File file) throws IOException { + this(file.toPath(), false); + } + + public FileAttributes(@Nonnull File file, boolean followLinks) throws IOException { + this(file.toPath(), followLinks); + } + + private static Map getUserCache(FileSystem fs) { + return UIDS_CACHE.computeIfAbsent(fs, f -> new ConcurrentHashMap<>()); + } + + private static Map getGroupCache(FileSystem fs) { + return GIDS_CACHE.computeIfAbsent(fs, f -> new ConcurrentHashMap<>()); + } + + public FileAttributes(@Nonnull Path path, boolean followLinks) throws IOException { + LinkOption[] options = followLinks ? FOLLOW_LINK_OPTIONS : NOFOLLOW_LINK_OPTIONS; Set views = path.getFileSystem().supportedFileAttributeViews(); String names; - if ( views.contains( "unix" ) ) - { - names = "unix:*"; - } - else if ( views.contains( "posix" ) ) - { + if (views.contains("unix")) { + names = + "unix:gid,uid,isSymbolicLink,isRegularFile,isDirectory,isOther,mode,permissions,size,lastModifiedTime"; + } else if (views.contains("posix")) { names = "posix:*"; - } - else - { + } else { names = "basic:*"; } - Map attrs = Files.readAttributes( path, names, LinkOption.NOFOLLOW_LINKS); - if ( !attrs.containsKey( "group" ) && !attrs.containsKey( "owner" ) && views.contains( "owner" ) ) - { - Map ownerAttrs = Files.readAttributes( path, "owner:*", LinkOption.NOFOLLOW_LINKS); - Map newAttrs = new HashMap<>( attrs ); - newAttrs.putAll( ownerAttrs ); - attrs = newAttrs; + Map attrs = Files.readAttributes(path, names, options); + this.groupId = (Integer) attrs.get("gid"); + if (attrs.containsKey("group")) { + this.groupName = ((Principal) attrs.get("group")).getName(); + } else if (this.groupId != null) { + Map cache = getGroupCache(path.getFileSystem()); + String name = cache.get(this.groupId); + if (name == null) { + name = getPrincipalName(path, "unix:group"); + cache.put(this.groupId, name); + } + this.groupName = name; + } else { + this.groupName = null; } - this.groupId = (Integer) attrs.get( "gid" ); - this.groupName = attrs.containsKey( "group" ) ? ((Principal) attrs.get( "group" ) ).getName() : null; - this.userId = (Integer) attrs.get( "uid" ); - this.userName = attrs.containsKey( "owner" ) ? ((Principal) attrs.get( "owner" ) ).getName() : null; - this.symbolicLink = (Boolean) attrs.get( "isSymbolicLink" ); - this.regularFile = (Boolean) attrs.get( "isRegularFile" ); - this.directory = (Boolean) attrs.get( "isDirectory" ); - this.other = (Boolean) attrs.get( "isOther" ); - this.octalMode = attrs.containsKey( "mode" ) ? (Integer) attrs.get( "mode" ) & 0xfff : PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE; - this.permissions = attrs.containsKey( "permissions" ) ? (Set) attrs.get( "permissions" ) : Collections.emptySet(); - this.size = (Long) attrs.get( "size" ); - this.lastModifiedTime = (FileTime) attrs.get( "lastModifiedTime" ); - } - - public FileAttributes( @Nullable Integer userId, String userName, @Nullable Integer groupId, @Nullable String groupName, - int octalMode, boolean symbolicLink, boolean regularFile, boolean directory, boolean other, - Set permissions, long size, FileTime lastModifiedTime) { + this.userId = (Integer) attrs.get("uid"); + if (attrs.containsKey("owner")) { + this.userName = ((Principal) attrs.get("owner")).getName(); + } else if (this.userId != null) { + Map cache = getUserCache(path.getFileSystem()); + String name = cache.get(this.userId); + if (name == null) { + name = getPrincipalName(path, "unix:owner"); + cache.put(this.userId, name); + } + this.userName = name; + } else if (views.contains("owner")) { + this.userName = getPrincipalName(path, "owner:owner"); + } else { + this.userName = null; + } + this.symbolicLink = (Boolean) attrs.get("isSymbolicLink"); + this.regularFile = (Boolean) attrs.get("isRegularFile"); + this.directory = (Boolean) attrs.get("isDirectory"); + this.other = (Boolean) attrs.get("isOther"); + this.octalMode = attrs.containsKey("mode") + ? (Integer) attrs.get("mode") & 0xfff + : PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE; + //noinspection unchecked + this.permissions = attrs.containsKey("permissions") + ? (Set) attrs.get("permissions") + : Collections.emptySet(); + this.size = (Long) attrs.get("size"); + this.lastModifiedTime = (FileTime) attrs.get("lastModifiedTime"); + } + + private static String getPrincipalName(Path path, String attribute) throws IOException { + Object owner = Files.getAttribute(path, attribute, LinkOption.NOFOLLOW_LINKS); + return ((Principal) owner).getName(); + } + + public FileAttributes( + @Nullable Integer userId, + String userName, + @Nullable Integer groupId, + @Nullable String groupName, + int octalMode, + boolean symbolicLink, + boolean regularFile, + boolean directory, + boolean other, + Set permissions, + long size, + FileTime lastModifiedTime) { this.userId = userId; this.userName = userName; this.groupId = groupId; @@ -126,214 +192,174 @@ public FileAttributes( @Nullable Integer userId, String userName, @Nullable Inte this.lastModifiedTime = lastModifiedTime; } - public static @Nonnull - PlexusIoResourceAttributes uncached( @Nonnull File file ) - throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + public static @Nonnull PlexusIoResourceAttributes uncached(@Nonnull File file) throws IOException { + return new FileAttributes(file); } @Nullable - public Integer getGroupId() - { + public Integer getGroupId() { return groupId; } - public boolean hasGroupId() - { + public boolean hasGroupId() { return false; } - public boolean hasUserId() - { + public boolean hasUserId() { return false; } @Nullable - public String getGroupName() - { + public String getGroupName() { return groupName; } - public Integer getUserId() - { + public Integer getUserId() { return userId; } - public String getUserName() - { + public String getUserName() { return userName; } - public boolean isGroupExecutable() - { - return containsPermission( PosixFilePermission.GROUP_EXECUTE ); + public boolean isGroupExecutable() { + return containsPermission(PosixFilePermission.GROUP_EXECUTE); } - private boolean containsPermission( PosixFilePermission groupExecute ) - { - return permissions.contains( groupExecute ); + private boolean containsPermission(PosixFilePermission groupExecute) { + return permissions.contains(groupExecute); } - public boolean isGroupReadable() - { - return containsPermission( PosixFilePermission.GROUP_READ ); + public boolean isGroupReadable() { + return containsPermission(PosixFilePermission.GROUP_READ); } - public boolean isGroupWritable() - { - return containsPermission( PosixFilePermission.GROUP_WRITE ); + public boolean isGroupWritable() { + return containsPermission(PosixFilePermission.GROUP_WRITE); } - public boolean isOwnerExecutable() - { - return containsPermission( PosixFilePermission.OWNER_EXECUTE ); + public boolean isOwnerExecutable() { + return containsPermission(PosixFilePermission.OWNER_EXECUTE); } - public boolean isOwnerReadable() - { - return containsPermission( PosixFilePermission.OWNER_READ ); + public boolean isOwnerReadable() { + return containsPermission(PosixFilePermission.OWNER_READ); } - public boolean isOwnerWritable() - { - return containsPermission( PosixFilePermission.OWNER_WRITE ); + public boolean isOwnerWritable() { + return containsPermission(PosixFilePermission.OWNER_WRITE); } - public boolean isWorldExecutable() - { - return containsPermission( PosixFilePermission.OTHERS_EXECUTE ); - + public boolean isWorldExecutable() { + return containsPermission(PosixFilePermission.OTHERS_EXECUTE); } - public boolean isWorldReadable() - { - return containsPermission( PosixFilePermission.OTHERS_READ ); + public boolean isWorldReadable() { + return containsPermission(PosixFilePermission.OTHERS_READ); } - public boolean isWorldWritable() - { - return containsPermission( PosixFilePermission.OTHERS_WRITE ); + public boolean isWorldWritable() { + return containsPermission(PosixFilePermission.OTHERS_WRITE); } - public String toString() - { + public String toString() { StringBuilder sb = new StringBuilder(); - sb.append( System.lineSeparator() ); - sb.append( "File Attributes:" ); - sb.append( System.lineSeparator() ); - sb.append( "------------------------------" ); - sb.append( System.lineSeparator() ); - sb.append( "user: " ); - sb.append( userName == null ? "" : userName ); - sb.append( System.lineSeparator() ); - sb.append( "group: " ); - sb.append( groupName == null ? "" : groupName ); - sb.append( System.lineSeparator() ); - sb.append( "uid: " ); - sb.append( hasUserId() ? Integer.toString( userId ) : "" ); - sb.append( System.lineSeparator() ); - sb.append( "gid: " ); - sb.append( hasGroupId() ? Integer.toString( groupId ) : "" ); + sb.append(System.lineSeparator()); + sb.append("File Attributes:"); + sb.append(System.lineSeparator()); + sb.append("------------------------------"); + sb.append(System.lineSeparator()); + sb.append("user: "); + sb.append(userName == null ? "" : userName); + sb.append(System.lineSeparator()); + sb.append("group: "); + sb.append(groupName == null ? "" : groupName); + sb.append(System.lineSeparator()); + sb.append("uid: "); + sb.append(hasUserId() ? Integer.toString(userId) : ""); + sb.append(System.lineSeparator()); + sb.append("gid: "); + sb.append(hasGroupId() ? Integer.toString(groupId) : ""); return sb.toString(); } - public int getOctalMode() - { + public int getOctalMode() { return octalMode; } - public int calculatePosixOctalMode() - { + public int calculatePosixOctalMode() { int result = 0; - if ( isOwnerReadable() ) - { + if (isOwnerReadable()) { result |= AttributeConstants.OCTAL_OWNER_READ; } - if ( isOwnerWritable() ) - { + if (isOwnerWritable()) { result |= AttributeConstants.OCTAL_OWNER_WRITE; } - if ( isOwnerExecutable() ) - { + if (isOwnerExecutable()) { result |= AttributeConstants.OCTAL_OWNER_EXECUTE; } - if ( isGroupReadable() ) - { + if (isGroupReadable()) { result |= AttributeConstants.OCTAL_GROUP_READ; } - if ( isGroupWritable() ) - { + if (isGroupWritable()) { result |= AttributeConstants.OCTAL_GROUP_WRITE; } - if ( isGroupExecutable() ) - { + if (isGroupExecutable()) { result |= AttributeConstants.OCTAL_GROUP_EXECUTE; } - if ( isWorldReadable() ) - { + if (isWorldReadable()) { result |= AttributeConstants.OCTAL_WORLD_READ; } - if ( isWorldWritable() ) - { + if (isWorldWritable()) { result |= AttributeConstants.OCTAL_WORLD_WRITE; } - if ( isWorldExecutable() ) - { + if (isWorldExecutable()) { result |= AttributeConstants.OCTAL_WORLD_EXECUTE; } return result; } - public String getOctalModeString() - { - return Integer.toString( getOctalMode(), 8 ); + public String getOctalModeString() { + return Integer.toString(getOctalMode(), 8); } - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return symbolicLink; } - public boolean isRegularFile() - { + public boolean isRegularFile() { return regularFile; } - public boolean isDirectory() - { + public boolean isDirectory() { return directory; } - public boolean isOther() - { + public boolean isOther() { return other; } - public long getSize() - { + public long getSize() { return size; } - public FileTime getLastModifiedTime() - { + public FileTime getLastModifiedTime() { return lastModifiedTime; } - protected Set getPermissions() - { + protected Set getPermissions() { return permissions; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils.java b/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils.java index 3e2c44b8..1d707385 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtils.java @@ -16,196 +16,145 @@ * limitations under the License. */ -import org.codehaus.plexus.util.FileUtils; - import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -@SuppressWarnings( { "NullableProblems" } ) -public final class PlexusIoResourceAttributeUtils -{ +import org.codehaus.plexus.util.FileUtils; + +@SuppressWarnings({"NullableProblems"}) +public final class PlexusIoResourceAttributeUtils { - private PlexusIoResourceAttributeUtils() - { - } + private PlexusIoResourceAttributeUtils() {} - public static PlexusIoResourceAttributes mergeAttributes( PlexusIoResourceAttributes override, - PlexusIoResourceAttributes base, - PlexusIoResourceAttributes def ) - { - if ( override == null ) - { + public static PlexusIoResourceAttributes mergeAttributes( + PlexusIoResourceAttributes override, PlexusIoResourceAttributes base, PlexusIoResourceAttributes def) { + if (override == null) { return base; } - if ( base == null ) - { + if (base == null) { return new SimpleResourceAttributes( override.getUserId() != null && override.getUserId() != -1 ? override.getUserId() - : def != null && def.getUserId() != null && def.getUserId() != -1 - ? def.getUserId() - : null, - override.getUserName() != null - ? override.getUserName() - : def != null - ? def.getUserName() - : null, + : def != null && def.getUserId() != null && def.getUserId() != -1 ? def.getUserId() : null, + override.getUserName() != null ? override.getUserName() : def != null ? def.getUserName() : null, override.getGroupId() != null && override.getGroupId() != -1 ? override.getGroupId() : def != null && def.getGroupId() != null && def.getGroupId() != -1 - ? def.getGroupId() - : null, - override.getGroupName() != null - ? override.getGroupName() - : def != null - ? def.getGroupName() - : null, - override.getOctalMode() ); - } - else - { + ? def.getGroupId() + : null, + override.getGroupName() != null ? override.getGroupName() : def != null ? def.getGroupName() : null, + override.getOctalMode()); + } else { Integer uid = override.getUserId() != null && override.getUserId() != -1 ? override.getUserId() : base.getUserId() != null && base.getUserId() != -1 - ? base.getUserId() - : def.getUserId() != null && def.getUserId() != -1 - ? def.getUserId() - : null; + ? base.getUserId() + : def.getUserId() != null && def.getUserId() != -1 ? def.getUserId() : null; String uname = override.getUserName() != null ? override.getUserName() - : base.getUserName() != null - ? base.getUserName() - : def.getUserName(); + : base.getUserName() != null ? base.getUserName() : def.getUserName(); Integer gid = override.getGroupId() != null && override.getGroupId() != -1 ? override.getGroupId() : base.getGroupId() != null && base.getGroupId() != -1 - ? base.getGroupId() - : def.getGroupId() != null && def.getGroupId() != -1 - ? def.getGroupId() - : null; + ? base.getGroupId() + : def.getGroupId() != null && def.getGroupId() != -1 ? def.getGroupId() : null; String gname = override.getGroupName() != null ? override.getGroupName() - : base.getGroupName() != null - ? base.getGroupName() - : def.getGroupName(); + : base.getGroupName() != null ? base.getGroupName() : def.getGroupName(); int mode = override.getOctalMode() > 0 ? override.getOctalMode() - : base.getOctalMode() >= 0 - ? base.getOctalMode() - : def.getOctalMode(); - if ( base instanceof FileAttributes ) - { - return new UserGroupModeFileAttributes( uid, uname, gid, gname, mode, (FileAttributes) base ); - } - else - { - return new SimpleResourceAttributes( uid, uname, gid, gname, mode, base.isSymbolicLink() ); + : base.getOctalMode() >= 0 ? base.getOctalMode() : def.getOctalMode(); + if (base instanceof FileAttributes) { + return new UserGroupModeFileAttributes(uid, uname, gid, gname, mode, (FileAttributes) base); + } else { + return new SimpleResourceAttributes(uid, uname, gid, gname, mode, base.isSymbolicLink()); } } } - public static boolean isGroupExecutableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_GROUP_EXECUTE ); + public static boolean isGroupExecutableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_GROUP_EXECUTE); } - public static boolean isGroupReadableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_GROUP_READ ); + public static boolean isGroupReadableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_GROUP_READ); } - public static boolean isGroupWritableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_GROUP_WRITE ); + public static boolean isGroupWritableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_GROUP_WRITE); } - public static boolean isOwnerExecutableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_OWNER_EXECUTE ); + public static boolean isOwnerExecutableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_OWNER_EXECUTE); } - public static boolean isOwnerReadableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_OWNER_READ ); + public static boolean isOwnerReadableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_OWNER_READ); } - public static boolean isOwnerWritableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_OWNER_WRITE ); + public static boolean isOwnerWritableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_OWNER_WRITE); } - public static boolean isWorldExecutableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_WORLD_EXECUTE ); + public static boolean isWorldExecutableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_WORLD_EXECUTE); } - public static boolean isWorldReadableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_WORLD_READ ); + public static boolean isWorldReadableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_WORLD_READ); } - public static boolean isWorldWritableInOctal( int mode ) - { - return isOctalModeEnabled( mode, AttributeConstants.OCTAL_WORLD_WRITE ); + public static boolean isWorldWritableInOctal(int mode) { + return isOctalModeEnabled(mode, AttributeConstants.OCTAL_WORLD_WRITE); } - public static boolean isOctalModeEnabled( int mode, int targetMode ) - { - return ( mode & targetMode ) != 0; + public static boolean isOctalModeEnabled(int mode, int targetMode) { + return (mode & targetMode) != 0; } - @SuppressWarnings( { "UnusedDeclaration" } ) - public static PlexusIoResourceAttributes getFileAttributes( File file ) - throws IOException - { - Map byPath = getFileAttributesByPath( file, false ); - final PlexusIoResourceAttributes o = byPath.get( file.getAbsolutePath() ); - if ( o == null ) - { + public static PlexusIoResourceAttributes getFileAttributes(File file) throws IOException { + return getFileAttributes(file, false); + } + + public static PlexusIoResourceAttributes getFileAttributes(File file, boolean followLinks) throws IOException { + Map byPath = getFileAttributesByPath(file, false, followLinks); + final PlexusIoResourceAttributes o = byPath.get(file.getAbsolutePath()); + if (o == null) { // We're on a crappy old java version (5) or the OS from hell. Just "fail". return SimpleResourceAttributes.lastResortDummyAttributesForBrokenOS(); - } return o; } - public static Map getFileAttributesByPath( File dir ) - throws IOException - { - return getFileAttributesByPath( dir, true ); + public static Map getFileAttributesByPath(File dir) throws IOException { + return getFileAttributesByPath(dir, true); } - public static @Nonnull - Map getFileAttributesByPath( @Nonnull File dir, - boolean recursive ) - throws IOException - { - Map userCache = new HashMap<>(); - Map groupCache = new HashMap<>(); + public static @Nonnull Map getFileAttributesByPath( + @Nonnull File dir, boolean recursive) throws IOException { + return getFileAttributesByPath(dir, recursive, false); + } + + public static @Nonnull Map getFileAttributesByPath( + @Nonnull File dir, boolean recursive, boolean followLinks) throws IOException { final List fileAndDirectoryNames; - if ( recursive && dir.isDirectory() ) - { - fileAndDirectoryNames = FileUtils.getFileAndDirectoryNames( dir, null, null, true, true, true, true ); - } - else - { - fileAndDirectoryNames = Collections.singletonList( dir.getAbsolutePath() ); + if (recursive && dir.isDirectory()) { + fileAndDirectoryNames = FileUtils.getFileAndDirectoryNames(dir, null, null, true, true, true, true); + } else { + fileAndDirectoryNames = Collections.singletonList(dir.getAbsolutePath()); } final Map attributesByPath = new LinkedHashMap<>(); - for ( String fileAndDirectoryName : fileAndDirectoryNames ) - { - attributesByPath.put( fileAndDirectoryName, - new FileAttributes( new File( fileAndDirectoryName ), userCache, groupCache ) ); + for (String fileAndDirectoryName : fileAndDirectoryNames) { + attributesByPath.put(fileAndDirectoryName, new FileAttributes(new File(fileAndDirectoryName), followLinks)); } return attributesByPath; } - } diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes.java b/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes.java index 21b29db9..2aa0ef6a 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributes.java @@ -16,11 +16,9 @@ * limitations under the License. */ -import javax.annotation.Nonnull; import javax.annotation.Nullable; -public interface PlexusIoResourceAttributes -{ +public interface PlexusIoResourceAttributes { int UNKNOWN_OCTAL_MODE = -1; boolean isOwnerReadable(); @@ -46,7 +44,7 @@ public interface PlexusIoResourceAttributes * @return The unix user id, may be null ("not set"), even on unix */ Integer getUserId(); - + /** * Gets the unix group id. * @return The unix group id, may be null ("not set"), even on unix @@ -74,13 +72,10 @@ public interface PlexusIoResourceAttributes */ int getOctalMode(); - @Nonnull - //String getOctalModeString(); - /** * Indicates if this is a symbolic link element. * For file-based resource attributes this value may be always "false" for versions prior to java7. * @return True if the file is a symlink or false if not. */ boolean isSymbolicLink(); -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributes.java b/src/main/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributes.java index a92d7411..3fdf7320 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributes.java @@ -21,9 +21,7 @@ /* * A very simple pojo based PlexusIoResourceAttributes without any kind of backing */ -public class SimpleResourceAttributes - implements PlexusIoResourceAttributes -{ +public class SimpleResourceAttributes implements PlexusIoResourceAttributes { private Integer gid; @@ -37,8 +35,7 @@ public class SimpleResourceAttributes private boolean isSymbolicLink; - public SimpleResourceAttributes( Integer uid, String userName, Integer gid, String groupName, int mode ) - { + public SimpleResourceAttributes(Integer uid, String userName, Integer gid, String groupName, int mode) { this.uid = uid; this.userName = userName; this.gid = gid; @@ -46,8 +43,8 @@ public SimpleResourceAttributes( Integer uid, String userName, Integer gid, Stri this.mode = mode; } - public SimpleResourceAttributes( Integer uid, String userName, Integer gid, String groupName, int mode, boolean isSymbolicLink ) - { + public SimpleResourceAttributes( + Integer uid, String userName, Integer gid, String groupName, int mode, boolean isSymbolicLink) { this.uid = uid; this.userName = userName; this.gid = gid; @@ -56,146 +53,119 @@ public SimpleResourceAttributes( Integer uid, String userName, Integer gid, Stri this.isSymbolicLink = isSymbolicLink; } - public static PlexusIoResourceAttributes lastResortDummyAttributesForBrokenOS() - { + public static PlexusIoResourceAttributes lastResortDummyAttributesForBrokenOS() { return new SimpleResourceAttributes(); } - SimpleResourceAttributes() - { - } + SimpleResourceAttributes() {} - public int getOctalMode() - { + public int getOctalMode() { return mode; } - @Nullable public Integer getGroupId() - { + @Nullable + public Integer getGroupId() { return gid; } - @Nullable public String getGroupName() - { + @Nullable + public String getGroupName() { return groupName; } - - public Integer getUserId() - { + public Integer getUserId() { return uid; } - public String getUserName() - { + public String getUserName() { return userName; } - public boolean isGroupExecutable() - { - return PlexusIoResourceAttributeUtils.isGroupExecutableInOctal( mode ); + public boolean isGroupExecutable() { + return PlexusIoResourceAttributeUtils.isGroupExecutableInOctal(mode); } - public boolean isGroupReadable() - { - return PlexusIoResourceAttributeUtils.isGroupReadableInOctal( mode ); + public boolean isGroupReadable() { + return PlexusIoResourceAttributeUtils.isGroupReadableInOctal(mode); } - public boolean isGroupWritable() - { - return PlexusIoResourceAttributeUtils.isGroupWritableInOctal( mode ); + public boolean isGroupWritable() { + return PlexusIoResourceAttributeUtils.isGroupWritableInOctal(mode); } - public boolean isOwnerExecutable() - { - return PlexusIoResourceAttributeUtils.isOwnerExecutableInOctal( mode ); + public boolean isOwnerExecutable() { + return PlexusIoResourceAttributeUtils.isOwnerExecutableInOctal(mode); } - public boolean isOwnerReadable() - { - return PlexusIoResourceAttributeUtils.isOwnerReadableInOctal( mode ); + public boolean isOwnerReadable() { + return PlexusIoResourceAttributeUtils.isOwnerReadableInOctal(mode); } - public boolean isOwnerWritable() - { - return PlexusIoResourceAttributeUtils.isOwnerWritableInOctal( mode ); + public boolean isOwnerWritable() { + return PlexusIoResourceAttributeUtils.isOwnerWritableInOctal(mode); } - public boolean isWorldExecutable() - { - return PlexusIoResourceAttributeUtils.isWorldExecutableInOctal( mode ); + public boolean isWorldExecutable() { + return PlexusIoResourceAttributeUtils.isWorldExecutableInOctal(mode); } - public boolean isWorldReadable() - { - return PlexusIoResourceAttributeUtils.isWorldReadableInOctal( mode ); + public boolean isWorldReadable() { + return PlexusIoResourceAttributeUtils.isWorldReadableInOctal(mode); } - public boolean isWorldWritable() - { - return PlexusIoResourceAttributeUtils.isWorldWritableInOctal( mode ); + public boolean isWorldWritable() { + return PlexusIoResourceAttributeUtils.isWorldWritableInOctal(mode); } - public String getOctalModeString() - { - return Integer.toString( mode, 8 ); + public String getOctalModeString() { + return Integer.toString(mode, 8); } - public PlexusIoResourceAttributes setOctalMode( int mode ) - { + public PlexusIoResourceAttributes setOctalMode(int mode) { this.mode = mode; return this; } - public PlexusIoResourceAttributes setGroupId( Integer gid ) - { + public PlexusIoResourceAttributes setGroupId(Integer gid) { this.gid = gid; return this; } - public PlexusIoResourceAttributes setGroupName( String name ) - { + public PlexusIoResourceAttributes setGroupName(String name) { this.groupName = name; return this; } - public PlexusIoResourceAttributes setUserId( Integer uid ) - { + public PlexusIoResourceAttributes setUserId(Integer uid) { this.uid = uid; return this; } - public PlexusIoResourceAttributes setUserName( String name ) - { + public PlexusIoResourceAttributes setUserName(String name) { this.userName = name; return this; } - public PlexusIoResourceAttributes setOctalModeString( String mode ) - { - setOctalMode( Integer.parseInt( mode, 8 ) ); + public PlexusIoResourceAttributes setOctalModeString(String mode) { + setOctalMode(Integer.parseInt(mode, 8)); return this; } - public String toString() - { + public String toString() { return String.format( - "%nResource Attributes:%n------------------------------%nuser: %s%ngroup: %s%nuid: %d%ngid: %d%nmode: %06o", - userName == null ? "" : userName, - groupName == null ? "" : groupName, - uid != null ? uid : 0, - gid != null ? gid : 0, - mode ); + "%nResource Attributes:%n------------------------------%nuser: %s%ngroup: %s%nuid: %d%ngid: %d%nmode: %06o", + userName == null ? "" : userName, + groupName == null ? "" : groupName, + uid != null ? uid : 0, + gid != null ? gid : 0, + mode); } - - public void setSymbolicLink( boolean isSymbolicLink ) - { + public void setSymbolicLink(boolean isSymbolicLink) { this.isSymbolicLink = isSymbolicLink; } - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return isSymbolicLink; } } diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/SymlinkUtils.java b/src/main/java/org/codehaus/plexus/components/io/attributes/SymlinkUtils.java index beddad07..6c6ea684 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/SymlinkUtils.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/SymlinkUtils.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.components.io.attributes; import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -25,8 +26,7 @@ /** * @author Kristian Rosenvold */ -public class SymlinkUtils -{ +public class SymlinkUtils { /** * Reads the target of the symbolic link * @@ -34,25 +34,15 @@ public class SymlinkUtils * @return A file that is the target of the symlink * @throws java.io.IOException */ - - public static @Nonnull - File readSymbolicLink( @Nonnull File symlink ) - throws IOException - { - final java.nio.file.Path path = java.nio.file.Files.readSymbolicLink( symlink.toPath() ); - return path.toFile(); + public static @Nonnull File readSymbolicLink(@Nonnull File symlink) throws IOException { + return Files.readSymbolicLink(symlink.toPath()).toFile(); } - public static @Nonnull - File createSymbolicLink( @Nonnull File symlink, File target ) - throws IOException - { + public static @Nonnull File createSymbolicLink(@Nonnull File symlink, File target) throws IOException { Path link = symlink.toPath(); - if ( !Files.exists( link, LinkOption.NOFOLLOW_LINKS ) ) - { - link = java.nio.file.Files.createSymbolicLink( link, target.toPath() ); + if (!Files.exists(link, LinkOption.NOFOLLOW_LINKS)) { + link = Files.createSymbolicLink(link, target.toPath()); } return link.toFile(); - } } diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/UserGroupModeFileAttributes.java b/src/main/java/org/codehaus/plexus/components/io/attributes/UserGroupModeFileAttributes.java index 37984b17..df21c1a1 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/UserGroupModeFileAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/UserGroupModeFileAttributes.java @@ -16,32 +16,35 @@ * limitations under the License. */ -import javax.annotation.Nullable; - /* * A very simple pojo based PlexusIoResourceAttributes without any kind of backing */ -public class UserGroupModeFileAttributes - extends FileAttributes -{ +public class UserGroupModeFileAttributes extends FileAttributes { - public UserGroupModeFileAttributes( Integer uid, String userName, Integer gid, String groupName, int mode, FileAttributes base ) - { - super( uid, userName, gid, groupName, mode, - base.isSymbolicLink(), base.isRegularFile(), base.isDirectory(), base.isOther(), - base.getPermissions(), base.getSize(), base.getLastModifiedTime() ); + public UserGroupModeFileAttributes( + Integer uid, String userName, Integer gid, String groupName, int mode, FileAttributes base) { + super( + uid, + userName, + gid, + groupName, + mode, + base.isSymbolicLink(), + base.isRegularFile(), + base.isDirectory(), + base.isOther(), + base.getPermissions(), + base.getSize(), + base.getLastModifiedTime()); } - public String toString() - { + public String toString() { return String.format( - "%nResource Attributes:%n------------------------------%nuser: %s%ngroup: %s%nuid: %d%ngid: %d%nmode: %06o", - getUserName() == null ? "" : getUserName(), - getGroupName() == null ? "" : getGroupName(), - getUserId() != null ? getUserId() : 0, - getGroupId() != null ? getGroupId() : 0, - getOctalMode() ); + "%nResource Attributes:%n------------------------------%nuser: %s%ngroup: %s%nuid: %d%ngid: %d%nmode: %06o", + getUserName() == null ? "" : getUserName(), + getGroupName() == null ? "" : getGroupName(), + getUserId() != null ? getUserId() : 0, + getGroupId() != null ? getGroupId() : 0, + getOctalMode()); } - - } diff --git a/src/main/java/org/codehaus/plexus/components/io/attributes/proxy/PlexusIoProxyResourceAttributes.java b/src/main/java/org/codehaus/plexus/components/io/attributes/proxy/PlexusIoProxyResourceAttributes.java index e579c66e..15194fe8 100644 --- a/src/main/java/org/codehaus/plexus/components/io/attributes/proxy/PlexusIoProxyResourceAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/attributes/proxy/PlexusIoProxyResourceAttributes.java @@ -1,98 +1,76 @@ package org.codehaus.plexus.components.io.attributes.proxy; -import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; - import javax.annotation.Nullable; -public class PlexusIoProxyResourceAttributes - implements PlexusIoResourceAttributes +import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; +public class PlexusIoProxyResourceAttributes implements PlexusIoResourceAttributes { -{ - PlexusIoResourceAttributes target; + final PlexusIoResourceAttributes target; - public PlexusIoProxyResourceAttributes( PlexusIoResourceAttributes thisAttr ) - { + public PlexusIoProxyResourceAttributes(PlexusIoResourceAttributes thisAttr) { this.target = thisAttr; } - public boolean isOwnerReadable() - { + public boolean isOwnerReadable() { return target.isOwnerReadable(); } - public int getOctalMode() - { + public int getOctalMode() { return target.getOctalMode(); } - public String getUserName() - { + public String getUserName() { return target.getUserName(); } - public boolean isGroupReadable() - { + public boolean isGroupReadable() { return target.isGroupReadable(); } - public boolean isWorldExecutable() - { + public boolean isWorldExecutable() { return target.isWorldExecutable(); } - @Nullable public Integer getGroupId() - { + @Nullable + public Integer getGroupId() { return target.getGroupId(); } - public boolean isGroupWritable() - { + public boolean isGroupWritable() { return target.isGroupWritable(); } - public Integer getUserId() - { + public Integer getUserId() { return target.getUserId(); } -/* public String getOctalModeString() - { - return target.getOctalModeString(); - } -*/ - public boolean isOwnerWritable() - { + public boolean isOwnerWritable() { return target.isOwnerWritable(); } - public boolean isOwnerExecutable() - { + public boolean isOwnerExecutable() { return target.isOwnerExecutable(); } - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return target.isSymbolicLink(); } - public boolean isGroupExecutable() - { + public boolean isGroupExecutable() { return target.isGroupExecutable(); } - public boolean isWorldWritable() - { + public boolean isWorldWritable() { return target.isWorldWritable(); } - @Nullable public String getGroupName() - { + @Nullable + public String getGroupName() { return target.getGroupName(); } - public boolean isWorldReadable() - { + public boolean isWorldReadable() { return target.isWorldReadable(); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/AbstractFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/AbstractFileMapper.java index 565ae9ea..141244fd 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/AbstractFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/AbstractFileMapper.java @@ -16,7 +16,6 @@ * limitations under the License. */ - import javax.annotation.Nonnull; /** @@ -25,16 +24,13 @@ * this might allow to extend the FileMapper interface later on * without loosing upwards compatibility. */ -public abstract class AbstractFileMapper implements FileMapper -{ +public abstract class AbstractFileMapper implements FileMapper { /** * Checks the input and returns it without modifications. */ - public @Nonnull String getMappedFileName( @Nonnull String pName ) - { - if ( pName == null || pName.length() == 0 ) - { - throw new IllegalArgumentException( "The source name must not be null." ); + public @Nonnull String getMappedFileName(@Nonnull String pName) { + if (pName == null || pName.isEmpty()) { + throw new IllegalArgumentException("The source name must not be null."); } return pName; } diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/DefaultFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/DefaultFileMapper.java new file mode 100644 index 00000000..57ead3c8 --- /dev/null +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/DefaultFileMapper.java @@ -0,0 +1,25 @@ +package org.codehaus.plexus.components.io.filemappers; + +/* + * Copyright 2007 The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import javax.inject.Named; + +/** + * Alias for {@link IdentityMapper} + */ +@Named +public class DefaultFileMapper extends IdentityMapper {} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/FileExtensionMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/FileExtensionMapper.java index ca4709ca..53023386 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/FileExtensionMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/FileExtensionMapper.java @@ -17,12 +17,13 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * An implementation of {@link FileMapper}, which changes the files extension. */ -public class FileExtensionMapper extends AbstractFileMapper -{ +@Named(FileExtensionMapper.ROLE_HINT) +public class FileExtensionMapper extends AbstractFileMapper { /** * The file extension mappers role-hint: "fileExtension". */ @@ -32,27 +33,21 @@ public class FileExtensionMapper extends AbstractFileMapper /** * Sets the target files extension. - * + * * @param pTargetExtension the target extensions * @throws IllegalArgumentException * The target extension is null or empty. */ - public void setTargetExtension( String pTargetExtension ) - { - if ( pTargetExtension == null ) - { - throw new IllegalArgumentException( "The target extension is null." ); + public void setTargetExtension(String pTargetExtension) { + if (pTargetExtension == null) { + throw new IllegalArgumentException("The target extension is null."); } - if ( pTargetExtension.length() == 0 ) - { - throw new IllegalArgumentException( "The target extension is empty." ); + if (pTargetExtension.isEmpty()) { + throw new IllegalArgumentException("The target extension is empty."); } - if ( pTargetExtension.charAt( 0 ) == '.' ) - { + if (pTargetExtension.charAt(0) == '.') { targetExtension = pTargetExtension; - } - else - { + } else { targetExtension = '.' + pTargetExtension; } } @@ -61,28 +56,23 @@ public void setTargetExtension( String pTargetExtension ) * Returns the target files extension. * @return The target extension */ - public String getTargetExtension() - { + public String getTargetExtension() { return targetExtension; } - @Nonnull public String getMappedFileName( @Nonnull String pName ) - { + @Nonnull + public String getMappedFileName(@Nonnull String pName) { final String ext = getTargetExtension(); - if ( ext == null ) - { - throw new IllegalStateException( "The target extension has not been set." ); + if (ext == null) { + throw new IllegalStateException("The target extension has not been set."); } - final String name = super.getMappedFileName( pName ); // Check arguments - final int dirSep = Math.max( pName.lastIndexOf( '/' ), pName.lastIndexOf( '\\' ) ); - final int offset = pName.lastIndexOf( '.' ); - if ( offset <= dirSep ) - { + final String name = super.getMappedFileName(pName); // Check arguments + final int dirSep = Math.max(pName.lastIndexOf('/'), pName.lastIndexOf('\\')); + final int offset = pName.lastIndexOf('.'); + if (offset <= dirSep) { return name + ext; - } - else - { - return name.substring( 0, offset ) + ext; + } else { + return name.substring(0, offset) + ext; } } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/FileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/FileMapper.java index a14b808c..77f414b1 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/FileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/FileMapper.java @@ -19,26 +19,15 @@ /** * Interface of a component, which may be used to map file names. */ -public interface FileMapper -{ - /** - * Role used to register component implementations with the container. - */ - public static final String ROLE = FileMapper.class.getName(); - - /** - * The default role-hint: "default". - */ - public static final String DEFAULT_ROLE_HINT = "default"; - +public interface FileMapper { /** * Maps the given source name to a target name. - * + * * @param pName * The source name. * @return The target name. * @throws IllegalArgumentException * The source name is null or empty. */ - public String getMappedFileName( String pName ); -} \ No newline at end of file + String getMappedFileName(String pName); +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/FlattenFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/FlattenFileMapper.java index 249c9fc4..517b3a11 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/FlattenFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/FlattenFileMapper.java @@ -17,30 +17,29 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * Implementation of a flattening file mapper: Removes all directory parts. */ -public class FlattenFileMapper extends AbstractFileMapper -{ +@Named(FlattenFileMapper.ROLE_HINT) +public class FlattenFileMapper extends AbstractFileMapper { /** * The flatten file mappers role-hint: "flatten". */ public static final String ROLE_HINT = "flatten"; - @Nonnull public String getMappedFileName( @Nonnull String pName ) - { - String name = super.getMappedFileName( pName ); // Check for null, etc. - int offset = pName.lastIndexOf( '/' ); - if ( offset >= 0 ) - { - name = name.substring( offset + 1 ); + @Nonnull + public String getMappedFileName(@Nonnull String pName) { + String name = super.getMappedFileName(pName); // Check for null, etc. + int offset = pName.lastIndexOf('/'); + if (offset >= 0) { + name = name.substring(offset + 1); } - offset = pName.lastIndexOf( '\\' ); - if ( offset >= 0 ) - { - name = name.substring( offset + 1 ); + offset = pName.lastIndexOf('\\'); + if (offset >= 0) { + name = name.substring(offset + 1); } return name; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/IdentityMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/IdentityMapper.java index f4533d69..789f7f3e 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/IdentityMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/IdentityMapper.java @@ -17,23 +17,23 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * Default implementation of {@link FileMapper}, which performs the identity mapping: All names are left unchanged. */ -public class IdentityMapper extends AbstractFileMapper -{ +@Named(IdentityMapper.ROLE_HINT) +public class IdentityMapper extends AbstractFileMapper { /** * The identity mappers role-hint: "identity". */ public static final String ROLE_HINT = "identity"; - @Nonnull public String getMappedFileName( @Nonnull String pName ) - { - if ( pName == null || pName.length() == 0 ) - { - throw new IllegalArgumentException( "The source name must not be null." ); + @Nonnull + public String getMappedFileName(@Nonnull String pName) { + if (pName == null || pName.isEmpty()) { + throw new IllegalArgumentException("The source name must not be null."); } return pName; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/MergeFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/MergeFileMapper.java index a4227490..796a428b 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/MergeFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/MergeFileMapper.java @@ -17,12 +17,13 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * A file mapper, which maps to a constant target name. */ -public class MergeFileMapper extends AbstractFileMapper -{ +@Named(MergeFileMapper.ROLE_HINT) +public class MergeFileMapper extends AbstractFileMapper { /** * The merge mappers role-hint: "merge". */ @@ -32,42 +33,37 @@ public class MergeFileMapper extends AbstractFileMapper /** * Sets the merge mappers target name. - * + * * @throws IllegalArgumentException * The target name is null or empty. */ - public void setTargetName( String pName ) - { - if ( pName == null ) - { - throw new IllegalArgumentException( "The target name is null." ); + public void setTargetName(String pName) { + if (pName == null) { + throw new IllegalArgumentException("The target name is null."); } - if ( pName.length() == 0 ) - { - throw new IllegalArgumentException( "The target name is empty." ); + if (pName.isEmpty()) { + throw new IllegalArgumentException("The target name is empty."); } targetName = pName; } /** * Returns the merge mappers target name. - * + * * @throws IllegalArgumentException * The target name is null or empty. */ - public String getTargetName() - { + public String getTargetName() { return targetName; } - @Nonnull public String getMappedFileName( @Nonnull String pName ) - { + @Nonnull + public String getMappedFileName(@Nonnull String pName) { final String name = getTargetName(); - if ( name == null ) - { - throw new IllegalStateException( "The target file name has not been set." ); + if (name == null) { + throw new IllegalStateException("The target file name has not been set."); } - super.getMappedFileName( pName ); // Check for null, etc. + super.getMappedFileName(pName); // Check for null, etc. return name; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/PrefixFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/PrefixFileMapper.java index 389a39c7..d3be2d31 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/PrefixFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/PrefixFileMapper.java @@ -17,12 +17,13 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * A file mapper, which maps by adding a prefix. */ -public class PrefixFileMapper extends AbstractFileMapper -{ +@Named(PrefixFileMapper.ROLE_HINT) +public class PrefixFileMapper extends AbstractFileMapper { /** * The merge mappers role-hint: "prefix". */ @@ -30,37 +31,33 @@ public class PrefixFileMapper extends AbstractFileMapper private String prefix; - @Nonnull public String getMappedFileName( @Nonnull String name ) - { - final String s = super.getMappedFileName( name ); // Check for null, etc. - return getMappedFileName( prefix, s ); + @Nonnull + public String getMappedFileName(@Nonnull String name) { + final String s = super.getMappedFileName(name); // Check for null, etc. + return getMappedFileName(prefix, s); } /** * Returns the prefix to add. */ - public String getPrefix() - { + public String getPrefix() { return prefix; } /** * Sets the prefix to add. */ - public void setPrefix( String prefix ) - { + public void setPrefix(String prefix) { this.prefix = prefix; } /** * Performs the mapping of a file name by adding a prefix. */ - public static String getMappedFileName( String prefix, String name ) - { - if ( prefix == null || prefix.length() == 0 ) - { + public static String getMappedFileName(String prefix, String name) { + if (prefix == null || prefix.isEmpty()) { return name; } return prefix + name; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/RegExpFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/RegExpFileMapper.java index 7e0382d7..aa4dc121 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/RegExpFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/RegExpFileMapper.java @@ -17,15 +17,16 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; + import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Implementation of a file mapper, which uses regular expressions. */ -public class RegExpFileMapper - extends AbstractFileMapper -{ +@Named(RegExpFileMapper.ROLE_HINT) +public class RegExpFileMapper extends AbstractFileMapper { /** * The regexp mappers role-hint: "regexp". */ @@ -40,32 +41,28 @@ public class RegExpFileMapper /** * Sets the regular expression pattern. */ - public void setPattern( String pPattern ) - { - pattern = Pattern.compile( pPattern ); + public void setPattern(String pPattern) { + pattern = Pattern.compile(pPattern); } /** * Returns the regular expression pattern. */ - public String getPattern() - { + public String getPattern() { return pattern == null ? null : pattern.pattern(); } /** * Sets the replacement string. */ - public void setReplacement( String pReplacement ) - { + public void setReplacement(String pReplacement) { replacement = pReplacement; } /** * Returns the replacement string. */ - public String getReplacement() - { + public String getReplacement() { return replacement; } @@ -73,8 +70,7 @@ public String getReplacement() * Returns, whether to replace the first occurrence of the pattern * (default), or all. */ - public boolean getReplaceAll() - { + public boolean getReplaceAll() { return replaceAll; } @@ -82,32 +78,26 @@ public boolean getReplaceAll() * Sets, whether to replace the first occurrence of the pattern * (default), or all. */ - public void setReplaceAll( boolean pReplaceAll ) - { + public void setReplaceAll(boolean pReplaceAll) { replaceAll = pReplaceAll; } @Nonnull - public String getMappedFileName( @Nonnull String pName) - { - final String name = super.getMappedFileName( pName ); - if ( pattern == null ) - { - throw new IllegalStateException( "The regular expression pattern has not been set." ); + public String getMappedFileName(@Nonnull String pName) { + final String name = super.getMappedFileName(pName); + if (pattern == null) { + throw new IllegalStateException("The regular expression pattern has not been set."); } - if (replacement == null) - { - throw new IllegalStateException( "The pattern replacement string has not been set." ); + if (replacement == null) { + throw new IllegalStateException("The pattern replacement string has not been set."); } - final Matcher matcher = pattern.matcher( name ); - if ( !matcher.find() ) - { + final Matcher matcher = pattern.matcher(name); + if (!matcher.find()) { return name; } - if ( !getReplaceAll() ) - { - return matcher.replaceFirst( replacement ); + if (!getReplaceAll()) { + return matcher.replaceFirst(replacement); } - return matcher.replaceAll( replacement ); + return matcher.replaceAll(replacement); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/filemappers/SuffixFileMapper.java b/src/main/java/org/codehaus/plexus/components/io/filemappers/SuffixFileMapper.java index 2372d840..3601ff01 100644 --- a/src/main/java/org/codehaus/plexus/components/io/filemappers/SuffixFileMapper.java +++ b/src/main/java/org/codehaus/plexus/components/io/filemappers/SuffixFileMapper.java @@ -15,17 +15,18 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; /** * A file mapper, which maps by adding a suffix to the filename. * If the filename contains dot, the suffix will be added before. * Example: {@code directory/archive.tar.gz => directory/archivesuffix.tar.gz} */ -public class SuffixFileMapper extends AbstractFileMapper -{ +@Named(SuffixFileMapper.ROLE_HINT) +public class SuffixFileMapper extends AbstractFileMapper { /** - * The suffix mappers role-hint: "suffix". - */ + * The suffix mappers role-hint: "suffix". + */ public static final String ROLE_HINT = "suffix"; private String suffix; @@ -33,40 +34,34 @@ public class SuffixFileMapper extends AbstractFileMapper /** * Returns the suffix to add. */ - public String getSuffix() - { + public String getSuffix() { return suffix; } /** * Sets the suffix to add. */ - public void setSuffix( String suffix ) - { - if ( suffix == null ) - { - throw new IllegalArgumentException( "The suffix is null." ); + public void setSuffix(String suffix) { + if (suffix == null) { + throw new IllegalArgumentException("The suffix is null."); } this.suffix = suffix; } @Nonnull - public String getMappedFileName( @Nonnull String pName) - { - final String name = super.getMappedFileName( pName ); - if ( suffix == null ) - { - throw new IllegalStateException( "The suffix has not been set." ); + public String getMappedFileName(@Nonnull String pName) { + final String name = super.getMappedFileName(pName); + if (suffix == null) { + throw new IllegalStateException("The suffix has not been set."); } - final int dirSep = Math.max( name.lastIndexOf( '/' ), name.lastIndexOf( '\\' ) ); - String filename = dirSep > 0 ? name.substring( dirSep + 1 ) : name; - String dirname = dirSep > 0 ? name.substring( 0, dirSep + 1 ) : ""; - if ( filename.contains( "." ) ) - { - String beforeExtension = filename.substring( 0, filename.indexOf( '.' ) ); - String afterExtension = filename.substring( filename.indexOf( '.' ) + 1 ) ; + final int dirSep = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); + String filename = dirSep > 0 ? name.substring(dirSep + 1) : name; + String dirname = dirSep > 0 ? name.substring(0, dirSep + 1) : ""; + if (filename.contains(".")) { + String beforeExtension = filename.substring(0, filename.indexOf('.')); + String afterExtension = filename.substring(filename.indexOf('.') + 1); return dirname + beforeExtension + suffix + "." + afterExtension; } return name + suffix; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector.java b/src/main/java/org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector.java index 0bcfb5b6..cea7fe96 100644 --- a/src/main/java/org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector.java +++ b/src/main/java/org/codehaus/plexus/components/io/fileselectors/AllFilesFileSelector.java @@ -17,19 +17,21 @@ */ import javax.annotation.Nonnull; +import javax.inject.Named; +import javax.inject.Singleton; /** * The default file selector: Selects all files. */ -public class AllFilesFileSelector implements FileSelector -{ +@Singleton +@Named(AllFilesFileSelector.ROLE_HINT) +public class AllFilesFileSelector implements FileSelector { /** * The all files selectors role-hint: "all". */ public static final String ROLE_HINT = "all"; - public boolean isSelected( @Nonnull FileInfo fileInfo ) - { + public boolean isSelected(@Nonnull FileInfo fileInfo) { return true; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/fileselectors/DefaultFileSelector.java b/src/main/java/org/codehaus/plexus/components/io/fileselectors/DefaultFileSelector.java new file mode 100644 index 00000000..5886f857 --- /dev/null +++ b/src/main/java/org/codehaus/plexus/components/io/fileselectors/DefaultFileSelector.java @@ -0,0 +1,27 @@ +package org.codehaus.plexus.components.io.fileselectors; + +/* + * Copyright 2007 The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import javax.inject.Named; +import javax.inject.Singleton; + +/** + * Alias for {@link AllFilesFileSelector} + */ +@Singleton +@Named +public class DefaultFileSelector extends AllFilesFileSelector {} diff --git a/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileInfo.java b/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileInfo.java index 615160c7..8fab34bf 100644 --- a/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileInfo.java +++ b/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileInfo.java @@ -16,11 +16,11 @@ * limitations under the License. */ -import org.codehaus.plexus.components.io.functions.NameSupplier; - import java.io.IOException; import java.io.InputStream; +import org.codehaus.plexus.components.io.functions.NameSupplier; + /** * An object implementing this interface is passed to the * file selector when the method @@ -28,8 +28,7 @@ * is invoked. This object provides information about * the file to select or deselect. */ -public interface FileInfo extends NameSupplier -{ +public interface FileInfo extends NameSupplier { /** * Returns the resources name, which may include path components, * like directory names, or something like that. The resources name @@ -66,4 +65,4 @@ public interface FileInfo extends NameSupplier * This method will return "false" for java versions prior to java7. */ boolean isSymbolicLink(); -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileSelector.java b/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileSelector.java index e5cf7cf0..ac84157f 100644 --- a/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileSelector.java +++ b/src/main/java/org/codehaus/plexus/components/io/fileselectors/FileSelector.java @@ -17,28 +17,18 @@ */ import javax.annotation.Nonnull; + import java.io.IOException; /** * Interface of a component, which selects/deselects files. */ -public interface FileSelector -{ - /** - * Role used to register component implementations with the container. - */ - public static final String ROLE = FileSelector.class.getName(); - - /** - * The default role-hint: "default". - */ - public static final String DEFAULT_ROLE_HINT = "default"; - +public interface FileSelector { /** * Returns, whether the given file is selected. * @param fileInfo An instance of FileInfo with the files meta data. * It is recommended, that the caller creates an instance * of {@link org.codehaus.plexus.components.io.resources.PlexusIoResource}. */ - boolean isSelected( @Nonnull FileInfo fileInfo ) throws IOException; -} \ No newline at end of file + boolean isSelected(@Nonnull FileInfo fileInfo) throws IOException; +} diff --git a/src/main/java/org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector.java b/src/main/java/org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector.java index 309dba64..9f7af5f6 100644 --- a/src/main/java/org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector.java +++ b/src/main/java/org/codehaus/plexus/components/io/fileselectors/IncludeExcludeFileSelector.java @@ -16,28 +16,28 @@ * limitations under the License. */ +import javax.annotation.Nonnull; +import javax.annotation.Nullable; +import javax.inject.Named; + import java.io.File; import org.codehaus.plexus.util.FileUtils; import org.codehaus.plexus.util.MatchPatterns; import org.codehaus.plexus.util.SelectorUtils; -import javax.annotation.Nonnull; -import javax.annotation.Nullable; - /** * This file selector uses a set of patterns for including/excluding * files. */ -public class IncludeExcludeFileSelector - implements FileSelector -{ +@Named(IncludeExcludeFileSelector.ROLE_HINT) +public class IncludeExcludeFileSelector implements FileSelector { /** * The include/exclude file selectors role-hint: "standard". */ public static final String ROLE_HINT = "standard"; - private static final MatchPatterns ALL_INCLUDES = MatchPatterns.from( getCanonicalName( "**/*" ) ); + private static final MatchPatterns ALL_INCLUDES = MatchPatterns.from(getCanonicalName("**/*")); private static final MatchPatterns ZERO_EXCLUDES = MatchPatterns.from(); @@ -61,9 +61,8 @@ public class IncludeExcludeFileSelector * @return true when the name matches against at least one * exclude pattern, or false otherwise. */ - protected boolean isExcluded( @Nonnull String name ) - { - return computedExcludes.matches( name, isCaseSensitive ); + protected boolean isExcluded(@Nonnull String name) { + return computedExcludes.matches(name, isCaseSensitive); } /** @@ -79,35 +78,27 @@ protected boolean isExcluded( @Nonnull String name ) * list is given, all elements must be * non-null. */ - public void setIncludes( @Nullable String[] includes ) - { + public void setIncludes(@Nullable String[] includes) { this.includes = includes; - if ( includes == null ) - { + if (includes == null) { computedIncludes = ALL_INCLUDES; - } - else - { + } else { String[] cleaned; cleaned = new String[includes.length]; - for ( int i = 0; i < includes.length; i++ ) - { - cleaned[i] = asPattern( includes[i] ); + for (int i = 0; i < includes.length; i++) { + cleaned[i] = asPattern(includes[i]); } - computedIncludes = MatchPatterns.from( cleaned ); + computedIncludes = MatchPatterns.from(cleaned); } } - private static @Nonnull String getCanonicalName( @Nonnull String pName ) - { - return pName.replace( '/', File.separatorChar ).replace( '\\', File.separatorChar ); + private static @Nonnull String getCanonicalName(@Nonnull String pName) { + return pName.replace('/', File.separatorChar).replace('\\', File.separatorChar); } - private String asPattern( @Nonnull String pPattern ) - { - String pattern = getCanonicalName( pPattern.trim() ); - if ( pattern.endsWith( File.separator ) ) - { + private String asPattern(@Nonnull String pPattern) { + String pattern = getCanonicalName(pPattern.trim()); + if (pattern.endsWith(File.separator)) { pattern += "**"; } return pattern; @@ -122,8 +113,7 @@ private String asPattern( @Nonnull String pPattern ) * list is given, all elements must be * non-null. */ - public @Nullable String[] getIncludes() - { + public @Nullable String[] getIncludes() { return includes; } @@ -139,28 +129,21 @@ private String asPattern( @Nonnull String pPattern ) * should be excluded. If a non-null list is * given, all elements must be non-null. */ - public void setExcludes( @Nullable String[] excludes ) - { + public void setExcludes(@Nullable String[] excludes) { this.excludes = excludes; final String[] defaultExcludes = useDefaultExcludes ? FileUtils.getDefaultExcludes() : new String[] {}; - if ( excludes == null ) - { - computedExcludes = MatchPatterns.from( defaultExcludes ); - } - else - { + if (excludes == null) { + computedExcludes = MatchPatterns.from(defaultExcludes); + } else { String[] temp = new String[excludes.length + defaultExcludes.length]; - for ( int i = 0; i < excludes.length; i++ ) - { - temp[i] = asPattern( excludes[i] ); + for (int i = 0; i < excludes.length; i++) { + temp[i] = asPattern(excludes[i]); } - if ( defaultExcludes.length > 0 ) - { - System.arraycopy( defaultExcludes, 0, temp, excludes.length, defaultExcludes.length ); + if (defaultExcludes.length > 0) { + System.arraycopy(defaultExcludes, 0, temp, excludes.length, defaultExcludes.length); } - computedExcludes = MatchPatterns.from( temp ); - + computedExcludes = MatchPatterns.from(temp); } } @@ -172,8 +155,7 @@ public void setExcludes( @Nullable String[] excludes ) * should be excluded. If a non-null list is * given, all elements must be non-null. */ - public @Nullable String[] getExcludes() - { + public @Nullable String[] getExcludes() { return excludes; } @@ -184,10 +166,8 @@ public void setExcludes( @Nullable String[] excludes ) * @param isCaseSensitive Whether the pattern is case sensitive. * @return True, if the pattern matches, otherwise false */ - protected boolean matchPath( @Nonnull String pattern, @Nonnull String name, - boolean isCaseSensitive ) - { - return SelectorUtils.matchPath( pattern, name, isCaseSensitive ); + protected boolean matchPath(@Nonnull String pattern, @Nonnull String name, boolean isCaseSensitive) { + return SelectorUtils.matchPath(pattern, name, isCaseSensitive); } /** @@ -198,23 +178,20 @@ protected boolean matchPath( @Nonnull String pattern, @Nonnull String name, * @return true when the name matches against at least one * include pattern, or false otherwise. */ - protected boolean isIncluded( @Nonnull String name ) - { - return computedIncludes.matches( name, isCaseSensitive ); + protected boolean isIncluded(@Nonnull String name) { + return computedIncludes.matches(name, isCaseSensitive); } - public boolean isSelected( @Nonnull FileInfo fileInfo ) - { - final String name = getCanonicalName( fileInfo.getName() ); - return isIncluded( name ) && !isExcluded( name ); + public boolean isSelected(@Nonnull FileInfo fileInfo) { + final String name = getCanonicalName(fileInfo.getName()); + return isIncluded(name) && !isExcluded(name); } /** * Returns, whether the include/exclude patterns are case sensitive. * @return True, if the patterns are case sensitive (default), or false. */ - public boolean isCaseSensitive() - { + public boolean isCaseSensitive() { return isCaseSensitive; } @@ -222,8 +199,7 @@ public boolean isCaseSensitive() * Sets, whether the include/exclude patterns are case sensitive. * @param caseSensitive True, if the patterns are case sensitive (default), or false. */ - public void setCaseSensitive( boolean caseSensitive ) - { + public void setCaseSensitive(boolean caseSensitive) { isCaseSensitive = caseSensitive; } @@ -231,8 +207,7 @@ public void setCaseSensitive( boolean caseSensitive ) * Returns, whether to use the default excludes, as specified by * {@link FileUtils#getDefaultExcludes()}. */ - public boolean isUseDefaultExcludes() - { + public boolean isUseDefaultExcludes() { return useDefaultExcludes; } @@ -240,9 +215,8 @@ public boolean isUseDefaultExcludes() * Sets, whether to use the default excludes, as specified by * {@link FileUtils#getDefaultExcludes()}. */ - public void setUseDefaultExcludes( boolean pUseDefaultExcludes ) - { + public void setUseDefaultExcludes(boolean pUseDefaultExcludes) { useDefaultExcludes = pUseDefaultExcludes; - setExcludes( excludes ); + setExcludes(excludes); } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/ContentSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/ContentSupplier.java index 9c885b6f..21b3ec1e 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/ContentSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/ContentSupplier.java @@ -24,7 +24,6 @@ * * Someday this will extends java.util.function.Supplier */ -public interface ContentSupplier -{ +public interface ContentSupplier { InputStream getContents() throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/FileSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/FileSupplier.java index 116c279f..1fbee255 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/FileSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/FileSupplier.java @@ -17,13 +17,13 @@ */ import javax.annotation.Nonnull; + import java.io.File; /** * Implemented by resources that are files on something filesystem-like. */ -public interface FileSupplier -{ +public interface FileSupplier { /** * Supplies the file for this resource, not null. * @return The file diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/InputStreamTransformer.java b/src/main/java/org/codehaus/plexus/components/io/functions/InputStreamTransformer.java index f0073dbf..5907e10b 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/InputStreamTransformer.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/InputStreamTransformer.java @@ -15,21 +15,21 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -import org.codehaus.plexus.components.io.resources.PlexusIoResource; - import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; +import org.codehaus.plexus.components.io.resources.PlexusIoResource; + /** * Transform a stream into some other kind of stream. May be used to apply filtering or other * kinds of transformations. */ -public interface InputStreamTransformer -{ +public interface InputStreamTransformer { /** * Transform the supplied input stream into another input stream. - * + *

* The close method will be delegated through the entire call chain * * @param resource The p-io resource the stream is for @@ -37,5 +37,6 @@ public interface InputStreamTransformer * @return A transformed stream or possibly the supplied stream * @throws IOException */ - @Nonnull InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream ) throws IOException; + @Nonnull + InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream) throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/NameSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/NameSupplier.java index 179cc807..64204314 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/NameSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/NameSupplier.java @@ -16,8 +16,7 @@ * limitations under the License. */ -public interface NameSupplier -{ +public interface NameSupplier { /** * Returns the resources name, which may include path components, * like directory names, or something like that. The resources name diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/PlexusIoResourceConsumer.java b/src/main/java/org/codehaus/plexus/components/io/functions/PlexusIoResourceConsumer.java index 841a724f..893074fe 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/PlexusIoResourceConsumer.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/PlexusIoResourceConsumer.java @@ -23,7 +23,6 @@ * Consume a PlexusIoResource * @author Kristian Rosenvold */ -public interface PlexusIoResourceConsumer -{ - void accept( PlexusIoResource resource ) throws IOException; +public interface PlexusIoResourceConsumer { + void accept(PlexusIoResource resource) throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/ResourceAttributeSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/ResourceAttributeSupplier.java index a14e3bf2..c8f1c060 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/ResourceAttributeSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/ResourceAttributeSupplier.java @@ -18,7 +18,6 @@ import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; -public interface ResourceAttributeSupplier -{ +public interface ResourceAttributeSupplier { PlexusIoResourceAttributes getAttributes(); } diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/SizeSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/SizeSupplier.java index 05a5b402..bfb3c97b 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/SizeSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/SizeSupplier.java @@ -16,7 +16,6 @@ * limitations under the License. */ -public interface SizeSupplier -{ +public interface SizeSupplier { long getSize(); } diff --git a/src/main/java/org/codehaus/plexus/components/io/functions/SymlinkDestinationSupplier.java b/src/main/java/org/codehaus/plexus/components/io/functions/SymlinkDestinationSupplier.java index 8aa8dfbb..e47e7ce0 100644 --- a/src/main/java/org/codehaus/plexus/components/io/functions/SymlinkDestinationSupplier.java +++ b/src/main/java/org/codehaus/plexus/components/io/functions/SymlinkDestinationSupplier.java @@ -21,8 +21,6 @@ /** * @author Kristian Rosenvold */ -public interface SymlinkDestinationSupplier -{ - public String getSymlinkDestination() - throws IOException; +public interface SymlinkDestinationSupplier { + String getSymlinkDestination() throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoArchiveResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoArchiveResourceCollection.java index 573b234a..03d73cfa 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoArchiveResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoArchiveResourceCollection.java @@ -21,8 +21,6 @@ import java.io.IOException; import java.util.Iterator; -import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; - /** * Default implementation of {@link PlexusIoFileResourceCollection} for * zip files, tar files, etc. @@ -30,28 +28,23 @@ * */ public abstract class AbstractPlexusIoArchiveResourceCollection extends AbstractPlexusIoResourceCollection - implements PlexusIoArchivedResourceCollection -{ + implements PlexusIoArchivedResourceCollection { private File file; - protected AbstractPlexusIoArchiveResourceCollection() - { - } + protected AbstractPlexusIoArchiveResourceCollection() {} /** * Sets the zip file */ - public void setFile( File file ) - { + public void setFile(File file) { this.file = file; } /** * Returns the zip file */ - public File getFile() - { + public File getFile() { return file; } @@ -62,100 +55,71 @@ public File getFile() */ protected abstract Iterator getEntries() throws IOException; - public Iterator getResources() throws IOException - { + public Iterator getResources() throws IOException { return new FilteringIterator(); } - class FilteringIterator - implements Iterator, Closeable - { + class FilteringIterator implements Iterator, Closeable { final Iterator it = getEntries(); PlexusIoResource next; - public FilteringIterator() - throws IOException - { - } + public FilteringIterator() throws IOException {} - boolean doNext() - { - while ( it.hasNext() ) - { + boolean doNext() { + while (it.hasNext()) { PlexusIoResource candidate = it.next(); - try - { - if ( isSelected( candidate ) ) - { + try { + if (isSelected(candidate)) { next = candidate; return true; } - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } return false; } - public boolean hasNext() - { + + public boolean hasNext() { return doNext(); } - public PlexusIoResource next() - { - if ( next == null ) - doNext(); + public PlexusIoResource next() { + if (next == null) doNext(); PlexusIoResource res = next; next = null; return res; } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - public void close() - throws IOException - { - if ( it instanceof Closeable ) - { - ( (Closeable) it ).close(); + public void close() throws IOException { + if (it instanceof Closeable) { + ((Closeable) it).close(); } } } - public Stream stream() - { - return new Stream() - { - public void forEach( PlexusIoResourceConsumer resourceConsumer ) - throws IOException - { - - final Iterator it = getEntries(); - while ( it.hasNext() ) - { - final PlexusIoResource res = it.next(); - if ( isSelected( res ) ) - { - resourceConsumer.accept( res ); - } - } - if ( it instanceof Closeable ) - { - ( (Closeable) it ).close(); + + public Stream stream() { + return resourceConsumer -> { + Iterator it = getEntries(); + while (it.hasNext()) { + final PlexusIoResource res = it.next(); + if (isSelected(res)) { + resourceConsumer.accept(res); } } + if (it instanceof Closeable) { + ((Closeable) it).close(); + } }; } - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { File f = getFile(); return f == null ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : f.lastModified(); } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource.java b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource.java index 736c4d32..b9bedec1 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResource.java @@ -21,17 +21,19 @@ /** * Default implementation of {@link PlexusIoResource}. */ -public abstract class AbstractPlexusIoResource implements PlexusIoResource -{ +public abstract class AbstractPlexusIoResource implements PlexusIoResource { private final String name; private final long lastModified, size; - private final boolean isFile, isDirectory, isExisting; - protected AbstractPlexusIoResource( @Nonnull String name, long lastModified, long size, boolean isFile, - boolean isDirectory, boolean isExisting ) - { + protected AbstractPlexusIoResource( + @Nonnull String name, + long lastModified, + long size, + boolean isFile, + boolean isDirectory, + boolean isExisting) { this.name = name; this.lastModified = lastModified; this.size = size; @@ -40,39 +42,32 @@ protected AbstractPlexusIoResource( @Nonnull String name, long lastModified, lon this.isExisting = isExisting; } - public long getLastModified() - { + public long getLastModified() { return lastModified; } @Nonnull - public String getName() - { + public String getName() { return name; } - public long getSize() - { + public long getSize() { return size; } - public boolean isDirectory() - { + public boolean isDirectory() { return isDirectory; } - public boolean isExisting() - { + public boolean isExisting() { return isExisting; } - public boolean isFile() - { + public boolean isFile() { return isFile; } - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return false; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection.java index 431b762e..f0dfe91c 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollection.java @@ -16,30 +16,26 @@ * limitations under the License. */ -import org.codehaus.plexus.components.io.filemappers.FileMapper; -import org.codehaus.plexus.components.io.filemappers.PrefixFileMapper; -import org.codehaus.plexus.components.io.fileselectors.FileSelector; -import org.codehaus.plexus.components.io.functions.InputStreamTransformer; - import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; import java.util.Iterator; +import org.codehaus.plexus.components.io.filemappers.FileMapper; +import org.codehaus.plexus.components.io.filemappers.PrefixFileMapper; +import org.codehaus.plexus.components.io.fileselectors.FileSelector; +import org.codehaus.plexus.components.io.functions.InputStreamTransformer; + /** * Default implementation of a resource collection. */ -public abstract class AbstractPlexusIoResourceCollection - implements PlexusIoResourceCollection -{ +public abstract class AbstractPlexusIoResourceCollection implements PlexusIoResourceCollection { - static class IdentityTransformer - implements InputStreamTransformer - { + static class IdentityTransformer implements InputStreamTransformer { @Nonnull - public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream ) - throws IOException - { + public InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream) + throws IOException { return inputStream; } } @@ -64,16 +60,13 @@ public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull Input private InputStreamTransformer streamTransformer = identityTransformer; - protected AbstractPlexusIoResourceCollection() - { - } + protected AbstractPlexusIoResourceCollection() {} /** * Sets a string of patterns, which excluded files * should match. */ - public void setExcludes( String[] excludes ) - { + public void setExcludes(String[] excludes) { this.excludes = excludes; } @@ -81,8 +74,7 @@ public void setExcludes( String[] excludes ) * Returns a string of patterns, which excluded files * should match. */ - public String[] getExcludes() - { + public String[] getExcludes() { return excludes; } @@ -90,8 +82,7 @@ public String[] getExcludes() * Sets a set of file selectors, which should be used * to select the included files. */ - public void setFileSelectors( FileSelector[] fileSelectors ) - { + public void setFileSelectors(FileSelector[] fileSelectors) { this.fileSelectors = fileSelectors; } @@ -99,25 +90,19 @@ public void setFileSelectors( FileSelector[] fileSelectors ) * Returns a set of file selectors, which should be used * to select the included files. */ - public FileSelector[] getFileSelectors() - { + public FileSelector[] getFileSelectors() { return fileSelectors; } - public void setStreamTransformer( InputStreamTransformer streamTransformer ) - { - if ( streamTransformer == null ) - { + public void setStreamTransformer(InputStreamTransformer streamTransformer) { + if (streamTransformer == null) { this.streamTransformer = identityTransformer; - } - else - { + } else { this.streamTransformer = streamTransformer; } } - protected InputStreamTransformer getStreamTransformer() - { + protected InputStreamTransformer getStreamTransformer() { return streamTransformer; } @@ -125,8 +110,7 @@ protected InputStreamTransformer getStreamTransformer() * Sets a string of patterns, which included files * should match. */ - public void setIncludes( String[] includes ) - { + public void setIncludes(String[] includes) { this.includes = includes; } @@ -134,8 +118,7 @@ public void setIncludes( String[] includes ) * Returns a string of patterns, which included files * should match. */ - public String[] getIncludes() - { + public String[] getIncludes() { return includes; } @@ -143,8 +126,7 @@ public String[] getIncludes() * Sets the prefix, which the file sets contents shall * have. */ - public void setPrefix( String prefix ) - { + public void setPrefix(String prefix) { this.prefix = prefix; } @@ -152,8 +134,7 @@ public void setPrefix( String prefix ) * Returns the prefix, which the file sets contents shall * have. */ - public String getPrefix() - { + public String getPrefix() { return prefix; } @@ -161,8 +142,7 @@ public String getPrefix() * Sets, whether the include/exclude patterns are * case sensitive. Defaults to true. */ - public void setCaseSensitive( boolean caseSensitive ) - { + public void setCaseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; } @@ -170,8 +150,7 @@ public void setCaseSensitive( boolean caseSensitive ) * Returns, whether the include/exclude patterns are * case sensitive. Defaults to true. */ - public boolean isCaseSensitive() - { + public boolean isCaseSensitive() { return caseSensitive; } @@ -179,8 +158,7 @@ public boolean isCaseSensitive() * Sets, whether the default excludes are being * applied. Defaults to true. */ - public void setUsingDefaultExcludes( boolean usingDefaultExcludes ) - { + public void setUsingDefaultExcludes(boolean usingDefaultExcludes) { this.usingDefaultExcludes = usingDefaultExcludes; } @@ -188,8 +166,7 @@ public void setUsingDefaultExcludes( boolean usingDefaultExcludes ) * Returns, whether the default excludes are being * applied. Defaults to true. */ - public boolean isUsingDefaultExcludes() - { + public boolean isUsingDefaultExcludes() { return usingDefaultExcludes; } @@ -197,8 +174,7 @@ public boolean isUsingDefaultExcludes() * Sets, whether empty directories are being included. Defaults * to true. */ - public void setIncludingEmptyDirectories( boolean includingEmptyDirectories ) - { + public void setIncludingEmptyDirectories(boolean includingEmptyDirectories) { this.includingEmptyDirectories = includingEmptyDirectories; } @@ -206,21 +182,15 @@ public void setIncludingEmptyDirectories( boolean includingEmptyDirectories ) * Returns, whether empty directories are being included. Defaults * to true. */ - public boolean isIncludingEmptyDirectories() - { + public boolean isIncludingEmptyDirectories() { return includingEmptyDirectories; } - protected boolean isSelected( PlexusIoResource plexusIoResource ) - throws IOException - { + protected boolean isSelected(PlexusIoResource plexusIoResource) throws IOException { FileSelector[] fileSelectors = getFileSelectors(); - if ( fileSelectors != null ) - { - for ( FileSelector fileSelector : fileSelectors ) - { - if ( !fileSelector.isSelected( plexusIoResource ) ) - { + if (fileSelectors != null) { + for (FileSelector fileSelector : fileSelectors) { + if (!fileSelector.isSelected(plexusIoResource)) { return false; } } @@ -232,8 +202,7 @@ protected boolean isSelected( PlexusIoResource plexusIoResource ) * Returns the file name mappers, which are used to transform * the resource names. */ - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return fileMappers; } @@ -241,76 +210,54 @@ public FileMapper[] getFileMappers() * Sets the file name mappers, which are used to transform * the resource names. */ - public void setFileMappers( FileMapper[] fileMappers ) - { + public void setFileMappers(FileMapper[] fileMappers) { this.fileMappers = fileMappers; } - public Iterator iterator() - { - try - { + public Iterator iterator() { + try { return getResources(); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } - public String getName( PlexusIoResource resource ) - { - return getName( resource.getName() ); + public String getName(PlexusIoResource resource) { + return getName(resource.getName()); } - protected String getName( String resourceName ) - { + protected String getName(String resourceName) { String name = resourceName; final FileMapper[] mappers = getFileMappers(); - if ( mappers != null ) - { - for ( FileMapper mapper : mappers ) - { - name = mapper.getMappedFileName( name ); + if (mappers != null) { + for (FileMapper mapper : mappers) { + name = mapper.getMappedFileName(name); } } - return PrefixFileMapper.getMappedFileName( getPrefix(), name ); + return PrefixFileMapper.getMappedFileName(getPrefix(), name); } - - public InputStream getInputStream( PlexusIoResource resource ) - throws IOException - { + public InputStream getInputStream(PlexusIoResource resource) throws IOException { InputStream contents = resource.getContents(); - return new ClosingInputStream( streamTransformer.transform( resource, contents ), contents ); + return new ClosingInputStream(streamTransformer.transform(resource, contents), contents); } - - public PlexusIoResource resolve( final PlexusIoResource resource ) - throws IOException - { - final Deferred deferred = new Deferred( resource, this, streamTransformer != identityTransformer ); + public PlexusIoResource resolve(final PlexusIoResource resource) throws IOException { + final Deferred deferred = new Deferred(resource, this, streamTransformer != identityTransformer); return deferred.asResource(); } - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { long lastModified = PlexusIoResource.UNKNOWN_MODIFICATION_DATE; - for ( final Iterator iter = getResources(); iter.hasNext(); ) - { - final PlexusIoResource res = (PlexusIoResource) iter.next(); - long l = res.getLastModified(); - if ( l == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ) - { + for (Iterator iter = getResources(); iter.hasNext(); ) { + long l = iter.next().getLastModified(); + if (l == PlexusIoResource.UNKNOWN_MODIFICATION_DATE) { return PlexusIoResource.UNKNOWN_MODIFICATION_DATE; } - if ( lastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE || l > lastModified ) - { + if (lastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE || l > lastModified) { lastModified = l; } } return lastModified; } - -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionWithAttributes.java b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionWithAttributes.java index e8bee2f5..5b158db2 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionWithAttributes.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionWithAttributes.java @@ -22,9 +22,7 @@ /** * Default implementation of a resource collection with attributes. */ -public abstract class AbstractPlexusIoResourceCollectionWithAttributes - extends AbstractPlexusIoResourceCollection -{ +public abstract class AbstractPlexusIoResourceCollectionWithAttributes extends AbstractPlexusIoResourceCollection { private PlexusIoResourceAttributes defaultFileAttributes; @@ -34,61 +32,47 @@ public abstract class AbstractPlexusIoResourceCollectionWithAttributes private PlexusIoResourceAttributes overrideDirAttributes; - protected AbstractPlexusIoResourceCollectionWithAttributes() - { - } + protected AbstractPlexusIoResourceCollectionWithAttributes() {} - protected PlexusIoResourceAttributes getDefaultFileAttributes() - { + protected PlexusIoResourceAttributes getDefaultFileAttributes() { return defaultFileAttributes; } - protected void setDefaultFileAttributes( final PlexusIoResourceAttributes defaultFileAttributes ) - { + protected void setDefaultFileAttributes(final PlexusIoResourceAttributes defaultFileAttributes) { this.defaultFileAttributes = defaultFileAttributes; } - protected PlexusIoResourceAttributes getDefaultDirAttributes() - { + protected PlexusIoResourceAttributes getDefaultDirAttributes() { return defaultDirAttributes; } - protected void setDefaultDirAttributes( final PlexusIoResourceAttributes defaultDirAttributes ) - { + protected void setDefaultDirAttributes(final PlexusIoResourceAttributes defaultDirAttributes) { this.defaultDirAttributes = defaultDirAttributes; } - protected PlexusIoResourceAttributes getOverrideFileAttributes() - { + protected PlexusIoResourceAttributes getOverrideFileAttributes() { return overrideFileAttributes; } - protected void setOverrideFileAttributes( final PlexusIoResourceAttributes overrideFileAttributes ) - { + protected void setOverrideFileAttributes(final PlexusIoResourceAttributes overrideFileAttributes) { this.overrideFileAttributes = overrideFileAttributes; } - protected PlexusIoResourceAttributes getOverrideDirAttributes() - { + protected PlexusIoResourceAttributes getOverrideDirAttributes() { return overrideDirAttributes; } - protected void setOverrideDirAttributes( final PlexusIoResourceAttributes overrideDirAttributes ) - { + protected void setOverrideDirAttributes(final PlexusIoResourceAttributes overrideDirAttributes) { this.overrideDirAttributes = overrideDirAttributes; } - protected PlexusIoResourceAttributes mergeAttributes( PlexusIoResourceAttributes currentAttrs, boolean isDirectory ) - { - if ( isDirectory ) - { - currentAttrs = PlexusIoResourceAttributeUtils.mergeAttributes( getOverrideDirAttributes(), currentAttrs, - getDefaultDirAttributes() ); - } - else - { - currentAttrs = PlexusIoResourceAttributeUtils.mergeAttributes( getOverrideFileAttributes(), currentAttrs, - getDefaultFileAttributes() ); + protected PlexusIoResourceAttributes mergeAttributes(PlexusIoResourceAttributes currentAttrs, boolean isDirectory) { + if (isDirectory) { + currentAttrs = PlexusIoResourceAttributeUtils.mergeAttributes( + getOverrideDirAttributes(), currentAttrs, getDefaultDirAttributes()); + } else { + currentAttrs = PlexusIoResourceAttributeUtils.mergeAttributes( + getOverrideFileAttributes(), currentAttrs, getDefaultFileAttributes()); } return currentAttrs; } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/ClosingInputStream.java b/src/main/java/org/codehaus/plexus/components/io/resources/ClosingInputStream.java index 8eb275ff..13f210e3 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/ClosingInputStream.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/ClosingInputStream.java @@ -6,78 +6,59 @@ /** * @author Kristian Rosenvold */ -public class ClosingInputStream - extends InputStream -{ +public class ClosingInputStream extends InputStream { private final InputStream target; private final InputStream other; - public ClosingInputStream( InputStream target, InputStream other ) - { + public ClosingInputStream(InputStream target, InputStream other) { this.target = target; this.other = other; } @Override - public int read() - throws IOException - { + public int read() throws IOException { return target.read(); } @Override - public int read( byte[] b ) - throws IOException - { - return target.read( b ); + public int read(byte[] b) throws IOException { + return target.read(b); } @Override - public int read( byte[] b, int off, int len ) - throws IOException - { - return target.read( b, off, len ); + public int read(byte[] b, int off, int len) throws IOException { + return target.read(b, off, len); } @Override - public long skip( long n ) - throws IOException - { - return target.skip( n ); + public long skip(long n) throws IOException { + return target.skip(n); } @Override - public int available() - throws IOException - { + public int available() throws IOException { return target.available(); } @Override - public void close() - throws IOException - { + public void close() throws IOException { other.close(); target.close(); } @Override - public void mark( int readlimit ) - { - target.mark( readlimit ); + public void mark(int readlimit) { + target.mark(readlimit); } @Override - public void reset() - throws IOException - { + public void reset() throws IOException { target.reset(); } @Override - public boolean markSupported() - { + public boolean markSupported() { return target.markSupported(); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/DefaultPlexusIoFileResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/DefaultPlexusIoFileResourceCollection.java new file mode 100644 index 00000000..fbfdccc0 --- /dev/null +++ b/src/main/java/org/codehaus/plexus/components/io/resources/DefaultPlexusIoFileResourceCollection.java @@ -0,0 +1,25 @@ +package org.codehaus.plexus.components.io.resources; + +/* + * Copyright 2007 The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import javax.inject.Named; + +/** + * Alias for {@link PlexusIoFileResourceCollection} + */ +@Named +public class DefaultPlexusIoFileResourceCollection extends PlexusIoFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/Deferred.java b/src/main/java/org/codehaus/plexus/components/io/resources/Deferred.java index 77b4af1e..7db54f3d 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/Deferred.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/Deferred.java @@ -15,6 +15,13 @@ */ package org.codehaus.plexus.components.io.resources; +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; + import org.apache.commons.io.IOUtils; import org.apache.commons.io.output.DeferredFileOutputStream; import org.codehaus.plexus.components.io.functions.ContentSupplier; @@ -22,55 +29,41 @@ import org.codehaus.plexus.components.io.functions.SizeSupplier; import org.codehaus.plexus.components.io.resources.proxy.ProxyFactory; -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; - -class Deferred implements ContentSupplier, NameSupplier, SizeSupplier -{ +class Deferred implements ContentSupplier, NameSupplier, SizeSupplier { final DeferredFileOutputStream dfos; final PlexusIoResource resource; final PlexusIoResourceCollection owner; - public Deferred( final PlexusIoResource resource, PlexusIoResourceCollection owner, boolean hasTransformer ) - throws IOException - { + public Deferred(final PlexusIoResource resource, PlexusIoResourceCollection owner, boolean hasTransformer) + throws IOException { this.resource = resource; this.owner = owner; - dfos = hasTransformer ? new DeferredFileOutputStream( 5000000, "p-archiver", null, null ) : null; - if ( dfos != null ) - { - InputStream inputStream = owner.getInputStream( resource ); - IOUtils.copy( inputStream, dfos ); - IOUtils.closeQuietly( inputStream ); + dfos = hasTransformer + ? DeferredFileOutputStream.builder() + .setThreshold(5000000) + .setPrefix("p-archiver") + .get() + : null; + if (dfos != null) { + InputStream inputStream = owner.getInputStream(resource); + IOUtils.copy(inputStream, dfos); + IOUtils.closeQuietly(inputStream); } - } @Nonnull - public InputStream getContents() - throws IOException - { - if ( dfos == null ) - { + public InputStream getContents() throws IOException { + if (dfos == null) { return resource.getContents(); } - if ( dfos.isInMemory() ) - { - return new ByteArrayInputStream( dfos.getData() ); - } - else - { - return new FileInputStream( dfos.getFile() ) - { + if (dfos.isInMemory()) { + return new ByteArrayInputStream(dfos.getData()); + } else { + return new FileInputStream(dfos.getFile()) { @Override - public void close() - throws IOException - { + public void close() throws IOException { super.close(); dfos.getFile().delete(); } @@ -78,30 +71,22 @@ public void close() } } - public long getSize() - { - if ( dfos == null ) - { + public long getSize() { + if (dfos == null) { return resource.getSize(); } - if ( dfos.isInMemory() ) - { + if (dfos.isInMemory()) { return dfos.getByteCount(); - } - else - { + } else { return dfos.getFile().length(); } } - public String getName() - { - return owner.getName( resource ); + public String getName() { + return owner.getName(resource); } - public PlexusIoResource asResource() - { - return ProxyFactory.createProxy( resource, Deferred.this ); + public PlexusIoResource asResource() { + return ProxyFactory.createProxy(resource, Deferred.this); } - } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/EncodingSupported.java b/src/main/java/org/codehaus/plexus/components/io/resources/EncodingSupported.java index ffaa6dcc..f036a3de 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/EncodingSupported.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/EncodingSupported.java @@ -21,11 +21,10 @@ /** * Implemented by plexus io resources that support some kind of encoding notion */ -public interface EncodingSupported -{ +public interface EncodingSupported { /** * Supplies the encoding to be used for decoding filenames/paths * @param charset The charset to use */ - public void setEncoding( Charset charset ); + void setEncoding(Charset charset); } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/LinefeedMode.java b/src/main/java/org/codehaus/plexus/components/io/resources/LinefeedMode.java index 281c2a97..b7c9ab64 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/LinefeedMode.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/LinefeedMode.java @@ -18,7 +18,8 @@ /** * @author Kristian Rosenvold */ -public enum LinefeedMode -{ - dos, unix, preserve +public enum LinefeedMode { + dos, + unix, + preserve } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection.java index a5e1270e..56b7051b 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoArchivedResourceCollection.java @@ -22,16 +22,14 @@ * Extension of {@link PlexusIoResourceCollection} for archive * files: zip, tar, gzip, bzip2, etc. files. */ -public interface PlexusIoArchivedResourceCollection - extends PlexusIoResourceCollection -{ +public interface PlexusIoArchivedResourceCollection extends PlexusIoResourceCollection { /** * Sets the archive file */ - void setFile( File file ); + void setFile(File file); /** * Returns the archive file */ File getFile(); -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection.java index 8be86877..64ba973c 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoCompressedFileResourceCollection.java @@ -16,12 +16,8 @@ * limitations under the License. */ -import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; -import org.codehaus.plexus.components.io.functions.ContentSupplier; -import org.codehaus.plexus.components.io.functions.InputStreamTransformer; -import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; - import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -29,166 +25,129 @@ import java.util.Collections; import java.util.Iterator; +import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; +import org.codehaus.plexus.components.io.functions.ContentSupplier; +import org.codehaus.plexus.components.io.functions.InputStreamTransformer; +import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; /** * Abstract base class for compressed files, aka singleton * resource collections. */ public abstract class PlexusIoCompressedFileResourceCollection - implements PlexusIoArchivedResourceCollection, Iterable -{ + implements PlexusIoArchivedResourceCollection, Iterable { private File file; private String path; private InputStreamTransformer streamTransformers = AbstractPlexusIoResourceCollection.identityTransformer; - - public File getFile() - { + public File getFile() { return file; } - public void setFile( File file ) - { + public void setFile(File file) { this.file = file; - } - public String getPath() - { + public String getPath() { return path; } - public void setPath( String path ) - { + public void setPath(String path) { this.path = path; - } // return the file attributes of the uncompressed file // may be null. - protected abstract PlexusIoResourceAttributes getAttributes( File f ) - throws IOException; + protected abstract PlexusIoResourceAttributes getAttributes(File f) throws IOException; - public void setStreamTransformer( InputStreamTransformer streamTransformers ) - { + public void setStreamTransformer(InputStreamTransformer streamTransformers) { this.streamTransformers = streamTransformers; } - public Stream stream() - { - return new Stream() - { - public void forEach( PlexusIoResourceConsumer resourceConsumer ) - throws IOException - { + public Stream stream() { + return new Stream() { + public void forEach(PlexusIoResourceConsumer resourceConsumer) throws IOException { final Iterator it = getResources(); - while ( it.hasNext() ) - { - resourceConsumer.accept( it.next() ); + while (it.hasNext()) { + resourceConsumer.accept(it.next()); } - if ( it instanceof Closeable ) - { - ( (Closeable) it ).close(); + if (it instanceof Closeable) { + ((Closeable) it).close(); } } }; } - public Iterator getResources() - throws IOException - { + public Iterator getResources() throws IOException { final File f = getFile(); - final String p = ( getPath() == null ? getName( f ) : getPath() ).replace( '\\', '/' ); - if ( f == null ) - { - throw new IOException( "No archive file is set." ); + final String p = (getPath() == null ? getName(f) : getPath()).replace('\\', '/'); + if (f == null) { + throw new IOException("No archive file is set."); } - if ( !f.isFile() ) - { - throw new IOException( "The archive file " + f.getPath() + " does not exist or is no file." ); + if (!f.isFile()) { + throw new IOException("The archive file " + f.getPath() + " does not exist or is no file."); } - final PlexusIoResourceAttributes attributes = getAttributes( f ); + final PlexusIoResourceAttributes attributes = getAttributes(f); - final ContentSupplier contentSupplier = new ContentSupplier() - { + final ContentSupplier contentSupplier = new ContentSupplier() { @Nonnull - public InputStream getContents() - throws IOException - { - return getInputStream( f ); + public InputStream getContents() throws IOException { + return getInputStream(f); } }; - final PlexusIoResource resource = - ResourceFactory.createResource( f, p, contentSupplier, attributes ); + final PlexusIoResource resource = ResourceFactory.createResource(f, p, contentSupplier, attributes); - return Collections.singleton( resource ).iterator(); + return Collections.singleton(resource).iterator(); } - protected String getName( File file ) - throws IOException - { + protected String getName(File file) throws IOException { final String name = file.getPath(); final String ext = getDefaultExtension(); - if ( ext != null && ext.length() > 0 && name.endsWith( ext ) ) - { - return name.substring( 0, name.length() - ext.length() ); + if (ext != null && !ext.isEmpty() && name.endsWith(ext)) { + return name.substring(0, name.length() - ext.length()); } return name; } protected abstract String getDefaultExtension(); - protected abstract @Nonnull InputStream getInputStream( File file ) - throws IOException; + protected abstract @Nonnull InputStream getInputStream(File file) throws IOException; - public InputStream getInputStream( PlexusIoResource resource ) - throws IOException - { + public InputStream getInputStream(PlexusIoResource resource) throws IOException { InputStream contents = resource.getContents(); - return new ClosingInputStream( streamTransformers.transform( resource, contents ), contents ); + return new ClosingInputStream(streamTransformers.transform(resource, contents), contents); } - public PlexusIoResource resolve( final PlexusIoResource resource ) - throws IOException - { - final Deferred deferred = new Deferred( resource, this, streamTransformers - != AbstractPlexusIoResourceCollection.identityTransformer ); + public PlexusIoResource resolve(final PlexusIoResource resource) throws IOException { + final Deferred deferred = new Deferred( + resource, this, streamTransformers != AbstractPlexusIoResourceCollection.identityTransformer); return deferred.asResource(); } - - public Iterator iterator() - { - try - { + public Iterator iterator() { + try { return getResources(); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } - public String getName( PlexusIoResource resource ) - { + public String getName(PlexusIoResource resource) { return resource.getName(); } - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { File f = getFile(); return f == null ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : f.lastModified(); } - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { // There is a single resource in the collection so it is safe return true; } -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResource.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResource.java index c999a32c..dd262cb9 100755 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResource.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResource.java @@ -16,12 +16,15 @@ * limitations under the License. */ +import javax.annotation.Nonnull; + import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.nio.file.Files; import java.nio.file.attribute.FileTime; import org.apache.commons.io.IOUtils; @@ -34,113 +37,113 @@ import org.codehaus.plexus.components.io.functions.InputStreamTransformer; import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; -import javax.annotation.Nonnull; +import static java.util.Objects.requireNonNull; /** * Implementation of {@link PlexusIoResource} for files. */ -public class PlexusIoFileResource - extends AbstractPlexusIoResource - implements ResourceAttributeSupplier, FileSupplier +public class PlexusIoFileResource extends AbstractPlexusIoResource implements ResourceAttributeSupplier, FileSupplier { -{ @Nonnull private final File file; @Nonnull private final PlexusIoResourceAttributes attributes; + @Nonnull + private final FileAttributes fileAttributes; + private final ContentSupplier contentSupplier; private final DeferredFileOutputStream dfos; - protected PlexusIoFileResource( @Nonnull File file, @Nonnull String name, - @Nonnull PlexusIoResourceAttributes attrs ) - throws IOException - { - this( file, name, attrs, null, null ); + protected PlexusIoFileResource(@Nonnull File file, @Nonnull String name, @Nonnull PlexusIoResourceAttributes attrs) + throws IOException { + this(file, name, attrs, null, null); } - @SuppressWarnings( "ConstantConditions" ) - PlexusIoFileResource( @Nonnull final File file, @Nonnull String name, @Nonnull PlexusIoResourceAttributes attrs, - final ContentSupplier contentSupplier, final InputStreamTransformer streamTransformer ) - throws IOException - { - super( name, file.lastModified(), file.length(), file.isFile(), file.isDirectory(), file.exists() ); - this.file = file; + PlexusIoFileResource( + @Nonnull final File file, + @Nonnull String name, + @Nonnull PlexusIoResourceAttributes attrs, + final ContentSupplier contentSupplier, + final InputStreamTransformer streamTransformer) + throws IOException { + this(file, name, attrs, new FileAttributes(file, true), contentSupplier, streamTransformer); + } - this.contentSupplier = contentSupplier != null ? contentSupplier : getRootContentSupplier( file ); + PlexusIoFileResource( + @Nonnull final File file, + @Nonnull String name, + @Nonnull PlexusIoResourceAttributes attrs, + @Nonnull FileAttributes fileAttributes, + final ContentSupplier contentSupplier, + final InputStreamTransformer streamTransformer) + throws IOException { + super( + name, + fileAttributes.getLastModifiedTime().toMillis(), + fileAttributes.getSize(), + fileAttributes.isRegularFile(), + fileAttributes.isDirectory(), + fileAttributes.isRegularFile() + || fileAttributes.isDirectory() + || fileAttributes.isSymbolicLink() + || fileAttributes.isOther()); + this.file = file; + this.attributes = requireNonNull(attrs, "attributes is null for file " + file.getName()); + this.fileAttributes = requireNonNull(fileAttributes, "fileAttributes is null for file " + file.getName()); + this.contentSupplier = contentSupplier != null ? contentSupplier : getRootContentSupplier(file); boolean hasTransformer = streamTransformer != null && streamTransformer != identityTransformer; InputStreamTransformer transToUse = streamTransformer != null ? streamTransformer : identityTransformer; - dfos = hasTransformer && file.isFile() ? asDeferredStream( this.contentSupplier, transToUse, this ) : null; - if ( attrs == null ) - throw new IllegalArgumentException( "attrs is null for file " + file.getName() ); - this.attributes = attrs; + dfos = hasTransformer && file.isFile() ? asDeferredStream(this.contentSupplier, transToUse, this) : null; } - private static DeferredFileOutputStream asDeferredStream( @Nonnull ContentSupplier supplier, - @Nonnull InputStreamTransformer transToUse, - PlexusIoResource resource ) - throws IOException - { - DeferredFileOutputStream dfos = new DeferredFileOutputStream( 5000000, "p-archiver", null, null ); + private static DeferredFileOutputStream asDeferredStream( + @Nonnull ContentSupplier supplier, @Nonnull InputStreamTransformer transToUse, PlexusIoResource resource) + throws IOException { + DeferredFileOutputStream dfos = DeferredFileOutputStream.builder() + .setThreshold(5000000) + .setPrefix("p-archiver") + .get(); InputStream inputStream = supplier.getContents(); - InputStream transformed = transToUse.transform( resource, inputStream ); - IOUtils.copy( transformed, dfos ); - IOUtils.closeQuietly( inputStream ); - IOUtils.closeQuietly( transformed ); + InputStream transformed = transToUse.transform(resource, inputStream); + IOUtils.copy(transformed, dfos); + IOUtils.closeQuietly(inputStream); + IOUtils.closeQuietly(transformed); return dfos; } - private static ContentSupplier getRootContentSupplier( final File file ) - { - return new ContentSupplier() - { - public InputStream getContents() - throws IOException - { - return new FileInputStream( file ); - } - }; + private static ContentSupplier getRootContentSupplier(final File file) { + return () -> Files.newInputStream(file.toPath()); } - public static String getName( File file ) - { - return file.getPath().replace( '\\', '/' ); + public static String getName(File file) { + return file.getPath().replace('\\', '/'); } /** * Returns the resource file. */ @Nonnull - public File getFile() - { + public File getFile() { return file; } @Nonnull - public InputStream getContents() - throws IOException - { - if ( dfos == null ) - { + public InputStream getContents() throws IOException { + if (dfos == null) { return contentSupplier.getContents(); } - if ( dfos.isInMemory() ) - { - return new ByteArrayInputStream( dfos.getData() ); - } - else - { - return new FileInputStream( dfos.getFile() ) - { - @SuppressWarnings( "ResultOfMethodCallIgnored" ) + if (dfos.isInMemory()) { + return new ByteArrayInputStream(dfos.getData()); + } else { + return new FileInputStream(dfos.getFile()) { + @SuppressWarnings("ResultOfMethodCallIgnored") @Override - public void close() - throws IOException - { + public void close() throws IOException { super.close(); dfos.getFile().delete(); } @@ -149,81 +152,63 @@ public void close() } @Nonnull - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return getFile().toURI().toURL(); } - public long getSize() - { - if ( dfos == null ) - { - if ( attributes instanceof FileAttributes) - { - return ( ( FileAttributes ) attributes ).getSize(); - } - return getFile().length(); + public long getSize() { + if (dfos == null) { + return fileAttributes.getSize(); } - if ( dfos.isInMemory() ) - { + if (dfos.isInMemory()) { return dfos.getByteCount(); - } - else - { + } else { return dfos.getFile().length(); } } - public boolean isDirectory() - { - if ( attributes instanceof FileAttributes ) - { - return ( ( FileAttributes ) attributes ).isDirectory(); - } - return getFile().isDirectory(); + public boolean isDirectory() { + return fileAttributes.isDirectory(); } - public boolean isExisting() - { - if ( attributes instanceof FileAttributes ) - { + public boolean isExisting() { + if (attributes instanceof FileAttributes) { return true; } return getFile().exists(); } - public boolean isFile() - { - if ( attributes instanceof FileAttributes ) - { - return ( ( FileAttributes ) attributes ).isRegularFile(); - } - return getFile().isFile(); + public boolean isFile() { + return fileAttributes.isRegularFile(); } @Nonnull - public PlexusIoResourceAttributes getAttributes() - { + public PlexusIoResourceAttributes getAttributes() { return attributes; } - public long getLastModified() - { - if ( attributes instanceof FileAttributes ) - { - FileTime lastModified = ( ( FileAttributes ) attributes ).getLastModifiedTime(); - if ( lastModified != null ) - { - return lastModified.toMillis(); - } + @Nonnull + public FileAttributes getFileAttributes() { + return fileAttributes; + } + + public long getLastModified() { + FileTime lastModified = fileAttributes.getLastModifiedTime(); + if (lastModified != null) { + return lastModified.toMillis(); } - return AttributeUtils.getLastModified( getFile() ); + return AttributeUtils.getLastModified(getFile()); } - @Override public boolean isSymbolicLink() { + @Override + public boolean isSymbolicLink() { return getAttributes().isSymbolicLink(); } - private static final InputStreamTransformer identityTransformer = AbstractPlexusIoResourceCollection.identityTransformer; -} \ No newline at end of file + protected DeferredFileOutputStream getDfos() { + return dfos; + } + + private static final InputStreamTransformer identityTransformer = + AbstractPlexusIoResourceCollection.identityTransformer; +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResourceCollection.java index 75631f15..71dcc5f3 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoFileResourceCollection.java @@ -16,12 +16,7 @@ * limitations under the License. */ -import org.codehaus.plexus.components.io.attributes.FileAttributes; -import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; -import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes; -import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; -import org.codehaus.plexus.util.DirectoryScanner; -import org.codehaus.plexus.util.StringUtils; +import javax.inject.Named; import java.io.Closeable; import java.io.File; @@ -29,19 +24,24 @@ import java.io.InputStream; import java.util.ArrayList; import java.util.Comparator; -import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; +import org.codehaus.plexus.components.io.attributes.FileAttributes; +import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; +import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes; +import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; +import org.codehaus.plexus.util.DirectoryScanner; +import org.codehaus.plexus.util.StringUtils; + /** * Implementation of {@link PlexusIoResourceCollection} for the set * of files in a common directory. */ -public class PlexusIoFileResourceCollection - extends AbstractPlexusIoResourceCollectionWithAttributes -{ +@Named(PlexusIoFileResourceCollection.ROLE_HINT) +public class PlexusIoFileResourceCollection extends AbstractPlexusIoResourceCollectionWithAttributes { /** * Role hint of this component */ @@ -56,45 +56,33 @@ public class PlexusIoFileResourceCollection */ private Comparator filenameComparator; - public PlexusIoFileResourceCollection() - { - } + public PlexusIoFileResourceCollection() {} - - public PlexusIoResource resolve( final PlexusIoResource resource ) - throws IOException - { + public PlexusIoResource resolve(final PlexusIoResource resource) throws IOException { return resource; } - @Override - public InputStream getInputStream( PlexusIoResource resource ) - throws IOException - { + public InputStream getInputStream(PlexusIoResource resource) throws IOException { return resource.getContents(); } - @Override - public String getName( PlexusIoResource resource ) - { + public String getName(PlexusIoResource resource) { return resource.getName(); } /** * @param baseDir The base directory of the file collection */ - public void setBaseDir( File baseDir ) - { + public void setBaseDir(File baseDir) { this.baseDir = baseDir; } /** * @return Returns the file collections base directory. */ - public File getBaseDir() - { + public File getBaseDir() { return baseDir; } @@ -102,176 +90,149 @@ public File getBaseDir() * @return Returns, whether symbolic links should be followed. * Defaults to true. */ - public boolean isFollowingSymLinks() - { + public boolean isFollowingSymLinks() { return isFollowingSymLinks; } /** * @param pIsFollowingSymLinks whether symbolic links should be followed */ - @SuppressWarnings({ "UnusedDeclaration" }) - public void setFollowingSymLinks( boolean pIsFollowingSymLinks ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public void setFollowingSymLinks(boolean pIsFollowingSymLinks) { isFollowingSymLinks = pIsFollowingSymLinks; } - public void setDefaultAttributes( final int uid, final String userName, final int gid, final String groupName, - final int fileMode, final int dirMode ) - { - setDefaultFileAttributes( createDefaults( uid, userName, gid, groupName, fileMode ) ); + public void setDefaultAttributes( + final int uid, + final String userName, + final int gid, + final String groupName, + final int fileMode, + final int dirMode) { + setDefaultFileAttributes(createDefaults(uid, userName, gid, groupName, fileMode)); - setDefaultDirAttributes( createDefaults( uid, userName, gid, groupName, dirMode ) ); + setDefaultDirAttributes(createDefaults(uid, userName, gid, groupName, dirMode)); } - public void setOverrideAttributes( final int uid, final String userName, final int gid, final String groupName, - final int fileMode, final int dirMode ) - { - setOverrideFileAttributes( createDefaults( uid, userName, gid, groupName, fileMode ) ); + public void setOverrideAttributes( + final int uid, + final String userName, + final int gid, + final String groupName, + final int fileMode, + final int dirMode) { + setOverrideFileAttributes(createDefaults(uid, userName, gid, groupName, fileMode)); - setOverrideDirAttributes( createDefaults( uid, userName, gid, groupName, dirMode ) ); + setOverrideDirAttributes(createDefaults(uid, userName, gid, groupName, dirMode)); } - private static PlexusIoResourceAttributes createDefaults( final int uid, final String userName, final int gid, - final String groupName, final int mode ) - { - return new SimpleResourceAttributes( uid, userName, gid, groupName, - mode >= 0 ? mode : PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ); + private static PlexusIoResourceAttributes createDefaults( + final int uid, final String userName, final int gid, final String groupName, final int mode) { + return new SimpleResourceAttributes( + uid, userName, gid, groupName, mode >= 0 ? mode : PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE); } - @Override - public void setPrefix( String prefix ) - { + public void setPrefix(String prefix) { char nonSeparator = File.separatorChar == '/' ? '\\' : '/'; - super.setPrefix( StringUtils.replace( prefix, nonSeparator, File.separatorChar ) ); + super.setPrefix(StringUtils.replace(prefix, nonSeparator, File.separatorChar)); } - private void addResources( List result, String[] resources ) - throws IOException - { + private void addResources(List result, String[] resources) throws IOException { final File dir = getBaseDir(); - final HashMap cache1 = new HashMap<>(); - final HashMap cache2 = new HashMap<>(); - for ( String name : resources ) - { - String sourceDir = name.replace( '\\', '/' ); - File f = new File( dir, sourceDir ); + for (String name : resources) { + String sourceDir = name.replace('\\', '/'); + File f = new File(dir, sourceDir); - FileAttributes fattrs = new FileAttributes( f, cache1, cache2 ); - PlexusIoResourceAttributes attrs = mergeAttributes( fattrs, fattrs.isDirectory() ); + FileAttributes fattrs = new FileAttributes(f); + PlexusIoResourceAttributes attrs = mergeAttributes(fattrs, fattrs.isDirectory()); - String remappedName = getName( name ); + String remappedName = getName(name); PlexusIoResource resource = - ResourceFactory.createResource( f, remappedName, null, getStreamTransformer(), attrs ); + ResourceFactory.createResource(f, remappedName, null, getStreamTransformer(), attrs); - if ( isSelected( resource ) ) - { - result.add( resource ); + if (isSelected(resource)) { + result.add(resource); } } } - public Stream stream() - { - return new Stream() - { - public void forEach( PlexusIoResourceConsumer resourceConsumer ) - throws IOException - { + public Stream stream() { + return new Stream() { + public void forEach(PlexusIoResourceConsumer resourceConsumer) throws IOException { Iterator resources = getResources(); - while ( resources.hasNext() ) - { + while (resources.hasNext()) { PlexusIoResource next = resources.next(); - if ( isSelected( next ) ) - { - resourceConsumer.accept( next ); + if (isSelected(next)) { + resourceConsumer.accept(next); } } - if ( resources instanceof Closeable ) - { - ( (Closeable) resources ).close(); + if (resources instanceof Closeable) { + ((Closeable) resources).close(); } - } - public void forEach( ExecutorService es, final PlexusIoResourceConsumer resourceConsumer ) - throws IOException - { + public void forEach(ExecutorService es, final PlexusIoResourceConsumer resourceConsumer) + throws IOException { Iterator resources = getResources(); - while ( resources.hasNext() ) - { + while (resources.hasNext()) { final PlexusIoResource next = resources.next(); - Callable future = new Callable() - { - public Object call() - throws Exception - { - resourceConsumer.accept( next ); + Callable future = new Callable() { + public Object call() throws Exception { + resourceConsumer.accept(next); return this; } }; - es.submit( future ); + es.submit(future); } - if ( resources instanceof Closeable ) - { - ( (Closeable) resources ).close(); + if (resources instanceof Closeable) { + ((Closeable) resources).close(); } - } }; - } - public Iterator getResources() - throws IOException - { + public Iterator getResources() throws IOException { final DirectoryScanner ds = new DirectoryScanner(); final File dir = getBaseDir(); - ds.setBasedir( dir ); + ds.setBasedir(dir); final String[] inc = getIncludes(); - if ( inc != null && inc.length > 0 ) - { - ds.setIncludes( inc ); + if (inc != null && inc.length > 0) { + ds.setIncludes(inc); } final String[] exc = getExcludes(); - if ( exc != null && exc.length > 0 ) - { - ds.setExcludes( exc ); + if (exc != null && exc.length > 0) { + ds.setExcludes(exc); } - if ( isUsingDefaultExcludes() ) - { + if (isUsingDefaultExcludes()) { ds.addDefaultExcludes(); } - ds.setCaseSensitive( isCaseSensitive() ); - ds.setFollowSymlinks( isFollowingSymLinks() ); - ds.setFilenameComparator( filenameComparator ); + ds.setCaseSensitive(isCaseSensitive()); + ds.setFollowSymlinks(isFollowingSymLinks()); + ds.setFilenameComparator(filenameComparator); ds.scan(); final List result = new ArrayList<>(); - if ( isIncludingEmptyDirectories() ) - { + if (isIncludingEmptyDirectories()) { String[] dirs = ds.getIncludedDirectories(); - addResources( result, dirs ); + addResources(result, dirs); } String[] files = ds.getIncludedFiles(); - addResources( result, files ); + addResources(result, files); return result.iterator(); } - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { return true; } /** * @since 3.2.0 */ - public void setFilenameComparator( Comparator filenameComparator ) - { + public void setFilenameComparator(Comparator filenameComparator) { this.filenameComparator = filenameComparator; } } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResource.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResource.java index 887e84f7..7653744c 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResource.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResource.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; import java.net.URL; @@ -24,24 +26,20 @@ import org.codehaus.plexus.components.io.functions.ContentSupplier; import org.codehaus.plexus.components.io.functions.SizeSupplier; -import javax.annotation.Nonnull; - - /** * A resource is a file-like entity. It may be an actual file, * an URL, a zip entry, or something like that. */ -public interface PlexusIoResource extends FileInfo, SizeSupplier, ContentSupplier -{ +public interface PlexusIoResource extends FileInfo, SizeSupplier, ContentSupplier { /** * Unknown resource size. */ - public static final long UNKNOWN_RESOURCE_SIZE = -1; + long UNKNOWN_RESOURCE_SIZE = -1; /** * Unknown modification date */ - public static final long UNKNOWN_MODIFICATION_DATE = 0; + long UNKNOWN_MODIFICATION_DATE = 0; /** * Returns the date, when the resource was last modified, if known. @@ -61,7 +59,6 @@ public interface PlexusIoResource extends FileInfo, SizeSupplier, ContentSupplie */ long getSize(); - /** * Returns, whether the {@link FileInfo} refers to a file. */ @@ -76,7 +73,7 @@ public interface PlexusIoResource extends FileInfo, SizeSupplier, ContentSupplie * Creates an {@link java.io.InputStream}, which may be used to read * the files contents. This is useful, if the file selector * comes to a decision based on the files contents. - * + *

* Please note that this InputStream is unbuffered. Clients should wrap this in a * BufferedInputStream or attempt reading reasonably large chunks (8K+). */ @@ -90,4 +87,4 @@ public interface PlexusIoResource extends FileInfo, SizeSupplier, ContentSupplie * In the latter case, you are forced to use {@link #getContents()}. */ URL getURL() throws IOException; -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection.java index 3100d4d8..d4c2287f 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoResourceCollection.java @@ -23,19 +23,7 @@ /** * A resource collection is a set of {@link PlexusIoResource} instances. */ -public interface PlexusIoResourceCollection extends Iterable -{ - /** - * Role of the ResourceCollection component. - */ - public static final String ROLE = PlexusIoResourceCollection.class.getName(); - - /** - * Role hint of the default resource collection, which is a set - * of files in a base directory. - */ - public static final String DEFAULT_ROLE_HINT = "default"; - +public interface PlexusIoResourceCollection extends Iterable { /** * Returns an iterator over the resources in the collection. * @return An iterator @@ -47,7 +35,7 @@ public interface PlexusIoResourceCollection extends Iterable * Returns the resources as a stream. * @return A stream for functional iteration */ - public Stream stream(); + Stream stream(); /** * Returns the resources suggested name. This is used for @@ -56,7 +44,7 @@ public interface PlexusIoResourceCollection extends Iterable * calling {@link #getResources()}. * @return The resource name. If it is a file, it should be normalized to platform separators */ - String getName( PlexusIoResource resource ); + String getName(PlexusIoResource resource); /** * Returns the collections last modification time. For a @@ -77,7 +65,7 @@ public interface PlexusIoResourceCollection extends Iterable * @return A possibly transformed resource * @throws IOException when something goes bad */ - InputStream getInputStream( PlexusIoResource resource ) throws IOException; + InputStream getInputStream(PlexusIoResource resource) throws IOException; /** * Resolves the supplied resource into a "real" resource. Resolving @@ -87,7 +75,7 @@ public interface PlexusIoResourceCollection extends Iterable * @return A possibly transformed resource * @throws IOException when something goes bad */ - PlexusIoResource resolve( PlexusIoResource resource ) throws IOException; + PlexusIoResource resolve(PlexusIoResource resource) throws IOException; /** * Indicates if this collection supports concurrent access to its resources. @@ -107,5 +95,4 @@ public interface PlexusIoResourceCollection extends Iterable * otherwise {@code false} */ boolean isConcurrentAccessSupported(); - -} \ No newline at end of file +} diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoSymlinkResource.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoSymlinkResource.java index 05a24cfd..1c6b867d 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoSymlinkResource.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoSymlinkResource.java @@ -1,29 +1,90 @@ package org.codehaus.plexus.components.io.resources; -import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; -import org.codehaus.plexus.components.io.attributes.SymlinkUtils; -import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; - import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; +import java.nio.file.Path; + +import org.apache.commons.io.output.DeferredFileOutputStream; +import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; +import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; + +public class PlexusIoSymlinkResource extends PlexusIoFileResource implements SymlinkDestinationSupplier { + private final String symLinkDestination; + private final PlexusIoFileResource targetResource; + + PlexusIoSymlinkResource(@Nonnull File symlinkfile, String name, @Nonnull PlexusIoResourceAttributes attrs) + throws IOException { + this(symlinkfile, name, attrs, symlinkfile.toPath()); + } + + PlexusIoSymlinkResource( + @Nonnull File symlinkfile, String name, @Nonnull PlexusIoResourceAttributes attrs, Path linkPath) + throws IOException { + this(symlinkfile, name, attrs, linkPath, java.nio.file.Files.readSymbolicLink(linkPath)); + } + + private PlexusIoSymlinkResource( + @Nonnull File symlinkfile, String name, @Nonnull PlexusIoResourceAttributes attrs, Path path, Path linkPath) + throws IOException { + this(symlinkfile, name, attrs, linkPath.toString(), (PlexusIoFileResource) + ResourceFactory.createResource(path.resolveSibling(linkPath).toFile())); + } -public class PlexusIoSymlinkResource - extends PlexusIoFileResource - implements SymlinkDestinationSupplier -{ - private final File symnlinkDestination; + private PlexusIoSymlinkResource( + @Nonnull File symlinkfile, + String name, + @Nonnull PlexusIoResourceAttributes attrs, + String symLinkDestination, + PlexusIoFileResource targetResource) + throws IOException { + super(symlinkfile, name, attrs, targetResource.getFileAttributes(), null, null); + this.symLinkDestination = symLinkDestination; + this.targetResource = targetResource; + } + + public String getSymlinkDestination() throws IOException { + return symLinkDestination; + } + + public PlexusIoResource getTarget() { + return targetResource; + } + + public PlexusIoResource getLink() throws IOException { + return new PlexusIoFileResource(getFile(), getName(), getAttributes()); + } + + @Override + public long getSize() { + DeferredFileOutputStream dfos = getDfos(); + if (dfos == null) { + return targetResource.getSize(); + } else if (dfos.isInMemory()) { + return dfos.getByteCount(); + } else { + return dfos.getFile().length(); + } + } + + @Override + public boolean isDirectory() { + return targetResource.isDirectory(); + } + + @Override + public boolean isExisting() { + return targetResource.isExisting(); + } - PlexusIoSymlinkResource( @Nonnull File symlinkfile, String name, @Nonnull PlexusIoResourceAttributes attrs ) - throws IOException - { - super( symlinkfile, name, attrs ); - this.symnlinkDestination = null; + @Override + public boolean isFile() { + return targetResource.isFile(); } - public String getSymlinkDestination() - throws IOException - { - return symnlinkDestination == null ? SymlinkUtils.readSymbolicLink( getFile() ).getPath() : symnlinkDestination.getPath(); + @Override + public long getLastModified() { + return targetResource.getLastModified(); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoURLResource.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoURLResource.java index d840b9e7..6a414b7b 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoURLResource.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoURLResource.java @@ -17,41 +17,36 @@ */ import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; -public abstract class PlexusIoURLResource - extends AbstractPlexusIoResource -{ - protected PlexusIoURLResource( @Nonnull String name, long lastModified, long size, boolean isFile, - boolean isDirectory, boolean isExisting ) - { - super( name, lastModified, size, isFile, isDirectory, isExisting ); +public abstract class PlexusIoURLResource extends AbstractPlexusIoResource { + protected PlexusIoURLResource( + @Nonnull String name, + long lastModified, + long size, + boolean isFile, + boolean isDirectory, + boolean isExisting) { + super(name, lastModified, size, isFile, isDirectory, isExisting); } @Nonnull - public InputStream getContents() - throws IOException - { + public InputStream getContents() throws IOException { final URL url = getURL(); - try - { + try { URLConnection uc = url.openConnection(); - uc.setUseCaches( false ); + uc.setUseCaches(false); return uc.getInputStream(); - } - catch ( IOException e ) - { - IOException ex = new IOException( getDescriptionForError( url ) ); - ex.initCause( e ); - throw ex; + } catch (IOException e) { + throw new IOException(getDescriptionForError(url), e); } } - public String getDescriptionForError( URL url ) - { + public String getDescriptionForError(URL url) { return url != null ? url.toExternalForm() : "url=null"; } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/ResourceFactory.java b/src/main/java/org/codehaus/plexus/components/io/resources/ResourceFactory.java index a482a32a..8db319b4 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/ResourceFactory.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/ResourceFactory.java @@ -1,60 +1,56 @@ package org.codehaus.plexus.components.io.resources; +import java.io.File; +import java.io.IOException; + +import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.functions.ContentSupplier; import org.codehaus.plexus.components.io.functions.InputStreamTransformer; -import java.io.File; -import java.io.IOException; - import static org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributeUtils.getFileAttributes; import static org.codehaus.plexus.components.io.resources.PlexusIoFileResource.getName; /** * @author Kristian Rosenvold */ -public class ResourceFactory -{ - public static PlexusIoResource createResource( File f ) - throws IOException - { - return createResource( f, getName( f ), null, null, getFileAttributes( f ) ); +public class ResourceFactory { + public static PlexusIoResource createResource(File f) throws IOException { + return createResource(f, getName(f), null, null, getFileAttributes(f)); } - public static PlexusIoResource createResource( File f, String name ) - throws IOException - { - return createResource( f, name, null, null, getFileAttributes( f ) ); + public static PlexusIoResource createResource(File f, String name) throws IOException { + return createResource(f, name, null, null, getFileAttributes(f)); } - public static PlexusIoResource createResource( File f, String name, final ContentSupplier contentSupplier, - PlexusIoResourceAttributes attributes ) - throws IOException - { - return createResource( f, name, contentSupplier, null, attributes ); + public static PlexusIoResource createResource( + File f, String name, final ContentSupplier contentSupplier, PlexusIoResourceAttributes attributes) + throws IOException { + return createResource(f, name, contentSupplier, null, attributes); } - public static PlexusIoResource createResource( File f, InputStreamTransformer inputStreamTransformer ) - throws IOException - { - return createResource( f, getName( f ), null, inputStreamTransformer, getFileAttributes( f ) ); + public static PlexusIoResource createResource(File f, InputStreamTransformer inputStreamTransformer) + throws IOException { + return createResource(f, getName(f), null, inputStreamTransformer, getFileAttributes(f)); } - public static PlexusIoResource createResource( File f, String name, final ContentSupplier contentSupplier, - InputStreamTransformer inputStreamTransformer ) - throws IOException - { - return createResource( f, name, contentSupplier, inputStreamTransformer, getFileAttributes( f ) ); + public static PlexusIoResource createResource( + File f, String name, final ContentSupplier contentSupplier, InputStreamTransformer inputStreamTransformer) + throws IOException { + return createResource(f, name, contentSupplier, inputStreamTransformer, getFileAttributes(f)); } - public static PlexusIoResource createResource( File f, String name, final ContentSupplier contentSupplier, - InputStreamTransformer inputStreamTransformer, - PlexusIoResourceAttributes attributes ) - throws IOException - { + public static PlexusIoResource createResource( + File f, + String name, + final ContentSupplier contentSupplier, + InputStreamTransformer inputStreamTransformer, + PlexusIoResourceAttributes attributes) + throws IOException { boolean symbolicLink = attributes.isSymbolicLink(); - return symbolicLink ? new PlexusIoSymlinkResource( f, name, attributes ) - : new PlexusIoFileResource(f, name, attributes, contentSupplier, inputStreamTransformer); + return symbolicLink + ? new PlexusIoSymlinkResource(f, name, attributes) + : new PlexusIoFileResource( + f, name, attributes, new FileAttributes(f, true), contentSupplier, inputStreamTransformer); } - } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/Stream.java b/src/main/java/org/codehaus/plexus/components/io/resources/Stream.java index e3576d1f..ab6946e3 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/Stream.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/Stream.java @@ -15,17 +15,15 @@ * limitations under the License. */ -import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; - import java.io.IOException; -public interface Stream -{ +import org.codehaus.plexus.components.io.functions.PlexusIoResourceConsumer; + +public interface Stream { /** * Invokes the #PlexusIoResourceConsumer for each resource in this collection * @param resourceConsumer The consumer of the resource * @throws java.io.IOException . */ - public void forEach( PlexusIoResourceConsumer resourceConsumer ) throws IOException; - + void forEach(PlexusIoResourceConsumer resourceConsumer) throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ForwardingIterator.java b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ForwardingIterator.java index 37b5c9a8..cb077018 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ForwardingIterator.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ForwardingIterator.java @@ -15,45 +15,35 @@ */ package org.codehaus.plexus.components.io.resources.proxy; -import org.codehaus.plexus.components.io.resources.PlexusIoResource; - import java.io.Closeable; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; -abstract class ForwardingIterator - implements Iterator, Closeable -{ +import org.codehaus.plexus.components.io.resources.PlexusIoResource; + +abstract class ForwardingIterator implements Iterator, Closeable { private final Object possiblyCloseable; private PlexusIoResource next = null; - ForwardingIterator( Object possiblyCloseable ) - { + ForwardingIterator(Object possiblyCloseable) { this.possiblyCloseable = possiblyCloseable; } - public boolean hasNext() - { - if ( next == null ) - { - try - { + public boolean hasNext() { + if (next == null) { + try { next = getNextResource(); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + } catch (IOException e) { + throw new RuntimeException(e); } } return next != null; } - public PlexusIoResource next() - { - if ( !hasNext() ) - { + public PlexusIoResource next() { + if (!hasNext()) { throw new NoSuchElementException(); } PlexusIoResource ret = next; @@ -61,19 +51,14 @@ public PlexusIoResource next() return ret; } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } - public void close() - throws IOException - { - if ( possiblyCloseable instanceof Closeable ) - { - ( (Closeable) possiblyCloseable ).close(); + public void close() throws IOException { + if (possiblyCloseable instanceof Closeable) { + ((Closeable) possiblyCloseable).close(); } - } /** diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollection.java index 61c16d80..ffa94301 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollection.java @@ -16,6 +16,12 @@ * limitations under the License. */ +import javax.annotation.Nonnull; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Iterator; + import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes; import org.codehaus.plexus.components.io.filemappers.FileMapper; @@ -31,174 +37,143 @@ import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; import org.codehaus.plexus.components.io.resources.Stream; -import javax.annotation.Nonnull; -import java.io.IOException; -import java.nio.charset.Charset; -import java.util.Iterator; - /** * Implementation of {@link PlexusIoResourceCollection} for an archives contents. */ -public class PlexusIoProxyResourceCollection - extends AbstractPlexusIoResourceCollectionWithAttributes implements EncodingSupported -{ - private PlexusIoResourceCollection src; - +public class PlexusIoProxyResourceCollection extends AbstractPlexusIoResourceCollectionWithAttributes + implements EncodingSupported { + private final PlexusIoResourceCollection src; - public PlexusIoProxyResourceCollection( @Nonnull PlexusIoResourceCollection src ) - { + public PlexusIoProxyResourceCollection(@Nonnull PlexusIoResourceCollection src) { this.src = src; } /** * Returns the archive to read. */ - public PlexusIoResourceCollection getSrc() - { + public PlexusIoResourceCollection getSrc() { return src; } - public void setDefaultAttributes( final int uid, final String userName, final int gid, final String groupName, - final int fileMode, final int dirMode ) - { - setDefaultFileAttributes( new SimpleResourceAttributes( uid, userName, gid, groupName, fileMode ) ); + public void setDefaultAttributes( + final int uid, + final String userName, + final int gid, + final String groupName, + final int fileMode, + final int dirMode) { + setDefaultFileAttributes(new SimpleResourceAttributes(uid, userName, gid, groupName, fileMode)); - setDefaultDirAttributes( new SimpleResourceAttributes( uid, userName, gid, groupName, dirMode ) ); + setDefaultDirAttributes(new SimpleResourceAttributes(uid, userName, gid, groupName, dirMode)); } - public void setOverrideAttributes( final int uid, final String userName, final int gid, final String groupName, - final int fileMode, final int dirMode ) - { - setOverrideFileAttributes( new SimpleResourceAttributes( uid, userName, gid, groupName, fileMode ) ); + public void setOverrideAttributes( + final int uid, + final String userName, + final int gid, + final String groupName, + final int fileMode, + final int dirMode) { + setOverrideFileAttributes(new SimpleResourceAttributes(uid, userName, gid, groupName, fileMode)); - setOverrideDirAttributes( new SimpleResourceAttributes( uid, userName, gid, groupName, dirMode ) ); + setOverrideDirAttributes(new SimpleResourceAttributes(uid, userName, gid, groupName, dirMode)); } @Override - public void setStreamTransformer( InputStreamTransformer streamTransformer ) - { - if ( src instanceof AbstractPlexusIoResourceCollection ) - { - ( (AbstractPlexusIoResourceCollection) src ).setStreamTransformer( streamTransformer ); + public void setStreamTransformer(InputStreamTransformer streamTransformer) { + if (src instanceof AbstractPlexusIoResourceCollection) { + ((AbstractPlexusIoResourceCollection) src).setStreamTransformer(streamTransformer); } - super.setStreamTransformer( streamTransformer ); + super.setStreamTransformer(streamTransformer); } - protected FileSelector getDefaultFileSelector() - { + protected FileSelector getDefaultFileSelector() { final IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); - fileSelector.setIncludes( getIncludes() ); - fileSelector.setExcludes( getExcludes() ); - fileSelector.setCaseSensitive( isCaseSensitive() ); - fileSelector.setUseDefaultExcludes( isUsingDefaultExcludes() ); + fileSelector.setIncludes(getIncludes()); + fileSelector.setExcludes(getExcludes()); + fileSelector.setCaseSensitive(isCaseSensitive()); + fileSelector.setUseDefaultExcludes(isUsingDefaultExcludes()); return fileSelector; } - private String getNonEmptyPrfix() - { + private String getNonEmptyPrfix() { String prefix = getPrefix(); - if ( prefix != null && prefix.length() == 0 ) - { + if (prefix != null && prefix.isEmpty()) { return null; } return prefix; - } - class FwdIterator - extends ForwardingIterator - { - Iterator iter; + class FwdIterator extends ForwardingIterator { + final Iterator iter; private final FileSelector fileSelector = getDefaultFileSelector(); private final String prefix = getNonEmptyPrfix(); - FwdIterator( Iterator resources ) - { - super( resources ); + FwdIterator(Iterator resources) { + super(resources); this.iter = resources; } /** * Returns the next resource or null if no next resource; */ - protected PlexusIoResource getNextResource() - throws IOException - { - if ( !iter.hasNext() ) - return null; + protected PlexusIoResource getNextResource() throws IOException { + if (!iter.hasNext()) return null; PlexusIoResource plexusIoResource = iter.next(); - while ( ( !fileSelector.isSelected( plexusIoResource ) || !isSelected( plexusIoResource ) ) - || ( plexusIoResource.isDirectory() && !isIncludingEmptyDirectories() ) ) - { - if ( !iter.hasNext() ) - return null; + while ((!fileSelector.isSelected(plexusIoResource) || !isSelected(plexusIoResource)) + || (plexusIoResource.isDirectory() && !isIncludingEmptyDirectories())) { + if (!iter.hasNext()) return null; plexusIoResource = iter.next(); } PlexusIoResourceAttributes attrs = null; - if ( plexusIoResource instanceof ResourceAttributeSupplier ) - { - attrs = ( (ResourceAttributeSupplier) plexusIoResource ).getAttributes(); + if (plexusIoResource instanceof ResourceAttributeSupplier) { + attrs = ((ResourceAttributeSupplier) plexusIoResource).getAttributes(); } - if ( attrs == null ) - { + if (attrs == null) { attrs = SimpleResourceAttributes.lastResortDummyAttributesForBrokenOS(); } - attrs = mergeAttributes( attrs, plexusIoResource.isDirectory() ); + attrs = mergeAttributes(attrs, plexusIoResource.isDirectory()); - if ( prefix != null ) - { + if (prefix != null) { final String name = plexusIoResource.getName(); final PlexusIoResourceAttributes attrs2 = attrs; - DualSupplier supplier = new DualSupplier() - { - public String getName() - { + DualSupplier supplier = new DualSupplier() { + public String getName() { return prefix + name; } - public PlexusIoResourceAttributes getAttributes() - { + public PlexusIoResourceAttributes getAttributes() { return attrs2; } }; - plexusIoResource = ProxyFactory.createProxy( plexusIoResource, supplier ); + plexusIoResource = ProxyFactory.createProxy(plexusIoResource, supplier); } return plexusIoResource; } } - public Stream stream() - { + public Stream stream() { return getSrc().stream(); } - public Iterator getResources() - throws IOException - { - return new FwdIterator( getSrc().getResources() ); + public Iterator getResources() throws IOException { + return new FwdIterator(getSrc().getResources()); } - abstract static class DualSupplier - implements NameSupplier, ResourceAttributeSupplier - { - - } + abstract static class DualSupplier implements NameSupplier, ResourceAttributeSupplier {} - public String getName( final PlexusIoResource resource ) - { + public String getName(final PlexusIoResource resource) { String name = resource.getName(); final FileMapper[] mappers = getFileMappers(); - if ( mappers != null ) - { - for ( FileMapper mapper : mappers ) - { - name = mapper.getMappedFileName( name ); + if (mappers != null) { + for (FileMapper mapper : mappers) { + name = mapper.getMappedFileName(name); } } /* @@ -208,22 +183,17 @@ public String getName( final PlexusIoResource resource ) return name; } - public long getLastModified() - throws IOException - { + public long getLastModified() throws IOException { return src.getLastModified(); } - public void setEncoding( Charset charset ) - { - if ( src instanceof EncodingSupported ) - { - ( (EncodingSupported) src ).setEncoding( charset ); + public void setEncoding(Charset charset) { + if (src instanceof EncodingSupported) { + ((EncodingSupported) src).setEncoding(charset); } } - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { return src.isConcurrentAccessSupported(); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactory.java b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactory.java index 4b4bf9bd..3670a2e5 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactory.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactory.java @@ -15,32 +15,29 @@ */ package org.codehaus.plexus.components.io.resources.proxy; -import org.codehaus.plexus.components.io.functions.FileSupplier; -import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; -import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; -import org.codehaus.plexus.components.io.resources.PlexusIoResource; - import javax.annotation.Nonnull; + import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.List; -public class ProxyFactory -{ - public static PlexusIoResource createProxy( @Nonnull PlexusIoResource target, Object alternateSupplier ) - { +import org.codehaus.plexus.components.io.functions.FileSupplier; +import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; +import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; +import org.codehaus.plexus.components.io.resources.PlexusIoResource; + +public class ProxyFactory { + public static PlexusIoResource createProxy(@Nonnull PlexusIoResource target, Object alternateSupplier) { List interfaces = new ArrayList<>(); - interfaces.add( PlexusIoResource.class ); - if ( target instanceof SymlinkDestinationSupplier ) - interfaces.add( SymlinkDestinationSupplier.class ); - if ( target instanceof FileSupplier ) - interfaces.add( FileSupplier.class ); - if ( target instanceof ResourceAttributeSupplier ) - interfaces.add( ResourceAttributeSupplier.class ); + interfaces.add(PlexusIoResource.class); + if (target instanceof SymlinkDestinationSupplier) interfaces.add(SymlinkDestinationSupplier.class); + if (target instanceof FileSupplier) interfaces.add(FileSupplier.class); + if (target instanceof ResourceAttributeSupplier) interfaces.add(ResourceAttributeSupplier.class); - return (PlexusIoResource) Proxy.newProxyInstance( PlexusIoResource.class.getClassLoader(), - interfaces.toArray( new Class[0] ), - new ResourceInvocationHandler( target, alternateSupplier ) ); + return (PlexusIoResource) Proxy.newProxyInstance( + PlexusIoResource.class.getClassLoader(), + interfaces.toArray(new Class[0]), + new ResourceInvocationHandler(target, alternateSupplier)); } } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ResourceInvocationHandler.java b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ResourceInvocationHandler.java index d8601757..7ac62cec 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ResourceInvocationHandler.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/proxy/ResourceInvocationHandler.java @@ -15,6 +15,11 @@ */ package org.codehaus.plexus.components.io.resources.proxy; +import javax.annotation.Nonnull; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; + import org.codehaus.plexus.components.io.functions.ContentSupplier; import org.codehaus.plexus.components.io.functions.NameSupplier; import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; @@ -22,14 +27,8 @@ import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -import javax.annotation.Nonnull; -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -class ResourceInvocationHandler - implements InvocationHandler -{ - private PlexusIoResource testImpl; +class ResourceInvocationHandler implements InvocationHandler { + private final PlexusIoResource testImpl; private final ContentSupplier contentSupplier; private final NameSupplier nameSupplier; @@ -37,53 +36,40 @@ class ResourceInvocationHandler private final SymlinkDestinationSupplier symlinkDestinationSupplier; private final ResourceAttributeSupplier resourceAttributeSupplier; - public ResourceInvocationHandler( @Nonnull PlexusIoResource target, Object alternativeHandler ) - { + public ResourceInvocationHandler(@Nonnull PlexusIoResource target, Object alternativeHandler) { this.testImpl = target; - this.contentSupplier = asOrNull( alternativeHandler, ContentSupplier.class ); - this.nameSupplier = asOrNull( alternativeHandler, NameSupplier.class ); - this.sizeSupplier = asOrNull( alternativeHandler, SizeSupplier.class ); - this.symlinkDestinationSupplier = asOrNull( alternativeHandler, SymlinkDestinationSupplier.class ); - this.resourceAttributeSupplier = asOrNull( alternativeHandler, ResourceAttributeSupplier.class ); - + this.contentSupplier = asOrNull(alternativeHandler, ContentSupplier.class); + this.nameSupplier = asOrNull(alternativeHandler, NameSupplier.class); + this.sizeSupplier = asOrNull(alternativeHandler, SizeSupplier.class); + this.symlinkDestinationSupplier = asOrNull(alternativeHandler, SymlinkDestinationSupplier.class); + this.resourceAttributeSupplier = asOrNull(alternativeHandler, ResourceAttributeSupplier.class); } - @SuppressWarnings( "unchecked" ) - private static T asOrNull( Object instance, Class clazz ) - { - if ( instance != null && clazz.isAssignableFrom( instance.getClass() ) ) - return (T) instance; - else - return null; + @SuppressWarnings("unchecked") + private static T asOrNull(Object instance, Class clazz) { + if (instance != null && clazz.isAssignableFrom(instance.getClass())) return (T) instance; + else return null; } - public Object invoke( Object proxy, Method method, Object[] args ) - throws Throwable - { + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String name = method.getName(); - if ( contentSupplier != null && "getContents".equals( name ) ) - { + if (contentSupplier != null && "getContents".equals(name)) { return contentSupplier.getContents(); } - if ( nameSupplier != null && "getName".equals( name ) ) - { + if (nameSupplier != null && "getName".equals(name)) { return nameSupplier.getName(); } - if ( sizeSupplier != null && "getSize".equals( name ) ) - { + if (sizeSupplier != null && "getSize".equals(name)) { return sizeSupplier.getSize(); } - if ( symlinkDestinationSupplier != null && "getSymlinkDestination".equals( name ) ) - { + if (symlinkDestinationSupplier != null && "getSymlinkDestination".equals(name)) { return symlinkDestinationSupplier.getSymlinkDestination(); } - if ( resourceAttributeSupplier != null && "getAttributes".equals( name ) ) - { + if (resourceAttributeSupplier != null && "getAttributes".equals(name)) { return resourceAttributeSupplier.getAttributes(); } - return method.invoke( testImpl, args ); + return method.invoke(testImpl, args); } } - diff --git a/src/main/resources/META-INF/plexus/components.xml b/src/main/resources/META-INF/plexus/components.xml deleted file mode 100644 index 544289a7..00000000 --- a/src/main/resources/META-INF/plexus/components.xml +++ /dev/null @@ -1,95 +0,0 @@ - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - identity - org.codehaus.plexus.components.io.filemappers.IdentityMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - default - org.codehaus.plexus.components.io.filemappers.IdentityMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - fileExtension - org.codehaus.plexus.components.io.filemappers.FileExtensionMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - flatten - org.codehaus.plexus.components.io.filemappers.FlattenFileMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - merge - org.codehaus.plexus.components.io.filemappers.MergeFileMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - prefix - org.codehaus.plexus.components.io.filemappers.PrefixFileMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - suffix - org.codehaus.plexus.components.io.filemappers.SuffixFileMapper - per-lookup - - - - org.codehaus.plexus.components.io.filemappers.FileMapper - regexp - org.codehaus.plexus.components.io.filemappers.RegExpFileMapper - per-lookup - - - - - org.codehaus.plexus.components.io.fileselectors.FileSelector - default - org.codehaus.plexus.components.io.fileselectors.AllFilesFileSelector - singleton - - - - org.codehaus.plexus.components.io.fileselectors.FileSelector - all - org.codehaus.plexus.components.io.fileselectors.AllFilesFileSelector - singleton - - - - org.codehaus.plexus.components.io.fileselectors.FileSelector - standard - org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector - singleton - - - - - org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection - default - org.codehaus.plexus.components.io.resources.PlexusIoFileResourceCollection - per-lookup - - - org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection - files - org.codehaus.plexus.components.io.resources.PlexusIoFileResourceCollection - per-lookup - - - diff --git a/src/site/site.xml b/src/site/site.xml index 6731ab96..c4497389 100644 --- a/src/site/site.xml +++ b/src/site/site.xml @@ -1,8 +1,8 @@ - + +

@@ -16,4 +16,4 @@ - + diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/AbstractResourceAttributesTCK.java b/src/test/java/org/codehaus/plexus/components/io/attributes/AbstractResourceAttributesTCK.java index 0e0351ba..50daec39 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/AbstractResourceAttributesTCK.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/AbstractResourceAttributesTCK.java @@ -16,101 +16,95 @@ * limitations under the License. */ -import junit.framework.TestCase; - -public abstract class AbstractResourceAttributesTCK - extends TestCase -{ - - protected AbstractResourceAttributesTCK() - { - } - - protected abstract PlexusIoResourceAttributes newAttributes( int mode ); +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public abstract class AbstractResourceAttributesTCK { - protected abstract PlexusIoResourceAttributes newAttributes( String mode ); + protected AbstractResourceAttributesTCK() {} + protected abstract PlexusIoResourceAttributes newAttributes(int mode); - public final void testSetOctalModeString_OwnerModes() - { - verifyStringOctalModeSet( "700", new boolean[] { true, true, true, false, false, false, false, false, false } ); - verifyStringOctalModeSet( "600", new boolean[] { true, true, false, false, false, false, false, false, false } ); - verifyStringOctalModeSet( "400", new boolean[] { true, false, false, false, false, false, false, false, false } ); - verifyStringOctalModeSet( "200", new boolean[] { false, true, false, false, false, false, false, false, false } ); + protected abstract PlexusIoResourceAttributes newAttributes(String mode); + + @Test + final void testSetOctalModeString_OwnerModes() { + verifyStringOctalModeSet("700", new boolean[] {true, true, true, false, false, false, false, false, false}); + verifyStringOctalModeSet("600", new boolean[] {true, true, false, false, false, false, false, false, false}); + verifyStringOctalModeSet("400", new boolean[] {true, false, false, false, false, false, false, false, false}); + verifyStringOctalModeSet("200", new boolean[] {false, true, false, false, false, false, false, false, false}); } - public final void testSetOctalModeString_GroupModes() - { - verifyStringOctalModeSet( "070", new boolean[] { false, false, false, true, true, true, false, false, false } ); - verifyStringOctalModeSet( "060", new boolean[] { false, false, false, true, true, false, false, false, false } ); - verifyStringOctalModeSet( "040", new boolean[] { false, false, false, true, false, false, false, false, false } ); - verifyStringOctalModeSet( "020", new boolean[] { false, false, false, false, true, false, false, false, false } ); + @Test + final void testSetOctalModeString_GroupModes() { + verifyStringOctalModeSet("070", new boolean[] {false, false, false, true, true, true, false, false, false}); + verifyStringOctalModeSet("060", new boolean[] {false, false, false, true, true, false, false, false, false}); + verifyStringOctalModeSet("040", new boolean[] {false, false, false, true, false, false, false, false, false}); + verifyStringOctalModeSet("020", new boolean[] {false, false, false, false, true, false, false, false, false}); } - public final void testSetOctalModeString_WorldModes() - { - verifyStringOctalModeSet( "007", new boolean[] { false, false, false, false, false, false, true, true, true } ); - verifyStringOctalModeSet( "006", new boolean[] { false, false, false, false, false, false, true, true, false } ); - verifyStringOctalModeSet( "004", new boolean[] { false, false, false, false, false, false, true, false, false } ); - verifyStringOctalModeSet( "002", new boolean[] { false, false, false, false, false, false, false, true, false } ); + @Test + final void testSetOctalModeString_WorldModes() { + verifyStringOctalModeSet("007", new boolean[] {false, false, false, false, false, false, true, true, true}); + verifyStringOctalModeSet("006", new boolean[] {false, false, false, false, false, false, true, true, false}); + verifyStringOctalModeSet("004", new boolean[] {false, false, false, false, false, false, true, false, false}); + verifyStringOctalModeSet("002", new boolean[] {false, false, false, false, false, false, false, true, false}); } - public final void testSetOctalMode_OwnerModes() - { - verifyOctalModeSet( "700", new boolean[] { true, true, true, false, false, false, false, false, false } ); - verifyOctalModeSet( "600", new boolean[] { true, true, false, false, false, false, false, false, false } ); - verifyOctalModeSet( "400", new boolean[] { true, false, false, false, false, false, false, false, false } ); - verifyOctalModeSet( "200", new boolean[] { false, true, false, false, false, false, false, false, false } ); + @Test + final void testSetOctalMode_OwnerModes() { + verifyOctalModeSet("700", new boolean[] {true, true, true, false, false, false, false, false, false}); + verifyOctalModeSet("600", new boolean[] {true, true, false, false, false, false, false, false, false}); + verifyOctalModeSet("400", new boolean[] {true, false, false, false, false, false, false, false, false}); + verifyOctalModeSet("200", new boolean[] {false, true, false, false, false, false, false, false, false}); } - public final void testSetOctalMode_GroupModes() - { - verifyOctalModeSet( "070", new boolean[] { false, false, false, true, true, true, false, false, false } ); - verifyOctalModeSet( "060", new boolean[] { false, false, false, true, true, false, false, false, false } ); - verifyOctalModeSet( "040", new boolean[] { false, false, false, true, false, false, false, false, false } ); - verifyOctalModeSet( "020", new boolean[] { false, false, false, false, true, false, false, false, false } ); + @Test + final void testSetOctalMode_GroupModes() { + verifyOctalModeSet("070", new boolean[] {false, false, false, true, true, true, false, false, false}); + verifyOctalModeSet("060", new boolean[] {false, false, false, true, true, false, false, false, false}); + verifyOctalModeSet("040", new boolean[] {false, false, false, true, false, false, false, false, false}); + verifyOctalModeSet("020", new boolean[] {false, false, false, false, true, false, false, false, false}); } - public final void testSetOctalMode_WorldModes() - { - verifyOctalModeSet( "007", new boolean[] { false, false, false, false, false, false, true, true, true } ); - verifyOctalModeSet( "006", new boolean[] { false, false, false, false, false, false, true, true, false } ); - verifyOctalModeSet( "004", new boolean[] { false, false, false, false, false, false, true, false, false } ); - verifyOctalModeSet( "002", new boolean[] { false, false, false, false, false, false, false, true, false } ); + @Test + final void testSetOctalMode_WorldModes() { + verifyOctalModeSet("007", new boolean[] {false, false, false, false, false, false, true, true, true}); + verifyOctalModeSet("006", new boolean[] {false, false, false, false, false, false, true, true, false}); + verifyOctalModeSet("004", new boolean[] {false, false, false, false, false, false, true, false, false}); + verifyOctalModeSet("002", new boolean[] {false, false, false, false, false, false, false, true, false}); } - private void verifyStringOctalModeSet( String mode, boolean[] checkValues ) - { - PlexusIoResourceAttributes attrs = newAttributes( Integer.parseInt( mode, 8 ) ); + private void verifyStringOctalModeSet(String mode, boolean[] checkValues) { + PlexusIoResourceAttributes attrs = newAttributes(Integer.parseInt(mode, 8)); - assertEquals( checkValues[0], attrs.isOwnerReadable() ); - assertEquals( checkValues[1], attrs.isOwnerWritable() ); - assertEquals( checkValues[2], attrs.isOwnerExecutable() ); + assertEquals(checkValues[0], attrs.isOwnerReadable()); + assertEquals(checkValues[1], attrs.isOwnerWritable()); + assertEquals(checkValues[2], attrs.isOwnerExecutable()); - assertEquals( checkValues[3], attrs.isGroupReadable() ); - assertEquals( checkValues[4], attrs.isGroupWritable() ); - assertEquals( checkValues[5], attrs.isGroupExecutable() ); + assertEquals(checkValues[3], attrs.isGroupReadable()); + assertEquals(checkValues[4], attrs.isGroupWritable()); + assertEquals(checkValues[5], attrs.isGroupExecutable()); - assertEquals( checkValues[6], attrs.isWorldReadable() ); - assertEquals( checkValues[7], attrs.isWorldWritable() ); - assertEquals( checkValues[8], attrs.isWorldExecutable() ); + assertEquals(checkValues[6], attrs.isWorldReadable()); + assertEquals(checkValues[7], attrs.isWorldWritable()); + assertEquals(checkValues[8], attrs.isWorldExecutable()); } - private void verifyOctalModeSet( String mode, boolean[] checkValues ) - { - PlexusIoResourceAttributes attrs = newAttributes( Integer.parseInt( mode, 8 ) ); + private void verifyOctalModeSet(String mode, boolean[] checkValues) { + PlexusIoResourceAttributes attrs = newAttributes(Integer.parseInt(mode, 8)); - assertEquals( checkValues[0], attrs.isOwnerReadable() ); - assertEquals( checkValues[1], attrs.isOwnerWritable() ); - assertEquals( checkValues[2], attrs.isOwnerExecutable() ); + assertEquals(checkValues[0], attrs.isOwnerReadable()); + assertEquals(checkValues[1], attrs.isOwnerWritable()); + assertEquals(checkValues[2], attrs.isOwnerExecutable()); - assertEquals( checkValues[3], attrs.isGroupReadable() ); - assertEquals( checkValues[4], attrs.isGroupWritable() ); - assertEquals( checkValues[5], attrs.isGroupExecutable() ); + assertEquals(checkValues[3], attrs.isGroupReadable()); + assertEquals(checkValues[4], attrs.isGroupWritable()); + assertEquals(checkValues[5], attrs.isGroupExecutable()); - assertEquals( checkValues[6], attrs.isWorldReadable() ); - assertEquals( checkValues[7], attrs.isWorldWritable() ); - assertEquals( checkValues[8], attrs.isWorldExecutable() ); + assertEquals(checkValues[6], attrs.isWorldReadable()); + assertEquals(checkValues[7], attrs.isWorldWritable()); + assertEquals(checkValues[8], attrs.isWorldExecutable()); } - -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/AttributeUtilsTest.java b/src/test/java/org/codehaus/plexus/components/io/attributes/AttributeUtilsTest.java index dee75ad5..8a56959b 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/AttributeUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/AttributeUtilsTest.java @@ -1,69 +1,66 @@ package org.codehaus.plexus.components.io.attributes; -import junit.framework.TestCase; -import org.codehaus.plexus.util.Os; - import java.io.File; import java.io.IOException; import java.nio.file.attribute.PosixFilePermission; -import java.util.HashMap; import java.util.Set; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Kristian Rosenvold */ -public class AttributeUtilsTest - extends TestCase -{ - public void testMiscPatterns() - throws Exception - { - final Set permissions = AttributeUtils.getPermissions( 0124 ); - assertTrue( permissions.contains( PosixFilePermission.OWNER_EXECUTE ) ); - assertTrue( permissions.contains( PosixFilePermission.GROUP_WRITE ) ); - assertTrue( permissions.contains( PosixFilePermission.OTHERS_READ ) ); +@SuppressWarnings("OctalInteger") +public class AttributeUtilsTest { + @Test + void testMiscPatterns() { + final Set permissions = AttributeUtils.getPermissions(0124); + assertTrue(permissions.contains(PosixFilePermission.OWNER_EXECUTE)); + assertTrue(permissions.contains(PosixFilePermission.GROUP_WRITE)); + assertTrue(permissions.contains(PosixFilePermission.OTHERS_READ)); } - public void testMorePatterns() throws Exception - { - final Set permissions = AttributeUtils.getPermissions( 0241 ); - assertTrue( permissions.contains( PosixFilePermission.OWNER_WRITE ) ); - assertTrue( permissions.contains( PosixFilePermission.GROUP_READ ) ); - assertTrue( permissions.contains( PosixFilePermission.OTHERS_EXECUTE ) ); + @Test + void testMorePatterns() { + final Set permissions = AttributeUtils.getPermissions(0241); + assertTrue(permissions.contains(PosixFilePermission.OWNER_WRITE)); + assertTrue(permissions.contains(PosixFilePermission.GROUP_READ)); + assertTrue(permissions.contains(PosixFilePermission.OTHERS_EXECUTE)); } - public void testEvenMorePatterns() throws Exception - { - final Set permissions = AttributeUtils.getPermissions( 0412 ); - assertTrue( permissions.contains( PosixFilePermission.OWNER_READ ) ); - assertTrue( permissions.contains( PosixFilePermission.GROUP_EXECUTE ) ); - assertTrue( permissions.contains( PosixFilePermission.OTHERS_WRITE ) ); + @Test + void testEvenMorePatterns() { + final Set permissions = AttributeUtils.getPermissions(0412); + assertTrue(permissions.contains(PosixFilePermission.OWNER_READ)); + assertTrue(permissions.contains(PosixFilePermission.GROUP_EXECUTE)); + assertTrue(permissions.contains(PosixFilePermission.OTHERS_WRITE)); } - public void test777() - throws Exception - { - final Set permissions = AttributeUtils.getPermissions( 0777 ); - assertTrue( permissions.size() == 9 ); + @Test + void test777() { + final Set permissions = AttributeUtils.getPermissions(0777); + assertEquals(9, permissions.size()); } - public void testChmodBackAndForth() - throws IOException - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - return; - final File bxx = File.createTempFile( "bxx", "ff" ); - AttributeUtils.chmod( bxx, 0422 ); - PlexusIoResourceAttributes firstAttrs = - new FileAttributes( bxx, new HashMap(), new HashMap() ); - assertTrue( firstAttrs.isOwnerReadable() ); - assertFalse( firstAttrs.isOwnerWritable() ); - assertFalse( firstAttrs.isOwnerExecutable() ); - AttributeUtils.chmod( bxx, 0777 ); - PlexusIoResourceAttributes secondAttrs = - new FileAttributes( bxx, new HashMap(), new HashMap() ); - assertTrue( secondAttrs.isOwnerReadable() ); - assertTrue( secondAttrs.isOwnerWritable() ); - assertTrue( secondAttrs.isOwnerExecutable() ); + @Test + @DisabledOnOs(OS.WINDOWS) + void testChmodBackAndForth() throws IOException { + final File bxx = File.createTempFile("bxx", "ff"); + AttributeUtils.chmod(bxx, 0422); + PlexusIoResourceAttributes firstAttrs = new FileAttributes(bxx); + assertTrue(firstAttrs.isOwnerReadable()); + assertFalse(firstAttrs.isOwnerWritable()); + assertFalse(firstAttrs.isOwnerExecutable()); + AttributeUtils.chmod(bxx, 0777); + PlexusIoResourceAttributes secondAttrs = new FileAttributes(bxx); + assertTrue(secondAttrs.isOwnerReadable()); + assertTrue(secondAttrs.isOwnerWritable()); + assertTrue(secondAttrs.isOwnerExecutable()); } } diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/FileAttributesTest.java b/src/test/java/org/codehaus/plexus/components/io/attributes/FileAttributesTest.java index 8e5073c8..3449f76f 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/FileAttributesTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/FileAttributesTest.java @@ -17,33 +17,22 @@ */ import java.io.File; -import java.util.HashMap; -import java.util.Map; -import org.codehaus.plexus.util.Os; -import junit.framework.TestCase; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; + +import static org.junit.jupiter.api.Assertions.assertNotNull; /** * @author Kristian Rosenvold */ -public class FileAttributesTest - extends TestCase -{ - public void testGetPosixFileAttributes() - throws Exception - { - - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - return; - } - - File file = new File( "." ); - Map userCache = new HashMap<>(); - Map groupCache = new HashMap<>(); - - PlexusIoResourceAttributes fa = new FileAttributes( file, userCache, groupCache ); - assertNotNull( fa ); +public class FileAttributesTest { + @Test + @DisabledOnOs(OS.WINDOWS) + void testGetPosixFileAttributes() throws Exception { + File file = new File("."); + PlexusIoResourceAttributes fa = new FileAttributes(file); + assertNotNull(fa); } - } diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtilsTest.java b/src/test/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtilsTest.java index 573fb2d8..4712e822 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/PlexusIoResourceAttributeUtilsTest.java @@ -16,350 +16,317 @@ * limitations under the License. */ -import org.codehaus.plexus.util.Os; -import org.codehaus.plexus.util.StringUtils; -import org.codehaus.plexus.util.cli.CommandLineException; -import org.codehaus.plexus.util.cli.CommandLineUtils; -import org.codehaus.plexus.util.cli.Commandline; - import java.io.File; import java.io.IOException; import java.net.URL; +import java.nio.file.NoSuchFileException; import java.util.Map; -import junit.framework.TestCase; +import org.codehaus.plexus.util.StringUtils; +import org.codehaus.plexus.util.cli.CommandLineException; +import org.codehaus.plexus.util.cli.CommandLineUtils; +import org.codehaus.plexus.util.cli.Commandline; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; import static org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributeUtils.getFileAttributes; +import static org.junit.jupiter.api.Assertions.*; -public class PlexusIoResourceAttributeUtilsTest - extends TestCase -{ - - public void testGetAttributesForThisTestClass() - throws IOException - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - System.out.println( "WARNING: Unsupported OS, skipping test" ); - return; - } +@SuppressWarnings("OctalInteger") +public class PlexusIoResourceAttributeUtilsTest { - URL resource = Thread.currentThread().getContextClassLoader().getResource( - getClass().getName().replace( '.', '/' ) + ".class" ); + @Test + @DisabledOnOs(OS.WINDOWS) + void testGetAttributesForThisTestClass() throws IOException { + URL resource = Thread.currentThread() + .getContextClassLoader() + .getResource(getClass().getName().replace('.', '/') + ".class"); - if ( resource == null ) - { - throw new IllegalStateException( - "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER." ); + if (resource == null) { + throw new IllegalStateException("SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER."); } - File f = new File( resource.getPath().replaceAll( "%20", " " ) ); + File f = new File(resource.getPath().replaceAll("%20", " ")); - Map attrs = - PlexusIoResourceAttributeUtils.getFileAttributesByPath( f, true ); + Map attrs = PlexusIoResourceAttributeUtils.getFileAttributesByPath(f, true); - PlexusIoResourceAttributes fileAttrs = attrs.get( f.getAbsolutePath() ); + PlexusIoResourceAttributes fileAttrs = attrs.get(f.getAbsolutePath()); - System.out.println( "Got attributes for: " + f.getAbsolutePath() + fileAttrs ); + System.out.println("Got attributes for: " + f.getAbsolutePath() + fileAttrs); - assertNotNull( fileAttrs ); - assertTrue( fileAttrs.isOwnerReadable() ); - assertEquals( System.getProperty( "user.name" ), fileAttrs.getUserName() ); + assertNotNull(fileAttrs); + assertTrue(fileAttrs.isOwnerReadable()); + assertEquals(System.getProperty("user.name"), fileAttrs.getUserName()); } - public void testDirectory() - throws IOException, CommandLineException - { - - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - return; // Nothing to do here. - } - - URL resource = Thread.currentThread().getContextClassLoader().getResource( - getClass().getName().replace( '.', '/' ) + ".class" ); + @Test + @DisabledOnOs(OS.WINDOWS) + void testDirectory() throws IOException, CommandLineException { + URL resource = Thread.currentThread() + .getContextClassLoader() + .getResource(getClass().getName().replace('.', '/') + ".class"); - if ( resource == null ) - { - throw new IllegalStateException( - "SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER." ); + if (resource == null) { + throw new IllegalStateException("SOMETHING IS VERY WRONG. CANNOT FIND THIS TEST CLASS IN THE CLASSLOADER."); } - File f = new File( resource.getPath().replaceAll( "%20", " " ) ); + File f = new File(resource.getPath().replaceAll("%20", " ")); final File aDir = f.getParentFile().getParentFile().getParentFile(); - Commandline commandLine = new Commandline( "chmod" ); - commandLine.addArguments( new String[] { "763", f.getAbsolutePath() } ); + Commandline commandLine = new Commandline("chmod"); + commandLine.addArguments(new String[] {"763", f.getAbsolutePath()}); - CommandLineUtils.executeCommandLine( commandLine, null, null ); + CommandLineUtils.executeCommandLine(commandLine, null, null); Map attrs = - PlexusIoResourceAttributeUtils.getFileAttributesByPath( aDir, true ); + PlexusIoResourceAttributeUtils.getFileAttributesByPath(aDir, true); - PlexusIoResourceAttributes fileAttrs = attrs.get( f.getAbsolutePath() ); + PlexusIoResourceAttributes fileAttrs = attrs.get(f.getAbsolutePath()); - assertTrue( fileAttrs.isGroupReadable() ); - assertTrue( fileAttrs.isGroupWritable() ); - assertFalse( fileAttrs.isGroupExecutable() ); + assertTrue(fileAttrs.isGroupReadable()); + assertTrue(fileAttrs.isGroupWritable()); + assertFalse(fileAttrs.isGroupExecutable()); - assertTrue( fileAttrs.isOwnerExecutable() ); - assertTrue( fileAttrs.isOwnerReadable() ); - assertTrue( fileAttrs.isOwnerWritable() ); + assertTrue(fileAttrs.isOwnerExecutable()); + assertTrue(fileAttrs.isOwnerReadable()); + assertTrue(fileAttrs.isOwnerWritable()); - assertTrue( fileAttrs.isWorldExecutable() ); - assertFalse( fileAttrs.isWorldReadable() ); - assertTrue( fileAttrs.isWorldWritable() ); + assertTrue(fileAttrs.isWorldExecutable()); + assertFalse(fileAttrs.isWorldReadable()); + assertTrue(fileAttrs.isWorldWritable()); - assertNotNull( fileAttrs ); + assertNotNull(fileAttrs); } - public void testSrcResource() - throws IOException - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - return; // Nothing to do here. - } - - File dir = new File( "src/test/resources/symlinks" ); + @Test + @DisabledOnOs(OS.WINDOWS) + void testSrcResource() throws IOException { + File dir = new File("src/test/resources/symlinks"); final Map fileAttributesByPathScreenScrape = - PlexusIoResourceAttributeUtils.getFileAttributesByPath( dir, true ); - assertNotNull( fileAttributesByPathScreenScrape ); + PlexusIoResourceAttributeUtils.getFileAttributesByPath(dir, true); + assertNotNull(fileAttributesByPathScreenScrape); PlexusIoResourceAttributes pr = null; - for ( String s : fileAttributesByPathScreenScrape.keySet() ) - { - if ( s.endsWith( "targetFile.txt" ) ) - pr = fileAttributesByPathScreenScrape.get( s ); + for (String s : fileAttributesByPathScreenScrape.keySet()) { + if (s.endsWith("targetFile.txt")) pr = fileAttributesByPathScreenScrape.get(s); } - assertNotNull( pr ); + assertNotNull(pr); - assertTrue( pr.getOctalMode() > 0 ); + assertTrue(pr.getOctalMode() > 0); } - public void testNonExistingDirectory() - { - File dir = new File( "src/test/noSuchDirectory" ); - try - { - PlexusIoResourceAttributeUtils.getFileAttributesByPath( dir, true ); - fail( "We were supposed to get an io exceptions" ); - } - catch ( IOException ignore ) - { - ignore.printStackTrace(); - } + + @Test + void testNonExistingDirectory() { + assertThrows(NoSuchFileException.class, () -> { + File dir = new File("src/test/noSuchDirectory"); + PlexusIoResourceAttributeUtils.getFileAttributesByPath(dir, true); + }); } - public void testMergeAttributesWithNullBase() - { - PlexusIoResourceAttributes override = - new SimpleResourceAttributes( 1001, "myUser", 1001, "test", 0 ); - PlexusIoResourceAttributes defaults = - new SimpleResourceAttributes( 1000, "defaultUser", 1000, "defaultTest", 0 ); + @Test + void testMergeAttributesWithNullBase() { + PlexusIoResourceAttributes override = new SimpleResourceAttributes(1001, "myUser", 1001, "test", 0); + PlexusIoResourceAttributes defaults = new SimpleResourceAttributes(1000, "defaultUser", 1000, "defaultTest", 0); PlexusIoResourceAttributes attributes; - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, null, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, null, defaults); - assertEquals( Integer.valueOf( 1001 ), attributes.getGroupId() ); - assertEquals( Integer.valueOf( 1001 ), attributes.getUserId() ); + assertEquals(Integer.valueOf(1001), attributes.getGroupId()); + assertEquals(Integer.valueOf(1001), attributes.getUserId()); } - public void testMergeAttributesWithNullOverrideGroup() - { - final PlexusIoResourceAttributes override = - new SimpleResourceAttributes( 1001, "myUser", -1, null, 0 ); + @Test + void testMergeAttributesWithNullOverrideGroup() { + final PlexusIoResourceAttributes override = new SimpleResourceAttributes(1001, "myUser", -1, null, 0); final PlexusIoResourceAttributes defaults = - new SimpleResourceAttributes( 1000, "defaultUser", 1000, "defaultGroup", 0 ); + new SimpleResourceAttributes(1000, "defaultUser", 1000, "defaultGroup", 0); PlexusIoResourceAttributes attributes = - PlexusIoResourceAttributeUtils.mergeAttributes( override, null, defaults ); + PlexusIoResourceAttributeUtils.mergeAttributes(override, null, defaults); - assertEquals( attributes.getGroupId(), Integer.valueOf( 1000 ) ); - assertEquals( attributes.getUserId(), Integer.valueOf( 1001 ) ); + assertEquals(attributes.getGroupId(), Integer.valueOf(1000)); + assertEquals(attributes.getUserId(), Integer.valueOf(1001)); } - public void testMergeAttributesOverride() - { + @Test + void testMergeAttributesOverride() { final PlexusIoResourceAttributes blank = new SimpleResourceAttributes(); - final PlexusIoResourceAttributes invalid = new SimpleResourceAttributes( -1, null, -1, null, -1 ); + final PlexusIoResourceAttributes invalid = new SimpleResourceAttributes(-1, null, -1, null, -1); final PlexusIoResourceAttributes override = - new SimpleResourceAttributes( 1111, "testUser", 2222, "testGroup", 0777 ); + new SimpleResourceAttributes(1111, "testUser", 2222, "testGroup", 0777); final PlexusIoResourceAttributes defaults = - new SimpleResourceAttributes( 3333, "defaultUser", 4444, "defaultGroup", 0444 ); - final PlexusIoResourceAttributes base = - new SimpleResourceAttributes( 5555, "baseUser", 6666, "baseGroup", 0111 ); - - PlexusIoResourceAttributes attributes; + new SimpleResourceAttributes(3333, "defaultUser", 4444, "defaultGroup", 0444); + final PlexusIoResourceAttributes base = new SimpleResourceAttributes(5555, "baseUser", 6666, "baseGroup", 0111); // When override is null, base is returned verbatim - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( null, null, null ); - assertNull( attributes ); + assertNull(PlexusIoResourceAttributeUtils.mergeAttributes(null, null, null)); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( null, null, defaults ); - assertNull( attributes ); + assertNull(PlexusIoResourceAttributeUtils.mergeAttributes(null, null, defaults)); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( null, base, null ); - assertSame( base, attributes ); + assertSame(base, PlexusIoResourceAttributeUtils.mergeAttributes(null, base, null)); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( null, base, defaults ); - assertSame( base, attributes ); + assertSame(base, PlexusIoResourceAttributeUtils.mergeAttributes(null, base, defaults)); // Test cases when override is non-null - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, null, null ); + PlexusIoResourceAttributes attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, null, null); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, base, null ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, base, null); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, null, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, null, defaults); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, base, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, base, defaults); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, blank, null ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, blank, null); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( override, invalid, null ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(override, invalid, null); - assertEquals( Integer.valueOf( 1111 ), attributes.getUserId() ); - assertEquals( "testUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 2222 ), attributes.getGroupId() ); - assertEquals( "testGroup", attributes.getGroupName() ); - assertEquals( 0777, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(1111), attributes.getUserId()); + assertEquals("testUser", attributes.getUserName()); + assertEquals(Integer.valueOf(2222), attributes.getGroupId()); + assertEquals("testGroup", attributes.getGroupName()); + assertEquals(0777, attributes.getOctalMode()); // Test cases when override has only blank values - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( blank, base, null ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(blank, base, null); - assertEquals( Integer.valueOf( 5555 ), attributes.getUserId() ); - assertEquals( "baseUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 6666 ), attributes.getGroupId() ); - assertEquals( "baseGroup", attributes.getGroupName() ); - assertEquals( 0111, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(5555), attributes.getUserId()); + assertEquals("baseUser", attributes.getUserName()); + assertEquals(Integer.valueOf(6666), attributes.getGroupId()); + assertEquals("baseGroup", attributes.getGroupName()); + assertEquals(0111, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( invalid, base, null ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(invalid, base, null); - assertEquals( Integer.valueOf( 5555 ), attributes.getUserId() ); - assertEquals( "baseUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 6666 ), attributes.getGroupId() ); - assertEquals( "baseGroup", attributes.getGroupName() ); - assertEquals( 0111, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(5555), attributes.getUserId()); + assertEquals("baseUser", attributes.getUserName()); + assertEquals(Integer.valueOf(6666), attributes.getGroupId()); + assertEquals("baseGroup", attributes.getGroupName()); + assertEquals(0111, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( blank, base, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(blank, base, defaults); - assertEquals( Integer.valueOf( 5555 ), attributes.getUserId() ); - assertEquals( "baseUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 6666 ), attributes.getGroupId() ); - assertEquals( "baseGroup", attributes.getGroupName() ); - assertEquals( 0111, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(5555), attributes.getUserId()); + assertEquals("baseUser", attributes.getUserName()); + assertEquals(Integer.valueOf(6666), attributes.getGroupId()); + assertEquals("baseGroup", attributes.getGroupName()); + assertEquals(0111, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( invalid, base, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(invalid, base, defaults); - assertEquals( Integer.valueOf( 5555 ), attributes.getUserId() ); - assertEquals( "baseUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 6666 ), attributes.getGroupId() ); - assertEquals( "baseGroup", attributes.getGroupName() ); - assertEquals( 0111, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(5555), attributes.getUserId()); + assertEquals("baseUser", attributes.getUserName()); + assertEquals(Integer.valueOf(6666), attributes.getGroupId()); + assertEquals("baseGroup", attributes.getGroupName()); + assertEquals(0111, attributes.getOctalMode()); } - public void testFileAttributes() - throws IOException - { - PlexusIoResourceAttributes attrs = getFileAttributes( new File( "src/test/resources/symlinks/src/fileW.txt" ) ); - assertFalse( attrs.isSymbolicLink() ); - assertTrue( StringUtils.isNotEmpty( attrs.getUserName() ) ); - if ( !Os.isFamily( Os.FAMILY_WINDOWS ) ) - { - assertTrue( StringUtils.isNotEmpty( attrs.getGroupName() ) ); - assertNotNull( attrs.getGroupId() ); - assertNotNull( attrs.getUserId() ); - } + @Test + void testFileAttributesGeneric() throws IOException { + PlexusIoResourceAttributes attrs = getFileAttributes(new File("src/test/resources/symlinks/src/fileW.txt")); + assertFalse(attrs.isSymbolicLink()); + assertTrue(StringUtils.isNotEmpty(attrs.getUserName())); } - public void testMergeAttributesDefault() - { - final PlexusIoResourceAttributes blank = new SimpleResourceAttributes( null, null, null, null, 0 ); - final PlexusIoResourceAttributes invalid = new SimpleResourceAttributes( -1, null, -1, null, -1 ); + @Test + @DisabledOnOs(OS.WINDOWS) + void testFileAttributes() throws IOException { + PlexusIoResourceAttributes attrs = getFileAttributes(new File("src/test/resources/symlinks/src/fileW.txt")); + assertFalse(attrs.isSymbolicLink()); + assertTrue(StringUtils.isNotEmpty(attrs.getUserName())); + assertTrue(StringUtils.isNotEmpty(attrs.getGroupName())); + assertNotNull(attrs.getGroupId()); + assertNotNull(attrs.getUserId()); + } + + @Test + void testMergeAttributesDefault() { + final PlexusIoResourceAttributes blank = new SimpleResourceAttributes(null, null, null, null, 0); + final PlexusIoResourceAttributes invalid = new SimpleResourceAttributes(-1, null, -1, null, -1); final PlexusIoResourceAttributes defaults = - new SimpleResourceAttributes( 3333, "defaultUser", 4444, "defaultGroup", 0444 ); + new SimpleResourceAttributes(3333, "defaultUser", 4444, "defaultGroup", 0444); PlexusIoResourceAttributes attributes; // Test cases when override and base have blank values - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( blank, blank, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(blank, blank, defaults); - assertEquals( Integer.valueOf( 3333 ), attributes.getUserId() ); - assertEquals( "defaultUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 4444 ), attributes.getGroupId() ); - assertEquals( "defaultGroup", attributes.getGroupName() ); + assertEquals(Integer.valueOf(3333), attributes.getUserId()); + assertEquals("defaultUser", attributes.getUserName()); + assertEquals(Integer.valueOf(4444), attributes.getGroupId()); + assertEquals("defaultGroup", attributes.getGroupName()); // 0 is a borderline case, for backwards compatibility it is not overridden by value from defaults - assertEquals( 0, attributes.getOctalMode() ); + assertEquals(0, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( invalid, blank, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(invalid, blank, defaults); - assertEquals( Integer.valueOf( 3333 ), attributes.getUserId() ); - assertEquals( "defaultUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 4444 ), attributes.getGroupId() ); - assertEquals( "defaultGroup", attributes.getGroupName() ); + assertEquals(Integer.valueOf(3333), attributes.getUserId()); + assertEquals("defaultUser", attributes.getUserName()); + assertEquals(Integer.valueOf(4444), attributes.getGroupId()); + assertEquals("defaultGroup", attributes.getGroupName()); // 0 is a borderline case, for backwards compatibility it is not overridden by value from defaults // Not just that, but 0 is correct. - assertEquals( 0, attributes.getOctalMode() ); + assertEquals(0, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( blank, invalid, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(blank, invalid, defaults); - assertEquals( Integer.valueOf( 3333 ), attributes.getUserId() ); - assertEquals( "defaultUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 4444 ), attributes.getGroupId() ); - assertEquals( "defaultGroup", attributes.getGroupName() ); - assertEquals( 0444, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(3333), attributes.getUserId()); + assertEquals("defaultUser", attributes.getUserName()); + assertEquals(Integer.valueOf(4444), attributes.getGroupId()); + assertEquals("defaultGroup", attributes.getGroupName()); + assertEquals(0444, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( invalid, invalid, defaults ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(invalid, invalid, defaults); - assertEquals( Integer.valueOf( 3333 ), attributes.getUserId() ); - assertEquals( "defaultUser", attributes.getUserName() ); - assertEquals( Integer.valueOf( 4444 ), attributes.getGroupId() ); - assertEquals( "defaultGroup", attributes.getGroupName() ); - assertEquals( 0444, attributes.getOctalMode() ); + assertEquals(Integer.valueOf(3333), attributes.getUserId()); + assertEquals("defaultUser", attributes.getUserName()); + assertEquals(Integer.valueOf(4444), attributes.getGroupId()); + assertEquals("defaultGroup", attributes.getGroupName()); + assertEquals(0444, attributes.getOctalMode()); // Test cases when invalid defaults should not override blank values - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( blank, blank, invalid ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(blank, blank, invalid); - assertNull( attributes.getUserId() ); - assertNull( attributes.getUserName() ); - assertNull( attributes.getGroupId() ); - assertNull( attributes.getGroupName() ); - assertEquals( 0, attributes.getOctalMode() ); + assertNull(attributes.getUserId()); + assertNull(attributes.getUserName()); + assertNull(attributes.getGroupId()); + assertNull(attributes.getGroupName()); + assertEquals(0, attributes.getOctalMode()); - attributes = PlexusIoResourceAttributeUtils.mergeAttributes( invalid, blank, invalid ); + attributes = PlexusIoResourceAttributeUtils.mergeAttributes(invalid, blank, invalid); - assertNull( attributes.getUserId() ); - assertNull( attributes.getUserName() ); - assertNull( attributes.getGroupId() ); - assertNull( attributes.getGroupName() ); - assertEquals( 0, attributes.getOctalMode() ); + assertNull(attributes.getUserId()); + assertNull(attributes.getUserName()); + assertNull(attributes.getGroupId()); + assertNull(attributes.getGroupName()); + assertEquals(0, attributes.getOctalMode()); } - } diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributesTest.java b/src/test/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributesTest.java index 9673f884..9383fcd3 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributesTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/SimpleResourceAttributesTest.java @@ -16,21 +16,17 @@ * limitations under the License. */ -public class SimpleResourceAttributesTest - extends AbstractResourceAttributesTCK -{ +public class SimpleResourceAttributesTest extends AbstractResourceAttributesTCK { - protected PlexusIoResourceAttributes newAttributes( int mode ) - { + protected PlexusIoResourceAttributes newAttributes(int mode) { final SimpleResourceAttributes simpleResourceAttributes = new SimpleResourceAttributes(); - simpleResourceAttributes.setOctalMode( mode ); + simpleResourceAttributes.setOctalMode(mode); return simpleResourceAttributes; } - protected PlexusIoResourceAttributes newAttributes( String mode ) - { + protected PlexusIoResourceAttributes newAttributes(String mode) { final SimpleResourceAttributes simpleResourceAttributes = new SimpleResourceAttributes(); - simpleResourceAttributes.setOctalModeString( mode ); + simpleResourceAttributes.setOctalModeString(mode); return simpleResourceAttributes; } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/attributes/SymlinkUtilsTest.java b/src/test/java/org/codehaus/plexus/components/io/attributes/SymlinkUtilsTest.java index 0d1875d7..7b216bb6 100644 --- a/src/test/java/org/codehaus/plexus/components/io/attributes/SymlinkUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/attributes/SymlinkUtilsTest.java @@ -16,68 +16,51 @@ package org.codehaus.plexus.components.io.attributes; -import org.apache.commons.io.FileUtils; -import org.junit.Before; -import org.junit.Test; - import java.io.File; import java.io.IOException; import java.nio.file.Files; -import static org.junit.Assert.*; +import org.apache.commons.io.FileUtils; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; -public class SymlinkUtilsTest -{ - File target = new File( "target/symlinkCapabilities" ); +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.junit.jupiter.api.Assertions.*; - String expected = "This is a filed that we'll be symlinking to\n"; +public class SymlinkUtilsTest { + final File target = new File("target/symlinkCapabilities"); - @Before - public void setup() - throws IOException - { - FileUtils.deleteDirectory( target ); - Files.createDirectories( target.toPath() ); - } - - @Test - public void testName() - throws Exception - { + final String expected = "This is a filed that we'll be symlinking to\n"; + @BeforeEach + public void setup() throws IOException { + FileUtils.deleteDirectory(target); + Files.createDirectories(target.toPath()); } @Test - public void create_read_symbolic_link_to_file() - throws Exception - { - File symlink = new File( target, "symlinkToTarget" ); - File relativePath = createTargetFile( target ); - SymlinkUtils.createSymbolicLink( symlink, relativePath ); - assertEquals( expected, FileUtils.readFileToString( symlink ) ); - assertEquals( new File( "actualFile" ), - SymlinkUtils.readSymbolicLink( new File( target, "symlinkToTarget" ) ) ); + void create_read_symbolic_link_to_file() throws Exception { + File symlink = new File(target, "symlinkToTarget"); + File relativePath = createTargetFile(target); + SymlinkUtils.createSymbolicLink(symlink, relativePath); + assertEquals(expected, FileUtils.readFileToString(symlink, UTF_8)); + assertEquals(new File("actualFile"), SymlinkUtils.readSymbolicLink(new File(target, "symlinkToTarget"))); } @Test - public void create_read_symbolic_link_to_directory() - throws Exception - { - File subDir = new File( target, "aSubDir" ); - createTargetFile( subDir ); - File symlink = new File( target, "symlinkToDir" ); - SymlinkUtils.createSymbolicLink( symlink, new File( "aSubDir" ) ); - assertEquals( expected, FileUtils.readFileToString( new File( symlink, "actualFile" ) ) ); - assertEquals( new File( "aSubDir" ), SymlinkUtils.readSymbolicLink( new File( target, "symlinkToDir" ) ) ); - + void create_read_symbolic_link_to_directory() throws Exception { + File subDir = new File(target, "aSubDir"); + createTargetFile(subDir); + File symlink = new File(target, "symlinkToDir"); + SymlinkUtils.createSymbolicLink(symlink, new File("aSubDir")); + assertEquals(expected, FileUtils.readFileToString(new File(symlink, "actualFile"), UTF_8)); + assertEquals(new File("aSubDir"), SymlinkUtils.readSymbolicLink(new File(target, "symlinkToDir"))); } - private File createTargetFile( File target ) - throws IOException - { - File relativePath = new File( "actualFile" ); - File actualFile = new File( target, relativePath.getPath() ); - FileUtils.write( actualFile, expected ); + private File createTargetFile(File target) throws IOException { + File relativePath = new File("actualFile"); + File actualFile = new File(target, relativePath.getPath()); + FileUtils.write(actualFile, expected, UTF_8); return relativePath; } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/filemappers/FileMapperTest.java b/src/test/java/org/codehaus/plexus/components/io/filemappers/FileMapperTest.java index a19a683c..fbd7d948 100644 --- a/src/test/java/org/codehaus/plexus/components/io/filemappers/FileMapperTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/filemappers/FileMapperTest.java @@ -16,198 +16,221 @@ * limitations under the License. */ +import javax.inject.Inject; + import java.lang.reflect.UndeclaredThrowableException; import java.util.Arrays; -import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.PlexusContainer; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; /** * Test case for the various file mappers. */ -public class FileMapperTest extends PlexusTestCase -{ - protected void testFileMapper( FileMapper pMapper, String[] pInput, String[] pOutput ) - { - for ( int i = 0; i < pInput.length; i++ ) - { +@PlexusTest +public class FileMapperTest { + @Inject + PlexusContainer container; + + protected void testFileMapper(FileMapper pMapper, String[] pInput, String[] pOutput) { + for (int i = 0; i < pInput.length; i++) { final String input = pInput[i]; final String output = pOutput[i]; final String result; - try - { - if ( output == null ) - { - try - { - pMapper.getMappedFileName( input ); - fail( "Expected IllegalArgumentException for mapper " + pMapper.getClass().getName() - + " and input: " + input ); - } - catch ( IllegalArgumentException e ) - { + try { + if (output == null) { + try { + pMapper.getMappedFileName(input); + fail("Expected IllegalArgumentException for mapper " + + pMapper.getClass().getName() + " and input: " + input); + } catch (IllegalArgumentException e) { // Ok } continue; } - result = pMapper.getMappedFileName( input ); - if ( output.equals( result ) ) - { + result = pMapper.getMappedFileName(input); + if (output.equals(result)) { continue; } + } catch (Throwable t) { + throw new UndeclaredThrowableException( + t, + "Mapper " + pMapper.getClass().getName() + " failed for input " + input + ": " + + t.getMessage()); } - catch ( Throwable t ) - { - throw new UndeclaredThrowableException( t, "Mapper " + pMapper.getClass().getName() - + " failed for input " + input + ": " + t.getMessage() ); - } - if ( !output.equals( result ) ) - { - fail( "Mapper " + pMapper.getClass().getName() + " failed for input nr. " + i - + ", " + input + ": Expected " + output - + ", got " + result ); + if (!output.equals(result)) { + fail("Mapper " + pMapper.getClass().getName() + " failed for input nr. " + i + + ", " + input + ": Expected " + output + + ", got " + result); } } } - protected static final String[] SAMPLES = - new String[] { null, "", "a", "xyz.gif", "b/a", "b/xyz.gif", "b\\a", "b\\xyz.gif", "c.c/a", "c.c/xyz.gif", - "c.c\\a", "c.c\\xyz.gif" }; - - public void testIdentityMapper() throws Exception - { + protected static final String[] SAMPLES = new String[] { + null, + "", + "a", + "xyz.gif", + "b/a", + "b/xyz.gif", + "b\\a", + "b\\xyz.gif", + "c.c/a", + "c.c/xyz.gif", + "c.c\\a", + "c.c\\xyz.gif" + }; + + @Test + void testIdentityMapper() throws Exception { final String[] results = getIdentityResults(); - testFileMapper( new IdentityMapper(), SAMPLES, results ); + testFileMapper(new IdentityMapper(), SAMPLES, results); } - private String[] getIdentityResults() - { + private String[] getIdentityResults() { final String[] results = new String[SAMPLES.length]; - System.arraycopy( SAMPLES, 0, results, 0, SAMPLES.length ); + System.arraycopy(SAMPLES, 0, results, 0, SAMPLES.length); results[1] = null; return results; } - public void testDefaultMapper() throws Exception - { + @Test + void testDefaultMapper() throws Exception { final String[] results = getIdentityResults(); - testFileMapper( (FileMapper) lookup( FileMapper.ROLE ), SAMPLES, results ); - testFileMapper( (FileMapper) lookup( FileMapper.ROLE, IdentityMapper.ROLE_HINT ), SAMPLES, results ); - testFileMapper( (FileMapper) lookup( FileMapper.ROLE, FileMapper.DEFAULT_ROLE_HINT ), SAMPLES, results ); + testFileMapper(container.lookup(FileMapper.class), SAMPLES, results); + testFileMapper(container.lookup(FileMapper.class, IdentityMapper.ROLE_HINT), SAMPLES, results); + testFileMapper(container.lookup(FileMapper.class), SAMPLES, results); } - public void testFileExtensionMapper() throws Exception - { + @Test + void testFileExtensionMapper() throws Exception { final String[] results = getIdentityResults(); - for ( int i = 2; i <= 10; i += 2 ) - { + for (int i = 2; i <= 10; i += 2) { results[i] += ".png"; } - for ( int i = 3; i <= 11; i += 2 ) - { - results[i] = results[i].substring( 0, results[i].length() - ".gif".length() ) + ".png"; + for (int i = 3; i <= 11; i += 2) { + results[i] = results[i].substring(0, results[i].length() - ".gif".length()) + ".png"; } - testFileExtensionMapper( results, new FileExtensionMapper() ); - testFileExtensionMapper( results, (FileExtensionMapper) lookup( FileMapper.ROLE, FileExtensionMapper.ROLE_HINT ) ); + testFileExtensionMapper(results, new FileExtensionMapper()); + testFileExtensionMapper( + results, (FileExtensionMapper) container.lookup(FileMapper.class, FileExtensionMapper.ROLE_HINT)); } - private void testFileExtensionMapper( final String[] results, final FileExtensionMapper mapper ) - { - mapper.setTargetExtension( "png" ); - testFileMapper( mapper, SAMPLES, results ); - mapper.setTargetExtension( ".png" ); - testFileMapper( mapper, SAMPLES, results ); + private void testFileExtensionMapper(final String[] results, final FileExtensionMapper mapper) { + mapper.setTargetExtension("png"); + testFileMapper(mapper, SAMPLES, results); + mapper.setTargetExtension(".png"); + testFileMapper(mapper, SAMPLES, results); } - public void testFlattenMapper() throws Exception - { + @Test + void testFlattenMapper() throws Exception { final String[] results = getIdentityResults(); results[4] = results[6] = results[8] = results[10] = results[2]; results[5] = results[7] = results[9] = results[11] = results[3]; - testFileMapper( new FlattenFileMapper(), SAMPLES, results ); - testFileMapper( (FileMapper) lookup( FileMapper.ROLE, FlattenFileMapper.ROLE_HINT ), SAMPLES, results ); + testFileMapper(new FlattenFileMapper(), SAMPLES, results); + testFileMapper(container.lookup(FileMapper.class, FlattenFileMapper.ROLE_HINT), SAMPLES, results); } - private void testMergeMapper( String pTargetName, String[] pResults, MergeFileMapper pMapper ) - { - pMapper.setTargetName( pTargetName ); - testFileMapper( pMapper, SAMPLES, pResults ); + private void testMergeMapper(String pTargetName, String[] pResults, MergeFileMapper pMapper) { + pMapper.setTargetName(pTargetName); + testFileMapper(pMapper, SAMPLES, pResults); } - public void testMergeMapper() throws Exception - { + @Test + void testMergeMapper() throws Exception { final String[] results = getIdentityResults(); final String targetName = "zgh"; - for ( int i = 2; i < results.length; i++ ) - { + for (int i = 2; i < results.length; i++) { results[i] = targetName; } - testMergeMapper( targetName, results, new MergeFileMapper() ); - testMergeMapper( targetName, results, (MergeFileMapper) lookup( FileMapper.ROLE, MergeFileMapper.ROLE_HINT ) ); + testMergeMapper(targetName, results, new MergeFileMapper()); + testMergeMapper( + targetName, results, (MergeFileMapper) container.lookup(FileMapper.class, MergeFileMapper.ROLE_HINT)); } - public void testPrefixMapper() throws Exception - { + @Test + void testPrefixMapper() throws Exception { final String prefix = "x7Rtf"; final String[] results = getIdentityResults(); - testFileMapper( new PrefixFileMapper(), SAMPLES, results ); - testFileMapper( (PrefixFileMapper) lookup( FileMapper.ROLE, PrefixFileMapper.ROLE_HINT ), SAMPLES, results ); - for ( int i = 0; i < results.length; i++ ) - { - if ( results[i] != null ) - { + testFileMapper(new PrefixFileMapper(), SAMPLES, results); + testFileMapper(container.lookup(FileMapper.class, PrefixFileMapper.ROLE_HINT), SAMPLES, results); + for (int i = 0; i < results.length; i++) { + if (results[i] != null) { results[i] = prefix + results[i]; } } PrefixFileMapper mapper = new PrefixFileMapper(); - mapper.setPrefix( prefix ); - testFileMapper( mapper, SAMPLES, results ); - mapper = (PrefixFileMapper) lookup( FileMapper.ROLE, PrefixFileMapper.ROLE_HINT ); - mapper.setPrefix( prefix ); - testFileMapper( mapper, SAMPLES, results ); + mapper.setPrefix(prefix); + testFileMapper(mapper, SAMPLES, results); + mapper = (PrefixFileMapper) container.lookup(FileMapper.class, PrefixFileMapper.ROLE_HINT); + mapper.setPrefix(prefix); + testFileMapper(mapper, SAMPLES, results); } - public void testSuffixMapper() throws Exception - { + @Test + void testSuffixMapper() throws Exception { final String suffix = "suffix"; - String[] samples = Arrays.copyOf( SAMPLES, SAMPLES.length + 2 ); + String[] samples = Arrays.copyOf(SAMPLES, SAMPLES.length + 2); samples[samples.length - 2] = "archive.tar.gz"; samples[samples.length - 1] = "directory/archive.tar.gz"; - String[] results = new String[] { null, null, "asuffix", "xyzsuffix.gif", "b/asuffix", "b/xyzsuffix.gif", - "b\\asuffix", "b\\xyzsuffix.gif", "c.c/asuffix", "c.c/xyzsuffix.gif", "c.c\\asuffix", "c.c\\xyzsuffix.gif", - "archivesuffix.tar.gz", "directory/archivesuffix.tar.gz" }; + String[] results = new String[] { + null, + null, + "asuffix", + "xyzsuffix.gif", + "b/asuffix", + "b/xyzsuffix.gif", + "b\\asuffix", + "b\\xyzsuffix.gif", + "c.c/asuffix", + "c.c/xyzsuffix.gif", + "c.c\\asuffix", + "c.c\\xyzsuffix.gif", + "archivesuffix.tar.gz", + "directory/archivesuffix.tar.gz" + }; SuffixFileMapper mapper = new SuffixFileMapper(); - mapper.setSuffix( suffix ); - testFileMapper( mapper, samples, results ); - mapper = (SuffixFileMapper) lookup( FileMapper.ROLE, SuffixFileMapper.ROLE_HINT ); - mapper.setSuffix( suffix ); - testFileMapper( mapper, samples, results ); + mapper.setSuffix(suffix); + testFileMapper(mapper, samples, results); + mapper = (SuffixFileMapper) container.lookup(FileMapper.class, SuffixFileMapper.ROLE_HINT); + mapper.setSuffix(suffix); + testFileMapper(mapper, samples, results); } - private RegExpFileMapper configure( RegExpFileMapper pMapper, String pPattern, String pReplacement ) - { - pMapper.setPattern( pPattern ); - pMapper.setReplacement( pReplacement ); + private RegExpFileMapper configure(RegExpFileMapper pMapper, String pPattern, String pReplacement) { + pMapper.setPattern(pPattern); + pMapper.setReplacement(pReplacement); return pMapper; } - public void testRegExpFileMapper() throws Exception - { + @Test + void testRegExpFileMapper() throws Exception { final String[] results = getIdentityResults(); results[3] = "xyz.jpg"; results[5] = "b/xyz.jpg"; results[7] = "b\\xyz.jpg"; results[9] = "c.c/xyz.jpg"; results[11] = "c.c\\xyz.jpg"; - testFileMapper( configure(new RegExpFileMapper(), "\\.gif$", ".jpg"), SAMPLES, results ); - testFileMapper( configure(new RegExpFileMapper(), "^(.*)\\.gif$", "$1.jpg"), SAMPLES, results ); - testFileMapper( configure((RegExpFileMapper) lookup( FileMapper.ROLE, RegExpFileMapper.ROLE_HINT ), "\\.gif$", ".jpg"), SAMPLES, results ); - final RegExpFileMapper mapper = configure( new RegExpFileMapper(), "c", "f" ); - mapper.setReplaceAll( true ); + testFileMapper(configure(new RegExpFileMapper(), "\\.gif$", ".jpg"), SAMPLES, results); + testFileMapper(configure(new RegExpFileMapper(), "^(.*)\\.gif$", "$1.jpg"), SAMPLES, results); + testFileMapper( + configure( + (RegExpFileMapper) container.lookup(FileMapper.class, RegExpFileMapper.ROLE_HINT), + "\\.gif$", + ".jpg"), + SAMPLES, + results); + final RegExpFileMapper mapper = configure(new RegExpFileMapper(), "c", "f"); + mapper.setReplaceAll(true); final String[] fResults = getIdentityResults(); fResults[8] = "f.f/a"; fResults[9] = "f.f/xyz.gif"; fResults[10] = "f.f\\a"; fResults[11] = "f.f\\xyz.gif"; - testFileMapper( mapper, SAMPLES, fResults ); + testFileMapper(mapper, SAMPLES, fResults); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/filemappers/FileSelectorTest.java b/src/test/java/org/codehaus/plexus/components/io/filemappers/FileSelectorTest.java index 1aed4169..6879c7f0 100644 --- a/src/test/java/org/codehaus/plexus/components/io/filemappers/FileSelectorTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/filemappers/FileSelectorTest.java @@ -16,136 +16,120 @@ * limitations under the License. */ +import javax.annotation.Nonnull; +import javax.inject.Inject; + import java.io.IOException; import java.io.InputStream; import java.net.URL; +import java.util.Arrays; -import org.codehaus.plexus.PlexusTestCase; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.components.io.fileselectors.AllFilesFileSelector; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.fileselectors.IncludeExcludeFileSelector; import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource; +import org.codehaus.plexus.testing.PlexusTest; +import org.junit.jupiter.api.Test; -import javax.annotation.Nonnull; - +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * Test case for implementations of {@link FileSelector}. */ -public class FileSelectorTest extends PlexusTestCase -{ - protected void testFileSelector( FileSelector pSelector, String[] pInput, boolean[] pOutput) - throws IOException - { - for ( int i = 0; i < pInput.length; i++ ) - { +@PlexusTest +public class FileSelectorTest { + + @Inject + PlexusContainer container; + + protected void testFileSelector(FileSelector pSelector, String[] pInput, boolean[] pOutput) throws IOException { + for (int i = 0; i < pInput.length; i++) { final String name = pInput[i]; - AbstractPlexusIoResource resource = new AbstractPlexusIoResource( name, 0, 0, true, false, true ) - { + AbstractPlexusIoResource resource = new AbstractPlexusIoResource(name, 0, 0, true, false, true) { @Nonnull - public InputStream getContents() throws IOException - { - throw new IllegalStateException( "Not implemented" ); + public InputStream getContents() { + throw new IllegalStateException("Not implemented"); } - public URL getURL() throws IOException - { - throw new IllegalStateException( "Not implemented" ); + public URL getURL() { + throw new IllegalStateException("Not implemented"); } }; - boolean result = pSelector.isSelected( resource ); - if ( result != pOutput[i] ) - { - fail( "Test fails for selector " + pSelector.getClass().getName() - + " and input " + name + ": Expected " - + pOutput[i] ); + boolean result = pSelector.isSelected(resource); + if (result != pOutput[i]) { + fail("Test fails for selector " + pSelector.getClass().getName() + + " and input " + name + ": Expected " + + pOutput[i]); } } } - protected static final String[] SAMPLES = - new String[] - { - "foo/x.gif", - "foo/y.png", - "bar/x.gif" - }; + protected static final String[] SAMPLES = new String[] {"foo/x.gif", "foo/y.png", "bar/x.gif"}; - protected void testFileSelector( AllFilesFileSelector pSelector ) throws Exception - { + protected void testFileSelector(AllFilesFileSelector pSelector) throws Exception { final boolean[] trues = getAllTrues(); - testFileSelector( pSelector, SAMPLES, trues ); + testFileSelector(pSelector, SAMPLES, trues); } - private boolean[] getAllTrues() - { + private boolean[] getAllTrues() { final boolean[] trues = new boolean[SAMPLES.length]; - for ( int i = 0; i < trues.length; i++ ) - { - trues[i] = true; - } + Arrays.fill(trues, true); return trues; } - public void testAllFilesFileSelector() throws Exception - { - testFileSelector( new AllFilesFileSelector() ); - testFileSelector( (AllFilesFileSelector) lookup( FileSelector.ROLE, FileSelector.DEFAULT_ROLE_HINT ) ); - testFileSelector( (AllFilesFileSelector) lookup( FileSelector.ROLE, AllFilesFileSelector.ROLE_HINT ) ); + @Test + void testAllFilesFileSelector() throws Exception { + testFileSelector(new AllFilesFileSelector()); + testFileSelector((AllFilesFileSelector) container.lookup(FileSelector.class)); + testFileSelector((AllFilesFileSelector) container.lookup(FileSelector.class, AllFilesFileSelector.ROLE_HINT)); } - protected boolean[] getIncludeGifs( String[] pSamples ) - { + protected boolean[] getIncludeGifs(String[] pSamples) { boolean[] result = new boolean[pSamples.length]; - for ( int i = 0; i < pSamples.length; i++ ) - { - result[i] = pSamples[i].endsWith( ".gif" ); + for (int i = 0; i < pSamples.length; i++) { + result[i] = pSamples[i].endsWith(".gif"); } return result; } - protected boolean[] getExcludeBar( String[] pSamples, boolean[] pResult ) - { - for ( int i = 0; i < pSamples.length; i++ ) - { - if ( pSamples[i].startsWith( "bar/" ) ) - { + protected boolean[] getExcludeBar(String[] pSamples, boolean[] pResult) { + for (int i = 0; i < pSamples.length; i++) { + if (pSamples[i].startsWith("bar/")) { pResult[i] = false; } } return pResult; } - - protected void testFileSelector( IncludeExcludeFileSelector pSelector ) throws Exception - { - testFileSelector( pSelector, SAMPLES, getAllTrues() ); - pSelector.setIncludes( new String[] { "**/*.gif" } ); - testFileSelector( pSelector, SAMPLES, getIncludeGifs( SAMPLES ) ); - pSelector.setExcludes( new String[] { "bar/*" } ); - testFileSelector( pSelector, SAMPLES, getExcludeBar( SAMPLES, getIncludeGifs( SAMPLES ) ) ); - pSelector.setIncludes( null ); - testFileSelector( pSelector, SAMPLES, getExcludeBar( SAMPLES, getAllTrues() ) ); + + protected void testFileSelector(IncludeExcludeFileSelector pSelector) throws Exception { + testFileSelector(pSelector, SAMPLES, getAllTrues()); + pSelector.setIncludes(new String[] {"**/*.gif"}); + testFileSelector(pSelector, SAMPLES, getIncludeGifs(SAMPLES)); + pSelector.setExcludes(new String[] {"bar/*"}); + testFileSelector(pSelector, SAMPLES, getExcludeBar(SAMPLES, getIncludeGifs(SAMPLES))); + pSelector.setIncludes(null); + testFileSelector(pSelector, SAMPLES, getExcludeBar(SAMPLES, getAllTrues())); } - public void testIncludeExcludeFileSelector() throws Exception - { - testFileSelector( new IncludeExcludeFileSelector() ); - testFileSelector( (IncludeExcludeFileSelector) lookup( FileSelector.ROLE, - IncludeExcludeFileSelector.ROLE_HINT ) ); + @Test + void testIncludeExcludeFileSelector() throws Exception { + testFileSelector(new IncludeExcludeFileSelector()); + testFileSelector((IncludeExcludeFileSelector) + container.lookup(FileSelector.class, IncludeExcludeFileSelector.ROLE_HINT)); } - - public void testIncludeExcludeFileSelector_SetExcludes() throws Exception - { + + @Test + void testIncludeExcludeFileSelector_SetExcludes() { IncludeExcludeFileSelector selector = new IncludeExcludeFileSelector(); // Test that the setExcludes method does not modify the excludes. - selector.setExcludes( SAMPLES ); + selector.setExcludes(SAMPLES); String[] sltrExcludes = selector.getExcludes(); - assertEquals( SAMPLES.length, sltrExcludes.length ); - for ( int i = 0; i < sltrExcludes.length; ++i ) - { - assertEquals( SAMPLES[i], sltrExcludes[i] ); + assertEquals(SAMPLES.length, sltrExcludes.length); + for (int i = 0; i < sltrExcludes.length; ++i) { + assertEquals(SAMPLES[i], sltrExcludes[i]); } - } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/filemappers/ResourcesTest.java b/src/test/java/org/codehaus/plexus/components/io/filemappers/ResourcesTest.java index 0d59eb9c..540da593 100644 --- a/src/test/java/org/codehaus/plexus/components/io/filemappers/ResourcesTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/filemappers/ResourcesTest.java @@ -16,6 +16,8 @@ * limitations under the License. */ +import javax.inject.Inject; + import java.io.Closeable; import java.io.File; import java.io.FileInputStream; @@ -23,227 +25,185 @@ import java.io.IOException; import java.io.InputStream; import java.net.URLConnection; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.util.Iterator; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.components.io.resources.AbstractPlexusIoArchiveResourceCollection; +import org.codehaus.plexus.PlexusContainer; import org.codehaus.plexus.components.io.resources.PlexusIoFileResource; import org.codehaus.plexus.components.io.resources.PlexusIoFileResourceCollection; import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; +import org.codehaus.plexus.testing.PlexusTest; import org.codehaus.plexus.util.FileUtils; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; /** * Test case for resource collections. */ -public class ResourcesTest extends PlexusTestCase -{ +@PlexusTest +public class ResourcesTest { + + @Inject + PlexusContainer container; + private static final String X_PATH = "x"; private static final String A_PATH = X_PATH + "/a"; private static final String B_PATH = X_PATH + "/b"; private static final String Y_PATH = "y"; - private File getTestDir() - { - final String testDirPath = System.getProperty( "plexus.io.testDirPath" ); - return new File( testDirPath == null ? "target/plexus.io.testDir" : testDirPath ); + private File getTestDir() { + final String testDirPath = System.getProperty("plexus.io.testDirPath"); + return new File(testDirPath == null ? "target/plexus.io.testDir" : testDirPath); } - private File getFilesDir() - { - return new File( getTestDir(), "files" ); + private File getFilesDir() { + return new File(getTestDir(), "files"); } - private void createFiles() - throws IOException - { + private void createFiles() throws IOException { final File baseDir = getFilesDir(); - FileUtils.deleteDirectory( baseDir ); - FileUtils.mkdir( baseDir.getPath() ); - final File aFile = new File( baseDir, A_PATH ); - FileUtils.mkdir( aFile.getParentFile().getPath() ); - FileOutputStream fos = new FileOutputStream( aFile ); - fos.write( "0123456789".getBytes( "US-ASCII" ) ); + FileUtils.deleteDirectory(baseDir); + FileUtils.mkdir(baseDir.getPath()); + final File aFile = new File(baseDir, A_PATH); + FileUtils.mkdir(aFile.getParentFile().getPath()); + FileOutputStream fos = new FileOutputStream(aFile); + fos.write("0123456789".getBytes(StandardCharsets.US_ASCII)); fos.close(); - final File bFile = new File( baseDir, B_PATH ); - fos = new FileOutputStream( bFile ); - fos.write( "abcdefghijklmnopqrstuvwxyz".getBytes( "US-ASCII" ) ); + final File bFile = new File(baseDir, B_PATH); + fos = new FileOutputStream(bFile); + fos.write("abcdefghijklmnopqrstuvwxyz".getBytes(StandardCharsets.US_ASCII)); fos.close(); - final File yDir = new File( baseDir, Y_PATH ); - FileUtils.mkdir( yDir.getPath() ); + final File yDir = new File(baseDir, Y_PATH); + FileUtils.mkdir(yDir.getPath()); } - private void addDirToZipFile( ZipOutputStream zos, File dir, String path ) - throws IOException - { - final String prefix = path == null ? "" : ( path + "/" ); + private void addDirToZipFile(ZipOutputStream zos, File dir, String path) throws IOException { + final String prefix = path == null ? "" : (path + "/"); File[] files = dir.listFiles(); - for ( File f : files ) - { + for (File f : files) { final String entryName = prefix + f.getName(); - ZipEntry ze = new ZipEntry( entryName ); - if ( f.isFile() ) - { - ze.setSize( f.length() ); - zos.putNextEntry( ze ); - FileInputStream fis = new FileInputStream( f ); + ZipEntry ze = new ZipEntry(entryName); + if (f.isFile()) { + ze.setSize(f.length()); + zos.putNextEntry(ze); + FileInputStream fis = new FileInputStream(f); byte[] buffer = new byte[1024]; - for ( ;; ) - { - int res = fis.read( buffer ); - if ( res == -1 ) - { + for (; ; ) { + int res = fis.read(buffer); + if (res == -1) { break; } - if ( res > 0 ) - { - zos.write( buffer, 0, res ); + if (res > 0) { + zos.write(buffer, 0, res); } } fis.close(); - ze.setTime( f.lastModified() ); + ze.setTime(f.lastModified()); zos.closeEntry(); - } - else - { - addDirToZipFile( zos, f, entryName ); + } else { + addDirToZipFile(zos, f, entryName); } } } - private void createZipFile( File dest, File dir ) throws IOException - { - FileOutputStream fos = new FileOutputStream( dest ); - ZipOutputStream zos = new ZipOutputStream( fos ); - addDirToZipFile( zos, dir, null ); + private void createZipFile(File dest, File dir) throws IOException { + FileOutputStream fos = new FileOutputStream(dest); + ZipOutputStream zos = new ZipOutputStream(fos); + addDirToZipFile(zos, dir, null); zos.close(); } - private void compare( InputStream in, File file ) - throws IOException - { - try( InputStream fIn = new FileInputStream( file ) ) - { - for ( ;; ) - { + private void compare(InputStream in, File file) throws IOException { + try (InputStream fIn = Files.newInputStream(file.toPath())) { + for (; ; ) { int i1 = in.read(); int i2 = fIn.read(); - assertEquals( i2, i1 ); - if ( i1 == -1 ) - { + assertEquals(i2, i1); + if (i1 == -1) { break; } } } } - private void compare( PlexusIoResource res, File file ) - throws IOException - { - assertTrue( res.getLastModified() != PlexusIoResource.UNKNOWN_MODIFICATION_DATE ); - if ( res instanceof PlexusIoFileResource ) - { - assertEquals( res.getLastModified() / 1000, file.lastModified() / 1000 ); + private void compare(PlexusIoResource res, File file) throws IOException { + assertTrue(res.getLastModified() != PlexusIoResource.UNKNOWN_MODIFICATION_DATE); + if (res instanceof PlexusIoFileResource) { + assertEquals(res.getLastModified() / 1000, file.lastModified() / 1000); } - assertTrue( res.getSize() != PlexusIoResource.UNKNOWN_RESOURCE_SIZE ); - assertEquals( res.getSize(), file.length() ); + assertTrue(res.getSize() != PlexusIoResource.UNKNOWN_RESOURCE_SIZE); + assertEquals(res.getSize(), file.length()); InputStream in = res.getContents(); - compare( in, file ); + compare(in, file); in.close(); URLConnection uc = res.getURL().openConnection(); - uc.setUseCaches( false ); + uc.setUseCaches(false); in = uc.getInputStream(); - compare( in, file ); + compare(in, file); in.close(); } - private void testPlexusIoResourceCollection( PlexusIoResourceCollection plexusIoResourceCollection ) - throws IOException - { + private void testPlexusIoResourceCollection(PlexusIoResourceCollection plexusIoResourceCollection) + throws IOException { boolean xPathSeen = false; boolean yPathSeen = false; boolean aFileSeen = false; boolean bFileSeen = false; - Iterator iter = plexusIoResourceCollection.getResources(); - while ( iter.hasNext() ) - { - PlexusIoResource res = (PlexusIoResource) iter.next(); - final String resName = res.getName().replace( File.separatorChar, '/' ); - if ( res.isDirectory() ) - { - assertFalse( "The directory " + resName + " is a file.", res.isFile() ); - if ( X_PATH.equals( resName ) ) - { + Iterator iter = plexusIoResourceCollection.getResources(); + while (iter.hasNext()) { + PlexusIoResource res = iter.next(); + final String resName = res.getName().replace(File.separatorChar, '/'); + if (res.isDirectory()) { + assertFalse(res.isFile(), "The directory " + resName + " is a file."); + if (X_PATH.equals(resName)) { xPathSeen = true; - } - else if ( Y_PATH.equals( resName ) ) - { + } else if (Y_PATH.equals(resName)) { yPathSeen = true; - } - else if ( "".equals( resName ) || ".".equals( resName ) ) - { + } else if (resName.isEmpty() || ".".equals(resName)) { // Ignore me + } else { + fail("Unexpected directory entry: " + resName); } - else - { - fail( "Unexpected directory entry: " + resName ); - } - final File dir = new File( getFilesDir(), resName ); - assertTrue( "The directory " + dir + " doesn't exist.", dir.isDirectory() ); - } - else - { - assertTrue( "The file " + resName + " isn't reported to be a file.", res.isFile() ); - assertTrue( "The file " + resName + " doesn't exist.", res.isExisting() ); - final File f = new File( getFilesDir(), resName ); - assertTrue( "A file " + f + " doesn't exist.", f.isFile() && f.exists() ); - if ( A_PATH.equals( resName ) ) - { + final File dir = new File(getFilesDir(), resName); + assertTrue(dir.isDirectory(), "The directory " + dir + " doesn't exist."); + } else { + assertTrue(res.isFile(), "The file " + resName + " isn't reported to be a file."); + assertTrue(res.isExisting(), "The file " + resName + " doesn't exist."); + final File f = new File(getFilesDir(), resName); + assertTrue(f.isFile() && f.exists(), "A file " + f + " doesn't exist."); + if (A_PATH.equals(resName)) { aFileSeen = true; - } - else if ( B_PATH.equals( resName ) ) - { + } else if (B_PATH.equals(resName)) { bFileSeen = true; + } else { + fail("Unexpected file entry: " + resName); } - else - { - fail( "Unexpected file entry: " + resName ); - } - compare( res, f ); + compare(res, f); } } - assertTrue( aFileSeen ); - assertTrue( bFileSeen ); - if ( iter instanceof Closeable ) - { - ( (Closeable) iter ).close(); + assertTrue(aFileSeen); + assertTrue(bFileSeen); + if (iter instanceof Closeable) { + ((Closeable) iter).close(); } } - private void testFileResourceCollection( PlexusIoFileResourceCollection resourceCollection ) - throws IOException - { - resourceCollection.setBaseDir( getFilesDir() ); - testPlexusIoResourceCollection( resourceCollection ); + private void testFileResourceCollection(PlexusIoFileResourceCollection resourceCollection) throws IOException { + resourceCollection.setBaseDir(getFilesDir()); + testPlexusIoResourceCollection(resourceCollection); } - public void testFileCollection() throws Exception - { + @Test + void testFileCollection() throws Exception { createFiles(); - testFileResourceCollection( (PlexusIoFileResourceCollection) lookup( PlexusIoResourceCollection.ROLE, - PlexusIoResourceCollection.DEFAULT_ROLE_HINT ) ); - testFileResourceCollection( (PlexusIoFileResourceCollection) lookup( PlexusIoResourceCollection.ROLE, - PlexusIoFileResourceCollection.ROLE_HINT ) ); - } - - private void testZipFileCollection( AbstractPlexusIoArchiveResourceCollection resourceCollection, File zipFile ) - throws IOException - { - resourceCollection.setFile( zipFile ); - testPlexusIoResourceCollection( resourceCollection ); + testFileResourceCollection((PlexusIoFileResourceCollection) container.lookup(PlexusIoResourceCollection.class)); + testFileResourceCollection((PlexusIoFileResourceCollection) + container.lookup(PlexusIoResourceCollection.class, PlexusIoFileResourceCollection.ROLE_HINT)); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/filemappers/TestSupport.java b/src/test/java/org/codehaus/plexus/components/io/filemappers/TestSupport.java new file mode 100644 index 00000000..aa88691d --- /dev/null +++ b/src/test/java/org/codehaus/plexus/components/io/filemappers/TestSupport.java @@ -0,0 +1,24 @@ +package org.codehaus.plexus.components.io.filemappers; + +/* + * Copyright 2007 The Codehaus Foundation. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import org.eclipse.sisu.launch.InjectedTest; + +/** + * Support for componentized testing. + */ +public abstract class TestSupport extends InjectedTest {} diff --git a/src/test/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionTest.java b/src/test/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionTest.java index f3e46263..4e068ba3 100644 --- a/src/test/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/resources/AbstractPlexusIoResourceCollectionTest.java @@ -1,9 +1,7 @@ package org.codehaus.plexus.components.io.resources; -import junit.framework.TestCase; -import org.codehaus.plexus.components.io.functions.InputStreamTransformer; - import javax.annotation.Nonnull; + import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; @@ -11,76 +9,61 @@ import java.util.Arrays; import java.util.Iterator; +import org.codehaus.plexus.components.io.functions.InputStreamTransformer; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + /** * @author Kristian Rosenvold */ -public class AbstractPlexusIoResourceCollectionTest - extends TestCase -{ - @SuppressWarnings( "ResultOfMethodCallIgnored" ) - public void testGetIncludes() - throws Exception - { - AbstractPlexusIoResourceCollection sut = new AbstractPlexusIoResourceCollection() - { - public Iterator getResources() - throws IOException - { - return Arrays.asList( getResource( "r1" ), getResource( "r2" ) ).iterator(); +public class AbstractPlexusIoResourceCollectionTest { + @SuppressWarnings("ResultOfMethodCallIgnored") + @Test + void testGetIncludes() throws Exception { + AbstractPlexusIoResourceCollection sut = new AbstractPlexusIoResourceCollection() { + public Iterator getResources() { + return Arrays.asList(getResource("r1"), getResource("r2")).iterator(); } - public Stream stream() - { + public Stream stream() { throw new UnsupportedOperationException(); } - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { return true; } - }; - sut.setStreamTransformer( new InputStreamTransformer() - { + sut.setStreamTransformer(new InputStreamTransformer() { @Nonnull - public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull final InputStream inputStream ) - throws IOException - { + public InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull final InputStream inputStream) + throws IOException { final byte[] buf = new byte[2]; buf[0] = (byte) inputStream.read(); buf[1] = (byte) inputStream.read(); - return new ByteArrayInputStream( buf ); + return new ByteArrayInputStream(buf); } - } ); + }); final PlexusIoResource next = sut.getResources().next(); - final InputStream inputStream = sut.getInputStream( next ); + final InputStream inputStream = sut.getInputStream(next); inputStream.read(); inputStream.read(); - assertEquals( -1, inputStream.read() ); + assertEquals(-1, inputStream.read()); inputStream.close(); - } - private static PlexusIoResource getResource( final String r1 ) - { - return new AbstractPlexusIoResource( r1, 0, 0, true, false, true ) - { + private static PlexusIoResource getResource(final String r1) { + return new AbstractPlexusIoResource(r1, 0, 0, true, false, true) { @Nonnull - public InputStream getContents() - throws IOException - { - return new ByteArrayInputStream( (r1 + "Payload").getBytes() ); + public InputStream getContents() { + return new ByteArrayInputStream((r1 + "Payload").getBytes()); } - public URL getURL() - throws IOException - { - throw new IllegalStateException( "Not implemented" ); + public URL getURL() { + throw new IllegalStateException("Not implemented"); } }; } - } - diff --git a/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoFileSupplierResourceCollectionTest.java b/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoFileSupplierResourceCollectionTest.java index d45762d0..dfcce726 100755 --- a/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoFileSupplierResourceCollectionTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoFileSupplierResourceCollectionTest.java @@ -1,30 +1,28 @@ package org.codehaus.plexus.components.io.resources; -import junit.framework.TestCase; - import java.io.File; import java.util.Iterator; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertTrue; + /** * @author Kristian Rosenvold */ -public class PlexusIoFileSupplierResourceCollectionTest - extends TestCase -{ - public void testGetName() - throws Exception - { +public class PlexusIoFileSupplierResourceCollectionTest { + @Test + void testGetName() throws Exception { PlexusIoFileResourceCollection coll = new PlexusIoFileResourceCollection(); char nonSeparator = File.separatorChar == '/' ? '\\' : '/'; - coll.setPrefix( "fud" + nonSeparator ); + coll.setPrefix("fud" + nonSeparator); - coll.setBaseDir( new File( "src/test/resources/symlinks" ) ); + coll.setBaseDir(new File("src/test/resources/symlinks")); final Iterator resources = coll.getResources(); - while ( resources.hasNext() ) - { + while (resources.hasNext()) { final PlexusIoResource next = resources.next(); - final String name = coll.getName( next ); - assertTrue( name.indexOf( nonSeparator ) < 0 ); + final String name = coll.getName(next); + assertTrue(name.indexOf(nonSeparator) < 0); } } } diff --git a/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoPlexusIoFileResourceTest.java b/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoPlexusIoFileResourceTest.java index 17905f22..d61cf544 100644 --- a/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoPlexusIoFileResourceTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/resources/PlexusIoPlexusIoFileResourceTest.java @@ -5,25 +5,58 @@ import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; - -import junit.framework.TestCase; import org.codehaus.plexus.components.io.attributes.SymlinkUtils; -import org.codehaus.plexus.util.Os; - -public class PlexusIoPlexusIoFileResourceTest - extends TestCase { - - public void testRealSymlink() - throws IOException - { - if ( Os.isFamily( Os.FAMILY_WINDOWS ) ) - return; - final File file = new File( "src/test/resources/symlinks/src/symDir" ); - PlexusIoResourceAttributes attrs = FileAttributes.uncached( file ); - assertTrue( attrs.isSymbolicLink() ); - PlexusIoFileResource r = new PlexusIoFileResource( file, "symDir", attrs ); - assertTrue( r.isSymbolicLink() ); - final File target = SymlinkUtils.readSymbolicLink( file ); - assertTrue( target.getName().endsWith( "targetDir" ) ); +import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.DisabledOnOs; +import org.junit.jupiter.api.condition.OS; + +import static org.junit.jupiter.api.Assertions.*; + +public class PlexusIoPlexusIoFileResourceTest { + + @Test + @DisabledOnOs(OS.WINDOWS) + void testRealSymlink() throws IOException { + final File file = new File("src/test/resources/symlinks/src/symDir"); + PlexusIoResourceAttributes attrs = FileAttributes.uncached(file); + assertTrue(attrs.isSymbolicLink()); + PlexusIoResource r = ResourceFactory.createResource(file); + assertTrue(r.isSymbolicLink()); + assertTrue(r.isDirectory()); + final File target = SymlinkUtils.readSymbolicLink(file); + assertTrue(target.getName().endsWith("targetDir")); + assertTrue(r instanceof SymlinkDestinationSupplier); + assertEquals("targetDir/", ((SymlinkDestinationSupplier) r).getSymlinkDestination()); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void testSymSymlinkFile() throws IOException { + final File file = new File("src/test/resources/symlinks/src/symSymR"); + PlexusIoResource r = ResourceFactory.createResource(file); + assertTrue(r.isSymbolicLink()); + assertEquals(38, r.getSize()); + PlexusIoResource rL = ((PlexusIoSymlinkResource) r).getLink(); + assertFalse(rL instanceof PlexusIoSymlinkResource); + PlexusIoResource rT = ((PlexusIoSymlinkResource) r).getTarget(); + assertTrue(rT instanceof PlexusIoSymlinkResource); + PlexusIoResource rTT = ((PlexusIoSymlinkResource) rT).getTarget(); + assertFalse(rTT instanceof PlexusIoSymlinkResource); + } + + @Test + @DisabledOnOs(OS.WINDOWS) + void testSymlinkFile() throws IOException { + final File file = new File("src/test/resources/symlinks/src/symR"); + PlexusIoResource r = ResourceFactory.createResource(file); + assertTrue(r.isSymbolicLink()); + assertEquals(38, r.getSize()); + + final File file2 = new File("src/test/resources/symlinks/src/symSymR"); + PlexusIoResource r2 = ResourceFactory.createResource(file2); + assertTrue(r2.isSymbolicLink()); + assertEquals(38, r2.getSize()); + PlexusIoResource r3 = ((PlexusIoSymlinkResource) r2).getTarget(); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollectionTest.java b/src/test/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollectionTest.java index a7f4b6d3..1ce7f92e 100644 --- a/src/test/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollectionTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/resources/proxy/PlexusIoProxyResourceCollectionTest.java @@ -16,122 +16,102 @@ * limitations under the License. */ -import org.codehaus.plexus.PlexusTestCase; -import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource; -import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResourceCollection; -import org.codehaus.plexus.components.io.resources.PlexusIoResource; -import org.codehaus.plexus.components.io.resources.Stream; - import javax.annotation.Nonnull; + import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Iterator; +import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource; +import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResourceCollection; +import org.codehaus.plexus.components.io.resources.PlexusIoResource; +import org.codehaus.plexus.components.io.resources.Stream; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; /** * Test case for {@link PlexusIoProxyResourceCollection}. */ -public class PlexusIoProxyResourceCollectionTest - extends PlexusTestCase -{ - private final String[] SAMPLE_INCLUDES = { "junk.*", "test/**", "dir*/file.xml" }; +public class PlexusIoProxyResourceCollectionTest { + private final String[] SAMPLE_INCLUDES = {"junk.*", "test/**", "dir*/file.xml"}; - private final String[] SAMPLE_EXCLUDES = { "*.junk", "somwhere/**" }; + private final String[] SAMPLE_EXCLUDES = {"*.junk", "somwhere/**"}; - public void testGetDefaultFileSelector() - throws Exception - { - PlexusIoProxyResourceCollection resCol = new PlexusIoProxyResourceCollection( null ); + @Test + void testGetDefaultFileSelector() { + PlexusIoProxyResourceCollection resCol = new PlexusIoProxyResourceCollection(null); // This will throw an exception if there is a bug resCol.getDefaultFileSelector(); - resCol.setIncludes( SAMPLE_INCLUDES ); - resCol.setExcludes( SAMPLE_EXCLUDES ); + resCol.setIncludes(SAMPLE_INCLUDES); + resCol.setExcludes(SAMPLE_EXCLUDES); // This will throw an exception if there is a bug resCol.getDefaultFileSelector(); - } - class CloseableIterator - implements Iterator, Closeable - { + static class CloseableIterator implements Iterator, Closeable { boolean next = true; boolean closed = false; - public void close() - throws IOException - { + public void close() { closed = true; } - public boolean hasNext() - { - if ( next ) - { + public boolean hasNext() { + if (next) { next = false; return true; } return false; } - public PlexusIoResource next() - { - return new AbstractPlexusIoResource( "fud", 123, 22, true, false, false ) - { + public PlexusIoResource next() { + return new AbstractPlexusIoResource("fud", 123, 22, true, false, false) { @Nonnull - public InputStream getContents() - throws IOException - { + public InputStream getContents() { return null; } - public URL getURL() - throws IOException - { + public URL getURL() { return null; } }; } - public void remove() - { + public void remove() { throw new UnsupportedOperationException(); } } - - public void testClosing() - throws IOException - { + + @Test + void testClosing() throws IOException { final CloseableIterator closeableIterator = new CloseableIterator(); PlexusIoProxyResourceCollection resCol = - new PlexusIoProxyResourceCollection( new AbstractPlexusIoResourceCollection() - { - public Iterator getResources() - throws IOException - { - return closeableIterator; - } - - public Stream stream() - { - throw new UnsupportedOperationException(); - } - - public boolean isConcurrentAccessSupported() - { - return true; - } - } ); + new PlexusIoProxyResourceCollection(new AbstractPlexusIoResourceCollection() { + public Iterator getResources() { + return closeableIterator; + } + + public Stream stream() { + throw new UnsupportedOperationException(); + } + + public boolean isConcurrentAccessSupported() { + return true; + } + }); Iterator resources1 = resCol.getResources(); resources1.hasNext(); resources1.next(); - assertFalse( resources1.hasNext() ); - ( (Closeable) resources1 ).close(); - assertTrue( closeableIterator.closed ); + assertFalse(resources1.hasNext()); + ((Closeable) resources1).close(); + assertTrue(closeableIterator.closed); } -} \ No newline at end of file +} diff --git a/src/test/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactoryTest.java b/src/test/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactoryTest.java index 380585fd..152b6331 100644 --- a/src/test/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactoryTest.java +++ b/src/test/java/org/codehaus/plexus/components/io/resources/proxy/ProxyFactoryTest.java @@ -1,6 +1,12 @@ package org.codehaus.plexus.components.io.resources.proxy; -import junit.framework.TestCase; +import javax.annotation.Nonnull; + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes; @@ -12,135 +18,79 @@ import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; import org.codehaus.plexus.components.io.resources.PlexusIoFileResource; import org.codehaus.plexus.components.io.resources.PlexusIoResource; +import org.junit.jupiter.api.Test; -import javax.annotation.Nonnull; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; +import static org.junit.jupiter.api.Assertions.*; + +public class ProxyFactoryTest { -public class ProxyFactoryTest - extends TestCase -{ - - public void testCreateProxy() - throws Exception - { - final PlexusIoResource proxy = ProxyFactory.createProxy( getPomResource(), null ); - assertTrue( proxy instanceof ResourceAttributeSupplier ); - assertTrue( proxy instanceof FileSupplier ); - assertFalse( proxy instanceof SymlinkDestinationSupplier ); + @Test + void testCreateProxy() throws Exception { + final PlexusIoResource proxy = ProxyFactory.createProxy(getPomResource(), null); + assertTrue(proxy instanceof ResourceAttributeSupplier); + assertTrue(proxy instanceof FileSupplier); + assertFalse(proxy instanceof SymlinkDestinationSupplier); } - public void testCreateProxyWithNameOverride() - throws Exception - { - NameSupplier ns = new NameSupplier() - { - public String getName() - { - return "fred"; - } - }; - final PlexusIoResource proxy = ProxyFactory.createProxy( getPomResource(), ns ); - assertEquals( "fred", proxy.getName() ); + @Test + void testCreateProxyWithNameOverride() throws Exception { + NameSupplier ns = () -> "fred"; + final PlexusIoResource proxy = ProxyFactory.createProxy(getPomResource(), ns); + assertEquals("fred", proxy.getName()); } - public void testCreateProxyWithResourceAttributeOverride() - throws Exception - { + @Test + void testCreateProxyWithResourceAttributeOverride() throws Exception { final PlexusIoResourceAttributes s = SimpleResourceAttributes.lastResortDummyAttributesForBrokenOS(); - ResourceAttributeSupplier ns = new ResourceAttributeSupplier() - { - public PlexusIoResourceAttributes getAttributes() - { - return s; - } - }; - final PlexusIoResource proxy = ProxyFactory.createProxy( getPomResource(), ns ); - assertSame( s, ( (ResourceAttributeSupplier) proxy ).getAttributes() ); + ResourceAttributeSupplier ns = () -> s; + final PlexusIoResource proxy = ProxyFactory.createProxy(getPomResource(), ns); + assertSame(s, ((ResourceAttributeSupplier) proxy).getAttributes()); } - public void testCreateProxyWithSizeSupplierOverride() - throws Exception - { + @Test + void testCreateProxyWithSizeSupplierOverride() throws Exception { final PlexusIoResourceAttributes s = SimpleResourceAttributes.lastResortDummyAttributesForBrokenOS(); - SizeSupplier ns = new SizeSupplier() - { - public long getSize() - { - return 42; - } - }; - final PlexusIoResource proxy = ProxyFactory.createProxy( getPomResource(), ns ); - assertEquals( 42, proxy.getSize() ); + SizeSupplier ns = () -> 42; + final PlexusIoResource proxy = ProxyFactory.createProxy(getPomResource(), ns); + assertEquals(42, proxy.getSize()); } - - public void testCreateProxyWithContentSupplierOverride() - throws Exception - { - final InputStream s = new ByteArrayInputStream( new byte[10] ); - ContentSupplier ns = new ContentSupplier() - { - public InputStream getContents() - throws IOException - { - return s; - } - - }; - final PlexusIoResource proxy = ProxyFactory.createProxy( getPomResource(), ns ); - assertEquals( s, proxy.getContents() ); + @Test + void testCreateProxyWithContentSupplierOverride() throws Exception { + final InputStream s = new ByteArrayInputStream(new byte[10]); + ContentSupplier ns = () -> s; + final PlexusIoResource proxy = ProxyFactory.createProxy(getPomResource(), ns); + assertEquals(s, proxy.getContents()); } - public void testCreateProxyWithSymlinkDestinationSupplierOverride() - throws Exception - { - SymlinkDestinationSupplier ns = new SymlinkDestinationSupplier() - { - public String getSymlinkDestination() - throws IOException - { - return "mordor"; - } - }; - final PlexusIoResource proxy = ProxyFactory.createProxy( getDummySymlinkResource(), ns ); - assertEquals( "mordor", ( (SymlinkDestinationSupplier) proxy ).getSymlinkDestination() ); + @Test + void testCreateProxyWithSymlinkDestinationSupplierOverride() throws Exception { + SymlinkDestinationSupplier ns = () -> "mordor"; + final PlexusIoResource proxy = ProxyFactory.createProxy(getDummySymlinkResource(), ns); + assertEquals("mordor", ((SymlinkDestinationSupplier) proxy).getSymlinkDestination()); } + private PlexusIoFileResource getPomResource() throws IOException { + final File file = new File("pom.xml"); + PlexusIoResourceAttributes attrs = FileAttributes.uncached(file); - private PlexusIoFileResource getPomResource() - throws IOException - { - final File file = new File( "pom.xml" ); - PlexusIoResourceAttributes attrs = FileAttributes.uncached( file ); - - return new PlexusIoFileResource( file, "pom.xml", attrs ){}; + return new PlexusIoFileResource(file, "pom.xml", attrs) {}; } - class Dummy extends PlexusIoFileResource - implements SymlinkDestinationSupplier - { - public Dummy( @Nonnull File file, @Nonnull PlexusIoResourceAttributes attrs ) - throws IOException - { - super( file, file.getName(), attrs ); + static class Dummy extends PlexusIoFileResource implements SymlinkDestinationSupplier { + public Dummy(@Nonnull File file, @Nonnull PlexusIoResourceAttributes attrs) throws IOException { + super(file, file.getName(), attrs); } - public String getSymlinkDestination() - throws IOException - { - throw new IllegalStateException( "Unsupported" ); + public String getSymlinkDestination() { + throw new IllegalStateException("Unsupported"); } } - private Dummy getDummySymlinkResource() - throws IOException - { - final File file = new File( "pom.xml" ); - PlexusIoResourceAttributes attrs = FileAttributes.uncached( file ); - return new Dummy( file, attrs ); - } + private Dummy getDummySymlinkResource() throws IOException { + final File file = new File("pom.xml"); + PlexusIoResourceAttributes attrs = FileAttributes.uncached(file); -} \ No newline at end of file + return new Dummy(file, attrs); + } +} diff --git a/src/test/resources/symlinks/src/symSymR b/src/test/resources/symlinks/src/symSymR new file mode 120000 index 00000000..95277162 --- /dev/null +++ b/src/test/resources/symlinks/src/symSymR @@ -0,0 +1 @@ +symR \ No newline at end of file