From 13b602af7169a8e49d47edf59f4154e1b834c0d8 Mon Sep 17 00:00:00 2001 From: Sylwester Lachiewicz Date: Mon, 22 May 2023 22:40:17 +0200 Subject: [PATCH] Reformat --- pom.xml | 35 +- .../archiver/AbstractArchiveFinalizer.java | 19 +- .../plexus/archiver/AbstractArchiver.java | 975 +++++++----------- .../plexus/archiver/AbstractUnArchiver.java | 292 +++--- .../plexus/archiver/ArchiveEntry.java | 220 ++-- .../codehaus/plexus/archiver/ArchiveFile.java | 10 +- .../plexus/archiver/ArchiveFileFilter.java | 10 +- .../archiver/ArchiveFilterException.java | 15 +- .../plexus/archiver/ArchiveFinalizer.java | 10 +- .../plexus/archiver/ArchivedFileSet.java | 8 +- .../codehaus/plexus/archiver/Archiver.java | 120 +-- .../plexus/archiver/ArchiverException.java | 15 +- .../codehaus/plexus/archiver/BaseFileSet.java | 5 +- .../DotDirectiveArchiveFinalizer.java | 70 +- .../org/codehaus/plexus/archiver/FileSet.java | 5 +- .../plexus/archiver/FinalizerEnabled.java | 8 +- .../plexus/archiver/ResourceIterator.java | 4 +- .../codehaus/plexus/archiver/UnArchiver.java | 27 +- .../codehaus/plexus/archiver/UnixStat.java | 4 +- .../plexus/archiver/bzip2/BZip2Archiver.java | 38 +- .../archiver/bzip2/BZip2Compressor.java | 39 +- .../archiver/bzip2/BZip2UnArchiver.java | 63 +- .../bzip2/PlexusIoBz2ResourceCollection.java | 7 +- .../PlexusIoBzip2ResourceCollection.java | 32 +- .../plexus/archiver/car/CarUnArchiver.java | 16 +- .../PlexusIoCarFileResourceCollection.java | 7 +- .../archiver/diags/DelgatingArchiver.java | 297 ++---- .../plexus/archiver/diags/DryRunArchiver.java | 147 +-- .../plexus/archiver/diags/NoOpArchiver.java | 304 ++---- .../archiver/diags/TrackingArchiver.java | 336 ++---- .../archiver/dir/DirectoryArchiver.java | 184 ++-- .../plexus/archiver/ear/EarArchiver.java | 88 +- .../plexus/archiver/ear/EarUnArchiver.java | 16 +- .../PlexusIoEarFileResourceCollection.java | 7 +- .../plexus/archiver/esb/EsbUnArchiver.java | 16 +- .../PlexusIoEsbFileResourceCollection.java | 7 +- .../exceptions/EmptyArchiveException.java | 15 +- .../filters/JarSecurityFileFilter.java | 15 +- .../filters/JarSecurityFileSelector.java | 23 +- .../plexus/archiver/gzip/GZipArchiver.java | 38 +- .../plexus/archiver/gzip/GZipCompressor.java | 43 +- .../plexus/archiver/gzip/GZipUnArchiver.java | 62 +- .../gzip/PlexusIoGzResourceCollection.java | 7 +- .../gzip/PlexusIoGzipResourceCollection.java | 32 +- .../plexus/archiver/jar/JarArchiver.java | 544 ++++------ .../jar/JarToolModularJarArchiver.java | 223 ++-- .../plexus/archiver/jar/JarUnArchiver.java | 17 +- .../archiver/jar/JdkManifestFactory.java | 82 +- .../plexus/archiver/jar/Manifest.java | 573 ++++------ .../archiver/jar/ManifestConstants.java | 4 +- .../archiver/jar/ManifestException.java | 10 +- .../archiver/jar/ModularJarArchiver.java | 31 +- .../PlexusIoJarFileResourceCollection.java | 26 +- .../archiver/manager/ArchiverManager.java | 24 +- .../manager/DefaultArchiverManager.java | 121 +-- .../manager/NoSuchArchiverException.java | 13 +- .../plexus/archiver/nar/NarUnArchiver.java | 16 +- .../PlexusIoNarFileResourceCollection.java | 7 +- .../plexus/archiver/par/ParUnArchiver.java | 16 +- .../PlexusIoJarFileResourceCollection.java | 7 +- .../PlexusIoRarFileResourceCollection.java | 7 +- .../plexus/archiver/rar/RarArchiver.java | 14 +- .../plexus/archiver/rar/RarUnArchiver.java | 16 +- .../PlexusIoVirtualFileResource.java | 63 +- .../PlexusIoVirtualSymlinkResource.java | 24 +- .../PlexusIoSarFileResourceCollection.java | 7 +- .../plexus/archiver/sar/SarUnArchiver.java | 16 +- .../PlexusIoSnappyResourceCollection.java | 31 +- .../archiver/snappy/SnappyArchiver.java | 38 +- .../archiver/snappy/SnappyCompressor.java | 39 +- .../archiver/snappy/SnappyUnArchiver.java | 63 +- .../PlexusIoSwcFileResourceCollection.java | 7 +- .../plexus/archiver/swc/SwcUnArchiver.java | 16 +- .../plexus/archiver/tar/BZip2TarFile.java | 16 +- .../plexus/archiver/tar/GZipTarFile.java | 17 +- .../PlexusIoTBZ2FileResourceCollection.java | 7 +- .../PlexusIoTGZFileResourceCollection.java | 7 +- .../PlexusIoTXZFileResourceCollection.java | 6 +- .../PlexusIoTZstdFileResourceCollection.java | 6 +- ...lexusIoTarBZip2FileResourceCollection.java | 12 +- .../PlexusIoTarFileResourceCollection.java | 55 +- ...PlexusIoTarGZipFileResourceCollection.java | 12 +- ...exusIoTarSnappyFileResourceCollection.java | 12 +- .../PlexusIoTarXZFileResourceCollection.java | 15 +- ...PlexusIoTarZstdFileResourceCollection.java | 16 +- .../plexus/archiver/tar/SnappyTarFile.java | 16 +- .../plexus/archiver/tar/TBZ2Archiver.java | 7 +- .../plexus/archiver/tar/TBZ2UnArchiver.java | 9 +- .../plexus/archiver/tar/TGZArchiver.java | 7 +- .../plexus/archiver/tar/TGZUnArchiver.java | 9 +- .../plexus/archiver/tar/TXZArchiver.java | 6 +- .../plexus/archiver/tar/TXZUnArchiver.java | 8 +- .../plexus/archiver/tar/TZstdArchiver.java | 6 +- .../plexus/archiver/tar/TZstdUnArchiver.java | 6 +- .../plexus/archiver/tar/TarArchiver.java | 378 +++---- .../plexus/archiver/tar/TarBZip2Archiver.java | 15 +- .../archiver/tar/TarBZip2UnArchiver.java | 20 +- .../codehaus/plexus/archiver/tar/TarFile.java | 133 +-- .../plexus/archiver/tar/TarGZipArchiver.java | 15 +- .../archiver/tar/TarGZipUnArchiver.java | 20 +- .../plexus/archiver/tar/TarLongFileMode.java | 40 +- .../plexus/archiver/tar/TarResource.java | 50 +- .../archiver/tar/TarSnappyArchiver.java | 15 +- .../archiver/tar/TarSnappyUnArchiver.java | 20 +- .../archiver/tar/TarSymlinkResource.java | 19 +- .../plexus/archiver/tar/TarUnArchiver.java | 140 +-- .../plexus/archiver/tar/TarXZArchiver.java | 14 +- .../plexus/archiver/tar/TarXZUnArchiver.java | 19 +- .../plexus/archiver/tar/TarZstdArchiver.java | 13 +- .../archiver/tar/TarZstdUnArchiver.java | 20 +- .../plexus/archiver/tar/XZTarFile.java | 15 +- .../plexus/archiver/tar/ZstdTarFile.java | 18 +- .../plexus/archiver/util/AbstractFileSet.java | 85 +- .../archiver/util/ArchiveEntryUtils.java | 41 +- .../plexus/archiver/util/Compressor.java | 53 +- .../archiver/util/DefaultArchivedFileSet.java | 26 +- .../plexus/archiver/util/DefaultFileSet.java | 29 +- .../plexus/archiver/util/FilePermission.java | 40 +- .../archiver/util/FilePermissionUtils.java | 73 +- .../plexus/archiver/util/FilterSupport.java | 30 +- .../plexus/archiver/util/ResourceUtils.java | 80 +- .../plexus/archiver/util/Streams.java | 141 +-- .../PlexusIoWarFileResourceCollection.java | 7 +- .../plexus/archiver/war/WarArchiver.java | 123 +-- .../plexus/archiver/war/WarUnArchiver.java | 16 +- .../xz/PlexusIoXZResourceCollection.java | 19 +- .../plexus/archiver/xz/XZArchiver.java | 40 +- .../plexus/archiver/xz/XZCompressor.java | 41 +- .../plexus/archiver/xz/XZUnArchiver.java | 61 +- .../archiver/zip/AbstractZipArchiver.java | 560 ++++------ .../archiver/zip/AbstractZipUnArchiver.java | 145 +-- .../plexus/archiver/zip/AddedDirs.java | 47 +- .../archiver/zip/AnonymousResource.java | 32 +- .../archiver/zip/ByteArrayOutputStream.java | 216 ++-- .../archiver/zip/ConcurrentJarCreator.java | 152 ++- .../zip/DeferredScatterOutputStream.java | 27 +- .../archiver/zip/OffloadingOutputStream.java | 45 +- ...exusArchiverZipFileResourceCollection.java | 56 +- .../PlexusIoZipFileResourceCollection.java | 161 ++- .../plexus/archiver/zip/ZipArchiver.java | 7 +- .../plexus/archiver/zip/ZipResource.java | 58 +- .../archiver/zip/ZipSymlinkResource.java | 30 +- .../plexus/archiver/zip/ZipUnArchiver.java | 16 +- .../zstd/PlexusIoZstdResourceCollection.java | 19 +- .../plexus/archiver/zstd/ZstdArchiver.java | 46 +- .../plexus/archiver/zstd/ZstdCompressor.java | 59 +- .../plexus/archiver/zstd/ZstdUnArchiver.java | 63 +- .../PlexusIoZipFileResourceCollection.java | 6 +- .../plexus/archiver/AbstractArchiverTest.java | 90 +- .../archiver/AbstractUnArchiverTest.java | 137 ++- .../archiver/BasePlexusArchiverTest.java | 45 +- .../DotDirectiveArchiveFinalizerTest.java | 50 +- .../plexus/archiver/DuplicateFilesTest.java | 124 +-- .../plexus/archiver/EmptyDirectoryTest.java | 58 +- .../codehaus/plexus/archiver/SymlinkTest.java | 119 +-- .../codehaus/plexus/archiver/TestSupport.java | 19 +- .../archiver/bzip2/BZip2ArchiverTest.java | 101 +- .../archiver/gzip/GZipArchiverTest.java | 97 +- .../archiver/jar/BaseJarArchiverTest.java | 44 +- .../jar/DirectoryArchiverUnpackJarTest.java | 68 +- .../plexus/archiver/jar/IndexTest.java | 119 ++- .../plexus/archiver/jar/JarArchiverTest.java | 144 +-- .../jar/JarToolModularJarArchiverTest.java | 348 +++---- .../archiver/jar/JdkManifestFactoryTest.java | 118 +-- .../plexus/archiver/jar/ManifestTest.java | 346 +++---- .../archiver/manager/ArchiverManagerTest.java | 267 +++-- .../plexus/archiver/rar/RarArchiverTest.java | 98 +- .../plexus/archiver/sar/SarArchiverTest.java | 19 +- .../archiver/snappy/SnappyArchiverTest.java | 100 +- .../plexus/archiver/tar/TarArchiverTest.java | 485 ++++----- .../archiver/tar/TarBZip2UnArchiverTest.java | 53 +- .../archiver/tar/TarFileAttributesTest.java | 177 ++-- .../plexus/archiver/tar/TarFileTest.java | 99 +- .../archiver/tar/TarGZipUnArchiverTest.java | 53 +- .../plexus/archiver/tar/TarRoundTripTest.java | 30 +- .../archiver/tar/TarSnappyUnArchiverTest.java | 52 +- .../archiver/tar/TarUnArchiverTest.java | 116 +-- .../archiver/tar/TarXzUnArchiverTest.java | 61 +- .../archiver/tar/TarZstdUnArchiverTest.java | 61 +- .../archiver/util/ArchiveEntryUtilsTest.java | 47 +- .../archiver/util/DefaultFileSetTest.java | 29 +- .../util/FilePermissionUtilsTest.java | 71 +- .../plexus/archiver/war/WarArchiverTest.java | 69 +- .../plexus/archiver/xz/XzArchiverTest.java | 110 +- .../archiver/zip/ArchiveFileComparator.java | 232 ++--- .../zip/ConcurrentJarCreatorTest.java | 146 ++- .../zip/OffloadingOutputStreamTest.java | 25 +- ...ArchiverZipFileResourceCollectionTest.java | 51 +- ...PlexusIoZipFileResourceCollectionTest.java | 126 +-- .../plexus/archiver/zip/ZipArchiverTest.java | 974 ++++++++--------- .../archiver/zip/ZipUnArchiverTest.java | 346 +++---- .../archiver/zstd/ZstdArchiverTest.java | 109 +- 192 files changed, 6115 insertions(+), 9533 deletions(-) diff --git a/pom.xml b/pom.xml index d86b40dcc..89995ae98 100644 --- a/pom.xml +++ b/pom.xml @@ -1,5 +1,4 @@ - 4.0.0 @@ -15,11 +14,24 @@ https://codehaus-plexus.github.io/plexus-archiver/ + + + Dan Tran + + + Richard van der Hoff + + + Tomasz 'Trog' Welman + trog@swmud.pl + + + scm:git:https://github.com/codehaus-plexus/plexus-archiver.git scm:git:https://github.com/codehaus-plexus/plexus-archiver.git - http://github.com/codehaus-plexus/plexus-archiver/tree/${project.scm.tag}/ plexus-archiver-4.6.1 + http://github.com/codehaus-plexus/plexus-archiver/tree/${project.scm.tag}/ jira @@ -38,19 +50,6 @@ 2023-05-05T22:34:21Z - - - Dan Tran - - - Richard van der Hoff - - - Tomasz 'Trog' Welman - trog@swmud.pl - - - @@ -182,15 +181,17 @@ org.apache.maven.plugins maven-scm-publish-plugin - ${project.reporting.outputDirectory} + ${project.reporting.outputDirectory} + scm-publish - site-deploy + publish-scm + site-deploy diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractArchiveFinalizer.java b/src/main/java/org/codehaus/plexus/archiver/AbstractArchiveFinalizer.java index 92edeb97b..6239677d5 100644 --- a/src/main/java/org/codehaus/plexus/archiver/AbstractArchiveFinalizer.java +++ b/src/main/java/org/codehaus/plexus/archiver/AbstractArchiveFinalizer.java @@ -1,23 +1,12 @@ package org.codehaus.plexus.archiver; -public abstract class AbstractArchiveFinalizer - implements ArchiveFinalizer -{ +public abstract class AbstractArchiveFinalizer implements ArchiveFinalizer { - protected AbstractArchiveFinalizer() - { - } + protected AbstractArchiveFinalizer() {} @Override - public void finalizeArchiveCreation( Archiver archiver ) - throws ArchiverException - { - } + public void finalizeArchiveCreation(Archiver archiver) throws ArchiverException {} @Override - public void finalizeArchiveExtraction( UnArchiver unarchiver ) - throws ArchiverException - { - } - + public void finalizeArchiveExtraction(UnArchiver unarchiver) throws ArchiverException {} } diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractArchiver.java b/src/main/java/org/codehaus/plexus/archiver/AbstractArchiver.java index c6b1b5577..65ca26220 100755 --- a/src/main/java/org/codehaus/plexus/archiver/AbstractArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/AbstractArchiver.java @@ -16,6 +16,10 @@ */ package org.codehaus.plexus.archiver; +import javax.annotation.Nonnull; +import javax.inject.Inject; +import javax.inject.Provider; + import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -33,9 +37,6 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; -import javax.annotation.Nonnull; -import javax.inject.Inject; -import javax.inject.Provider; import org.codehaus.plexus.archiver.manager.ArchiverManager; import org.codehaus.plexus.archiver.manager.NoSuchArchiverException; @@ -55,14 +56,11 @@ import static org.codehaus.plexus.archiver.util.DefaultArchivedFileSet.archivedFileSet; import static org.codehaus.plexus.archiver.util.DefaultFileSet.fileSet; -public abstract class AbstractArchiver - implements Archiver, FinalizerEnabled -{ +public abstract class AbstractArchiver implements Archiver, FinalizerEnabled { - private final Logger logger = LoggerFactory.getLogger( getClass() ); + private final Logger logger = LoggerFactory.getLogger(getClass()); - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } @@ -145,8 +143,7 @@ protected Logger getLogger() @Inject private Provider archiverManagerProvider; - private static class AddedResourceCollection - { + private static class AddedResourceCollection { private final PlexusIoResourceCollection resources; @@ -154,26 +151,19 @@ private static class AddedResourceCollection private final int forcedDirectoryMode; - public AddedResourceCollection( PlexusIoResourceCollection resources, int forcedFileMode, int forcedDirMode ) - { + public AddedResourceCollection(PlexusIoResourceCollection resources, int forcedFileMode, int forcedDirMode) { this.resources = resources; this.forcedFileMode = forcedFileMode; this.forcedDirectoryMode = forcedDirMode; } - private int maybeOverridden( int suggestedMode, boolean isDir ) - { - if ( isDir ) - { + private int maybeOverridden(int suggestedMode, boolean isDir) { + if (isDir) { return forcedDirectoryMode >= 0 ? forcedDirectoryMode : suggestedMode; - } - else - { + } else { return forcedFileMode >= 0 ? forcedFileMode : suggestedMode; - } } - } /** @@ -182,56 +172,43 @@ private int maybeOverridden( int suggestedMode, boolean isDir ) private boolean ignorePermissions = false; @Override - public String getDuplicateBehavior() - { + public String getDuplicateBehavior() { return duplicateBehavior; } @Override - public void setDuplicateBehavior( final String duplicate ) - { - if ( !Archiver.DUPLICATES_VALID_BEHAVIORS.contains( duplicate ) ) - { - throw new IllegalArgumentException( - "Invalid duplicate-file behavior: '" + duplicate + "'. Please specify one of: " - + Archiver.DUPLICATES_VALID_BEHAVIORS ); + public void setDuplicateBehavior(final String duplicate) { + if (!Archiver.DUPLICATES_VALID_BEHAVIORS.contains(duplicate)) { + throw new IllegalArgumentException("Invalid duplicate-file behavior: '" + duplicate + + "'. Please specify one of: " + Archiver.DUPLICATES_VALID_BEHAVIORS); } duplicateBehavior = duplicate; } @Override - public final void setFileMode( final int mode ) - { - if ( mode >= 0 ) - { - forcedFileMode = ( mode & UnixStat.PERM_MASK ) | UnixStat.FILE_FLAG; - } - else - { + public final void setFileMode(final int mode) { + if (mode >= 0) { + forcedFileMode = (mode & UnixStat.PERM_MASK) | UnixStat.FILE_FLAG; + } else { forcedFileMode = -1; } } @Override - public final void setDefaultFileMode( final int mode ) - { - defaultFileMode = ( mode & UnixStat.PERM_MASK ) | UnixStat.FILE_FLAG; + public final void setDefaultFileMode(final int mode) { + defaultFileMode = (mode & UnixStat.PERM_MASK) | UnixStat.FILE_FLAG; } @Override - public final int getOverrideFileMode() - { + public final int getOverrideFileMode() { return forcedFileMode; } @Override - public final int getFileMode() - { - if ( forcedFileMode < 0 ) - { - if ( defaultFileMode < 0 ) - { + public final int getFileMode() { + if (forcedFileMode < 0) { + if (defaultFileMode < 0) { return DEFAULT_FILE_MODE; } @@ -242,8 +219,7 @@ public final int getFileMode() } @Override - public final int getDefaultFileMode() - { + public final int getDefaultFileMode() { return defaultFileMode; } @@ -251,43 +227,33 @@ public final int getDefaultFileMode() * @deprecated Use {@link Archiver#getDefaultFileMode()}. */ @Deprecated - public final int getRawDefaultFileMode() - { + public final int getRawDefaultFileMode() { return getDefaultFileMode(); } @Override - public final void setDirectoryMode( final int mode ) - { - if ( mode >= 0 ) - { - forcedDirectoryMode = ( mode & UnixStat.PERM_MASK ) | UnixStat.DIR_FLAG; - } - else - { + public final void setDirectoryMode(final int mode) { + if (mode >= 0) { + forcedDirectoryMode = (mode & UnixStat.PERM_MASK) | UnixStat.DIR_FLAG; + } else { forcedDirectoryMode = -1; } } @Override - public final void setDefaultDirectoryMode( final int mode ) - { - defaultDirectoryMode = ( mode & UnixStat.PERM_MASK ) | UnixStat.DIR_FLAG; + public final void setDefaultDirectoryMode(final int mode) { + defaultDirectoryMode = (mode & UnixStat.PERM_MASK) | UnixStat.DIR_FLAG; } @Override - public final int getOverrideDirectoryMode() - { + public final int getOverrideDirectoryMode() { return forcedDirectoryMode; } @Override - public final int getDirectoryMode() - { - if ( forcedDirectoryMode < 0 ) - { - if ( defaultDirectoryMode < 0 ) - { + public final int getDirectoryMode() { + if (forcedDirectoryMode < 0) { + if (defaultDirectoryMode < 0) { return DEFAULT_DIR_MODE; } @@ -298,243 +264,217 @@ public final int getDirectoryMode() } @Override - public final int getDefaultDirectoryMode() - { - if ( defaultDirectoryMode < 0 ) - { + public final int getDefaultDirectoryMode() { + if (defaultDirectoryMode < 0) { return DEFAULT_DIR_MODE; - } - else - { + } else { return defaultDirectoryMode; } } @Override - public boolean getIncludeEmptyDirs() - { + public boolean getIncludeEmptyDirs() { return includeEmptyDirs; } @Override - public void setIncludeEmptyDirs( final boolean includeEmptyDirs ) - { + public void setIncludeEmptyDirs(final boolean includeEmptyDirs) { this.includeEmptyDirs = includeEmptyDirs; } @Override - public void addDirectory( @Nonnull final File directory ) - throws ArchiverException - { - addFileSet( - fileSet( directory ).prefixed( "" ).includeExclude( null, null ).includeEmptyDirs( includeEmptyDirs ) ); + public void addDirectory(@Nonnull final File directory) throws ArchiverException { + addFileSet(fileSet(directory).prefixed("").includeExclude(null, null).includeEmptyDirs(includeEmptyDirs)); } @Override - public void addDirectory( @Nonnull final File directory, final String prefix ) - throws ArchiverException - { + public void addDirectory(@Nonnull final File directory, final String prefix) throws ArchiverException { addFileSet( - fileSet( directory ).prefixed( prefix ).includeExclude( null, null ).includeEmptyDirs( includeEmptyDirs ) ); + fileSet(directory).prefixed(prefix).includeExclude(null, null).includeEmptyDirs(includeEmptyDirs)); } @Override - public void addDirectory( @Nonnull final File directory, final String[] includes, final String[] excludes ) - throws ArchiverException - { - addFileSet( fileSet( directory ).prefixed( "" ).includeExclude( includes, excludes ).includeEmptyDirs( - includeEmptyDirs ) ); + public void addDirectory(@Nonnull final File directory, final String[] includes, final String[] excludes) + throws ArchiverException { + addFileSet(fileSet(directory) + .prefixed("") + .includeExclude(includes, excludes) + .includeEmptyDirs(includeEmptyDirs)); } @Override - public void addDirectory( @Nonnull final File directory, final String prefix, final String[] includes, - final String[] excludes ) - throws ArchiverException - { - addFileSet( fileSet( directory ).prefixed( prefix ).includeExclude( includes, excludes ).includeEmptyDirs( - includeEmptyDirs ) ); + public void addDirectory( + @Nonnull final File directory, final String prefix, final String[] includes, final String[] excludes) + throws ArchiverException { + addFileSet(fileSet(directory) + .prefixed(prefix) + .includeExclude(includes, excludes) + .includeEmptyDirs(includeEmptyDirs)); } @Override - public void addFileSet( @Nonnull final FileSet fileSet ) - throws ArchiverException - { + public void addFileSet(@Nonnull final FileSet fileSet) throws ArchiverException { final File directory = fileSet.getDirectory(); - if ( directory == null ) - { - throw new ArchiverException( "The file sets base directory is null." ); + if (directory == null) { + throw new ArchiverException("The file sets base directory is null."); } - if ( !directory.isDirectory() ) - { - throw new ArchiverException( directory.getAbsolutePath() + " isn't a directory." ); + if (!directory.isDirectory()) { + throw new ArchiverException(directory.getAbsolutePath() + " isn't a directory."); } // The PlexusIoFileResourceCollection contains platform-specific File.separatorChar which // is an interesting cause of grief, see PLXCOMP-192 final PlexusIoFileResourceCollection collection = new PlexusIoFileResourceCollection(); - collection.setFollowingSymLinks( false ); - - collection.setIncludes( fileSet.getIncludes() ); - collection.setExcludes( fileSet.getExcludes() ); - collection.setBaseDir( directory ); - collection.setFileSelectors( fileSet.getFileSelectors() ); - collection.setIncludingEmptyDirectories( fileSet.isIncludingEmptyDirectories() ); - collection.setPrefix( fileSet.getPrefix() ); - collection.setCaseSensitive( fileSet.isCaseSensitive() ); - collection.setUsingDefaultExcludes( fileSet.isUsingDefaultExcludes() ); - collection.setStreamTransformer( fileSet.getStreamTransformer() ); - collection.setFileMappers( fileSet.getFileMappers() ); - collection.setFilenameComparator( getFilenameComparator() ); - - if ( getOverrideDirectoryMode() > -1 || getOverrideFileMode() > -1 || getOverrideUid() > -1 - || getOverrideGid() > -1 || getOverrideUserName() != null || getOverrideGroupName() != null ) - { - collection.setOverrideAttributes( getOverrideUid(), getOverrideUserName(), getOverrideGid(), - getOverrideGroupName(), getOverrideFileMode(), - getOverrideDirectoryMode() ); + collection.setFollowingSymLinks(false); + + collection.setIncludes(fileSet.getIncludes()); + collection.setExcludes(fileSet.getExcludes()); + collection.setBaseDir(directory); + collection.setFileSelectors(fileSet.getFileSelectors()); + collection.setIncludingEmptyDirectories(fileSet.isIncludingEmptyDirectories()); + collection.setPrefix(fileSet.getPrefix()); + collection.setCaseSensitive(fileSet.isCaseSensitive()); + collection.setUsingDefaultExcludes(fileSet.isUsingDefaultExcludes()); + collection.setStreamTransformer(fileSet.getStreamTransformer()); + collection.setFileMappers(fileSet.getFileMappers()); + collection.setFilenameComparator(getFilenameComparator()); + + if (getOverrideDirectoryMode() > -1 + || getOverrideFileMode() > -1 + || getOverrideUid() > -1 + || getOverrideGid() > -1 + || getOverrideUserName() != null + || getOverrideGroupName() != null) { + collection.setOverrideAttributes( + getOverrideUid(), + getOverrideUserName(), + getOverrideGid(), + getOverrideGroupName(), + getOverrideFileMode(), + getOverrideDirectoryMode()); } - if ( getDefaultDirectoryMode() > -1 || getDefaultFileMode() > -1 ) - { - collection.setDefaultAttributes( -1, null, -1, null, getDefaultFileMode(), getDefaultDirectoryMode() ); + if (getDefaultDirectoryMode() > -1 || getDefaultFileMode() > -1) { + collection.setDefaultAttributes(-1, null, -1, null, getDefaultFileMode(), getDefaultDirectoryMode()); } - addResources( collection ); + addResources(collection); } @Override - public void addFile( @Nonnull final File inputFile, @Nonnull final String destFileName ) - throws ArchiverException - { + public void addFile(@Nonnull final File inputFile, @Nonnull final String destFileName) throws ArchiverException { final int fileMode = getOverrideFileMode(); - addFile( inputFile, destFileName, fileMode ); + addFile(inputFile, destFileName, fileMode); } @Override - public void addSymlink( String symlinkName, String symlinkDestination ) - throws ArchiverException - { + public void addSymlink(String symlinkName, String symlinkDestination) throws ArchiverException { final int fileMode = getOverrideFileMode(); - addSymlink( symlinkName, fileMode, symlinkDestination ); + addSymlink(symlinkName, fileMode, symlinkDestination); } @Override - public void addSymlink( String symlinkName, int permissions, String symlinkDestination ) - throws ArchiverException - { + public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException { doAddResource( - ArchiveEntry.createSymlinkEntry( symlinkName, permissions, symlinkDestination, getDirectoryMode() ) ); - } - - private ArchiveEntry updateArchiveEntryAttributes( ArchiveEntry entry ) - { - if ( getOverrideUid() > -1 || getOverrideGid() > -1 || getOverrideUserName() != null - || getOverrideGroupName() != null ) - { - entry.setResourceAttributes( new SimpleResourceAttributes( getOverrideUid(), getOverrideUserName(), - getOverrideGid(), getOverrideGroupName(), - entry.getMode() ) ); + ArchiveEntry.createSymlinkEntry(symlinkName, permissions, symlinkDestination, getDirectoryMode())); + } + + private ArchiveEntry updateArchiveEntryAttributes(ArchiveEntry entry) { + if (getOverrideUid() > -1 + || getOverrideGid() > -1 + || getOverrideUserName() != null + || getOverrideGroupName() != null) { + entry.setResourceAttributes(new SimpleResourceAttributes( + getOverrideUid(), + getOverrideUserName(), + getOverrideGid(), + getOverrideGroupName(), + entry.getMode())); } return entry; } - protected ArchiveEntry asArchiveEntry( @Nonnull final PlexusIoResource resource, final String destFileName, - int permissions, PlexusIoResourceCollection collection ) - throws ArchiverException - { - if ( !resource.isExisting() ) - { - throw new ArchiverException( resource.getName() + " not found." ); + protected ArchiveEntry asArchiveEntry( + @Nonnull final PlexusIoResource resource, + final String destFileName, + int permissions, + PlexusIoResourceCollection collection) + throws ArchiverException { + if (!resource.isExisting()) { + throw new ArchiverException(resource.getName() + " not found."); } - if ( umask > 0 && permissions != PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) - { + if (umask > 0 && permissions != PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE) { permissions &= ~umask; } ArchiveEntry entry; - if ( resource.isFile() ) - { - entry = ArchiveEntry.createFileEntry( destFileName, resource, permissions, collection, getDirectoryMode() ); - } - else - { - entry = ArchiveEntry.createDirectoryEntry( destFileName, resource, permissions, getDirectoryMode() ); + if (resource.isFile()) { + entry = ArchiveEntry.createFileEntry(destFileName, resource, permissions, collection, getDirectoryMode()); + } else { + entry = ArchiveEntry.createDirectoryEntry(destFileName, resource, permissions, getDirectoryMode()); } - return updateArchiveEntryAttributes( entry ); + return updateArchiveEntryAttributes(entry); } - private ArchiveEntry asArchiveEntry( final AddedResourceCollection collection, final PlexusIoResource resource ) - throws ArchiverException - { - final String destFileName = collection.resources.getName( resource ); + private ArchiveEntry asArchiveEntry(final AddedResourceCollection collection, final PlexusIoResource resource) + throws ArchiverException { + final String destFileName = collection.resources.getName(resource); int fromResource = PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE; - if ( resource instanceof ResourceAttributeSupplier ) - { - final PlexusIoResourceAttributes attrs = ( (ResourceAttributeSupplier) resource ).getAttributes(); + if (resource instanceof ResourceAttributeSupplier) { + final PlexusIoResourceAttributes attrs = ((ResourceAttributeSupplier) resource).getAttributes(); - if ( attrs != null ) - { + if (attrs != null) { fromResource = attrs.getOctalMode(); } } - return asArchiveEntry( resource, destFileName, - collection.maybeOverridden( fromResource, resource.isDirectory() ), - collection.resources ); + return asArchiveEntry( + resource, + destFileName, + collection.maybeOverridden(fromResource, resource.isDirectory()), + collection.resources); } @Override - public void addResource( final PlexusIoResource resource, final String destFileName, final int permissions ) - throws ArchiverException - { - doAddResource( asArchiveEntry( resource, destFileName, permissions, null ) ); + public void addResource(final PlexusIoResource resource, final String destFileName, final int permissions) + throws ArchiverException { + doAddResource(asArchiveEntry(resource, destFileName, permissions, null)); } @Override - public void addFile( @Nonnull final File inputFile, @Nonnull String destFileName, int permissions ) - throws ArchiverException - { - if ( !inputFile.isFile() || !inputFile.exists() ) - { - throw new ArchiverException( inputFile.getAbsolutePath() + " isn't a file." ); + public void addFile(@Nonnull final File inputFile, @Nonnull String destFileName, int permissions) + throws ArchiverException { + if (!inputFile.isFile() || !inputFile.exists()) { + throw new ArchiverException(inputFile.getAbsolutePath() + " isn't a file."); } - if ( replacePathSlashesToJavaPaths ) - { - destFileName = destFileName.replace( '\\', '/' ); + if (replacePathSlashesToJavaPaths) { + destFileName = destFileName.replace('\\', '/'); } - if ( permissions < 0 ) - { + if (permissions < 0) { permissions = getOverrideFileMode(); } - try - { + try { // do a null check here, to avoid creating a file stream if there are no filters... - ArchiveEntry entry = - ArchiveEntry.createFileEntry( destFileName, inputFile, permissions, getDirectoryMode() ); - doAddResource( updateArchiveEntryAttributes( entry ) ); - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failed to determine inclusion status for: " + inputFile, e ); + ArchiveEntry entry = ArchiveEntry.createFileEntry(destFileName, inputFile, permissions, getDirectoryMode()); + doAddResource(updateArchiveEntryAttributes(entry)); + } catch (final IOException e) { + throw new ArchiverException("Failed to determine inclusion status for: " + inputFile, e); } } @Nonnull @Override - public ResourceIterator getResources() - throws ArchiverException - { - return new ResourceIterator() - { + public ResourceIterator getResources() throws ArchiverException { + return new ResourceIterator() { private final Iterator addedResourceIter = resources.iterator(); @@ -547,253 +487,189 @@ public ResourceIterator getResources() private final Set seenEntries = new HashSet<>(); @Override - public boolean hasNext() - { - do - { - if ( nextEntry == null ) - { - if ( ioResourceIter == null ) - { - if ( addedResourceIter.hasNext() ) - { + public boolean hasNext() { + do { + if (nextEntry == null) { + if (ioResourceIter == null) { + if (addedResourceIter.hasNext()) { final Object o = addedResourceIter.next(); - if ( o instanceof ArchiveEntry ) - { + if (o instanceof ArchiveEntry) { nextEntry = (ArchiveEntry) o; - } - else if ( o instanceof AddedResourceCollection ) - { + } else if (o instanceof AddedResourceCollection) { currentResourceCollection = (AddedResourceCollection) o; - try - { + try { ioResourceIter = currentResourceCollection.resources.getResources(); + } catch (final IOException e) { + throw new ArchiverException(e.getMessage(), e); } - catch ( final IOException e ) - { - throw new ArchiverException( e.getMessage(), e ); - } - } - else - { - return throwIllegalResourceType( o ); + } else { + return throwIllegalResourceType(o); } - } - else - { + } else { nextEntry = null; } - } - else - { - if ( ioResourceIter.hasNext() ) - { + } else { + if (ioResourceIter.hasNext()) { final PlexusIoResource resource = (PlexusIoResource) ioResourceIter.next(); - nextEntry = asArchiveEntry( currentResourceCollection, resource ); - } - else - { + nextEntry = asArchiveEntry(currentResourceCollection, resource); + } else { // this will leak handles in the IO iterator if the iterator is not fully consumed. // alternately we'd have to make this method return a Closeable iterator back // to the client and ditch the whole issue onto the client. // this does not really make any sense either, might equally well change the // api into something that is not broken by design. - addCloseable( ioResourceIter ); + addCloseable(ioResourceIter); ioResourceIter = null; } } } - if ( nextEntry != null && seenEntries.contains( normalizedForDuplicateCheck( nextEntry ) ) ) - { + if (nextEntry != null && seenEntries.contains(normalizedForDuplicateCheck(nextEntry))) { final String path = nextEntry.getName(); - if ( Archiver.DUPLICATES_PRESERVE.equals( duplicateBehavior ) - || Archiver.DUPLICATES_SKIP.equals( duplicateBehavior ) ) - { - if ( nextEntry.getType() == ArchiveEntry.FILE ) - { - getLogger().debug( path + " already added, skipping" ); + if (Archiver.DUPLICATES_PRESERVE.equals(duplicateBehavior) + || Archiver.DUPLICATES_SKIP.equals(duplicateBehavior)) { + if (nextEntry.getType() == ArchiveEntry.FILE) { + getLogger().debug(path + " already added, skipping"); } nextEntry = null; - } - else if ( Archiver.DUPLICATES_FAIL.equals( duplicateBehavior ) ) - { - throw new ArchiverException( - "Duplicate file " + path + " was found and the duplicate " + "attribute is 'fail'." ); - } - else - { + } else if (Archiver.DUPLICATES_FAIL.equals(duplicateBehavior)) { + throw new ArchiverException("Duplicate file " + path + " was found and the duplicate " + + "attribute is 'fail'."); + } else { // duplicate equal to add, so we continue - getLogger().debug( "duplicate file " + path + " found, adding." ); + getLogger().debug("duplicate file " + path + " found, adding."); } } - } - while ( nextEntry == null && !( ioResourceIter == null && !addedResourceIter.hasNext() ) ); + } while (nextEntry == null && !(ioResourceIter == null && !addedResourceIter.hasNext())); return nextEntry != null; } - private boolean throwIllegalResourceType( Object o ) - { + private boolean throwIllegalResourceType(Object o) { throw new IllegalStateException( - "An invalid resource of type: " + o.getClass().getName() + " was added to archiver: " - + getClass().getName() ); + "An invalid resource of type: " + o.getClass().getName() + " was added to archiver: " + + getClass().getName()); } @Override - public ArchiveEntry next() - { - if ( !hasNext() ) - { + public ArchiveEntry next() { + if (!hasNext()) { throw new NoSuchElementException(); } final ArchiveEntry next = nextEntry; nextEntry = null; - seenEntries.add( normalizedForDuplicateCheck( next ) ); + seenEntries.add(normalizedForDuplicateCheck(next)); return next; } @Override - public void remove() - { - throw new UnsupportedOperationException( "Does not support iterator" ); + public void remove() { + throw new UnsupportedOperationException("Does not support iterator"); } - private String normalizedForDuplicateCheck( ArchiveEntry entry ) - { - return entry.getName().replace( '\\', '/' ); + private String normalizedForDuplicateCheck(ArchiveEntry entry) { + return entry.getName().replace('\\', '/'); } - }; - } - private static void closeIfCloseable( Object resource ) - throws IOException - { - if ( resource == null ) - { + private static void closeIfCloseable(Object resource) throws IOException { + if (resource == null) { return; } - if ( resource instanceof Closeable ) - { - ( (Closeable) resource ).close(); + if (resource instanceof Closeable) { + ((Closeable) resource).close(); } - } - private static void closeQuietlyIfCloseable( Object resource ) - { - try - { - closeIfCloseable( resource ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + private static void closeQuietlyIfCloseable(Object resource) { + try { + closeIfCloseable(resource); + } catch (IOException e) { + throw new RuntimeException(e); } } @Override - public Map getFiles() - { - try - { + public Map getFiles() { + try { final Map map = new HashMap<>(); - for ( final ResourceIterator iter = getResources(); iter.hasNext(); ) - { + for (final ResourceIterator iter = getResources(); iter.hasNext(); ) { final ArchiveEntry entry = iter.next(); - if ( includeEmptyDirs || entry.getType() == ArchiveEntry.FILE ) - { - map.put( entry.getName(), entry ); + if (includeEmptyDirs || entry.getType() == ArchiveEntry.FILE) { + map.put(entry.getName(), entry); } } return map; - } - catch ( final ArchiverException e ) - { - throw new UndeclaredThrowableException( e ); + } catch (final ArchiverException e) { + throw new UndeclaredThrowableException(e); } } @Override - public File getDestFile() - { + public File getDestFile() { return destFile; } @Override - public void setDestFile( final File destFile ) - { + public void setDestFile(final File destFile) { this.destFile = destFile; - if ( destFile != null && destFile.getParentFile() != null ) - { + if (destFile != null && destFile.getParentFile() != null) { destFile.getParentFile().mkdirs(); } } - protected PlexusIoResourceCollection asResourceCollection( final ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { + protected PlexusIoResourceCollection asResourceCollection(final ArchivedFileSet fileSet, Charset charset) + throws ArchiverException { final File archiveFile = fileSet.getArchive(); final PlexusIoResourceCollection resources; - try - { - resources = archiverManagerProvider.get().getResourceCollection( archiveFile ); - } - catch ( final NoSuchArchiverException e ) - { + try { + resources = archiverManagerProvider.get().getResourceCollection(archiveFile); + } catch (final NoSuchArchiverException e) { throw new ArchiverException( - "Error adding archived file-set. PlexusIoResourceCollection not found for: " + archiveFile, e ); + "Error adding archived file-set. PlexusIoResourceCollection not found for: " + archiveFile, e); } - if ( resources instanceof EncodingSupported ) - { - ( (EncodingSupported) resources ).setEncoding( charset ); + if (resources instanceof EncodingSupported) { + ((EncodingSupported) resources).setEncoding(charset); } - if ( resources instanceof PlexusIoArchivedResourceCollection ) - { - ( (PlexusIoArchivedResourceCollection) resources ).setFile( fileSet.getArchive() ); - } - else - { - throw new ArchiverException( "Expected " + PlexusIoArchivedResourceCollection.class.getName() + ", got " - + resources.getClass().getName() ); + if (resources instanceof PlexusIoArchivedResourceCollection) { + ((PlexusIoArchivedResourceCollection) resources).setFile(fileSet.getArchive()); + } else { + throw new ArchiverException("Expected " + PlexusIoArchivedResourceCollection.class.getName() + ", got " + + resources.getClass().getName()); } - if ( resources instanceof AbstractPlexusIoResourceCollection ) - { - ( (AbstractPlexusIoResourceCollection) resources ).setStreamTransformer( fileSet.getStreamTransformer() ); + if (resources instanceof AbstractPlexusIoResourceCollection) { + ((AbstractPlexusIoResourceCollection) resources).setStreamTransformer(fileSet.getStreamTransformer()); } - final PlexusIoProxyResourceCollection proxy = new PlexusIoProxyResourceCollection( resources ); - - proxy.setExcludes( fileSet.getExcludes() ); - proxy.setIncludes( fileSet.getIncludes() ); - proxy.setIncludingEmptyDirectories( fileSet.isIncludingEmptyDirectories() ); - proxy.setCaseSensitive( fileSet.isCaseSensitive() ); - proxy.setPrefix( fileSet.getPrefix() ); - proxy.setUsingDefaultExcludes( fileSet.isUsingDefaultExcludes() ); - proxy.setFileSelectors( fileSet.getFileSelectors() ); - proxy.setStreamTransformer( fileSet.getStreamTransformer() ); - proxy.setFileMappers( fileSet.getFileMappers() ); - - if ( getOverrideDirectoryMode() > -1 || getOverrideFileMode() > -1 ) - { - proxy.setOverrideAttributes( -1, null, -1, null, getOverrideFileMode(), getOverrideDirectoryMode() ); + final PlexusIoProxyResourceCollection proxy = new PlexusIoProxyResourceCollection(resources); + + proxy.setExcludes(fileSet.getExcludes()); + proxy.setIncludes(fileSet.getIncludes()); + proxy.setIncludingEmptyDirectories(fileSet.isIncludingEmptyDirectories()); + proxy.setCaseSensitive(fileSet.isCaseSensitive()); + proxy.setPrefix(fileSet.getPrefix()); + proxy.setUsingDefaultExcludes(fileSet.isUsingDefaultExcludes()); + proxy.setFileSelectors(fileSet.getFileSelectors()); + proxy.setStreamTransformer(fileSet.getStreamTransformer()); + proxy.setFileMappers(fileSet.getFileMappers()); + + if (getOverrideDirectoryMode() > -1 || getOverrideFileMode() > -1) { + proxy.setOverrideAttributes(-1, null, -1, null, getOverrideFileMode(), getOverrideDirectoryMode()); } - if ( getDefaultDirectoryMode() > -1 || getDefaultFileMode() > -1 ) - { - proxy.setDefaultAttributes( -1, null, -1, null, getDefaultFileMode(), getDefaultDirectoryMode() ); + if (getDefaultDirectoryMode() > -1 || getDefaultFileMode() > -1) { + proxy.setDefaultAttributes(-1, null, -1, null, getDefaultFileMode(), getDefaultDirectoryMode()); } return proxy; @@ -803,167 +679,135 @@ protected PlexusIoResourceCollection asResourceCollection( final ArchivedFileSet * Adds a resource collection to the archive. */ @Override - public void addResources( final PlexusIoResourceCollection collection ) - throws ArchiverException - { - doAddResource( new AddedResourceCollection( collection, forcedFileMode, forcedDirectoryMode ) ); + public void addResources(final PlexusIoResourceCollection collection) throws ArchiverException { + doAddResource(new AddedResourceCollection(collection, forcedFileMode, forcedDirectoryMode)); } - private void doAddResource( Object item ) - { - resources.add( item ); + private void doAddResource(Object item) { + resources.add(item); } @Override - public void addArchivedFileSet( final ArchivedFileSet fileSet ) - throws ArchiverException - { - final PlexusIoResourceCollection resourceCollection = asResourceCollection( fileSet, null ); - addResources( resourceCollection ); + public void addArchivedFileSet(final ArchivedFileSet fileSet) throws ArchiverException { + final PlexusIoResourceCollection resourceCollection = asResourceCollection(fileSet, null); + addResources(resourceCollection); } @Override - public void addArchivedFileSet( final ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { - final PlexusIoResourceCollection resourceCollection = asResourceCollection( fileSet, charset ); - addResources( resourceCollection ); + public void addArchivedFileSet(final ArchivedFileSet fileSet, Charset charset) throws ArchiverException { + final PlexusIoResourceCollection resourceCollection = asResourceCollection(fileSet, charset); + addResources(resourceCollection); } /** * @since 1.0-alpha-7 */ @Override - public void addArchivedFileSet( @Nonnull final File archiveFile, final String prefix, final String[] includes, - final String[] excludes ) - throws ArchiverException - { - addArchivedFileSet( - archivedFileSet( archiveFile ).prefixed( prefix ).includeExclude( includes, excludes ).includeEmptyDirs( - includeEmptyDirs ) ); + public void addArchivedFileSet( + @Nonnull final File archiveFile, final String prefix, final String[] includes, final String[] excludes) + throws ArchiverException { + addArchivedFileSet(archivedFileSet(archiveFile) + .prefixed(prefix) + .includeExclude(includes, excludes) + .includeEmptyDirs(includeEmptyDirs)); } /** * @since 1.0-alpha-7 */ @Override - public void addArchivedFileSet( @Nonnull final File archiveFile, final String prefix ) - throws ArchiverException - { - addArchivedFileSet( archivedFileSet( archiveFile ).prefixed( prefix ).includeEmptyDirs( includeEmptyDirs ) ); + public void addArchivedFileSet(@Nonnull final File archiveFile, final String prefix) throws ArchiverException { + addArchivedFileSet(archivedFileSet(archiveFile).prefixed(prefix).includeEmptyDirs(includeEmptyDirs)); } /** * @since 1.0-alpha-7 */ @Override - public void addArchivedFileSet( @Nonnull final File archiveFile, final String[] includes, final String[] excludes ) - throws ArchiverException - { + public void addArchivedFileSet(@Nonnull final File archiveFile, final String[] includes, final String[] excludes) + throws ArchiverException { addArchivedFileSet( - archivedFileSet( archiveFile ).includeExclude( includes, excludes ).includeEmptyDirs( includeEmptyDirs ) ); + archivedFileSet(archiveFile).includeExclude(includes, excludes).includeEmptyDirs(includeEmptyDirs)); } /** * @since 1.0-alpha-7 */ @Override - public void addArchivedFileSet( @Nonnull final File archiveFile ) - throws ArchiverException - { - addArchivedFileSet( archivedFileSet( archiveFile ).includeEmptyDirs( includeEmptyDirs ) ); + public void addArchivedFileSet(@Nonnull final File archiveFile) throws ArchiverException { + addArchivedFileSet(archivedFileSet(archiveFile).includeEmptyDirs(includeEmptyDirs)); } @Override - public boolean isForced() - { + public boolean isForced() { return forced; } @Override - public void setForced( final boolean forced ) - { + public void setForced(final boolean forced) { this.forced = forced; } @Override - public void addArchiveFinalizer( final ArchiveFinalizer finalizer ) - { - if ( finalizers == null ) - { + public void addArchiveFinalizer(final ArchiveFinalizer finalizer) { + if (finalizers == null) { finalizers = new ArrayList<>(); } - finalizers.add( finalizer ); + finalizers.add(finalizer); } @Override - public void setArchiveFinalizers( final List archiveFinalizers ) - { + public void setArchiveFinalizers(final List archiveFinalizers) { finalizers = archiveFinalizers; } @Override - public void setDotFileDirectory( final File dotFileDirectory ) - { + public void setDotFileDirectory(final File dotFileDirectory) { this.dotFileDirectory = dotFileDirectory; } - protected boolean isUptodate() - throws ArchiverException - { + protected boolean isUptodate() throws ArchiverException { final File zipFile = getDestFile(); - if ( !zipFile.exists() ) - { - getLogger().debug( "isUp2date: false (Destination " + zipFile.getPath() + " not found.)" ); + if (!zipFile.exists()) { + getLogger().debug("isUp2date: false (Destination " + zipFile.getPath() + " not found.)"); return false; // File doesn't yet exist } final long destTimestamp = getFileLastModifiedTime(zipFile); final Iterator it = resources.iterator(); - if ( !it.hasNext() ) - { - getLogger().debug( "isUp2date: false (No input files.)" ); + if (!it.hasNext()) { + getLogger().debug("isUp2date: false (No input files.)"); return false; // No timestamp to compare } - while ( it.hasNext() ) - { + while (it.hasNext()) { final Object o = it.next(); final long l; - if ( o instanceof ArchiveEntry ) - { - l = ( (ArchiveEntry) o ).getResource().getLastModified(); - } - else if ( o instanceof AddedResourceCollection ) - { - try - { - l = ( (AddedResourceCollection) o ).resources.getLastModified(); + if (o instanceof ArchiveEntry) { + l = ((ArchiveEntry) o).getResource().getLastModified(); + } else if (o instanceof AddedResourceCollection) { + try { + l = ((AddedResourceCollection) o).resources.getLastModified(); + } catch (final IOException e) { + throw new ArchiverException(e.getMessage(), e); } - catch ( final IOException e ) - { - throw new ArchiverException( e.getMessage(), e ); - } - } - else - { - throw new IllegalStateException( "Invalid object type: " + o.getClass().getName() ); + } else { + throw new IllegalStateException( + "Invalid object type: " + o.getClass().getName()); } - if ( l == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ) - { + if (l == PlexusIoResource.UNKNOWN_MODIFICATION_DATE) { // Don't know what to do. Safe thing is to assume not up2date. - getLogger().debug( "isUp2date: false (Resource with unknown modification date found.)" ); + getLogger().debug("isUp2date: false (Resource with unknown modification date found.)"); return false; } - if ( l > destTimestamp ) - { - getLogger().debug( "isUp2date: false (Resource with newer modification date found.)" ); + if (l > destTimestamp) { + getLogger().debug("isUp2date: false (Resource with newer modification date found.)"); return false; } } - getLogger().debug( "isUp2date: true" ); + getLogger().debug("isUp2date: true"); return true; } @@ -974,101 +818,72 @@ else if ( o instanceof AddedResourceCollection ) * @return The last modified time in milliseconds of the file. * @throws ArchiverException In the case of an IOException, for example when the file does not exists. */ - private long getFileLastModifiedTime( File file ) - throws ArchiverException - { - try - { - return Files.getLastModifiedTime( file.toPath() ).toMillis(); - } - catch ( IOException e ) - { - throw new ArchiverException( e.getMessage(), e ); + private long getFileLastModifiedTime(File file) throws ArchiverException { + try { + return Files.getLastModifiedTime(file.toPath()).toMillis(); + } catch (IOException e) { + throw new ArchiverException(e.getMessage(), e); } } - protected boolean checkForced() - throws ArchiverException - { - if ( !isForced() && isSupportingForced() && isUptodate() ) - { - getLogger().debug( "Archive " + getDestFile() + " is uptodate." ); + protected boolean checkForced() throws ArchiverException { + if (!isForced() && isSupportingForced() && isUptodate()) { + getLogger().debug("Archive " + getDestFile() + " is uptodate."); return false; } return true; } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return false; } - protected void runArchiveFinalizers() - throws ArchiverException - { - if ( finalizers != null ) - { - for ( final ArchiveFinalizer finalizer : finalizers ) - { - finalizer.finalizeArchiveCreation( this ); + protected void runArchiveFinalizers() throws ArchiverException { + if (finalizers != null) { + for (final ArchiveFinalizer finalizer : finalizers) { + finalizer.finalizeArchiveCreation(this); } } } @Override - public final void createArchive() - throws ArchiverException, IOException - { + public final void createArchive() throws ArchiverException, IOException { validate(); - try - { - try - { - if ( dotFileDirectory != null ) - { - addArchiveFinalizer( new DotDirectiveArchiveFinalizer( dotFileDirectory ) ); + try { + try { + if (dotFileDirectory != null) { + addArchiveFinalizer(new DotDirectiveArchiveFinalizer(dotFileDirectory)); } runArchiveFinalizers(); execute(); - } - finally - { + } finally { close(); } - } - catch ( final IOException e ) - { + } catch (final IOException e) { String msg = "Problem creating " + getArchiveType() + ": " + e.getMessage(); final StringBuffer revertBuffer = new StringBuffer(); - if ( !revert( revertBuffer ) ) - { + if (!revert(revertBuffer)) { msg += revertBuffer.toString(); } - throw new ArchiverException( msg, e ); - } - finally - { + throw new ArchiverException(msg, e); + } finally { cleanUp(); } postCreateArchive(); } - protected boolean hasVirtualFiles() - { - if ( finalizers != null ) - { - for ( final ArchiveFinalizer finalizer : finalizers ) - { + protected boolean hasVirtualFiles() { + if (finalizers != null) { + for (final ArchiveFinalizer finalizer : finalizers) { final List virtualFiles = finalizer.getVirtualFiles(); - if ( ( virtualFiles != null ) && !virtualFiles.isEmpty() ) - { + if ((virtualFiles != null) && !virtualFiles.isEmpty()) { return true; } } @@ -1076,15 +891,11 @@ protected boolean hasVirtualFiles() return false; } - protected boolean revert( final StringBuffer messageBuffer ) - { + protected boolean revert(final StringBuffer messageBuffer) { return true; } - protected void validate() - throws ArchiverException, IOException - { - } + protected void validate() throws ArchiverException, IOException {} /** * This method is called after the archive creation @@ -1096,60 +907,44 @@ protected void validate() * * @since 3.6 */ - protected void postCreateArchive() - throws ArchiverException, IOException - { - } + protected void postCreateArchive() throws ArchiverException, IOException {} protected abstract String getArchiveType(); - private void addCloseable( Object maybeCloseable ) - { - if ( maybeCloseable instanceof Closeable ) - { - closeables.add( (Closeable) maybeCloseable ); + private void addCloseable(Object maybeCloseable) { + if (maybeCloseable instanceof Closeable) { + closeables.add((Closeable) maybeCloseable); } - } - private void closeIterators() - { - for ( Closeable closeable : closeables ) - { - closeQuietlyIfCloseable( closeable ); + private void closeIterators() { + for (Closeable closeable : closeables) { + closeQuietlyIfCloseable(closeable); } - } - protected abstract void close() - throws IOException; + protected abstract void close() throws IOException; - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { closeIterators(); - for ( Object resource : resources ) - { - if ( resource instanceof PlexusIoProxyResourceCollection ) - { - resource = ( (PlexusIoProxyResourceCollection) resource ).getSrc(); + for (Object resource : resources) { + if (resource instanceof PlexusIoProxyResourceCollection) { + resource = ((PlexusIoProxyResourceCollection) resource).getSrc(); } - closeIfCloseable( resource ); + closeIfCloseable(resource); } resources.clear(); } - protected abstract void execute() - throws ArchiverException, IOException; + protected abstract void execute() throws ArchiverException, IOException; /** * @since 1.1 */ @Override - public boolean isUseJvmChmod() - { + public boolean isUseJvmChmod() { return useJvmChmod; } @@ -1157,8 +952,7 @@ public boolean isUseJvmChmod() * @since 1.1 */ @Override - public void setUseJvmChmod( final boolean useJvmChmod ) - { + public void setUseJvmChmod(final boolean useJvmChmod) { this.useJvmChmod = useJvmChmod; } @@ -1166,8 +960,7 @@ public void setUseJvmChmod( final boolean useJvmChmod ) * @since 1.1 */ @Override - public boolean isIgnorePermissions() - { + public boolean isIgnorePermissions() { return ignorePermissions; } @@ -1175,8 +968,7 @@ public boolean isIgnorePermissions() * @since 1.1 */ @Override - public void setIgnorePermissions( final boolean ignorePermissions ) - { + public void setIgnorePermissions(final boolean ignorePermissions) { this.ignorePermissions = ignorePermissions; } @@ -1185,9 +977,8 @@ public void setIgnorePermissions( final boolean ignorePermissions ) */ @Override @Deprecated - public void setLastModifiedDate( Date lastModifiedDate ) - { - this.lastModifiedTime = lastModifiedDate != null ? FileTime.fromMillis( lastModifiedDate.getTime() ) : null; + public void setLastModifiedDate(Date lastModifiedDate) { + this.lastModifiedTime = lastModifiedDate != null ? FileTime.fromMillis(lastModifiedDate.getTime()) : null; } /** @@ -1195,91 +986,76 @@ public void setLastModifiedDate( Date lastModifiedDate ) */ @Override @Deprecated - public Date getLastModifiedDate() - { - return lastModifiedTime != null ? new Date( lastModifiedTime.toMillis() ) : null; + public Date getLastModifiedDate() { + return lastModifiedTime != null ? new Date(lastModifiedTime.toMillis()) : null; } @Override - public void setLastModifiedTime( FileTime lastModifiedTime ) - { + public void setLastModifiedTime(FileTime lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } @Override - public FileTime getLastModifiedTime() - { + public FileTime getLastModifiedTime() { return lastModifiedTime; } @Override - public void setFilenameComparator( Comparator filenameComparator ) - { + public void setFilenameComparator(Comparator filenameComparator) { this.filenameComparator = filenameComparator; } - public Comparator getFilenameComparator() - { + public Comparator getFilenameComparator() { return filenameComparator; } @Override - public void setOverrideUid( int uid ) - { + public void setOverrideUid(int uid) { overrideUid = uid; } @Override - public void setOverrideUserName( String userName ) - { + public void setOverrideUserName(String userName) { overrideUserName = userName; } @Override - public int getOverrideUid() - { + public int getOverrideUid() { return overrideUid; } @Override - public String getOverrideUserName() - { + public String getOverrideUserName() { return overrideUserName; } @Override - public void setOverrideGid( int gid ) - { + public void setOverrideGid(int gid) { overrideGid = gid; } @Override - public void setOverrideGroupName( String groupName ) - { + public void setOverrideGroupName(String groupName) { overrideGroupName = groupName; } @Override - public int getOverrideGid() - { + public int getOverrideGid() { return overrideGid; } @Override - public String getOverrideGroupName() - { + public String getOverrideGroupName() { return overrideGroupName; } @Override - public void setUmask( int umask ) - { + public void setUmask(int umask) { this.umask = umask; } @Override - public int getUmask() - { + public int getUmask() { return umask; } @@ -1288,28 +1064,26 @@ public int getUmask() */ @Override @Deprecated - public void configureReproducible( Date lastModifiedDate ) - { - configureReproducibleBuild( FileTime.fromMillis( lastModifiedDate.getTime() ) ); + public void configureReproducible(Date lastModifiedDate) { + configureReproducibleBuild(FileTime.fromMillis(lastModifiedDate.getTime())); } @Override - public void configureReproducibleBuild( FileTime lastModifiedTime ) - { + public void configureReproducibleBuild(FileTime lastModifiedTime) { // 1. force last modified date - setLastModifiedTime( normalizeLastModifiedTime ( lastModifiedTime ) ); + setLastModifiedTime(normalizeLastModifiedTime(lastModifiedTime)); // 2. sort filenames in each directory when scanning filesystem - setFilenameComparator( String::compareTo ); + setFilenameComparator(String::compareTo); // 3. ignore uid/gid from filesystem (for tar) - setOverrideUid( 0 ); - setOverrideUserName( "root" ); // is it possible to avoid this, like "tar --numeric-owner"? - setOverrideGid( 0 ); - setOverrideGroupName( "root" ); + setOverrideUid(0); + setOverrideUserName("root"); // is it possible to avoid this, like "tar --numeric-owner"? + setOverrideGid(0); + setOverrideGroupName("root"); // 4. set umask to 022 to avoid environment umask value particularly on group write - setUmask( 0_022 ); + setUmask(0_022); } /** @@ -1324,8 +1098,7 @@ public void configureReproducibleBuild( FileTime lastModifiedTime ) * * @see #configureReproducibleBuild(FileTime) */ - protected FileTime normalizeLastModifiedTime( FileTime lastModifiedTime ) - { + protected FileTime normalizeLastModifiedTime(FileTime lastModifiedTime) { return lastModifiedTime; } } diff --git a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java index 52454f1d4..e8a6a2e2d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/AbstractUnArchiver.java @@ -28,7 +28,6 @@ import java.util.List; import java.util.Locale; import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.LongAdder; import org.codehaus.plexus.archiver.util.ArchiveEntryUtils; import org.codehaus.plexus.components.io.attributes.SymlinkUtils; @@ -46,13 +45,10 @@ /** * @author Emmanuel Venisse */ -public abstract class AbstractUnArchiver - implements UnArchiver, FinalizerEnabled -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public abstract class AbstractUnArchiver implements UnArchiver, FinalizerEnabled { + private final Logger logger = LoggerFactory.getLogger(getClass()); - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } @@ -82,217 +78,170 @@ protected Logger getLogger() */ private boolean ignorePermissions = false; - public AbstractUnArchiver() - { + public AbstractUnArchiver() { // no op } - public AbstractUnArchiver( final File sourceFile ) - { + public AbstractUnArchiver(final File sourceFile) { this.sourceFile = sourceFile; } @Override - public File getDestDirectory() - { + public File getDestDirectory() { return destDirectory; } @Override - public void setDestDirectory( final File destDirectory ) - { + public void setDestDirectory(final File destDirectory) { this.destDirectory = destDirectory; } @Override - public File getDestFile() - { + public File getDestFile() { return destFile; } @Override - public void setDestFile( final File destFile ) - { + public void setDestFile(final File destFile) { this.destFile = destFile; } @Override - public File getSourceFile() - { + public File getSourceFile() { return sourceFile; } @Override - public void setSourceFile( final File sourceFile ) - { + public void setSourceFile(final File sourceFile) { this.sourceFile = sourceFile; } @Override - public boolean isOverwrite() - { + public boolean isOverwrite() { return overwrite; } @Override - public void setOverwrite( final boolean b ) - { + public void setOverwrite(final boolean b) { overwrite = b; } @Override - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return fileMappers; } @Override - public void setFileMappers( final FileMapper[] fileMappers ) - { + public void setFileMappers(final FileMapper[] fileMappers) { this.fileMappers = fileMappers; } @Override - public final void extract() - throws ArchiverException - { + public final void extract() throws ArchiverException { validate(); execute(); runArchiveFinalizers(); } @Override - public final void extract( final String path, final File outputDirectory ) - throws ArchiverException - { - validate( path, outputDirectory ); - execute( path, outputDirectory ); + public final void extract(final String path, final File outputDirectory) throws ArchiverException { + validate(path, outputDirectory); + execute(path, outputDirectory); runArchiveFinalizers(); } @Override - public void addArchiveFinalizer( final ArchiveFinalizer finalizer ) - { - if ( finalizers == null ) - { + public void addArchiveFinalizer(final ArchiveFinalizer finalizer) { + if (finalizers == null) { finalizers = new ArrayList<>(); } - finalizers.add( finalizer ); + finalizers.add(finalizer); } @Override - public void setArchiveFinalizers( final List archiveFinalizers ) - { + public void setArchiveFinalizers(final List archiveFinalizers) { finalizers = archiveFinalizers; } - private void runArchiveFinalizers() - throws ArchiverException - { - if ( finalizers != null ) - { - for ( ArchiveFinalizer finalizer : finalizers ) - { - finalizer.finalizeArchiveExtraction( this ); + private void runArchiveFinalizers() throws ArchiverException { + if (finalizers != null) { + for (ArchiveFinalizer finalizer : finalizers) { + finalizer.finalizeArchiveExtraction(this); } } } - protected void validate( final String path, final File outputDirectory ) - { - } + protected void validate(final String path, final File outputDirectory) {} - protected void validate() - throws ArchiverException - { - if ( sourceFile == null ) - { - throw new ArchiverException( "The source file isn't defined." ); + protected void validate() throws ArchiverException { + if (sourceFile == null) { + throw new ArchiverException("The source file isn't defined."); } - if ( sourceFile.isDirectory() ) - { - throw new ArchiverException( "The source must not be a directory." ); + if (sourceFile.isDirectory()) { + throw new ArchiverException("The source must not be a directory."); } - if ( !sourceFile.exists() ) - { - throw new ArchiverException( "The source file " + sourceFile + " doesn't exist." ); + if (!sourceFile.exists()) { + throw new ArchiverException("The source file " + sourceFile + " doesn't exist."); } - if ( destDirectory == null && destFile == null ) - { - throw new ArchiverException( "The destination isn't defined." ); + if (destDirectory == null && destFile == null) { + throw new ArchiverException("The destination isn't defined."); } - if ( destDirectory != null && destFile != null ) - { - throw new ArchiverException( "You must choose between a destination directory and a destination file." ); + if (destDirectory != null && destFile != null) { + throw new ArchiverException("You must choose between a destination directory and a destination file."); } - if ( destDirectory != null && !destDirectory.isDirectory() ) - { + if (destDirectory != null && !destDirectory.isDirectory()) { destFile = destDirectory; destDirectory = null; } - if ( destFile != null && destFile.isDirectory() ) - { + if (destFile != null && destFile.isDirectory()) { destDirectory = destFile; destFile = null; } } @Override - public void setFileSelectors( final FileSelector[] fileSelectors ) - { + public void setFileSelectors(final FileSelector[] fileSelectors) { this.fileSelectors = fileSelectors; } @Override - public FileSelector[] getFileSelectors() - { + public FileSelector[] getFileSelectors() { return fileSelectors; } - protected boolean isSelected( final String fileName, final PlexusIoResource fileInfo ) - throws ArchiverException - { - if ( fileSelectors != null ) - { - for ( FileSelector fileSelector : fileSelectors ) - { - try - { - - if ( !fileSelector.isSelected( fileInfo ) ) - { + protected boolean isSelected(final String fileName, final PlexusIoResource fileInfo) throws ArchiverException { + if (fileSelectors != null) { + for (FileSelector fileSelector : fileSelectors) { + try { + + if (!fileSelector.isSelected(fileInfo)) { return false; } - } - catch ( final IOException e ) - { + } catch (final IOException e) { throw new ArchiverException( - "Failed to check, whether " + fileInfo.getName() + " is selected: " + e.getMessage(), e ); + "Failed to check, whether " + fileInfo.getName() + " is selected: " + e.getMessage(), e); } } } return true; } - protected abstract void execute() - throws ArchiverException; + protected abstract void execute() throws ArchiverException; - protected abstract void execute( String path, File outputDirectory ) - throws ArchiverException; + protected abstract void execute(String path, File outputDirectory) throws ArchiverException; /** * @since 1.1 */ @Override - public boolean isUseJvmChmod() - { + public boolean isUseJvmChmod() { return useJvmChmod; } @@ -302,8 +251,7 @@ public boolean isUseJvmChmod() * @since 1.1 */ @Override - public void setUseJvmChmod( final boolean useJvmChmod ) - { + public void setUseJvmChmod(final boolean useJvmChmod) { this.useJvmChmod = useJvmChmod; } @@ -311,8 +259,7 @@ public void setUseJvmChmod( final boolean useJvmChmod ) * @since 1.1 */ @Override - public boolean isIgnorePermissions() - { + public boolean isIgnorePermissions() { return ignorePermissions; } @@ -320,26 +267,29 @@ public boolean isIgnorePermissions() * @since 1.1 */ @Override - public void setIgnorePermissions( final boolean ignorePermissions ) - { + public void setIgnorePermissions(final boolean ignorePermissions) { this.ignorePermissions = ignorePermissions; } - protected void extractFile( final File srcF, final File dir, final InputStream compressedInputStream, - String entryName, final Date entryDate, final boolean isDirectory, - final Integer mode, String symlinkDestination, final FileMapper[] fileMappers ) - throws IOException, ArchiverException - { - if ( fileMappers != null ) - { - for ( final FileMapper fileMapper : fileMappers ) - { - entryName = fileMapper.getMappedFileName( entryName ); + protected void extractFile( + final File srcF, + final File dir, + final InputStream compressedInputStream, + String entryName, + final Date entryDate, + final boolean isDirectory, + final Integer mode, + String symlinkDestination, + final FileMapper[] fileMappers) + throws IOException, ArchiverException { + if (fileMappers != null) { + for (final FileMapper fileMapper : fileMappers) { + entryName = fileMapper.getMappedFileName(entryName); } } // Hmm. Symlinks re-evaluate back to the original file here. Unsure if this is a good thing... - final File targetFileName = FileUtils.resolveFile( dir, entryName ); + final File targetFileName = FileUtils.resolveFile(dir, entryName); // Make sure that the resolved path of the extracted file doesn't escape the destination directory // getCanonicalFile().toPath() is used instead of getCanonicalPath() (returns String), @@ -347,104 +297,98 @@ protected void extractFile( final File srcF, final File dir, final InputStream c Path canonicalDirPath = dir.getCanonicalFile().toPath(); Path canonicalDestPath = targetFileName.getCanonicalFile().toPath(); - if ( !canonicalDestPath.startsWith( canonicalDirPath ) ) - { - throw new ArchiverException( "Entry is outside of the target directory (" + entryName + ")" ); + if (!canonicalDestPath.startsWith(canonicalDirPath)) { + throw new ArchiverException("Entry is outside of the target directory (" + entryName + ")"); } - try - { - if ( !shouldExtractEntry( dir, targetFileName, entryName, entryDate ) ) - { + try { + if (!shouldExtractEntry(dir, targetFileName, entryName, entryDate)) { return; } // create intermediary directories - sometimes zip don't add them final File dirF = targetFileName.getParentFile(); - if ( dirF != null ) - { + if (dirF != null) { dirF.mkdirs(); } - if ( !StringUtils.isEmpty( symlinkDestination ) ) - { - SymlinkUtils.createSymbolicLink( targetFileName, new File( symlinkDestination ) ); - } - else if ( isDirectory ) - { + if (!StringUtils.isEmpty(symlinkDestination)) { + SymlinkUtils.createSymbolicLink(targetFileName, new File(symlinkDestination)); + } else if (isDirectory) { targetFileName.mkdirs(); - } - else - { - try ( OutputStream out = Files.newOutputStream( targetFileName.toPath() ) ) - { - IOUtil.copy( compressedInputStream, out ); + } else { + try (OutputStream out = Files.newOutputStream(targetFileName.toPath())) { + IOUtil.copy(compressedInputStream, out); } } - targetFileName.setLastModified( entryDate.getTime() ); + targetFileName.setLastModified(entryDate.getTime()); - if ( !isIgnorePermissions() && mode != null && !isDirectory ) - { - ArchiveEntryUtils.chmod( targetFileName, mode ); + if (!isIgnorePermissions() && mode != null && !isDirectory) { + ArchiveEntryUtils.chmod(targetFileName, mode); } - } - catch ( final FileNotFoundException ex ) - { - getLogger().warn( "Unable to expand to file " + targetFileName.getPath() ); + } catch (final FileNotFoundException ex) { + getLogger().warn("Unable to expand to file " + targetFileName.getPath()); } } /** * Counter for casing message emitted, visible for testing. */ - final AtomicInteger casingMessageEmitted = new AtomicInteger( 0 ); + final AtomicInteger casingMessageEmitted = new AtomicInteger(0); // Visible for testing - protected boolean shouldExtractEntry( File targetDirectory, File targetFileName, String entryName, Date entryDate ) throws IOException - { + protected boolean shouldExtractEntry(File targetDirectory, File targetFileName, String entryName, Date entryDate) + throws IOException { // entryname | entrydate | filename | filedate | behavior // (1) readme.txt | 1970 | - | - | always extract if the file does not exist // (2) readme.txt | 1970 | readme.txt | 2020 | do not overwrite unless isOverwrite() is true - // (3) readme.txt | 2020 | readme.txt | 1970 | always override when the file is older than the archive entry - // (4) README.txt | 1970 | readme.txt | 2020 | case-insensitive filesystem: warn + do not overwrite unless isOverwrite() + // (3) readme.txt | 2020 | readme.txt | 1970 | always override when the file is older than the archive + // entry + // (4) README.txt | 1970 | readme.txt | 2020 | case-insensitive filesystem: warn + do not overwrite + // unless isOverwrite() // case-sensitive filesystem: extract without warning - // (5) README.txt | 2020 | readme.txt | 1970 | case-insensitive filesystem: warn + overwrite because entry is newer + // (5) README.txt | 2020 | readme.txt | 1970 | case-insensitive filesystem: warn + overwrite because + // entry is newer // case-sensitive filesystem: extract without warning // The canonical file name follows the name of the archive entry, but takes into account the case- // sensitivity of the filesystem. So on a case-sensitive file system, file.exists() returns false for // scenario (4) and (5). - // No matter the case sensitivity of the file system, file.exists() returns false when there is no file with the same name (1). - if ( !targetFileName.exists() ) - { + // No matter the case sensitivity of the file system, file.exists() returns false when there is no file with the + // same name (1). + if (!targetFileName.exists()) { return true; } - boolean entryIsDirectory = entryName.endsWith( "/" ); // directory entries always end with '/', regardless of the OS. + boolean entryIsDirectory = + entryName.endsWith("/"); // directory entries always end with '/', regardless of the OS. String canonicalDestPath = targetFileName.getCanonicalPath(); String suffix = (entryIsDirectory ? "/" : ""); - String relativeCanonicalDestPath = canonicalDestPath.replace( - targetDirectory.getCanonicalPath() + File.separatorChar, - "" ) - + suffix; + String relativeCanonicalDestPath = + canonicalDestPath.replace(targetDirectory.getCanonicalPath() + File.separatorChar, "") + suffix; boolean fileOnDiskIsOlderThanEntry = targetFileName.lastModified() < entryDate.getTime(); - boolean differentCasing = !normalizedFileSeparator( entryName ).equals( normalizedFileSeparator( relativeCanonicalDestPath ) ); + boolean differentCasing = + !normalizedFileSeparator(entryName).equals(normalizedFileSeparator(relativeCanonicalDestPath)); // Warn for case (4) and (5) if the file system is case-insensitive - if ( differentCasing ) - { - String casingMessage = String.format( Locale.ENGLISH, "Archive entry '%s' and existing file '%s' names differ only by case." - + " This may lead to an unexpected outcome on case-insensitive filesystems.", entryName, canonicalDestPath ); - getLogger().warn( casingMessage ); + if (differentCasing) { + String casingMessage = String.format( + Locale.ENGLISH, + "Archive entry '%s' and existing file '%s' names differ only by case." + + " This may lead to an unexpected outcome on case-insensitive filesystems.", + entryName, + canonicalDestPath); + getLogger().warn(casingMessage); casingMessageEmitted.incrementAndGet(); } - // Override the existing file if isOverwrite() is true or if the file on disk is older than the one in the archive + // Override the existing file if isOverwrite() is true or if the file on disk is older than the one in the + // archive return isOverwrite() || fileOnDiskIsOlderThanEntry; } - + private String normalizedFileSeparator(String pathOrEntry) { - return pathOrEntry.replace("/", File.separator); + return pathOrEntry.replace("/", File.separator); } } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiveEntry.java b/src/main/java/org/codehaus/plexus/archiver/ArchiveEntry.java index a17e9b32c..398dcc59c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiveEntry.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiveEntry.java @@ -16,10 +16,12 @@ */ package org.codehaus.plexus.archiver; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.resources.PlexusIoVirtualSymlinkResource; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; @@ -27,10 +29,10 @@ import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; import org.codehaus.plexus.components.io.resources.ResourceFactory; + import static org.codehaus.plexus.components.io.resources.ResourceFactory.createResource; -public class ArchiveEntry -{ +public class ArchiveEntry { public static final String ROLE = ArchiveEntry.class.getName(); @@ -40,7 +42,8 @@ public class ArchiveEntry public static final int SYMLINK = 3; - @Nonnull private final PlexusIoResource resource; + @Nonnull + private final PlexusIoResource resource; private final String name; @@ -48,7 +51,7 @@ public class ArchiveEntry private final int mode; - private final int defaultDirMode; // Sometimes a directory needs to be created. Which mode should it be ? + private final int defaultDirMode; // Sometimes a directory needs to be created. Which mode should it be ? // this mode is at the time of the creation of the archive entry, which is an important distinction private PlexusIoResourceAttributes attributes; @@ -64,50 +67,46 @@ public class ArchiveEntry * @param collection * @param defaultDirMode */ - private ArchiveEntry( String name, @Nonnull PlexusIoResource resource, int type, int mode, - PlexusIoResourceCollection collection, int defaultDirMode ) - { - try - { + private ArchiveEntry( + String name, + @Nonnull PlexusIoResource resource, + int type, + int mode, + PlexusIoResourceCollection collection, + int defaultDirMode) { + try { this.name = name; this.defaultDirMode = defaultDirMode; - this.resource = collection != null ? collection.resolve( resource ) : resource; - this.attributes = ( resource instanceof ResourceAttributeSupplier ) - ? ( (ResourceAttributeSupplier) resource ).getAttributes() : null; + this.resource = collection != null ? collection.resolve(resource) : resource; + this.attributes = (resource instanceof ResourceAttributeSupplier) + ? ((ResourceAttributeSupplier) resource).getAttributes() + : null; this.type = type; int permissions = mode; - if ( mode == PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE && this.attributes == null ) - { + if (mode == PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE && this.attributes == null) { permissions = resource.isFile() - ? Archiver.DEFAULT_FILE_MODE - : resource.isSymbolicLink() - ? Archiver.DEFAULT_SYMLILNK_MODE - : Archiver.DEFAULT_DIR_MODE; - + ? Archiver.DEFAULT_FILE_MODE + : resource.isSymbolicLink() ? Archiver.DEFAULT_SYMLILNK_MODE : Archiver.DEFAULT_DIR_MODE; } this.mode = permissions == PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE - ? permissions - : ( permissions & UnixStat.PERM_MASK ) | ( type == FILE - ? UnixStat.FILE_FLAG - : type == SYMLINK - ? UnixStat.LINK_FLAG - : UnixStat.DIR_FLAG ); - - this.addSynchronously = ( collection != null && !collection.isConcurrentAccessSupported() ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Error resolving resource " + resource.getName(), e ); + ? permissions + : (permissions & UnixStat.PERM_MASK) + | (type == FILE + ? UnixStat.FILE_FLAG + : type == SYMLINK ? UnixStat.LINK_FLAG : UnixStat.DIR_FLAG); + + this.addSynchronously = (collection != null && !collection.isConcurrentAccessSupported()); + } catch (IOException e) { + throw new ArchiverException("Error resolving resource " + resource.getName(), e); } } /** * @return the filename of this entry in the archive. */ - public String getName() - { + public String getName() { return name; } @@ -119,11 +118,9 @@ public String getName() * Consequently, you should use {@link #getInputStream()}- */ @Deprecated - public File getFile() - { - if ( resource instanceof PlexusIoFileResource ) - { - return ( (PlexusIoFileResource) resource ).getFile(); + public File getFile() { + if (resource instanceof PlexusIoFileResource) { + return ((PlexusIoFileResource) resource).getFile(); } return null; } @@ -131,46 +128,34 @@ public File getFile() /** * @return The resource contents. */ - public InputStream getInputStream() - throws IOException - { + public InputStream getInputStream() throws IOException { return resource.getContents(); } /** * @return FILE or DIRECTORY */ - public int getType() - { + public int getType() { return type; } /** * @return octal user/group/other unix like permissions. */ - public int getMode() - { - if ( mode != -1 ) - { + public int getMode() { + if (mode != -1) { return mode; } - if ( attributes != null && attributes.getOctalMode() > -1 ) - { + if (attributes != null && attributes.getOctalMode() > -1) { return attributes.getOctalMode(); } - return ( ( type == FILE - ? Archiver.DEFAULT_FILE_MODE - : type == SYMLINK - ? Archiver.DEFAULT_SYMLILNK_MODE - : Archiver.DEFAULT_DIR_MODE ) & UnixStat.PERM_MASK ) - | ( type == FILE - ? UnixStat.FILE_FLAG - : type == SYMLINK - ? UnixStat.LINK_FLAG - : UnixStat.DIR_FLAG ); - + return ((type == FILE + ? Archiver.DEFAULT_FILE_MODE + : type == SYMLINK ? Archiver.DEFAULT_SYMLILNK_MODE : Archiver.DEFAULT_DIR_MODE) + & UnixStat.PERM_MASK) + | (type == FILE ? UnixStat.FILE_FLAG : type == SYMLINK ? UnixStat.LINK_FLAG : UnixStat.DIR_FLAG); } /** @@ -179,112 +164,97 @@ public int getMode() * * @return {@code true} if this entry should be added synchronously */ - public boolean shouldAddSynchronously() - { + public boolean shouldAddSynchronously() { return addSynchronously; } - public static ArchiveEntry createFileEntry( String target, PlexusIoResource resource, int permissions, - PlexusIoResourceCollection collection, int defaultDirectoryPermissions ) - throws ArchiverException - { - if ( resource.isDirectory() ) - { - throw new ArchiverException( "Not a file: " + resource.getName() ); + public static ArchiveEntry createFileEntry( + String target, + PlexusIoResource resource, + int permissions, + PlexusIoResourceCollection collection, + int defaultDirectoryPermissions) + throws ArchiverException { + if (resource.isDirectory()) { + throw new ArchiverException("Not a file: " + resource.getName()); } final int type = resource.isSymbolicLink() ? SYMLINK : FILE; - return new ArchiveEntry( target, resource, type, permissions, collection, defaultDirectoryPermissions ); + return new ArchiveEntry(target, resource, type, permissions, collection, defaultDirectoryPermissions); } - public static ArchiveEntry createFileEntry( String target, File file, int permissions, - int defaultDirectoryPermissions ) - throws ArchiverException, IOException - { - if ( !file.isFile() ) - { - throw new ArchiverException( "Not a file: " + file ); + public static ArchiveEntry createFileEntry( + String target, File file, int permissions, int defaultDirectoryPermissions) + throws ArchiverException, IOException { + if (!file.isFile()) { + throw new ArchiverException("Not a file: " + file); } - final PlexusIoResource res = ResourceFactory.createResource( file ); + final PlexusIoResource res = ResourceFactory.createResource(file); final int type; - if ( res.isSymbolicLink() ) - { + if (res.isSymbolicLink()) { type = SYMLINK; - permissions = permissions & ~( UnixStat.FILE_FLAG ); // remove file flag again .doh. - } - else - { + permissions = permissions & ~(UnixStat.FILE_FLAG); // remove file flag again .doh. + } else { type = FILE; // File flag was there already. This is a bit of a mess ! } - return new ArchiveEntry( target, res, type, permissions, null, defaultDirectoryPermissions ); + return new ArchiveEntry(target, res, type, permissions, null, defaultDirectoryPermissions); } - public static ArchiveEntry createDirectoryEntry( String target, @Nonnull PlexusIoResource resource, int permissions, - int defaultDirectoryPermissions ) - throws ArchiverException - { - if ( !resource.isDirectory() ) - { - throw new ArchiverException( "Not a directory: " + resource.getName() ); + public static ArchiveEntry createDirectoryEntry( + String target, @Nonnull PlexusIoResource resource, int permissions, int defaultDirectoryPermissions) + throws ArchiverException { + if (!resource.isDirectory()) { + throw new ArchiverException("Not a directory: " + resource.getName()); } final int type; - if ( resource.isSymbolicLink() ) - { + if (resource.isSymbolicLink()) { type = SYMLINK; - permissions = permissions & ~( UnixStat.DIR_FLAG ); // remove dir flag again .doh. - } - else - { + permissions = permissions & ~(UnixStat.DIR_FLAG); // remove dir flag again .doh. + } else { type = DIRECTORY; // Dir flag was there already. This is a bit of a mess ! - } - return new ArchiveEntry( target, resource, type, permissions, null, defaultDirectoryPermissions ); + return new ArchiveEntry(target, resource, type, permissions, null, defaultDirectoryPermissions); } - public static ArchiveEntry createDirectoryEntry( String target, final File file, int permissions, - int defaultDirMode1 ) - throws ArchiverException, IOException - { - if ( !file.isDirectory() ) - { - throw new ArchiverException( "Not a directory: " + file ); + public static ArchiveEntry createDirectoryEntry( + String target, final File file, int permissions, int defaultDirMode1) + throws ArchiverException, IOException { + if (!file.isDirectory()) { + throw new ArchiverException("Not a directory: " + file); } - final PlexusIoResource res = createResource( file ); - return new ArchiveEntry( target, res, DIRECTORY, permissions, null, defaultDirMode1 ); + final PlexusIoResource res = createResource(file); + return new ArchiveEntry(target, res, DIRECTORY, permissions, null, defaultDirMode1); } - public static ArchiveEntry createSymlinkEntry( String symlinkName, int permissions, String symlinkDestination, - int defaultDirectoryPermissions ) - { + public static ArchiveEntry createSymlinkEntry( + String symlinkName, int permissions, String symlinkDestination, int defaultDirectoryPermissions) { final ArchiveEntry archiveEntry = new ArchiveEntry( - symlinkName, new PlexusIoVirtualSymlinkResource( new File( symlinkName ), symlinkDestination ), SYMLINK, - permissions, null, defaultDirectoryPermissions ); + symlinkName, + new PlexusIoVirtualSymlinkResource(new File(symlinkName), symlinkDestination), + SYMLINK, + permissions, + null, + defaultDirectoryPermissions); return archiveEntry; } - public PlexusIoResourceAttributes getResourceAttributes() - { + public PlexusIoResourceAttributes getResourceAttributes() { return attributes; } - public void setResourceAttributes( PlexusIoResourceAttributes attributes ) - { + public void setResourceAttributes(PlexusIoResourceAttributes attributes) { this.attributes = attributes; } - public @Nonnull - PlexusIoResource getResource() - { + public @Nonnull PlexusIoResource getResource() { return resource; } - public int getDefaultDirMode() - { + public int getDefaultDirMode() { return defaultDirMode; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiveFile.java b/src/main/java/org/codehaus/plexus/archiver/ArchiveFile.java index ceedd371b..4b6e432fe 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiveFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiveFile.java @@ -7,22 +7,18 @@ /** * Interface of a zip, or tar file. */ -public interface ArchiveFile -{ +public interface ArchiveFile { /** * Returns an enumeration with the archive files entries. * Any element returned by the enumeration is an instance * of {@link org.apache.commons.compress.archivers.ArchiveEntry}. */ - Enumeration getEntries() - throws IOException; + Enumeration getEntries() throws IOException; /** * Returns an {@link InputStream} with the given entries contents. * org.apache.commons.compress.archivers.ArchiveEntry */ - InputStream getInputStream( org.apache.commons.compress.archivers.ArchiveEntry entry ) - throws IOException; - + InputStream getInputStream(org.apache.commons.compress.archivers.ArchiveEntry entry) throws IOException; } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiveFileFilter.java b/src/main/java/org/codehaus/plexus/archiver/ArchiveFileFilter.java index d0fa98112..00536dd3e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiveFileFilter.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiveFileFilter.java @@ -1,16 +1,14 @@ package org.codehaus.plexus.archiver; -import org.codehaus.plexus.components.io.fileselectors.FileSelector; - import java.io.InputStream; +import org.codehaus.plexus.components.io.fileselectors.FileSelector; + /** * @deprecated Use {@link FileSelector} */ @Deprecated -public interface ArchiveFileFilter -{ - - boolean include( InputStream dataStream, String entryName ); +public interface ArchiveFileFilter { + boolean include(InputStream dataStream, String entryName); } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiveFilterException.java b/src/main/java/org/codehaus/plexus/archiver/ArchiveFilterException.java index e77f14d69..bc4d60ab4 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiveFilterException.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiveFilterException.java @@ -1,17 +1,12 @@ package org.codehaus.plexus.archiver; -public class ArchiveFilterException - extends Exception -{ +public class ArchiveFilterException extends Exception { - public ArchiveFilterException( String message, Throwable cause ) - { - super( message, cause ); + public ArchiveFilterException(String message, Throwable cause) { + super(message, cause); } - public ArchiveFilterException( String message ) - { - super( message ); + public ArchiveFilterException(String message) { + super(message); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiveFinalizer.java b/src/main/java/org/codehaus/plexus/archiver/ArchiveFinalizer.java index 56cbf3204..8d14f6dbe 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiveFinalizer.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiveFinalizer.java @@ -6,15 +6,11 @@ * An archive finalizer is just before archive creation (after user has added all files), * allowing the finalizer to do stuff like create manifests etc. */ -public interface ArchiveFinalizer -{ +public interface ArchiveFinalizer { - void finalizeArchiveCreation( Archiver archiver ) - throws ArchiverException; + void finalizeArchiveCreation(Archiver archiver) throws ArchiverException; - void finalizeArchiveExtraction( UnArchiver unarchiver ) - throws ArchiverException; + void finalizeArchiveExtraction(UnArchiver unarchiver) throws ArchiverException; List getVirtualFiles(); - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchivedFileSet.java b/src/main/java/org/codehaus/plexus/archiver/ArchivedFileSet.java index 2c2de9ca4..8f2101f6e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchivedFileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchivedFileSet.java @@ -1,22 +1,20 @@ package org.codehaus.plexus.archiver; -import java.io.File; import javax.annotation.CheckForNull; +import java.io.File; + /** * A file set, which consists of the files and directories in * an archive. * * @since 1.0-alpha-9 */ -public interface ArchivedFileSet - extends BaseFileSet -{ +public interface ArchivedFileSet extends BaseFileSet { /** * Returns the archive file. */ @CheckForNull File getArchive(); - } diff --git a/src/main/java/org/codehaus/plexus/archiver/Archiver.java b/src/main/java/org/codehaus/plexus/archiver/Archiver.java index 19b29d8c2..7f8ae3e24 100644 --- a/src/main/java/org/codehaus/plexus/archiver/Archiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/Archiver.java @@ -16,6 +16,8 @@ */ package org.codehaus.plexus.archiver; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -26,12 +28,10 @@ import java.util.Map; import java.util.Set; -import javax.annotation.Nonnull; import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; -public interface Archiver -{ +public interface Archiver { /** * Default value for the dirmode attribute. @@ -56,23 +56,19 @@ public interface Archiver String DUPLICATES_FAIL = "fail"; - Set DUPLICATES_VALID_BEHAVIORS = new HashSet() - { + Set DUPLICATES_VALID_BEHAVIORS = new HashSet() { private static final long serialVersionUID = 1L; - { - add( DUPLICATES_ADD ); - add( DUPLICATES_PRESERVE ); - add( DUPLICATES_SKIP ); - add( DUPLICATES_FAIL ); + add(DUPLICATES_ADD); + add(DUPLICATES_PRESERVE); + add(DUPLICATES_SKIP); + add(DUPLICATES_FAIL); } - }; - void createArchive() - throws ArchiverException, IOException; + void createArchive() throws ArchiverException, IOException; /** * Obsolete, use {@link #addFileSet(FileSet)}. @@ -80,8 +76,7 @@ void createArchive() * @deprecated Will go away in next major version */ @Deprecated - void addDirectory( @Nonnull File directory ) - throws ArchiverException; + void addDirectory(@Nonnull File directory) throws ArchiverException; /** * Obsolete, use {@link #addFileSet(FileSet)}. @@ -89,8 +84,7 @@ void addDirectory( @Nonnull File directory ) * @deprecated Will go away in next major version */ @Deprecated - void addDirectory( @Nonnull File directory, String prefix ) - throws ArchiverException; + void addDirectory(@Nonnull File directory, String prefix) throws ArchiverException; /** * Obsolete, use {@link #addFileSet(FileSet)}. @@ -98,8 +92,7 @@ void addDirectory( @Nonnull File directory, String prefix ) * @deprecated Will go away in next major version */ @Deprecated - void addDirectory( @Nonnull File directory, String[] includes, String[] excludes ) - throws ArchiverException; + void addDirectory(@Nonnull File directory, String[] includes, String[] excludes) throws ArchiverException; /** * Obsolete, use {@link #addFileSet(FileSet)}. @@ -107,8 +100,8 @@ void addDirectory( @Nonnull File directory, String[] includes, String[] excludes * @deprecated Will go away in next major version */ @Deprecated - void addDirectory( @Nonnull File directory, String prefix, String[] includes, String[] excludes ) - throws ArchiverException; + void addDirectory(@Nonnull File directory, String prefix, String[] includes, String[] excludes) + throws ArchiverException; /** * Adds the given file set to the archive. This method is basically obsoleting {@link #addDirectory(File)}, @@ -120,28 +113,22 @@ void addDirectory( @Nonnull File directory, String prefix, String[] includes, St * Adding the file set failed. * @since 1.0-alpha-9 */ - void addFileSet( @Nonnull FileSet fileSet ) - throws ArchiverException; + void addFileSet(@Nonnull FileSet fileSet) throws ArchiverException; - void addSymlink( String symlinkName, String symlinkDestination ) - throws ArchiverException; + void addSymlink(String symlinkName, String symlinkDestination) throws ArchiverException; - void addSymlink( String symlinkName, int permissions, String symlinkDestination ) - throws ArchiverException; + void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException; - void addFile( @Nonnull File inputFile, @Nonnull String destFileName ) - throws ArchiverException; + void addFile(@Nonnull File inputFile, @Nonnull String destFileName) throws ArchiverException; - void addFile( @Nonnull File inputFile, @Nonnull String destFileName, int permissions ) - throws ArchiverException; + void addFile(@Nonnull File inputFile, @Nonnull String destFileName, int permissions) throws ArchiverException; /** * Obsolete, use {@link #addArchivedFileSet(ArchivedFileSet)}. * * @deprecated Will go away in next major version */ - void addArchivedFileSet( @Nonnull File archiveFile ) - throws ArchiverException; + void addArchivedFileSet(@Nonnull File archiveFile) throws ArchiverException; /** * Obsolete, use {@link #addArchivedFileSet(ArchivedFileSet)}. @@ -149,8 +136,7 @@ void addArchivedFileSet( @Nonnull File archiveFile ) * @deprecated Will go away in next major version */ @Deprecated - void addArchivedFileSet( @Nonnull File archiveFile, String prefix ) - throws ArchiverException; + void addArchivedFileSet(@Nonnull File archiveFile, String prefix) throws ArchiverException; /** * Obsolete, use {@link #addArchivedFileSet(ArchivedFileSet)}. @@ -158,8 +144,7 @@ void addArchivedFileSet( @Nonnull File archiveFile, String prefix ) * @deprecated Will go away in next major version */ @Deprecated - void addArchivedFileSet( File archiveFile, String[] includes, String[] excludes ) - throws ArchiverException; + void addArchivedFileSet(File archiveFile, String[] includes, String[] excludes) throws ArchiverException; /** * Obsolete, use {@link #addArchivedFileSet(ArchivedFileSet)}. @@ -167,8 +152,8 @@ void addArchivedFileSet( File archiveFile, String[] includes, String[] excludes * @deprecated Will go away in next major version */ @Deprecated - void addArchivedFileSet( @Nonnull File archiveFile, String prefix, String[] includes, String[] excludes ) - throws ArchiverException; + void addArchivedFileSet(@Nonnull File archiveFile, String prefix, String[] includes, String[] excludes) + throws ArchiverException; /** * Adds the given archive file set to the archive. This method is basically obsoleting @@ -180,8 +165,7 @@ void addArchivedFileSet( @Nonnull File archiveFile, String prefix, String[] incl * * @since 1.0-alpha-9 */ - void addArchivedFileSet( ArchivedFileSet fileSet ) - throws ArchiverException; + void addArchivedFileSet(ArchivedFileSet fileSet) throws ArchiverException; /** * Adds the given archive file set to the archive. This method is basically obsoleting @@ -199,8 +183,7 @@ void addArchivedFileSet( ArchivedFileSet fileSet ) * * @since 1.0-alpha-9 */ - void addArchivedFileSet( ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException; + void addArchivedFileSet(ArchivedFileSet fileSet, Charset charset) throws ArchiverException; /** * Adds the given resource collection to the archive. @@ -209,8 +192,7 @@ void addArchivedFileSet( ArchivedFileSet fileSet, Charset charset ) * * @since 1.0-alpha-10 */ - void addResource( PlexusIoResource resource, String destFileName, int permissions ) - throws ArchiverException; + void addResource(PlexusIoResource resource, String destFileName, int permissions) throws ArchiverException; /** * Adds the given resource collection to the archive. @@ -219,20 +201,19 @@ void addResource( PlexusIoResource resource, String destFileName, int permission * * @since 1.0-alpha-10 */ - void addResources( PlexusIoResourceCollection resources ) - throws ArchiverException; + void addResources(PlexusIoResourceCollection resources) throws ArchiverException; File getDestFile(); - void setDestFile( File destFile ); + void setDestFile(File destFile); - void setFileMode( int mode ); + void setFileMode(int mode); int getFileMode(); int getOverrideFileMode(); - void setDefaultFileMode( int mode ); + void setDefaultFileMode(int mode); int getDefaultFileMode(); @@ -241,7 +222,7 @@ void addResources( PlexusIoResourceCollection resources ) * * @param mode */ - void setDirectoryMode( int mode ); + void setDirectoryMode(int mode); /** * Gets the forced mode for directories, falling back to default if none is forced. @@ -257,15 +238,15 @@ void addResources( PlexusIoResourceCollection resources ) * * @param mode */ - void setDefaultDirectoryMode( int mode ); + void setDefaultDirectoryMode(int mode); int getDefaultDirectoryMode(); boolean getIncludeEmptyDirs(); - void setIncludeEmptyDirs( boolean includeEmptyDirs ); + void setIncludeEmptyDirs(boolean includeEmptyDirs); - void setDotFileDirectory( File dotFileDirectory ); + void setDotFileDirectory(File dotFileDirectory); /** * Returns an iterator over instances of {@link ArchiveEntry}, which have previously been added by calls to @@ -275,8 +256,7 @@ void addResources( PlexusIoResourceCollection resources ) * @since 1.0-alpha-10 */ @Nonnull - ResourceIterator getResources() - throws ArchiverException; + ResourceIterator getResources() throws ArchiverException; /** * @deprecated Use {@link #getResources()} @@ -326,7 +306,7 @@ ResourceIterator getResources() * @see #isForced() * @see #isSupportingForced() */ - void setForced( boolean forced ); + void setForced(boolean forced); /** * Returns, whether the archive supports uptodate checks. If so, you may set {@link #setForced(boolean)} to true. @@ -354,7 +334,7 @@ ResourceIterator getResources() * See {@link Archiver#DUPLICATES_ADD}, {@link Archiver#DUPLICATES_SKIP}, {@link Archiver#DUPLICATES_PRESERVE}, * {@link Archiver#DUPLICATES_FAIL}. */ - void setDuplicateBehavior( String duplicate ); + void setDuplicateBehavior(String duplicate); /** * to use or not the jvm method for file permissions: user all not active for group permissions @@ -364,7 +344,7 @@ ResourceIterator getResources() * @deprecated this setting is now ignored. The jvm is always used. */ @Deprecated - void setUseJvmChmod( boolean useJvmChmod ); + void setUseJvmChmod(boolean useJvmChmod); /** * @@ -383,7 +363,7 @@ ResourceIterator getResources() /** * @since 1.1 */ - void setIgnorePermissions( final boolean ignorePermissions ); + void setIgnorePermissions(final boolean ignorePermissions); /** * Define forced last modification date for entries (if non null). @@ -393,7 +373,7 @@ ResourceIterator getResources() * @deprecated Use {@link #setLastModifiedTime(FileTime)} instead */ @Deprecated - void setLastModifiedDate( final Date lastModifiedDate ); + void setLastModifiedDate(final Date lastModifiedDate); /** * @since 4.2.0 @@ -410,7 +390,7 @@ ResourceIterator getResources() * @see #getLastModifiedTime() * @since 4.3.0 */ - void setLastModifiedTime( final FileTime lastModifiedTime ); + void setLastModifiedTime(final FileTime lastModifiedTime); /** * Returns the last modification time of the archiver. @@ -428,17 +408,17 @@ ResourceIterator getResources() * * @since 4.2.0 */ - void setFilenameComparator( Comparator filenameComparator ); + void setFilenameComparator(Comparator filenameComparator); /** * @since 4.2.0 */ - void setOverrideUid( int uid ); + void setOverrideUid(int uid); /** * @since 4.2.0 */ - void setOverrideUserName( String userName ); + void setOverrideUserName(String userName); /** * @since 4.2.0 @@ -453,12 +433,12 @@ ResourceIterator getResources() /** * @since 4.2.0 */ - void setOverrideGid( int gid ); + void setOverrideGid(int gid); /** * @since 4.2.0 */ - void setOverrideGroupName( String groupName ); + void setOverrideGroupName(String groupName); /** * @since 4.2.0 @@ -473,7 +453,7 @@ ResourceIterator getResources() /** * @since 4.7.0 */ - void setUmask( int umask ); + void setUmask(int umask); /** * @since 4.7.0 @@ -489,7 +469,7 @@ ResourceIterator getResources() * @deprecated Use {@link #configureReproducibleBuild(FileTime)} instead. */ @Deprecated - void configureReproducible( Date lastModifiedDate ); + void configureReproducible(Date lastModifiedDate); /** * Configure the archiver to create archives in a reproducible way (see @@ -505,5 +485,5 @@ ResourceIterator getResources() * @see Reproducible Builds * @since 4.3.0 */ - void configureReproducibleBuild( FileTime lastModifiedTime ); + void configureReproducibleBuild(FileTime lastModifiedTime); } diff --git a/src/main/java/org/codehaus/plexus/archiver/ArchiverException.java b/src/main/java/org/codehaus/plexus/archiver/ArchiverException.java index 2db433198..fb2413a1a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ArchiverException.java +++ b/src/main/java/org/codehaus/plexus/archiver/ArchiverException.java @@ -15,18 +15,13 @@ */ package org.codehaus.plexus.archiver; -public class ArchiverException - extends RuntimeException -{ +public class ArchiverException extends RuntimeException { - public ArchiverException( String message ) - { - super( message ); + public ArchiverException(String message) { + super(message); } - public ArchiverException( String message, Throwable cause ) - { - super( message, cause ); + public ArchiverException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/BaseFileSet.java b/src/main/java/org/codehaus/plexus/archiver/BaseFileSet.java index bcb8ae602..fd6110f7e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/BaseFileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/BaseFileSet.java @@ -1,6 +1,7 @@ package org.codehaus.plexus.archiver; import javax.annotation.CheckForNull; + import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.components.io.functions.InputStreamTransformer; @@ -11,8 +12,7 @@ * * @since 1.0-alpha-9 */ -public interface BaseFileSet -{ +public interface BaseFileSet { /** * Returns the prefix, which the file sets contents shall @@ -72,5 +72,4 @@ public interface BaseFileSet */ @CheckForNull FileMapper[] getFileMappers(); - } diff --git a/src/main/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizer.java b/src/main/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizer.java index e3f44da07..86c8d2be2 100644 --- a/src/main/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizer.java +++ b/src/main/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizer.java @@ -19,9 +19,7 @@ * * @author Jason van Zyl */ -public class DotDirectiveArchiveFinalizer - extends AbstractArchiveFinalizer -{ +public class DotDirectiveArchiveFinalizer extends AbstractArchiveFinalizer { private static final String DEFAULT_DOT_FILE_PREFIX = ".plxarc"; @@ -29,73 +27,55 @@ public class DotDirectiveArchiveFinalizer private final String dotFilePrefix; - public DotDirectiveArchiveFinalizer( File dotFileDirectory ) - { - this( dotFileDirectory, DEFAULT_DOT_FILE_PREFIX ); + public DotDirectiveArchiveFinalizer(File dotFileDirectory) { + this(dotFileDirectory, DEFAULT_DOT_FILE_PREFIX); } - public DotDirectiveArchiveFinalizer( File dotFileDirectory, String dotFilePrefix ) - { + public DotDirectiveArchiveFinalizer(File dotFileDirectory, String dotFilePrefix) { this.dotFileDirectory = dotFileDirectory; this.dotFilePrefix = dotFilePrefix; } @Override - public void finalizeArchiveCreation( Archiver archiver ) - throws ArchiverException - { - try - { - List dotFiles = FileUtils.getFiles( dotFileDirectory, dotFilePrefix + "*", null ); + public void finalizeArchiveCreation(Archiver archiver) throws ArchiverException { + try { + List dotFiles = FileUtils.getFiles(dotFileDirectory, dotFilePrefix + "*", null); - for ( File dotFile : dotFiles ) - { - try ( BufferedReader in = Files.newBufferedReader( dotFile.toPath(), StandardCharsets.UTF_8 ) ) - { + for (File dotFile : dotFiles) { + try (BufferedReader in = Files.newBufferedReader(dotFile.toPath(), StandardCharsets.UTF_8)) { - for ( String line = in.readLine(); line != null; line = in.readLine() ) - { - String[] s = StringUtils.split( line, ":" ); + for (String line = in.readLine(); line != null; line = in.readLine()) { + String[] s = StringUtils.split(line, ":"); - if ( s.length == 1 ) - { - File directory = new File( dotFileDirectory, s[0] ); + if (s.length == 1) { + File directory = new File(dotFileDirectory, s[0]); - System.out.println( "adding directory = " + directory ); + System.out.println("adding directory = " + directory); - archiver.addFileSet( new DefaultFileSet( directory ) ); - } - else - { - File directory = new File( dotFileDirectory, s[0] ); + archiver.addFileSet(new DefaultFileSet(directory)); + } else { + File directory = new File(dotFileDirectory, s[0]); - System.out.println( "adding directory = " + directory + " to: " + s[1] ); + System.out.println("adding directory = " + directory + " to: " + s[1]); - if ( s[1].endsWith( "/" ) ) - { + if (s[1].endsWith("/")) { - archiver.addFileSet( new DefaultFileSet( directory ).prefixed( s[1] ) ); - } - else - { - archiver.addFileSet( new DefaultFileSet( directory ).prefixed( s[1] + "/" ) ); + archiver.addFileSet(new DefaultFileSet(directory).prefixed(s[1])); + } else { + archiver.addFileSet(new DefaultFileSet(directory).prefixed(s[1] + "/")); } } } } } - } - catch ( IOException e ) - { - throw new ArchiverException( "Error processing dot files.", e ); + } catch (IOException e) { + throw new ArchiverException("Error processing dot files.", e); } } @Override - public List getVirtualFiles() - { + public List getVirtualFiles() { return Collections.EMPTY_LIST; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/FileSet.java b/src/main/java/org/codehaus/plexus/archiver/FileSet.java index 740bbf83b..ff6f31cd2 100644 --- a/src/main/java/org/codehaus/plexus/archiver/FileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/FileSet.java @@ -8,13 +8,10 @@ * * @since 1.0-alpha-9 */ -public interface FileSet - extends BaseFileSet -{ +public interface FileSet extends BaseFileSet { /** * Returns the file sets base directory. */ File getDirectory(); - } diff --git a/src/main/java/org/codehaus/plexus/archiver/FinalizerEnabled.java b/src/main/java/org/codehaus/plexus/archiver/FinalizerEnabled.java index 6aa038c6a..cd0cc9d53 100644 --- a/src/main/java/org/codehaus/plexus/archiver/FinalizerEnabled.java +++ b/src/main/java/org/codehaus/plexus/archiver/FinalizerEnabled.java @@ -2,11 +2,9 @@ import java.util.List; -public interface FinalizerEnabled -{ +public interface FinalizerEnabled { - void addArchiveFinalizer( ArchiveFinalizer finalizer ); - - void setArchiveFinalizers( List archiveFinalizers ); + void addArchiveFinalizer(ArchiveFinalizer finalizer); + void setArchiveFinalizers(List archiveFinalizers); } diff --git a/src/main/java/org/codehaus/plexus/archiver/ResourceIterator.java b/src/main/java/org/codehaus/plexus/archiver/ResourceIterator.java index 2aa58b72a..4e768af65 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ResourceIterator.java +++ b/src/main/java/org/codehaus/plexus/archiver/ResourceIterator.java @@ -2,13 +2,11 @@ import java.util.Iterator; -public interface ResourceIterator extends Iterator -{ +public interface ResourceIterator extends Iterator { @Override boolean hasNext(); @Override ArchiveEntry next(); - } diff --git a/src/main/java/org/codehaus/plexus/archiver/UnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/UnArchiver.java index 486df7b4f..1c297dfe3 100644 --- a/src/main/java/org/codehaus/plexus/archiver/UnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/UnArchiver.java @@ -17,18 +17,17 @@ package org.codehaus.plexus.archiver; import java.io.File; + import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.components.io.fileselectors.FileSelector; -public interface UnArchiver -{ +public interface UnArchiver { /** * Extract the archive. * * @throws ArchiverException */ - void extract() - throws ArchiverException; + void extract() throws ArchiverException; /** * Take a path into the archive and extract it to the specified directory. @@ -38,22 +37,21 @@ void extract() * * @throws ArchiverException */ - void extract( String path, File outputDirectory ) - throws ArchiverException; + void extract(String path, File outputDirectory) throws ArchiverException; File getDestDirectory(); - void setDestDirectory( File destDirectory ); + void setDestDirectory(File destDirectory); // todo What is this? If you're extracting isn't it always to a directory. I think it would be cool to extract an // archive to another archive but I don't think we support this right now. File getDestFile(); - void setDestFile( File destFile ); + void setDestFile(File destFile); File getSourceFile(); - void setSourceFile( File sourceFile ); + void setSourceFile(File sourceFile); /** * Gets a flag indicating destination files are always overwritten. @@ -68,7 +66,7 @@ void extract( String path, File outputDirectory ) /** * Should we overwrite files in dest, even if they are newer than the corresponding entries in the archive? */ - void setOverwrite( boolean b ); + void setOverwrite(boolean b); /** * Get chain of components which rewrite the target path of each unpacked file. @@ -87,13 +85,13 @@ void extract( String path, File outputDirectory ) * * @since 3.7.0 */ - void setFileMappers( FileMapper[] fileMappers ); + void setFileMappers(FileMapper[] fileMappers); /** * Sets a set of {@link FileSelector} instances, which may be used to select the files to extract from the archive. * If file selectors are present, then a file is only extracted, if it is confirmed by all file selectors. */ - void setFileSelectors( FileSelector[] selectors ); + void setFileSelectors(FileSelector[] selectors); /** * Returns a set of {@link FileSelector} instances, which may be used to select the files to extract from the @@ -109,7 +107,7 @@ void extract( String path, File outputDirectory ) * @deprecated this setting is now ignored. The jvm is always used. */ @Deprecated - void setUseJvmChmod( boolean useJvmChmod ); + void setUseJvmChmod(boolean useJvmChmod); /** * @since 1.1 @@ -127,6 +125,5 @@ void extract( String path, File outputDirectory ) /** * @since 1.1 */ - void setIgnorePermissions( final boolean ignorePermissions ); - + void setIgnorePermissions(final boolean ignorePermissions); } diff --git a/src/main/java/org/codehaus/plexus/archiver/UnixStat.java b/src/main/java/org/codehaus/plexus/archiver/UnixStat.java index ac2222214..ab463fbe7 100644 --- a/src/main/java/org/codehaus/plexus/archiver/UnixStat.java +++ b/src/main/java/org/codehaus/plexus/archiver/UnixStat.java @@ -21,8 +21,7 @@ * * from org.apache.ant.tools.zip.UnixStat v1.9 */ -public interface UnixStat -{ +public interface UnixStat { /** * Bits used for permissions (and sticky bit) @@ -76,5 +75,4 @@ public interface UnixStat * @since 1.1 */ int DEFAULT_FILE_PERM = 0_644; - } diff --git a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Archiver.java b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Archiver.java index 2f9449dcb..8359adb61 100644 --- a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Archiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Archiver.java @@ -19,59 +19,49 @@ import javax.inject.Named; import java.io.IOException; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.ResourceIterator; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; -@Named( "bzip2" ) -public class BZip2Archiver - extends AbstractArchiver -{ +@Named("bzip2") +public class BZip2Archiver extends AbstractArchiver { private final BZip2Compressor compressor = new BZip2Compressor(); @Override - public void execute() - throws ArchiverException, IOException - { - if ( !checkForced() ) - { + public void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } ArchiveEntry entry = iter.next(); - if ( iter.hasNext() ) - { - throw new ArchiverException( "There is more than one file in input." ); + if (iter.hasNext()) { + throw new ArchiverException("There is more than one file in input."); } - compressor.setSource( entry.getResource() ); - compressor.setDestFile( getDestFile() ); + compressor.setSource(entry.getResource()); + compressor.setDestFile(getDestFile()); compressor.compress(); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void close() - { + protected void close() { compressor.close(); } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "bzip2"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Compressor.java b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Compressor.java index 8bcad3335..00b82f6e1 100644 --- a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Compressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2Compressor.java @@ -17,15 +17,15 @@ package org.codehaus.plexus.archiver.bzip2; import java.io.IOException; + import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Compressor; + import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; -public class BZip2Compressor - extends Compressor -{ +public class BZip2Compressor extends Compressor { private BZip2CompressorOutputStream zOut; @@ -33,37 +33,26 @@ public class BZip2Compressor * perform the BZip2 compression operation. */ @Override - public void compress() - throws ArchiverException - { - try - { - zOut = new BZip2CompressorOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) ); + public void compress() throws ArchiverException { + try { + zOut = new BZip2CompressorOutputStream(bufferedOutputStream(fileOutputStream(getDestFile()))); // BUffering of the source stream seems to have little/no impact - compress( getSource(), zOut ); - } - catch ( IOException ioe ) - { + compress(getSource(), zOut); + } catch (IOException ioe) { String msg = "Problem creating bzip2 " + ioe.getMessage(); - throw new ArchiverException( msg, ioe ); + throw new ArchiverException(msg, ioe); } } @Override - public void close() - { - try - { - if ( this.zOut != null ) - { + public void close() { + try { + if (this.zOut != null) { this.zOut.close(); zOut = null; } - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure closing target.", e ); + } catch (final IOException e) { + throw new ArchiverException("Failure closing target.", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2UnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2UnArchiver.java index 07ab52f96..39ec52ace 100644 --- a/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2UnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/bzip2/BZip2UnArchiver.java @@ -16,15 +16,17 @@ */ package org.codehaus.plexus.archiver.bzip2; +import javax.annotation.Nonnull; +import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import javax.annotation.Nonnull; -import javax.inject.Named; import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream; import org.codehaus.plexus.archiver.AbstractUnArchiver; import org.codehaus.plexus.archiver.ArchiverException; + import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.copyFully; @@ -34,55 +36,42 @@ /** * @author Emmanuel Venisse */ -@Named( "bzip2" ) -public class BZip2UnArchiver - extends AbstractUnArchiver -{ +@Named("bzip2") +public class BZip2UnArchiver extends AbstractUnArchiver { - private final static String OPERATION_BZIP2 = "bzip2"; + private static final String OPERATION_BZIP2 = "bzip2"; - public BZip2UnArchiver() - { - } + public BZip2UnArchiver() {} - public BZip2UnArchiver( File sourceFile ) - { - super( sourceFile ); + public BZip2UnArchiver(File sourceFile) { + super(sourceFile); } @Override - protected void execute() - throws ArchiverException - { - if ( getSourceFile().lastModified() > getDestFile().lastModified() ) - { - getLogger().info( - "Expanding " + getSourceFile().getAbsolutePath() + " to " + getDestFile().getAbsolutePath() ); + protected void execute() throws ArchiverException { + if (getSourceFile().lastModified() > getDestFile().lastModified()) { + getLogger() + .info("Expanding " + getSourceFile().getAbsolutePath() + " to " + + getDestFile().getAbsolutePath()); - copyFully( getBZip2InputStream( bufferedInputStream( fileInputStream( getSourceFile(), OPERATION_BZIP2 ) ) ), - bufferedOutputStream( fileOutputStream( getDestFile(), OPERATION_BZIP2 ) ), OPERATION_BZIP2 ); + copyFully( + getBZip2InputStream(bufferedInputStream(fileInputStream(getSourceFile(), OPERATION_BZIP2))), + bufferedOutputStream(fileOutputStream(getDestFile(), OPERATION_BZIP2)), + OPERATION_BZIP2); } } - public static @Nonnull - BZip2CompressorInputStream getBZip2InputStream( InputStream bis ) - throws ArchiverException - { - try - { + public static @Nonnull BZip2CompressorInputStream getBZip2InputStream(InputStream bis) throws ArchiverException { + try { // Note that bis must be buffered for performance. Does not need buffering around BZip2CompressorInputStream - return new BZip2CompressorInputStream( bis ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Trouble creating BZIP2 compressor, invalid file ?", e ); + return new BZip2CompressorInputStream(bis); + } catch (IOException e) { + throw new ArchiverException("Trouble creating BZIP2 compressor, invalid file ?", e); } } @Override - protected void execute( String path, File outputDirectory ) - { - throw new UnsupportedOperationException( "Targeted extraction not supported in BZIP2 format." ); + protected void execute(String path, File outputDirectory) { + throw new UnsupportedOperationException("Targeted extraction not supported in BZIP2 format."); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBz2ResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBz2ResourceCollection.java index 59c447ee5..b66051559 100644 --- a/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBz2ResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBz2ResourceCollection.java @@ -5,8 +5,5 @@ /** * Alias of {@link PlexusIoBzip2ResourceCollection}. */ -@Named( "bz2" ) -public class PlexusIoBz2ResourceCollection - extends PlexusIoBzip2ResourceCollection -{ -} +@Named("bz2") +public class PlexusIoBz2ResourceCollection extends PlexusIoBzip2ResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBzip2ResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBzip2ResourceCollection.java index 651e0cb57..728337fba 100644 --- a/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBzip2ResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/bzip2/PlexusIoBzip2ResourceCollection.java @@ -1,47 +1,41 @@ package org.codehaus.plexus.archiver.bzip2; -import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; +import javax.annotation.Nonnull; +import javax.annotation.WillNotClose; +import javax.inject.Named; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; -import javax.annotation.Nonnull; -import javax.annotation.WillNotClose; -import javax.inject.Named; import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.resources.PlexusIoCompressedFileResourceCollection; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; +import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; + /** * Implementation of {@link PlexusIoResourceCollection} for * bzip2 compressed files. */ -@Named( "bzip2" ) -public class PlexusIoBzip2ResourceCollection - extends PlexusIoCompressedFileResourceCollection -{ +@Named("bzip2") +public class PlexusIoBzip2ResourceCollection extends PlexusIoCompressedFileResourceCollection { @Nonnull @Override - protected @WillNotClose - InputStream getInputStream( File file ) - throws IOException - { - return BZip2UnArchiver.getBZip2InputStream( fileInputStream( file ) ); + protected @WillNotClose InputStream getInputStream(File file) throws IOException { + return BZip2UnArchiver.getBZip2InputStream(fileInputStream(file)); } - @Override protected PlexusIoResourceAttributes getAttributes( File file ) throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + @Override + protected PlexusIoResourceAttributes getAttributes(File file) throws IOException { + return new FileAttributes(file, new HashMap(), new HashMap()); } @Override - protected String getDefaultExtension() - { + protected String getDefaultExtension() { return ".bz2"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/car/CarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/car/CarUnArchiver.java index 7ce6ba243..2e87203cd 100644 --- a/src/main/java/org/codehaus/plexus/archiver/car/CarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/car/CarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "car" ) -public class CarUnArchiver - extends ZipUnArchiver -{ +@Named("car") +public class CarUnArchiver extends ZipUnArchiver { - public CarUnArchiver() - { - } + public CarUnArchiver() {} - public CarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public CarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/car/PlexusIoCarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/car/PlexusIoCarFileResourceCollection.java index 465721e31..8edf39fdf 100644 --- a/src/main/java/org/codehaus/plexus/archiver/car/PlexusIoCarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/car/PlexusIoCarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "car" ) -public class PlexusIoCarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("car") +public class PlexusIoCarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/diags/DelgatingArchiver.java b/src/main/java/org/codehaus/plexus/archiver/diags/DelgatingArchiver.java index bd419431b..fafdcd3f4 100644 --- a/src/main/java/org/codehaus/plexus/archiver/diags/DelgatingArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/diags/DelgatingArchiver.java @@ -15,6 +15,8 @@ */ package org.codehaus.plexus.archiver.diags; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -22,7 +24,7 @@ import java.util.Comparator; import java.util.Date; import java.util.Map; -import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchivedFileSet; import org.codehaus.plexus.archiver.Archiver; @@ -32,306 +34,241 @@ import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; -@SuppressWarnings( -{ - "UnusedDeclaration", "deprecation" -} ) -public class DelgatingArchiver implements Archiver -{ +@SuppressWarnings({"UnusedDeclaration", "deprecation"}) +public class DelgatingArchiver implements Archiver { private final Archiver target; - public DelgatingArchiver( Archiver target ) - { + public DelgatingArchiver(Archiver target) { this.target = target; } @Override - public void createArchive() - throws ArchiverException, IOException - { + public void createArchive() throws ArchiverException, IOException { target.createArchive(); } @Deprecated @Override - public void addDirectory( @Nonnull File directory ) - throws ArchiverException - { - target.addDirectory( directory ); + public void addDirectory(@Nonnull File directory) throws ArchiverException { + target.addDirectory(directory); } @Deprecated @Override - public void addDirectory( @Nonnull File directory, String prefix ) - throws ArchiverException - { - target.addDirectory( directory, prefix ); + public void addDirectory(@Nonnull File directory, String prefix) throws ArchiverException { + target.addDirectory(directory, prefix); } @Deprecated @Override - public void addDirectory( @Nonnull File directory, String[] includes, String[] excludes ) - throws ArchiverException - { - target.addDirectory( directory, includes, excludes ); + public void addDirectory(@Nonnull File directory, String[] includes, String[] excludes) throws ArchiverException { + target.addDirectory(directory, includes, excludes); } @Override - public void addDirectory( @Nonnull File directory, String prefix, String[] includes, String[] excludes ) - throws ArchiverException - { - target.addDirectory( directory, prefix, includes, excludes ); + public void addDirectory(@Nonnull File directory, String prefix, String[] includes, String[] excludes) + throws ArchiverException { + target.addDirectory(directory, prefix, includes, excludes); } @Override - public void addFileSet( @Nonnull FileSet fileSet ) - throws ArchiverException - { - target.addFileSet( fileSet ); + public void addFileSet(@Nonnull FileSet fileSet) throws ArchiverException { + target.addFileSet(fileSet); } @Override - public void addSymlink( String symlinkName, String symlinkDestination ) - throws ArchiverException - { - target.addSymlink( symlinkName, symlinkDestination ); + public void addSymlink(String symlinkName, String symlinkDestination) throws ArchiverException { + target.addSymlink(symlinkName, symlinkDestination); } @Override - public void addSymlink( String symlinkName, int permissions, String symlinkDestination ) - throws ArchiverException - { - target.addSymlink( symlinkName, permissions, symlinkDestination ); + public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException { + target.addSymlink(symlinkName, permissions, symlinkDestination); } @Override - public void addFile( @Nonnull File inputFile, @Nonnull String destFileName ) - throws ArchiverException - { - target.addFile( inputFile, destFileName ); + public void addFile(@Nonnull File inputFile, @Nonnull String destFileName) throws ArchiverException { + target.addFile(inputFile, destFileName); } @Override - public void addFile( @Nonnull File inputFile, @Nonnull String destFileName, int permissions ) - throws ArchiverException - { - target.addFile( inputFile, destFileName, permissions ); + public void addFile(@Nonnull File inputFile, @Nonnull String destFileName, int permissions) + throws ArchiverException { + target.addFile(inputFile, destFileName, permissions); } @Override - public void addArchivedFileSet( @Nonnull File archiveFile ) - throws ArchiverException - { - target.addArchivedFileSet( archiveFile ); + public void addArchivedFileSet(@Nonnull File archiveFile) throws ArchiverException { + target.addArchivedFileSet(archiveFile); } @Deprecated @Override - public void addArchivedFileSet( @Nonnull File archiveFile, String prefix ) - throws ArchiverException - { - target.addArchivedFileSet( archiveFile, prefix ); + public void addArchivedFileSet(@Nonnull File archiveFile, String prefix) throws ArchiverException { + target.addArchivedFileSet(archiveFile, prefix); } @Override - public void addArchivedFileSet( File archiveFile, String[] includes, String[] excludes ) - throws ArchiverException - { - target.addArchivedFileSet( archiveFile, includes, excludes ); + public void addArchivedFileSet(File archiveFile, String[] includes, String[] excludes) throws ArchiverException { + target.addArchivedFileSet(archiveFile, includes, excludes); } @Override - public void addArchivedFileSet( @Nonnull File archiveFile, String prefix, String[] includes, String[] excludes ) - throws ArchiverException - { - target.addArchivedFileSet( archiveFile, prefix, includes, excludes ); + public void addArchivedFileSet(@Nonnull File archiveFile, String prefix, String[] includes, String[] excludes) + throws ArchiverException { + target.addArchivedFileSet(archiveFile, prefix, includes, excludes); } @Override - public void addArchivedFileSet( ArchivedFileSet fileSet ) - throws ArchiverException - { - target.addArchivedFileSet( fileSet ); + public void addArchivedFileSet(ArchivedFileSet fileSet) throws ArchiverException { + target.addArchivedFileSet(fileSet); } @Override - public void addArchivedFileSet( ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { - target.addArchivedFileSet( fileSet, charset ); + public void addArchivedFileSet(ArchivedFileSet fileSet, Charset charset) throws ArchiverException { + target.addArchivedFileSet(fileSet, charset); } @Override - public void addResource( PlexusIoResource resource, String destFileName, int permissions ) - throws ArchiverException - { - target.addResource( resource, destFileName, permissions ); + public void addResource(PlexusIoResource resource, String destFileName, int permissions) throws ArchiverException { + target.addResource(resource, destFileName, permissions); } @Override - public void addResources( PlexusIoResourceCollection resources ) - throws ArchiverException - { - target.addResources( resources ); + public void addResources(PlexusIoResourceCollection resources) throws ArchiverException { + target.addResources(resources); } @Override - public File getDestFile() - { + public File getDestFile() { return target.getDestFile(); } @Override - public void setDestFile( File destFile ) - { - target.setDestFile( destFile ); + public void setDestFile(File destFile) { + target.setDestFile(destFile); } @Override - public void setFileMode( int mode ) - { - target.setFileMode( mode ); + public void setFileMode(int mode) { + target.setFileMode(mode); } @Override - public int getFileMode() - { + public int getFileMode() { return target.getFileMode(); } @Override - public int getOverrideFileMode() - { + public int getOverrideFileMode() { return target.getOverrideFileMode(); } @Override - public void setDefaultFileMode( int mode ) - { - target.setDefaultFileMode( mode ); + public void setDefaultFileMode(int mode) { + target.setDefaultFileMode(mode); } @Override - public int getDefaultFileMode() - { + public int getDefaultFileMode() { return target.getDefaultFileMode(); } @Override - public void setDirectoryMode( int mode ) - { - target.setDirectoryMode( mode ); + public void setDirectoryMode(int mode) { + target.setDirectoryMode(mode); } @Override - public int getDirectoryMode() - { + public int getDirectoryMode() { return target.getDirectoryMode(); } @Override - public int getOverrideDirectoryMode() - { + public int getOverrideDirectoryMode() { return target.getOverrideDirectoryMode(); } @Override - public void setDefaultDirectoryMode( int mode ) - { - target.setDefaultDirectoryMode( mode ); + public void setDefaultDirectoryMode(int mode) { + target.setDefaultDirectoryMode(mode); } @Override - public int getDefaultDirectoryMode() - { + public int getDefaultDirectoryMode() { return target.getDefaultDirectoryMode(); } @Override - public boolean getIncludeEmptyDirs() - { + public boolean getIncludeEmptyDirs() { return target.getIncludeEmptyDirs(); } @Override - public void setIncludeEmptyDirs( boolean includeEmptyDirs ) - { - target.setIncludeEmptyDirs( includeEmptyDirs ); + public void setIncludeEmptyDirs(boolean includeEmptyDirs) { + target.setIncludeEmptyDirs(includeEmptyDirs); } @Override - public void setDotFileDirectory( File dotFileDirectory ) - { - target.setDotFileDirectory( dotFileDirectory ); + public void setDotFileDirectory(File dotFileDirectory) { + target.setDotFileDirectory(dotFileDirectory); } @Nonnull @Override - public ResourceIterator getResources() - throws ArchiverException - { + public ResourceIterator getResources() throws ArchiverException { return target.getResources(); } @Override - public Map getFiles() - { + public Map getFiles() { return target.getFiles(); } @Override - public boolean isForced() - { + public boolean isForced() { return target.isForced(); } @Override - public void setForced( boolean forced ) - { - target.setForced( forced ); + public void setForced(boolean forced) { + target.setForced(forced); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return target.isSupportingForced(); } @Override - public String getDuplicateBehavior() - { + public String getDuplicateBehavior() { return target.getDuplicateBehavior(); } @Override - public void setDuplicateBehavior( String duplicate ) - { - target.setDuplicateBehavior( duplicate ); + public void setDuplicateBehavior(String duplicate) { + target.setDuplicateBehavior(duplicate); } @Override - public void setUseJvmChmod( boolean useJvmChmod ) - { - target.setUseJvmChmod( useJvmChmod ); + public void setUseJvmChmod(boolean useJvmChmod) { + target.setUseJvmChmod(useJvmChmod); } @Override - public boolean isUseJvmChmod() - { + public boolean isUseJvmChmod() { return target.isUseJvmChmod(); } @Override - public boolean isIgnorePermissions() - { + public boolean isIgnorePermissions() { return target.isIgnorePermissions(); } @Override - public void setIgnorePermissions( boolean ignorePermissions ) - { - target.setIgnorePermissions( ignorePermissions ); + public void setIgnorePermissions(boolean ignorePermissions) { + target.setIgnorePermissions(ignorePermissions); } /** @@ -339,9 +276,8 @@ public void setIgnorePermissions( boolean ignorePermissions ) */ @Override @Deprecated - public void setLastModifiedDate( final Date lastModifiedDate ) - { - target.setLastModifiedDate( lastModifiedDate ); + public void setLastModifiedDate(final Date lastModifiedDate) { + target.setLastModifiedDate(lastModifiedDate); } /** @@ -349,86 +285,72 @@ public void setLastModifiedDate( final Date lastModifiedDate ) */ @Override @Deprecated - public Date getLastModifiedDate() - { + public Date getLastModifiedDate() { return target.getLastModifiedDate(); } @Override - public void setLastModifiedTime( final FileTime lastModifiedTime ) - { - target.setLastModifiedTime( lastModifiedTime ); + public void setLastModifiedTime(final FileTime lastModifiedTime) { + target.setLastModifiedTime(lastModifiedTime); } @Override - public FileTime getLastModifiedTime() - { + public FileTime getLastModifiedTime() { return target.getLastModifiedTime(); } @Override - public void setFilenameComparator( final Comparator filenameComparator ) - { - target.setFilenameComparator( filenameComparator ); + public void setFilenameComparator(final Comparator filenameComparator) { + target.setFilenameComparator(filenameComparator); } @Override - public void setOverrideUid( int uid ) - { - target.setOverrideUid( uid ); + public void setOverrideUid(int uid) { + target.setOverrideUid(uid); } @Override - public void setOverrideUserName( String userName ) - { - target.setOverrideUserName( userName ); + public void setOverrideUserName(String userName) { + target.setOverrideUserName(userName); } @Override - public int getOverrideUid() - { + public int getOverrideUid() { return target.getOverrideUid(); } @Override - public String getOverrideUserName() - { + public String getOverrideUserName() { return target.getOverrideUserName(); } @Override - public void setOverrideGid( int gid ) - { - target.setOverrideGid( gid ); + public void setOverrideGid(int gid) { + target.setOverrideGid(gid); } @Override - public void setOverrideGroupName( String groupName ) - { - target.setOverrideGroupName( groupName ); + public void setOverrideGroupName(String groupName) { + target.setOverrideGroupName(groupName); } @Override - public int getOverrideGid() - { + public int getOverrideGid() { return target.getOverrideGid(); } @Override - public String getOverrideGroupName() - { + public String getOverrideGroupName() { return target.getOverrideGroupName(); } @Override - public void setUmask( int umask ) - { - target.setUmask( umask ); + public void setUmask(int umask) { + target.setUmask(umask); } @Override - public int getUmask() - { + public int getUmask() { return target.getUmask(); } @@ -437,15 +359,12 @@ public int getUmask() */ @Override @Deprecated - public void configureReproducible( Date lastModifiedDate ) - { - target.configureReproducible( lastModifiedDate ); + public void configureReproducible(Date lastModifiedDate) { + target.configureReproducible(lastModifiedDate); } @Override - public void configureReproducibleBuild( FileTime lastModifiedTime ) - { - target.configureReproducibleBuild( lastModifiedTime ); + public void configureReproducibleBuild(FileTime lastModifiedTime) { + target.configureReproducibleBuild(lastModifiedTime); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/diags/DryRunArchiver.java b/src/main/java/org/codehaus/plexus/archiver/diags/DryRunArchiver.java index 775885505..bc984eb1d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/diags/DryRunArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/diags/DryRunArchiver.java @@ -18,10 +18,12 @@ */ package org.codehaus.plexus.archiver.diags; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; -import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.ArchivedFileSet; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.ArchiverException; @@ -34,15 +36,12 @@ * A dry run archiver that does nothing. Some methods fall through to the underlying * archiver, but no actions are executed. */ -public class DryRunArchiver - extends DelgatingArchiver -{ +public class DryRunArchiver extends DelgatingArchiver { private final Logger logger; - public DryRunArchiver( final Archiver target, final Logger logger ) - { - super( target ); + public DryRunArchiver(final Archiver target, final Logger logger) { + super(target); this.logger = logger; } @@ -50,17 +49,14 @@ public DryRunArchiver( final Archiver target, final Logger logger ) * {@inheritDoc} */ @Override - public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix, final String[] includes, - final String[] excludes ) - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addArchivedFileSet( + final @Nonnull File archiveFile, final String prefix, final String[] includes, final String[] excludes) { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } - private void debug( final String message ) - { - if ( ( logger != null ) && logger.isDebugEnabled() ) - { - logger.debug( message ); + private void debug(final String message) { + if ((logger != null) && logger.isDebugEnabled()) { + logger.debug(message); } } @@ -68,182 +64,147 @@ private void debug( final String message ) * {@inheritDoc} */ @Override - public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addArchivedFileSet(final @Nonnull File archiveFile, final String prefix) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addArchivedFileSet( final File archiveFile, final String[] includes, final String[] excludes ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addArchivedFileSet(final File archiveFile, final String[] includes, final String[] excludes) + throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addArchivedFileSet( final @Nonnull File archiveFile ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addArchivedFileSet(final @Nonnull File archiveFile) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addDirectory( final @Nonnull File directory, final String prefix, final String[] includes, - final String[] excludes ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); - + public void addDirectory( + final @Nonnull File directory, final String prefix, final String[] includes, final String[] excludes) + throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addSymlink( String symlinkName, String symlinkDestination ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addSymlink(String symlinkName, String symlinkDestination) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addSymlink( String symlinkName, int permissions, String symlinkDestination ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addDirectory( final @Nonnull File directory, final String prefix ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addDirectory(final @Nonnull File directory, final String prefix) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addDirectory( final @Nonnull File directory, final String[] includes, final String[] excludes ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addDirectory(final @Nonnull File directory, final String[] includes, final String[] excludes) + throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addDirectory( final @Nonnull File directory ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addDirectory(final @Nonnull File directory) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName, final int permissions ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addFile(final @Nonnull File inputFile, final @Nonnull String destFileName, final int permissions) + throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addFile(final @Nonnull File inputFile, final @Nonnull String destFileName) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void createArchive() - throws ArchiverException, IOException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void createArchive() throws ArchiverException, IOException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void setDotFileDirectory( final File dotFileDirectory ) - { - throw new UnsupportedOperationException( - "Undocumented feature of plexus-archiver; this is not yet supported." ); + public void setDotFileDirectory(final File dotFileDirectory) { + throw new UnsupportedOperationException("Undocumented feature of plexus-archiver; this is not yet supported."); } /** * {@inheritDoc} */ @Override - public void addArchivedFileSet( final ArchivedFileSet fileSet ) - throws ArchiverException - { + public void addArchivedFileSet(final ArchivedFileSet fileSet) throws ArchiverException { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } @Override - public void addArchivedFileSet( ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addArchivedFileSet(ArchivedFileSet fileSet, Charset charset) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } /** * {@inheritDoc} */ @Override - public void addFileSet( final @Nonnull FileSet fileSet ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addFileSet(final @Nonnull FileSet fileSet) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } @Override - public void addResource( PlexusIoResource resource, String destFileName, int permissions ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addResource(PlexusIoResource resource, String destFileName, int permissions) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } @Override - public void addResources( PlexusIoResourceCollection resources ) - throws ArchiverException - { - debug( "DRY RUN: Skipping delegated call to: " + getMethodName() ); + public void addResources(PlexusIoResourceCollection resources) throws ArchiverException { + debug("DRY RUN: Skipping delegated call to: " + getMethodName()); } - private String getMethodName() - { + private String getMethodName() { final NullPointerException npe = new NullPointerException(); final StackTraceElement[] trace = npe.getStackTrace(); final StackTraceElement methodElement = trace[1]; return methodElement.getMethodName() + " (archiver line: " + methodElement.getLineNumber() + ")"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/diags/NoOpArchiver.java b/src/main/java/org/codehaus/plexus/archiver/diags/NoOpArchiver.java index 9a9344032..2c024ae07 100644 --- a/src/main/java/org/codehaus/plexus/archiver/diags/NoOpArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/diags/NoOpArchiver.java @@ -15,6 +15,8 @@ */ package org.codehaus.plexus.archiver.diags; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.nio.charset.Charset; @@ -23,7 +25,7 @@ import java.util.Comparator; import java.util.Date; import java.util.Map; -import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchivedFileSet; import org.codehaus.plexus.archiver.Archiver; @@ -36,316 +38,196 @@ /** * An archiver that does nothing. Really. */ -@SuppressWarnings( "UnusedDeclaration" ) -public class NoOpArchiver implements Archiver -{ +@SuppressWarnings("UnusedDeclaration") +public class NoOpArchiver implements Archiver { boolean useJvmChmod; private boolean ignorePermissions; @Override - public void createArchive() - throws ArchiverException, IOException - { - - } + public void createArchive() throws ArchiverException, IOException {} @Override - public void addDirectory( @Nonnull File directory ) - throws ArchiverException - { - - } + public void addDirectory(@Nonnull File directory) throws ArchiverException {} @Override - public void addDirectory( @Nonnull File directory, String prefix ) - throws ArchiverException - { - - } + public void addDirectory(@Nonnull File directory, String prefix) throws ArchiverException {} @Override - public void addDirectory( @Nonnull File directory, String[] includes, String[] excludes ) - throws ArchiverException - { - - } + public void addDirectory(@Nonnull File directory, String[] includes, String[] excludes) throws ArchiverException {} @Override - public void addDirectory( @Nonnull File directory, String prefix, String[] includes, String[] excludes ) - throws ArchiverException - { - - } + public void addDirectory(@Nonnull File directory, String prefix, String[] includes, String[] excludes) + throws ArchiverException {} @Override - public void addFileSet( @Nonnull FileSet fileSet ) - throws ArchiverException - { - - } + public void addFileSet(@Nonnull FileSet fileSet) throws ArchiverException {} @Override - public void addSymlink( String symlinkName, String symlinkDestination ) - throws ArchiverException - { - - } + public void addSymlink(String symlinkName, String symlinkDestination) throws ArchiverException {} @Override - public void addSymlink( String symlinkName, int permissions, String symlinkDestination ) - throws ArchiverException - { - - } + public void addSymlink(String symlinkName, int permissions, String symlinkDestination) throws ArchiverException {} @Override - public void addFile( @Nonnull File inputFile, @Nonnull String destFileName ) - throws ArchiverException - { - - } + public void addFile(@Nonnull File inputFile, @Nonnull String destFileName) throws ArchiverException {} @Override - public void addFile( @Nonnull File inputFile, @Nonnull String destFileName, int permissions ) - throws ArchiverException - { - - } + public void addFile(@Nonnull File inputFile, @Nonnull String destFileName, int permissions) + throws ArchiverException {} @Override - public void addArchivedFileSet( @Nonnull File archiveFile ) - throws ArchiverException - { - - } + public void addArchivedFileSet(@Nonnull File archiveFile) throws ArchiverException {} @Override - public void addArchivedFileSet( @Nonnull File archiveFile, String prefix ) - throws ArchiverException - { - - } + public void addArchivedFileSet(@Nonnull File archiveFile, String prefix) throws ArchiverException {} @Override - public void addArchivedFileSet( File archiveFile, String[] includes, String[] excludes ) - throws ArchiverException - { - - } + public void addArchivedFileSet(File archiveFile, String[] includes, String[] excludes) throws ArchiverException {} @Override - public void addArchivedFileSet( @Nonnull File archiveFile, String prefix, String[] includes, String[] excludes ) - throws ArchiverException - { - - } + public void addArchivedFileSet(@Nonnull File archiveFile, String prefix, String[] includes, String[] excludes) + throws ArchiverException {} @Override - public void addArchivedFileSet( ArchivedFileSet fileSet ) - throws ArchiverException - { - - } + public void addArchivedFileSet(ArchivedFileSet fileSet) throws ArchiverException {} @Override - public void addArchivedFileSet( ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { - - } + public void addArchivedFileSet(ArchivedFileSet fileSet, Charset charset) throws ArchiverException {} @Override - public void addResource( PlexusIoResource resource, String destFileName, int permissions ) - throws ArchiverException - { - - } + public void addResource(PlexusIoResource resource, String destFileName, int permissions) throws ArchiverException {} @Override - public void addResources( PlexusIoResourceCollection resources ) - throws ArchiverException - { - - } + public void addResources(PlexusIoResourceCollection resources) throws ArchiverException {} @Override - public File getDestFile() - { + public File getDestFile() { return null; } @Override - public void setDestFile( File destFile ) - { - - } + public void setDestFile(File destFile) {} @Override - public void setFileMode( int mode ) - { - - } + public void setFileMode(int mode) {} @Override - public int getFileMode() - { + public int getFileMode() { return 0; } @Override - public int getOverrideFileMode() - { + public int getOverrideFileMode() { return 0; } @Override - public void setDefaultFileMode( int mode ) - { - - } + public void setDefaultFileMode(int mode) {} @Override - public int getDefaultFileMode() - { + public int getDefaultFileMode() { return 0; } @Override - public void setDirectoryMode( int mode ) - { - - } + public void setDirectoryMode(int mode) {} @Override - public int getDirectoryMode() - { + public int getDirectoryMode() { return 0; } @Override - public int getOverrideDirectoryMode() - { + public int getOverrideDirectoryMode() { return 0; } @Override - public void setDefaultDirectoryMode( int mode ) - { - - } + public void setDefaultDirectoryMode(int mode) {} @Override - public int getDefaultDirectoryMode() - { + public int getDefaultDirectoryMode() { return 0; } @Override - public boolean getIncludeEmptyDirs() - { + public boolean getIncludeEmptyDirs() { return false; } @Override - public void setIncludeEmptyDirs( boolean includeEmptyDirs ) - { - - } + public void setIncludeEmptyDirs(boolean includeEmptyDirs) {} @Override - public void setDotFileDirectory( File dotFileDirectory ) - { - - } + public void setDotFileDirectory(File dotFileDirectory) {} @Nonnull @Override - public ResourceIterator getResources() - throws ArchiverException - { - return new ResourceIterator() - { + public ResourceIterator getResources() throws ArchiverException { + return new ResourceIterator() { @Override - public boolean hasNext() - { + public boolean hasNext() { return false; } @Override - public ArchiveEntry next() - { + public ArchiveEntry next() { return null; } @Override - public void remove() - { - throw new UnsupportedOperationException( "remove" ); + public void remove() { + throw new UnsupportedOperationException("remove"); } - }; } @Override - public Map getFiles() - { + public Map getFiles() { return Collections.emptyMap(); } @Override - public boolean isForced() - { + public boolean isForced() { return false; } @Override - public void setForced( boolean forced ) - { - - } + public void setForced(boolean forced) {} @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return false; } @Override - public String getDuplicateBehavior() - { + public String getDuplicateBehavior() { return null; } @Override - public void setDuplicateBehavior( String duplicate ) - { - - } + public void setDuplicateBehavior(String duplicate) {} @Override - public void setUseJvmChmod( boolean useJvmChmod ) - { + public void setUseJvmChmod(boolean useJvmChmod) { this.useJvmChmod = useJvmChmod; } @Override - public boolean isUseJvmChmod() - { + public boolean isUseJvmChmod() { return useJvmChmod; } @Override - public boolean isIgnorePermissions() - { + public boolean isIgnorePermissions() { return ignorePermissions; } @Override - public void setIgnorePermissions( boolean ignorePermissions ) - { + public void setIgnorePermissions(boolean ignorePermissions) { this.ignorePermissions = ignorePermissions; } @@ -354,96 +236,65 @@ public void setIgnorePermissions( boolean ignorePermissions ) */ @Override @Deprecated - public void setLastModifiedDate( final Date lastModifiedDate ) - { - - } + public void setLastModifiedDate(final Date lastModifiedDate) {} /** * @deprecated Use {@link #getLastModifiedTime()} instead. */ @Override @Deprecated - public Date getLastModifiedDate() - { + public Date getLastModifiedDate() { return null; } @Override - public void setLastModifiedTime( final FileTime lastModifiedTime ) - { - - } + public void setLastModifiedTime(final FileTime lastModifiedTime) {} @Override - public FileTime getLastModifiedTime() - { + public FileTime getLastModifiedTime() { return null; } @Override - public void setFilenameComparator( final Comparator filenameComparator ) - { - - } + public void setFilenameComparator(final Comparator filenameComparator) {} @Override - public void setOverrideUid( int uid ) - { - - } + public void setOverrideUid(int uid) {} @Override - public void setOverrideUserName( String userName ) - { - - } + public void setOverrideUserName(String userName) {} @Override - public int getOverrideUid() - { + public int getOverrideUid() { return 0; } @Override - public String getOverrideUserName() - { + public String getOverrideUserName() { return null; } @Override - public void setOverrideGid( int gid ) - { - - } + public void setOverrideGid(int gid) {} @Override - public void setOverrideGroupName( String groupName ) - { - - } + public void setOverrideGroupName(String groupName) {} @Override - public int getOverrideGid() - { + public int getOverrideGid() { return 0; } @Override - public String getOverrideGroupName() - { + public String getOverrideGroupName() { return null; } @Override - public void setUmask( int umask ) - { - - } + public void setUmask(int umask) {} @Override - public int getUmask() - { + public int getUmask() { return 0; } @@ -452,15 +303,8 @@ public int getUmask() */ @Override @Deprecated - public void configureReproducible( Date lastModifiedDate ) - { - - } + public void configureReproducible(Date lastModifiedDate) {} @Override - public void configureReproducibleBuild( FileTime lastModifiedTime ) - { - - } - + public void configureReproducibleBuild(FileTime lastModifiedTime) {} } diff --git a/src/main/java/org/codehaus/plexus/archiver/diags/TrackingArchiver.java b/src/main/java/org/codehaus/plexus/archiver/diags/TrackingArchiver.java index d2a9159e6..4d951de1a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/diags/TrackingArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/diags/TrackingArchiver.java @@ -45,9 +45,7 @@ /** * A diagnostic archiver that keeps track of stuff that has been added. */ -public class TrackingArchiver - implements Archiver -{ +public class TrackingArchiver implements Archiver { private File destFile; @@ -62,267 +60,195 @@ public class TrackingArchiver private Comparator filenameComparator; @Override - public void createArchive() - throws ArchiverException, IOException - { - } + public void createArchive() throws ArchiverException, IOException {} @Override - public void addDirectory( final @Nonnull File directory ) - throws ArchiverException - { - added.add( new Addition( directory, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addDirectory(final @Nonnull File directory) throws ArchiverException { + added.add(new Addition(directory, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addDirectory( final @Nonnull File directory, final String prefix ) - throws ArchiverException - { - added.add( new Addition( directory, prefix, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addDirectory(final @Nonnull File directory, final String prefix) throws ArchiverException { + added.add(new Addition(directory, prefix, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addDirectory( final @Nonnull File directory, final String[] includes, final String[] excludes ) - throws ArchiverException - { - added.add( new Addition( directory, null, includes, excludes, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addDirectory(final @Nonnull File directory, final String[] includes, final String[] excludes) + throws ArchiverException { + added.add(new Addition(directory, null, includes, excludes, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addDirectory( final @Nonnull File directory, final String prefix, final String[] includes, - final String[] excludes ) - throws ArchiverException - { - added.add( new Addition( directory, prefix, includes, excludes, - PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); - + public void addDirectory( + final @Nonnull File directory, final String prefix, final String[] includes, final String[] excludes) + throws ArchiverException { + added.add(new Addition(directory, prefix, includes, excludes, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addFileSet( final @Nonnull FileSet fileSet ) - throws ArchiverException - { - added.add( new Addition( fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addFileSet(final @Nonnull FileSet fileSet) throws ArchiverException { + added.add(new Addition(fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName ) - throws ArchiverException - { - added.add( new Addition( inputFile, destFileName, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addFile(final @Nonnull File inputFile, final @Nonnull String destFileName) throws ArchiverException { + added.add(new Addition(inputFile, destFileName, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addFile( final @Nonnull File inputFile, final @Nonnull String destFileName, final int permissions ) - throws ArchiverException - { - added.add( new Addition( inputFile, destFileName, null, null, permissions ) ); + public void addFile(final @Nonnull File inputFile, final @Nonnull String destFileName, final int permissions) + throws ArchiverException { + added.add(new Addition(inputFile, destFileName, null, null, permissions)); } @Override - public void addArchivedFileSet( final @Nonnull File archiveFile ) - throws ArchiverException - { - added.add( new Addition( archiveFile, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addArchivedFileSet(final @Nonnull File archiveFile) throws ArchiverException { + added.add(new Addition(archiveFile, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix ) - throws ArchiverException - { - added.add( new Addition( archiveFile, prefix, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addArchivedFileSet(final @Nonnull File archiveFile, final String prefix) throws ArchiverException { + added.add(new Addition(archiveFile, prefix, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addSymlink( String s, String s2 ) - throws ArchiverException - { - added.add( new Addition( s, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addSymlink(String s, String s2) throws ArchiverException { + added.add(new Addition(s, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addSymlink( String s, int i, String s2 ) - throws ArchiverException - { - added.add( new Addition( s, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); - + public void addSymlink(String s, int i, String s2) throws ArchiverException { + added.add(new Addition(s, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addArchivedFileSet( final File archiveFile, final String[] includes, final String[] excludes ) - throws ArchiverException - { - added.add( new Addition( archiveFile, null, includes, excludes, - PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); - + public void addArchivedFileSet(final File archiveFile, final String[] includes, final String[] excludes) + throws ArchiverException { + added.add(new Addition(archiveFile, null, includes, excludes, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addArchivedFileSet( final @Nonnull File archiveFile, final String prefix, final String[] includes, - final String[] excludes ) - throws ArchiverException - { - added.add( new Addition( archiveFile, prefix, includes, excludes, - PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); - + public void addArchivedFileSet( + final @Nonnull File archiveFile, final String prefix, final String[] includes, final String[] excludes) + throws ArchiverException { + added.add(new Addition(archiveFile, prefix, includes, excludes, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addArchivedFileSet( final ArchivedFileSet fileSet ) - throws ArchiverException - { - added.add( new Addition( fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addArchivedFileSet(final ArchivedFileSet fileSet) throws ArchiverException { + added.add(new Addition(fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addArchivedFileSet( final ArchivedFileSet fileSet, Charset charset ) - throws ArchiverException - { - added.add( new Addition( fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addArchivedFileSet(final ArchivedFileSet fileSet, Charset charset) throws ArchiverException { + added.add(new Addition(fileSet, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public void addResource( final PlexusIoResource resource, final String destFileName, final int permissions ) - throws ArchiverException - { - added.add( new Addition( resource, destFileName, null, null, permissions ) ); + public void addResource(final PlexusIoResource resource, final String destFileName, final int permissions) + throws ArchiverException { + added.add(new Addition(resource, destFileName, null, null, permissions)); } @Override - public void addResources( final PlexusIoResourceCollection resources ) - throws ArchiverException - { - added.add( new Addition( resources, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE ) ); + public void addResources(final PlexusIoResourceCollection resources) throws ArchiverException { + added.add(new Addition(resources, null, null, null, PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE)); } @Override - public File getDestFile() - { + public File getDestFile() { return destFile; } @Override - public void setDestFile( final File destFile ) - { + public void setDestFile(final File destFile) { this.destFile = destFile; } @Override - public void setFileMode( final int mode ) - { - } + public void setFileMode(final int mode) {} @Override - public int getFileMode() - { - return Integer.parseInt( "0644", 8 ); + public int getFileMode() { + return Integer.parseInt("0644", 8); } @Override - public int getOverrideFileMode() - { - return Integer.parseInt( "0644", 8 ); + public int getOverrideFileMode() { + return Integer.parseInt("0644", 8); } @Override - public void setDefaultFileMode( final int mode ) - { - } + public void setDefaultFileMode(final int mode) {} @Override - public int getDefaultFileMode() - { - return Integer.parseInt( "0644", 8 ); + public int getDefaultFileMode() { + return Integer.parseInt("0644", 8); } @Override - public void setDirectoryMode( final int mode ) - { - } + public void setDirectoryMode(final int mode) {} @Override - public int getDirectoryMode() - { - return Integer.parseInt( "0755", 8 ); + public int getDirectoryMode() { + return Integer.parseInt("0755", 8); } @Override - public int getOverrideDirectoryMode() - { - return Integer.parseInt( "0755", 8 ); + public int getOverrideDirectoryMode() { + return Integer.parseInt("0755", 8); } @Override - public void setDefaultDirectoryMode( final int mode ) - { - } + public void setDefaultDirectoryMode(final int mode) {} @Override - public int getDefaultDirectoryMode() - { - return Integer.parseInt( "0755", 8 ); + public int getDefaultDirectoryMode() { + return Integer.parseInt("0755", 8); } @Override - public boolean getIncludeEmptyDirs() - { + public boolean getIncludeEmptyDirs() { return false; } @Override - public void setIncludeEmptyDirs( final boolean includeEmptyDirs ) - { - } + public void setIncludeEmptyDirs(final boolean includeEmptyDirs) {} @Override - public void setDotFileDirectory( final File dotFileDirectory ) - { - } + public void setDotFileDirectory(final File dotFileDirectory) {} - public @Nonnull - @Override - ResourceIterator getResources() - throws ArchiverException - { - throw new RuntimeException( "Not implemented" ); + public @Nonnull @Override ResourceIterator getResources() throws ArchiverException { + throw new RuntimeException("Not implemented"); } @Override - public Map getFiles() - { + public Map getFiles() { return new HashMap<>(); } @Override - public boolean isForced() - { + public boolean isForced() { return false; } @Override - public void setForced( final boolean forced ) - { - } + public void setForced(final boolean forced) {} @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - public String getDuplicateBehavior() - { + public String getDuplicateBehavior() { return null; } @Override - public void setDuplicateBehavior( final String duplicate ) - { - } + public void setDuplicateBehavior(final String duplicate) {} - public class Addition - { + public class Addition { /** * {@inheritDoc} @@ -330,14 +256,12 @@ public class Addition * @see Object#toString() */ @Override - public String toString() - { + public String toString() { return "Addition (\n resource= " + resource + "\n directory= " + directory + "\n destination= " - + destination + "\n permissions= " + permissions + "\n includes= " - + ( includes == null ? "-none-" : StringUtils.join( includes, ", " ) ) - + "\n excludes= " - + ( excludes == null ? "-none-" : StringUtils.join( excludes, ", " ) ) + "\n)"; - + + destination + "\n permissions= " + permissions + "\n includes= " + + (includes == null ? "-none-" : StringUtils.join(includes, ", ")) + + "\n excludes= " + + (excludes == null ? "-none-" : StringUtils.join(excludes, ", ")) + "\n)"; } public final Object resource; @@ -352,27 +276,24 @@ public String toString() public final String[] excludes; - public Addition( final Object resource, final String destination, final String[] includes, - final String[] excludes, final int permissions ) - { + public Addition( + final Object resource, + final String destination, + final String[] includes, + final String[] excludes, + final int permissions) { this.resource = resource; - if ( resource instanceof FileSet ) - { + if (resource instanceof FileSet) { final FileSet fs = (FileSet) resource; directory = fs.getDirectory(); this.destination = fs.getPrefix(); this.includes = fs.getIncludes(); this.excludes = fs.getExcludes(); this.permissions = permissions; - } - else - { - if ( resource instanceof File && ( (File) resource ).isDirectory() ) - { + } else { + if (resource instanceof File && ((File) resource).isDirectory()) { directory = (File) resource; - } - else - { + } else { directory = null; } @@ -382,30 +303,25 @@ public Addition( final Object resource, final String destination, final String[] this.permissions = permissions; } } - } @Override - public boolean isUseJvmChmod() - { + public boolean isUseJvmChmod() { return useJvmChmod; } @Override - public void setUseJvmChmod( final boolean useJvmChmod ) - { + public void setUseJvmChmod(final boolean useJvmChmod) { this.useJvmChmod = useJvmChmod; } @Override - public boolean isIgnorePermissions() - { + public boolean isIgnorePermissions() { return ignorePermissions; } @Override - public void setIgnorePermissions( final boolean ignorePermissions ) - { + public void setIgnorePermissions(final boolean ignorePermissions) { this.ignorePermissions = ignorePermissions; } @@ -414,9 +330,8 @@ public void setIgnorePermissions( final boolean ignorePermissions ) */ @Override @Deprecated - public void setLastModifiedDate( final Date lastModifiedDate ) - { - this.lastModifiedTime = lastModifiedDate != null ? FileTime.fromMillis( lastModifiedDate.getTime() ) : null; + public void setLastModifiedDate(final Date lastModifiedDate) { + this.lastModifiedTime = lastModifiedDate != null ? FileTime.fromMillis(lastModifiedDate.getTime()) : null; } /** @@ -424,87 +339,66 @@ public void setLastModifiedDate( final Date lastModifiedDate ) */ @Override @Deprecated - public Date getLastModifiedDate() - { - return lastModifiedTime != null ? new Date( lastModifiedTime.toMillis() ) : null; + public Date getLastModifiedDate() { + return lastModifiedTime != null ? new Date(lastModifiedTime.toMillis()) : null; } @Override - public void setLastModifiedTime( final FileTime lastModifiedTime ) - { + public void setLastModifiedTime(final FileTime lastModifiedTime) { this.lastModifiedTime = lastModifiedTime; } @Override - public FileTime getLastModifiedTime() - { + public FileTime getLastModifiedTime() { return lastModifiedTime; } @Override - public void setFilenameComparator( final Comparator filenameComparator ) - { + public void setFilenameComparator(final Comparator filenameComparator) { this.filenameComparator = filenameComparator; } - public Comparator getFilenameComparator() - { + public Comparator getFilenameComparator() { return filenameComparator; } @Override - public void setOverrideUid( int uid ) - { - } + public void setOverrideUid(int uid) {} @Override - public void setOverrideUserName( String userName ) - { - } + public void setOverrideUserName(String userName) {} @Override - public int getOverrideUid() - { + public int getOverrideUid() { return 0; } @Override - public String getOverrideUserName() - { + public String getOverrideUserName() { return null; } @Override - public void setOverrideGid( int gid ) - { - } + public void setOverrideGid(int gid) {} @Override - public void setOverrideGroupName( String groupName ) - { - } + public void setOverrideGroupName(String groupName) {} @Override - public int getOverrideGid() - { + public int getOverrideGid() { return 0; } @Override - public String getOverrideGroupName() - { + public String getOverrideGroupName() { return null; } - @Override - public void setUmask( int umask ) - { - } + public void setUmask(int umask) {} @Override - public int getUmask() - { + public int getUmask() { return 0; } @@ -513,12 +407,8 @@ public int getUmask() */ @Override @Deprecated - public void configureReproducible( Date lastModifiedDate ) - { - } + public void configureReproducible(Date lastModifiedDate) {} @Override - public void configureReproducibleBuild( FileTime lastModifiedTime ) - { - } + public void configureReproducibleBuild(FileTime lastModifiedTime) {} } diff --git a/src/main/java/org/codehaus/plexus/archiver/dir/DirectoryArchiver.java b/src/main/java/org/codehaus/plexus/archiver/dir/DirectoryArchiver.java index 559272875..0b38f966a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/dir/DirectoryArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/dir/DirectoryArchiver.java @@ -23,6 +23,7 @@ import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.List; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; @@ -37,82 +38,64 @@ /** * A plexus archiver implementation that stores the files to archive in a directory. */ -@Named( "dir" ) -public class DirectoryArchiver - extends AbstractArchiver -{ +@Named("dir") +public class DirectoryArchiver extends AbstractArchiver { private final List directoryChmods = new ArrayList<>(); - public void resetArchiver() - throws IOException - { + public void resetArchiver() throws IOException { cleanUp(); } @Override - public void execute() - throws ArchiverException, IOException - { + public void execute() throws ArchiverException, IOException { // Most of this method was copied from org.codehaus.plexus.archiver.tar.TarArchiver // and modified to store files in a directory, not a tar archive. final ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } final File destDirectory = getDestFile(); - if ( destDirectory == null ) - { - throw new ArchiverException( "You must set the destination directory." ); + if (destDirectory == null) { + throw new ArchiverException("You must set the destination directory."); } - if ( destDirectory.exists() && !destDirectory.isDirectory() ) - { - throw new ArchiverException( destDirectory + " is not a directory." ); + if (destDirectory.exists() && !destDirectory.isDirectory()) { + throw new ArchiverException(destDirectory + " is not a directory."); } - if ( destDirectory.exists() && !destDirectory.canWrite() ) - { - throw new ArchiverException( destDirectory + " is not writable." ); + if (destDirectory.exists() && !destDirectory.canWrite()) { + throw new ArchiverException(destDirectory + " is not writable."); } - getLogger().info( "Copying files to " + destDirectory.getAbsolutePath() ); + getLogger().info("Copying files to " + destDirectory.getAbsolutePath()); - try - { - while ( iter.hasNext() ) - { + try { + while (iter.hasNext()) { final ArchiveEntry f = iter.next(); // Check if we don't add directory file in itself - if ( ResourceUtils.isSame( f.getResource(), destDirectory ) ) - { - throw new ArchiverException( "The destination directory cannot include itself." ); + if (ResourceUtils.isSame(f.getResource(), destDirectory)) { + throw new ArchiverException("The destination directory cannot include itself."); } String fileName = f.getName(); final String destDir = destDirectory.getCanonicalPath(); fileName = destDir + File.separator + fileName; PlexusIoResource resource = f.getResource(); - if ( resource instanceof SymlinkDestinationSupplier ) - { - String dest = ( (SymlinkDestinationSupplier) resource ).getSymlinkDestination(); - File target = new File( dest ); - File symlink = new File( fileName ); - makeParentDirectories( symlink ); - SymlinkUtils.createSymbolicLink( symlink, target ); - } - else - { - copyFile( f, fileName ); + if (resource instanceof SymlinkDestinationSupplier) { + String dest = ((SymlinkDestinationSupplier) resource).getSymlinkDestination(); + File target = new File(dest); + File symlink = new File(fileName); + makeParentDirectories(symlink); + SymlinkUtils.createSymbolicLink(symlink, target); + } else { + copyFile(f, fileName); } } - directoryChmods.forEach( Runnable::run ); + directoryChmods.forEach(Runnable::run); directoryChmods.clear(); - } - catch ( final IOException ioe ) - { + } catch (final IOException ioe) { final String message = "Problem copying files : " + ioe.getMessage(); - throw new ArchiverException( message, ioe ); + throw new ArchiverException(message, ioe); } } @@ -125,116 +108,87 @@ public void execute() * @throws ArchiverException If there is a problem creating the directory structure * @throws IOException If there is a problem copying the file */ - protected void copyFile( final ArchiveEntry entry, final String vPath ) - throws ArchiverException, IOException - { + protected void copyFile(final ArchiveEntry entry, final String vPath) throws ArchiverException, IOException { // don't add "" to the archive - if ( vPath.length() <= 0 ) - { + if (vPath.length() <= 0) { return; } final PlexusIoResource in = entry.getResource(); - final File outFile = new File( vPath ); + final File outFile = new File(vPath); final long inLastModified = in.getLastModified(); final long outLastModified = outFile.lastModified(); - if ( ResourceUtils.isUptodate( inLastModified, outLastModified ) ) - { + if (ResourceUtils.isUptodate(inLastModified, outLastModified)) { return; } - if ( !in.isDirectory() ) - { - makeParentDirectories( outFile ); - ResourceUtils.copyFile( entry.getInputStream(), outFile ); + if (!in.isDirectory()) { + makeParentDirectories(outFile); + ResourceUtils.copyFile(entry.getInputStream(), outFile); - setFileModes( entry, outFile, inLastModified ); - } - else - { // file is a directory - if ( outFile.exists() ) - { - if ( !outFile.isDirectory() ) - { + setFileModes(entry, outFile, inLastModified); + } else { // file is a directory + if (outFile.exists()) { + if (!outFile.isDirectory()) { // should we just delete the file and replace it with a directory? // throw an exception, let the user delete the file manually. - throw new ArchiverException( - "Expected directory and found file at copy destination of " + in.getName() + " to " + outFile ); + throw new ArchiverException("Expected directory and found file at copy destination of " + + in.getName() + " to " + outFile); } - } - else if ( !outFile.mkdirs() ) - { + } else if (!outFile.mkdirs()) { // Failure, unable to create specified directory for some unknown reason. - throw new ArchiverException( "Unable to create directory or parent directory of " + outFile ); + throw new ArchiverException("Unable to create directory or parent directory of " + outFile); } - directoryChmods.add( () -> { - try - { - setFileModes( entry, outFile, inLastModified ); + directoryChmods.add(() -> { + try { + setFileModes(entry, outFile, inLastModified); + } catch (IOException e) { + throw new ArchiverException("Failed setting file attributes", e); } - catch ( IOException e ) - { - throw new ArchiverException( "Failed setting file attributes", e ); - } - } ); + }); } - } - private static void makeParentDirectories( File file ) { - if ( !file.getParentFile().exists() ) - { + private static void makeParentDirectories(File file) { + if (!file.getParentFile().exists()) { // create the parent directory... - if ( !file.getParentFile().mkdirs() ) - { + if (!file.getParentFile().mkdirs()) { // Failure, unable to create specified directory for some unknown reason. - throw new ArchiverException( "Unable to create directory or parent directory of " + file ); + throw new ArchiverException("Unable to create directory or parent directory of " + file); } } } - private void setFileModes( ArchiveEntry entry, File outFile, long inLastModified ) - throws IOException - { - if ( !isIgnorePermissions() ) - { - ArchiveEntryUtils.chmod( outFile, entry.getMode() ); + private void setFileModes(ArchiveEntry entry, File outFile, long inLastModified) throws IOException { + if (!isIgnorePermissions()) { + ArchiveEntryUtils.chmod(outFile, entry.getMode()); } - if ( getLastModifiedTime() == null ) - { - FileTime fromMillis = FileTime.fromMillis( inLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE + if (getLastModifiedTime() == null) { + FileTime fromMillis = FileTime.fromMillis( + inLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ? System.currentTimeMillis() - : inLastModified ); - Files.setLastModifiedTime( outFile.toPath(), fromMillis ); - } - else - { - Files.setLastModifiedTime( outFile.toPath(), getLastModifiedTime() ); + : inLastModified); + Files.setLastModifiedTime(outFile.toPath(), fromMillis); + } else { + Files.setLastModifiedTime(outFile.toPath(), getLastModifiedTime()); } } @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { super.cleanUp(); - setIncludeEmptyDirs( false ); - setIncludeEmptyDirs( true ); + setIncludeEmptyDirs(false); + setIncludeEmptyDirs(true); } @Override - protected void close() - throws IOException - { - } + protected void close() throws IOException {} @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "directory"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ear/EarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/ear/EarArchiver.java index 2b2d5fadc..d71826c85 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ear/EarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/ear/EarArchiver.java @@ -20,6 +20,7 @@ import java.io.File; import java.io.IOException; + import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.jar.JarArchiver; @@ -29,10 +30,8 @@ /** * Creates a EAR archive. Based on WAR task */ -@Named( "ear" ) -public class EarArchiver - extends JarArchiver -{ +@Named("ear") +public class EarArchiver extends JarArchiver { private File deploymentDescriptor; @@ -41,8 +40,7 @@ public class EarArchiver /** * Create an Ear. */ - public EarArchiver() - { + public EarArchiver() { super(); archiveType = "ear"; } @@ -50,84 +48,63 @@ public EarArchiver() /** * File to incorporate as application.xml. */ - public void setAppxml( File descr ) - throws ArchiverException - { + public void setAppxml(File descr) throws ArchiverException { deploymentDescriptor = descr; - if ( !deploymentDescriptor.exists() ) - { - throw new ArchiverException( "Deployment descriptor: " + deploymentDescriptor + " does not exist." ); + if (!deploymentDescriptor.exists()) { + throw new ArchiverException("Deployment descriptor: " + deploymentDescriptor + " does not exist."); } - addFile( descr, "META-INF/application.xml" ); + addFile(descr, "META-INF/application.xml"); } /** * Adds archive. */ - public void addArchive( File fileName ) - throws ArchiverException - { - addDirectory( fileName.getParentFile(), "/", - new String[] - { - fileName.getName() - }, null ); - + public void addArchive(File fileName) throws ArchiverException { + addDirectory(fileName.getParentFile(), "/", new String[] {fileName.getName()}, null); } /** * Adds archives. */ - public void addArchives( File directoryName, String[] includes, String[] excludes ) - throws ArchiverException - { - addDirectory( directoryName, "/", includes, excludes ); + public void addArchives(File directoryName, String[] includes, String[] excludes) throws ArchiverException { + addDirectory(directoryName, "/", includes, excludes); } @Override - protected void initZipOutputStream( ConcurrentJarCreator zOut ) - throws ArchiverException, IOException - { + protected void initZipOutputStream(ConcurrentJarCreator zOut) throws ArchiverException, IOException { // If no webxml file is specified, it's an error. - if ( deploymentDescriptor == null && !isInUpdateMode() ) - { - throw new ArchiverException( "appxml attribute is required" ); + if (deploymentDescriptor == null && !isInUpdateMode()) { + throw new ArchiverException("appxml attribute is required"); } - super.initZipOutputStream( zOut ); + super.initZipOutputStream(zOut); } /** * Overridden from ZipArchiver class to deal with application.xml */ - protected void zipFile( ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath, int mode ) - throws IOException, ArchiverException - { + protected void zipFile(ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath, int mode) + throws IOException, ArchiverException { // If the file being added is META-INF/application.xml, we // warn if it's not the one specified in the "appxml" // attribute - or if it's being added twice, meaning the same // file is specified by the "appxml" attribute and in a // element. - if ( vPath.equalsIgnoreCase( "META-INF/application.xml" ) ) - { - if ( deploymentDescriptor == null - || !ResourceUtils.isCanonicalizedSame( entry.getResource(), deploymentDescriptor ) - || descriptorAdded ) - { - getLogger().warn( "Warning: selected " + archiveType - + " files include a META-INF/application.xml which will be ignored " - + "(please use appxml attribute to " + archiveType + " task)" ); - } - else - { - super.zipFile( entry, zOut, vPath ); + if (vPath.equalsIgnoreCase("META-INF/application.xml")) { + if (deploymentDescriptor == null + || !ResourceUtils.isCanonicalizedSame(entry.getResource(), deploymentDescriptor) + || descriptorAdded) { + getLogger() + .warn("Warning: selected " + archiveType + + " files include a META-INF/application.xml which will be ignored " + + "(please use appxml attribute to " + archiveType + " task)"); + } else { + super.zipFile(entry, zOut, vPath); descriptorAdded = true; } - } - else - { - super.zipFile( entry, zOut, vPath ); + } else { + super.zipFile(entry, zOut, vPath); } } @@ -136,11 +113,8 @@ protected void zipFile( ArchiveEntry entry, ConcurrentJarCreator zOut, String vP * time this task gets executed. */ @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { descriptorAdded = false; super.cleanUp(); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ear/EarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/ear/EarUnArchiver.java index a61003ac2..351cab3c9 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ear/EarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/ear/EarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "ear" ) -public class EarUnArchiver - extends ZipUnArchiver -{ +@Named("ear") +public class EarUnArchiver extends ZipUnArchiver { - public EarUnArchiver() - { - } + public EarUnArchiver() {} - public EarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public EarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/ear/PlexusIoEarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/ear/PlexusIoEarFileResourceCollection.java index bd0b7b4fc..a00ccaae7 100644 --- a/src/main/java/org/codehaus/plexus/archiver/ear/PlexusIoEarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/ear/PlexusIoEarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "ear" ) -public class PlexusIoEarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("ear") +public class PlexusIoEarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/esb/EsbUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/esb/EsbUnArchiver.java index e953c7557..9a062d99d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/esb/EsbUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/esb/EsbUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "esb" ) -public class EsbUnArchiver - extends ZipUnArchiver -{ +@Named("esb") +public class EsbUnArchiver extends ZipUnArchiver { - public EsbUnArchiver() - { - } + public EsbUnArchiver() {} - public EsbUnArchiver( File sourceFile ) - { - super( sourceFile ); + public EsbUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/esb/PlexusIoEsbFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/esb/PlexusIoEsbFileResourceCollection.java index c502a75ff..315cdd4be 100644 --- a/src/main/java/org/codehaus/plexus/archiver/esb/PlexusIoEsbFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/esb/PlexusIoEsbFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "esb" ) -public class PlexusIoEsbFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("esb") +public class PlexusIoEsbFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/exceptions/EmptyArchiveException.java b/src/main/java/org/codehaus/plexus/archiver/exceptions/EmptyArchiveException.java index c013844f7..66fe1fd80 100644 --- a/src/main/java/org/codehaus/plexus/archiver/exceptions/EmptyArchiveException.java +++ b/src/main/java/org/codehaus/plexus/archiver/exceptions/EmptyArchiveException.java @@ -17,18 +17,13 @@ import org.codehaus.plexus.archiver.ArchiverException; -public class EmptyArchiveException - extends ArchiverException -{ +public class EmptyArchiveException extends ArchiverException { - public EmptyArchiveException(String message ) - { - super( message ); + public EmptyArchiveException(String message) { + super(message); } - public EmptyArchiveException(String message, Throwable cause ) - { - super( message, cause ); + public EmptyArchiveException(String message, Throwable cause) { + super(message, cause); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileFilter.java b/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileFilter.java index 25d6c2685..19b9084f8 100644 --- a/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileFilter.java +++ b/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileFilter.java @@ -1,6 +1,7 @@ package org.codehaus.plexus.archiver.filters; import java.io.InputStream; + import org.codehaus.plexus.archiver.ArchiveFileFilter; import org.codehaus.plexus.util.SelectorUtils; @@ -8,24 +9,18 @@ * @deprecated Use {@link JarSecurityFileSelector} */ @Deprecated -public class JarSecurityFileFilter - implements ArchiveFileFilter -{ +public class JarSecurityFileFilter implements ArchiveFileFilter { public static final String[] SECURITY_FILE_PATTERNS = JarSecurityFileSelector.SECURITY_FILE_PATTERNS; @Override - public boolean include( InputStream dataStream, String entryName ) - { - for ( String pattern : SECURITY_FILE_PATTERNS ) - { - if ( SelectorUtils.match( pattern, entryName ) ) - { + public boolean include(InputStream dataStream, String entryName) { + for (String pattern : SECURITY_FILE_PATTERNS) { + if (SelectorUtils.match(pattern, entryName)) { return false; } } return true; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileSelector.java b/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileSelector.java index f9fb69a01..5b737820d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileSelector.java +++ b/src/main/java/org/codehaus/plexus/archiver/filters/JarSecurityFileSelector.java @@ -13,11 +13,12 @@ */ package org.codehaus.plexus.archiver.filters; -import java.io.IOException; import javax.annotation.Nonnull; import javax.inject.Named; import javax.inject.Singleton; +import java.io.IOException; + import org.codehaus.plexus.components.io.fileselectors.FileInfo; import org.codehaus.plexus.components.io.fileselectors.FileSelector; import org.codehaus.plexus.util.SelectorUtils; @@ -26,12 +27,9 @@ * @since 1.0-alpha-9 */ @Singleton -@Named( "jar-security" ) -public class JarSecurityFileSelector - implements FileSelector -{ - public static final String[] SECURITY_FILE_PATTERNS = - { +@Named("jar-security") +public class JarSecurityFileSelector implements FileSelector { + public static final String[] SECURITY_FILE_PATTERNS = { "META-INF/*.RSA", "META-INF/*.DSA", "META-INF/*.SF", @@ -43,20 +41,15 @@ public class JarSecurityFileSelector }; @Override - public boolean isSelected( @Nonnull FileInfo fileInfo ) - throws IOException - { + public boolean isSelected(@Nonnull FileInfo fileInfo) throws IOException { String name = fileInfo.getName(); - for ( String pattern : SECURITY_FILE_PATTERNS ) - { - if ( SelectorUtils.match( pattern, name ) ) - { + for (String pattern : SECURITY_FILE_PATTERNS) { + if (SelectorUtils.match(pattern, name)) { return false; } } return true; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipArchiver.java b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipArchiver.java index d21222f3d..c5a606103 100644 --- a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipArchiver.java @@ -19,59 +19,49 @@ import javax.inject.Named; import java.io.IOException; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.ResourceIterator; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; -@Named( "gzip" ) -public class GZipArchiver - extends AbstractArchiver -{ +@Named("gzip") +public class GZipArchiver extends AbstractArchiver { final GZipCompressor compressor = new GZipCompressor(); @Override - protected void execute() - throws ArchiverException, IOException - { - if ( !checkForced() ) - { + protected void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } ArchiveEntry entry = iter.next(); - if ( iter.hasNext() ) - { - throw new ArchiverException( "There is more than one file in input." ); + if (iter.hasNext()) { + throw new ArchiverException("There is more than one file in input."); } - compressor.setSource( entry.getResource() ); - compressor.setDestFile( getDestFile() ); + compressor.setSource(entry.getResource()); + compressor.setDestFile(getDestFile()); compressor.compress(); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void close() - { + protected void close() { compressor.close(); } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "gzip"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipCompressor.java b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipCompressor.java index e18213292..b7c993d50 100644 --- a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipCompressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipCompressor.java @@ -16,9 +16,6 @@ */ package org.codehaus.plexus.archiver.gzip; -import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; - import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; @@ -26,9 +23,10 @@ import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Compressor; -public class GZipCompressor - extends Compressor -{ +import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; + +public class GZipCompressor extends Compressor { private OutputStream zOut; @@ -36,36 +34,25 @@ public class GZipCompressor * perform the GZip compression operation. */ @Override - public void compress() - throws ArchiverException - { - try - { - zOut = bufferedOutputStream( new GZIPOutputStream( fileOutputStream( getDestFile() ) ) ); - compress( getSource(), zOut ); - } - catch ( IOException ioe ) - { + public void compress() throws ArchiverException { + try { + zOut = bufferedOutputStream(new GZIPOutputStream(fileOutputStream(getDestFile()))); + compress(getSource(), zOut); + } catch (IOException ioe) { String msg = "Problem creating gzip " + ioe.getMessage(); - throw new ArchiverException( msg, ioe ); + throw new ArchiverException(msg, ioe); } } @Override - public void close() - { - try - { - if ( this.zOut != null ) - { + public void close() { + try { + if (this.zOut != null) { this.zOut.close(); zOut = null; } - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure closing target.", e ); + } catch (final IOException e) { + throw new ArchiverException("Failure closing target.", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipUnArchiver.java index b8bb06a5b..b0ed94afb 100644 --- a/src/main/java/org/codehaus/plexus/archiver/gzip/GZipUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/gzip/GZipUnArchiver.java @@ -18,10 +18,6 @@ import javax.inject.Named; -import static org.codehaus.plexus.archiver.util.Streams.copyFully; -import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -31,56 +27,48 @@ import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Streams; +import static org.codehaus.plexus.archiver.util.Streams.copyFully; +import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; + /** * @author Emmanuel Venisse */ -@Named( "gzip" ) -public class GZipUnArchiver - extends AbstractUnArchiver -{ +@Named("gzip") +public class GZipUnArchiver extends AbstractUnArchiver { private static final String OPERATION_GZIP = "gzip"; - public GZipUnArchiver() - { - } + public GZipUnArchiver() {} - public GZipUnArchiver( File sourceFile ) - { - super( sourceFile ); + public GZipUnArchiver(File sourceFile) { + super(sourceFile); } @Override - protected void execute() - throws ArchiverException - { - if ( getSourceFile().lastModified() > getDestFile().lastModified() ) - { - getLogger().info( "Expanding " + getSourceFile().getAbsolutePath() + " to " - + getDestFile().getAbsolutePath() ); + protected void execute() throws ArchiverException { + if (getSourceFile().lastModified() > getDestFile().lastModified()) { + getLogger() + .info("Expanding " + getSourceFile().getAbsolutePath() + " to " + + getDestFile().getAbsolutePath()); - copyFully( getGzipInputStream( fileInputStream( getSourceFile(), OPERATION_GZIP ) ), - fileOutputStream( getDestFile(), OPERATION_GZIP ), OPERATION_GZIP ); + copyFully( + getGzipInputStream(fileInputStream(getSourceFile(), OPERATION_GZIP)), + fileOutputStream(getDestFile(), OPERATION_GZIP), + OPERATION_GZIP); } } - private InputStream getGzipInputStream( InputStream in ) - throws ArchiverException - { - try - { - return Streams.bufferedInputStream( new GZIPInputStream( in ) ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Problem creating GZIP input stream", e ); + private InputStream getGzipInputStream(InputStream in) throws ArchiverException { + try { + return Streams.bufferedInputStream(new GZIPInputStream(in)); + } catch (IOException e) { + throw new ArchiverException("Problem creating GZIP input stream", e); } } @Override - protected void execute( String path, File outputDirectory ) - { - throw new UnsupportedOperationException( "Targeted extraction not supported in GZIP format." ); + protected void execute(String path, File outputDirectory) { + throw new UnsupportedOperationException("Targeted extraction not supported in GZIP format."); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzResourceCollection.java index 89fce6420..7544c7b0a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzResourceCollection.java @@ -5,8 +5,5 @@ /** * Alias for {@link PlexusIoGzipResourceCollection} */ -@Named( "gz" ) -public class PlexusIoGzResourceCollection - extends PlexusIoGzipResourceCollection -{ -} +@Named("gz") +public class PlexusIoGzResourceCollection extends PlexusIoGzipResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzipResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzipResourceCollection.java index 8e90cf6f5..96c848f11 100644 --- a/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzipResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/gzip/PlexusIoGzipResourceCollection.java @@ -1,7 +1,7 @@ package org.codehaus.plexus.archiver.gzip; -import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; +import javax.annotation.Nonnull; +import javax.inject.Named; import java.io.File; import java.io.IOException; @@ -9,41 +9,33 @@ import java.util.HashMap; import java.util.zip.GZIPInputStream; -import javax.annotation.Nonnull; -import javax.inject.Named; - import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.resources.PlexusIoCompressedFileResourceCollection; +import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; + /** * Abstract base class for compressed files, aka singleton * resource collections. */ -@Named( "gzip" ) -public class PlexusIoGzipResourceCollection - extends PlexusIoCompressedFileResourceCollection -{ +@Named("gzip") +public class PlexusIoGzipResourceCollection extends PlexusIoCompressedFileResourceCollection { @Override - protected String getDefaultExtension() - { + protected String getDefaultExtension() { return ".gz"; } @Nonnull @Override - protected InputStream getInputStream( File file ) - throws IOException - { - return bufferedInputStream( new GZIPInputStream( fileInputStream( file ) ) ); + protected InputStream getInputStream(File file) throws IOException { + return bufferedInputStream(new GZIPInputStream(fileInputStream(file))); } @Override - protected PlexusIoResourceAttributes getAttributes( File file ) - throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + protected PlexusIoResourceAttributes getAttributes(File file) throws IOException { + return new FileAttributes(file, new HashMap(), new HashMap()); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/JarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/jar/JarArchiver.java index 99eeb81c2..e574e2e23 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/JarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/JarArchiver.java @@ -18,10 +18,6 @@ import javax.inject.Named; -import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -49,13 +45,15 @@ import org.codehaus.plexus.archiver.zip.ConcurrentJarCreator; import org.codehaus.plexus.archiver.zip.ZipArchiver; +import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; + /** * Base class for tasks that build archives in JAR file format. */ -@Named( "jar" ) -public class JarArchiver - extends ZipArchiver -{ +@Named("jar") +public class JarArchiver extends ZipArchiver { /** * the name of the meta-inf dir @@ -160,11 +158,10 @@ public class JarArchiver /** * constructor */ - public JarArchiver() - { + public JarArchiver() { super(); archiveType = "jar"; - setEncoding( "UTF8" ); + setEncoding("UTF8"); rootEntries = new ArrayList<>(); } @@ -176,8 +173,7 @@ public JarArchiver() * @deprecated See JDK-8302819 */ @Deprecated - public void setIndex( boolean flag ) - { + public void setIndex(boolean flag) { index = flag; } @@ -186,18 +182,13 @@ public void setIndex( boolean flag ) * * @param minimalDefaultManifest true to create minimal default manifest */ - public void setMinimalDefaultManifest( boolean minimalDefaultManifest ) { + public void setMinimalDefaultManifest(boolean minimalDefaultManifest) { this.minimalDefaultManifest = minimalDefaultManifest; } - @SuppressWarnings( - { - "JavaDoc", "UnusedDeclaration" - } ) + @SuppressWarnings({"JavaDoc", "UnusedDeclaration"}) @Deprecated // Useless method. Manifests should be UTF-8 by convention. Calling this setter does nothing - public void setManifestEncoding( String manifestEncoding ) - { - } + public void setManifestEncoding(String manifestEncoding) {} /** * Allows the manifest for the archive file to be provided inline @@ -207,16 +198,11 @@ public void setManifestEncoding( String manifestEncoding ) * * @throws ManifestException */ - public void addConfiguredManifest( Manifest newManifest ) - throws ManifestException - { - if ( configuredManifest == null ) - { + public void addConfiguredManifest(Manifest newManifest) throws ManifestException { + if (configuredManifest == null) { configuredManifest = newManifest; - } - else - { - JdkManifestFactory.merge( configuredManifest, newManifest, false ); + } else { + JdkManifestFactory.merge(configuredManifest, newManifest, false); } savedConfiguredManifest = configuredManifest; } @@ -229,45 +215,29 @@ public void addConfiguredManifest( Manifest newManifest ) * * @throws org.codehaus.plexus.archiver.ArchiverException */ - @SuppressWarnings( - { - "UnusedDeclaration" - } ) - public void setManifest( File manifestFile ) - throws ArchiverException - { - if ( !manifestFile.exists() ) - { - throw new ArchiverException( "Manifest file: " + manifestFile + " does not exist." ); + @SuppressWarnings({"UnusedDeclaration"}) + public void setManifest(File manifestFile) throws ArchiverException { + if (!manifestFile.exists()) { + throw new ArchiverException("Manifest file: " + manifestFile + " does not exist."); } this.manifestFile = manifestFile; } - private Manifest getManifest( File manifestFile ) - throws ArchiverException - { - try ( InputStream in = fileInputStream( manifestFile ) ) - { - return getManifest( in ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Unable to read manifest file: " + manifestFile + " (" + e.getMessage() + ")", - e ); + private Manifest getManifest(File manifestFile) throws ArchiverException { + try (InputStream in = fileInputStream(manifestFile)) { + return getManifest(in); + } catch (IOException e) { + throw new ArchiverException( + "Unable to read manifest file: " + manifestFile + " (" + e.getMessage() + ")", e); } } - private Manifest getManifest( InputStream is ) - throws ArchiverException - { - try - { - return new Manifest( is ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Unable to read manifest file" + " (" + e.getMessage() + ")", e ); + private Manifest getManifest(InputStream is) throws ArchiverException { + try { + return new Manifest(is); + } catch (IOException e) { + throw new ArchiverException("Unable to read manifest file" + " (" + e.getMessage() + ")", e); } } @@ -284,17 +254,12 @@ private Manifest getManifest( InputStream is ) * * @param config setting for found manifest behavior. */ - @SuppressWarnings( - { - "UnusedDeclaration" - } ) - public void setFilesetmanifest( FilesetManifestConfig config ) - { + @SuppressWarnings({"UnusedDeclaration"}) + public void setFilesetmanifest(FilesetManifestConfig config) { filesetManifestConfig = config; mergeManifestsMain = FilesetManifestConfig.merge == config; - if ( ( filesetManifestConfig != null ) && filesetManifestConfig != FilesetManifestConfig.skip ) - { + if ((filesetManifestConfig != null) && filesetManifestConfig != FilesetManifestConfig.skip) { doubleFilePass = true; } @@ -305,34 +270,27 @@ public void setFilesetmanifest( FilesetManifestConfig config ) * @deprecated See JDK-8302819 */ @Deprecated - public void addConfiguredIndexJars( File indexJar ) - { - if ( indexJars == null ) - { + public void addConfiguredIndexJars(File indexJar) { + if (indexJars == null) { indexJars = new ArrayList<>(); } - indexJars.add( indexJar.getAbsolutePath() ); + indexJars.add(indexJar.getAbsolutePath()); } @Override - protected void initZipOutputStream( ConcurrentJarCreator zOut ) - throws ArchiverException, IOException - { - if ( !skipWriting ) - { + protected void initZipOutputStream(ConcurrentJarCreator zOut) throws ArchiverException, IOException { + if (!skipWriting) { Manifest jarManifest = createManifest(); - writeManifest( zOut, jarManifest ); + writeManifest(zOut, jarManifest); } } @Override - protected boolean hasVirtualFiles() - { - getLogger().debug( "\n\n\nChecking for jar manifest virtual files...\n\n\n" ); + protected boolean hasVirtualFiles() { + getLogger().debug("\n\n\nChecking for jar manifest virtual files...\n\n\n"); System.out.flush(); - return ( configuredManifest != null ) || ( manifest != null ) || ( manifestFile != null ) - || super.hasVirtualFiles(); + return (configuredManifest != null) || (manifest != null) || (manifestFile != null) || super.hasVirtualFiles(); } /** @@ -344,16 +302,13 @@ protected boolean hasVirtualFiles() * * @throws ArchiverException */ - protected Manifest createManifest() - throws ArchiverException - { - Manifest finalManifest = Manifest.getDefaultManifest( minimalDefaultManifest ); + protected Manifest createManifest() throws ArchiverException { + Manifest finalManifest = Manifest.getDefaultManifest(minimalDefaultManifest); - if ( ( manifest == null ) && ( manifestFile != null ) ) - { + if ((manifest == null) && (manifestFile != null)) { // if we haven't got the manifest yet, attempt to // get it now and have manifest be the final merge - manifest = getManifest( manifestFile ); + manifest = getManifest(manifestFile); } /* @@ -363,44 +318,36 @@ protected Manifest createManifest() * * merge with null argument is a no-op */ - if ( isInUpdateMode() ) - { - JdkManifestFactory.merge( finalManifest, originalManifest, false ); + if (isInUpdateMode()) { + JdkManifestFactory.merge(finalManifest, originalManifest, false); } - JdkManifestFactory.merge( finalManifest, filesetManifest, false ); - JdkManifestFactory.merge( finalManifest, configuredManifest, false ); - JdkManifestFactory.merge( finalManifest, manifest, !mergeManifestsMain ); + JdkManifestFactory.merge(finalManifest, filesetManifest, false); + JdkManifestFactory.merge(finalManifest, configuredManifest, false); + JdkManifestFactory.merge(finalManifest, manifest, !mergeManifestsMain); return finalManifest; } - private void writeManifest( ConcurrentJarCreator zOut, Manifest manifest ) - throws IOException, ArchiverException - { - for ( Enumeration e = manifest.getWarnings(); e.hasMoreElements(); ) - { - getLogger().warn( "Manifest warning: " + e.nextElement() ); + private void writeManifest(ConcurrentJarCreator zOut, Manifest manifest) throws IOException, ArchiverException { + for (Enumeration e = manifest.getWarnings(); e.hasMoreElements(); ) { + getLogger().warn("Manifest warning: " + e.nextElement()); } - zipDir( null, zOut, "META-INF/", DEFAULT_DIR_MODE, getEncoding() ); + zipDir(null, zOut, "META-INF/", DEFAULT_DIR_MODE, getEncoding()); // time to write the manifest - ByteArrayOutputStream baos = new ByteArrayOutputStream( 128 ); - manifest.write( baos ); - InputStreamSupplier in = () -> new ByteArrayInputStream( baos.toByteArray() ); + ByteArrayOutputStream baos = new ByteArrayOutputStream(128); + manifest.write(baos); + InputStreamSupplier in = () -> new ByteArrayInputStream(baos.toByteArray()); - super.zipFile( in, zOut, MANIFEST_NAME, System.currentTimeMillis(), null, DEFAULT_FILE_MODE, null, - false ); - super.initZipOutputStream( zOut ); + super.zipFile(in, zOut, MANIFEST_NAME, System.currentTimeMillis(), null, DEFAULT_FILE_MODE, null, false); + super.initZipOutputStream(zOut); } @Override - protected void finalizeZipOutputStream( ConcurrentJarCreator zOut ) - throws IOException, ArchiverException - { - if ( index ) - { - createIndexList( zOut ); + protected void finalizeZipOutputStream(ConcurrentJarCreator zOut) throws IOException, ArchiverException { + if (index) { + createIndexList(zOut); } } @@ -418,72 +365,61 @@ protected void finalizeZipOutputStream( ConcurrentJarCreator zOut ) * @deprecated See JDK-8302819 */ @Deprecated - private void createIndexList( ConcurrentJarCreator zOut ) - throws IOException, ArchiverException - { - ByteArrayOutputStream baos = new ByteArrayOutputStream( 128 ); + private void createIndexList(ConcurrentJarCreator zOut) throws IOException, ArchiverException { + ByteArrayOutputStream baos = new ByteArrayOutputStream(128); // encoding must be UTF8 as specified in the specs. - PrintWriter writer = new PrintWriter( new OutputStreamWriter( baos, StandardCharsets.UTF_8 ) ); + PrintWriter writer = new PrintWriter(new OutputStreamWriter(baos, StandardCharsets.UTF_8)); // version-info blankline - writer.println( "JarIndex-Version: 1.0" ); + writer.println("JarIndex-Version: 1.0"); writer.println(); // header newline - writer.println( getDestFile().getName() ); + writer.println(getDestFile().getName()); // filter out META-INF if it doesn't contain anything other than the index and manifest. // this is what sun.misc.JarIndex does, guess we ought to be consistent. Set filteredDirs = addedDirs.allAddedDirs(); // our added dirs always have a trailing slash - if ( filteredDirs.contains( META_INF_NAME + '/' ) ) - { + if (filteredDirs.contains(META_INF_NAME + '/')) { boolean add = false; - for ( String entry : entries.keySet() ) - { - if ( entry.startsWith( META_INF_NAME + '/' ) && !entry.equals( INDEX_NAME ) - && !entry.equals( MANIFEST_NAME ) ) - { + for (String entry : entries.keySet()) { + if (entry.startsWith(META_INF_NAME + '/') + && !entry.equals(INDEX_NAME) + && !entry.equals(MANIFEST_NAME)) { add = true; break; } } - if ( !add ) - { - filteredDirs.remove( META_INF_NAME + '/' ); + if (!add) { + filteredDirs.remove(META_INF_NAME + '/'); } } - writeIndexLikeList( new ArrayList<>( filteredDirs ), rootEntries, writer ); + writeIndexLikeList(new ArrayList<>(filteredDirs), rootEntries, writer); writer.println(); - if ( indexJars != null ) - { + if (indexJars != null) { java.util.jar.Manifest mf = createManifest(); - String classpath = mf.getMainAttributes().getValue( ManifestConstants.ATTRIBUTE_CLASSPATH ); + String classpath = mf.getMainAttributes().getValue(ManifestConstants.ATTRIBUTE_CLASSPATH); String[] cpEntries = null; - if ( classpath != null ) - { - StringTokenizer tok = new StringTokenizer( classpath, " " ); - cpEntries = new String[ tok.countTokens() ]; + if (classpath != null) { + StringTokenizer tok = new StringTokenizer(classpath, " "); + cpEntries = new String[tok.countTokens()]; int c = 0; - while ( tok.hasMoreTokens() ) - { + while (tok.hasMoreTokens()) { cpEntries[c++] = tok.nextToken(); } } - for ( String indexJar : indexJars ) - { - String name = findJarName( indexJar, cpEntries ); - if ( name != null ) - { + for (String indexJar : indexJars) { + String name = findJarName(indexJar, cpEntries); + if (name != null) { List dirs = new ArrayList<>(); List files = new ArrayList<>(); - grabFilesAndDirs( indexJar, dirs, files ); - if ( dirs.size() + files.size() > 0 ) - { - writer.println( name ); - writeIndexLikeList( dirs, files, writer ); + grabFilesAndDirs(indexJar, dirs, files); + if (dirs.size() + files.size() > 0) { + writer.println(name); + writeIndexLikeList(dirs, files, writer); writer.println(); } } @@ -492,126 +428,98 @@ private void createIndexList( ConcurrentJarCreator zOut ) writer.flush(); - InputStreamSupplier in = () -> new ByteArrayInputStream( baos.toByteArray() ); + InputStreamSupplier in = () -> new ByteArrayInputStream(baos.toByteArray()); - super.zipFile( in, zOut, INDEX_NAME, System.currentTimeMillis(), null, - DEFAULT_FILE_MODE, null, true ); + super.zipFile(in, zOut, INDEX_NAME, System.currentTimeMillis(), null, DEFAULT_FILE_MODE, null, true); } /** * Overridden from Zip class to deal with manifests and index lists. */ @Override - protected void zipFile( InputStreamSupplier is, ConcurrentJarCreator zOut, String vPath, - long lastModified, File fromArchive, - int mode, String symlinkDestination, boolean addInParallel ) - throws IOException, ArchiverException - { - if ( MANIFEST_NAME.equalsIgnoreCase( vPath ) ) - { - if ( !doubleFilePass || skipWriting ) - { - try ( InputStream manifestInputStream = is.get() ) - { - filesetManifest( fromArchive, manifestInputStream ); + protected void zipFile( + InputStreamSupplier is, + ConcurrentJarCreator zOut, + String vPath, + long lastModified, + File fromArchive, + int mode, + String symlinkDestination, + boolean addInParallel) + throws IOException, ArchiverException { + if (MANIFEST_NAME.equalsIgnoreCase(vPath)) { + if (!doubleFilePass || skipWriting) { + try (InputStream manifestInputStream = is.get()) { + filesetManifest(fromArchive, manifestInputStream); } } - } - else if ( INDEX_NAME.equalsIgnoreCase( vPath ) && index ) - { - getLogger().warn( "Warning: selected " + archiveType + " files include a META-INF/INDEX.LIST which will" - + " be replaced by a newly generated one." ); - } - else - { - if ( index && !vPath.contains( "/" ) ) - { - rootEntries.add( vPath ); + } else if (INDEX_NAME.equalsIgnoreCase(vPath) && index) { + getLogger() + .warn("Warning: selected " + archiveType + " files include a META-INF/INDEX.LIST which will" + + " be replaced by a newly generated one."); + } else { + if (index && !vPath.contains("/")) { + rootEntries.add(vPath); } - super.zipFile( is, zOut, vPath, lastModified, fromArchive, mode, symlinkDestination, addInParallel ); + super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode, symlinkDestination, addInParallel); } } - private void filesetManifest( File file, InputStream is ) - throws ArchiverException - { - if ( ( manifestFile != null ) && manifestFile.equals( file ) ) - { + private void filesetManifest(File file, InputStream is) throws ArchiverException { + if ((manifestFile != null) && manifestFile.equals(file)) { // If this is the same name specified in 'manifest', this // is the manifest to use - getLogger().debug( "Found manifest " + file ); - if ( is != null ) - { - manifest = getManifest( is ); - } - else - { - manifest = getManifest( file ); + getLogger().debug("Found manifest " + file); + if (is != null) { + manifest = getManifest(is); + } else { + manifest = getManifest(file); } - } - else if ( ( filesetManifestConfig != null ) && filesetManifestConfig != FilesetManifestConfig.skip ) - { + } else if ((filesetManifestConfig != null) && filesetManifestConfig != FilesetManifestConfig.skip) { // we add this to our group of fileset manifests - getLogger().debug( "Found manifest to merge in file " + file ); + getLogger().debug("Found manifest to merge in file " + file); Manifest newManifest; - if ( is != null ) - { - newManifest = getManifest( is ); - } - else - { - newManifest = getManifest( file ); + if (is != null) { + newManifest = getManifest(is); + } else { + newManifest = getManifest(file); } - if ( filesetManifest == null ) - { + if (filesetManifest == null) { filesetManifest = newManifest; - } - else - { - JdkManifestFactory.merge( filesetManifest, newManifest, false ); + } else { + JdkManifestFactory.merge(filesetManifest, newManifest, false); } } } @Override - protected boolean createEmptyZip( File zipFile ) - throws ArchiverException - { - if ( !createEmpty ) - { + protected boolean createEmptyZip(File zipFile) throws ArchiverException { + if (!createEmpty) { return true; } - try - { - getLogger().debug( "Building MANIFEST-only jar: " + getDestFile().getAbsolutePath() ); + try { + getLogger().debug("Building MANIFEST-only jar: " + getDestFile().getAbsolutePath()); zipArchiveOutputStream = - new ZipArchiveOutputStream( bufferedOutputStream( fileOutputStream( getDestFile(), "jar" ) ) ); + new ZipArchiveOutputStream(bufferedOutputStream(fileOutputStream(getDestFile(), "jar"))); - zipArchiveOutputStream.setEncoding( getEncoding() ); - if ( isCompress() ) - { - zipArchiveOutputStream.setMethod( ZipArchiveOutputStream.DEFLATED ); - } - else - { - zipArchiveOutputStream.setMethod( ZipArchiveOutputStream.STORED ); + zipArchiveOutputStream.setEncoding(getEncoding()); + if (isCompress()) { + zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.DEFLATED); + } else { + zipArchiveOutputStream.setMethod(ZipArchiveOutputStream.STORED); } - ConcurrentJarCreator ps = - new ConcurrentJarCreator( isRecompressAddedZips(), Runtime.getRuntime().availableProcessors() ); - initZipOutputStream( ps ); - finalizeZipOutputStream( ps ); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Could not create almost empty JAR archive (" + ioe.getMessage() + ")", ioe ); - } - finally - { + ConcurrentJarCreator ps = new ConcurrentJarCreator( + isRecompressAddedZips(), Runtime.getRuntime().availableProcessors()); + initZipOutputStream(ps); + finalizeZipOutputStream(ps); + } catch (IOException ioe) { + throw new ArchiverException("Could not create almost empty JAR archive (" + ioe.getMessage() + ")", ioe); + } finally { // Close the output stream. - //IOUtil.close( zOut ); + // IOUtil.close( zOut ); createEmpty = false; } return true; @@ -624,14 +532,11 @@ protected boolean createEmptyZip( File zipFile ) * @see ZipArchiver#cleanUp */ @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { super.cleanUp(); // we want to save this info if we are going to make another pass - if ( !doubleFilePass || !skipWriting ) - { + if (!doubleFilePass || !skipWriting) { manifest = null; configuredManifest = savedConfiguredManifest; filesetManifest = null; @@ -646,8 +551,7 @@ protected void cleanUp() * @see ZipArchiver#reset */ @Override - public void reset() - { + public void reset() { super.reset(); configuredManifest = null; filesetManifestConfig = null; @@ -656,13 +560,10 @@ public void reset() index = false; } - public enum FilesetManifestConfig - { - + public enum FilesetManifestConfig { skip, merge, mergewithoutmain - } /** @@ -675,38 +576,32 @@ public enum FilesetManifestConfig * @deprecated See JDK-8302819 */ @Deprecated - protected final void writeIndexLikeList( List dirs, List files, PrintWriter writer ) - { + protected final void writeIndexLikeList(List dirs, List files, PrintWriter writer) { // JarIndex is sorting the directories by ascending order. // it has no value but cosmetic since it will be read into a // hashtable by the classloader, but we'll do so anyway. - Collections.sort( dirs ); - Collections.sort( files ); - for ( String dir : dirs ) - { + Collections.sort(dirs); + Collections.sort(files); + for (String dir : dirs) { // try to be smart, not to be fooled by a weird directory name - dir = dir.replace( '\\', '/' ); - if ( dir.startsWith( "./" ) ) - { - dir = dir.substring( 2 ); + dir = dir.replace('\\', '/'); + if (dir.startsWith("./")) { + dir = dir.substring(2); } - while ( dir.startsWith( "/" ) ) - { - dir = dir.substring( 1 ); + while (dir.startsWith("/")) { + dir = dir.substring(1); } - int pos = dir.lastIndexOf( '/' ); - if ( pos != -1 ) - { - dir = dir.substring( 0, pos ); + int pos = dir.lastIndexOf('/'); + if (pos != -1) { + dir = dir.substring(0, pos); } // name newline - writer.println( dir ); + writer.println(dir); } - for ( String file : files ) - { - writer.println( file ); + for (String file : files) { + writer.println(file); } } @@ -730,41 +625,34 @@ protected final void writeIndexLikeList( List dirs, List files, * * @return The guessed name */ - protected static String findJarName( String fileName, String[] classpath ) - { - if ( classpath == null ) - { - return new File( fileName ).getName(); + protected static String findJarName(String fileName, String[] classpath) { + if (classpath == null) { + return new File(fileName).getName(); } - fileName = fileName.replace( File.separatorChar, '/' ); + fileName = fileName.replace(File.separatorChar, '/'); // longest match comes first - SortedMap matches = new TreeMap<>( Comparator.comparingInt( String::length ).reversed() ); - - for ( String aClasspath : classpath ) - { - if ( fileName.endsWith( aClasspath ) ) - { - matches.put( aClasspath, aClasspath ); - } - else - { - int slash = aClasspath.indexOf( "/" ); + SortedMap matches = + new TreeMap<>(Comparator.comparingInt(String::length).reversed()); + + for (String aClasspath : classpath) { + if (fileName.endsWith(aClasspath)) { + matches.put(aClasspath, aClasspath); + } else { + int slash = aClasspath.indexOf("/"); String candidate = aClasspath; - while ( slash > -1 ) - { - candidate = candidate.substring( slash + 1 ); - if ( fileName.endsWith( candidate ) ) - { - matches.put( candidate, aClasspath ); + while (slash > -1) { + candidate = candidate.substring(slash + 1); + if (fileName.endsWith(candidate)) { + matches.put(candidate, aClasspath); break; } - slash = candidate.indexOf( "/" ); + slash = candidate.indexOf("/"); } } } - return matches.size() == 0 ? null : matches.get( matches.firstKey() ); + return matches.size() == 0 ? null : matches.get(matches.firstKey()); } /** @@ -777,51 +665,38 @@ protected static String findJarName( String fileName, String[] classpath ) * * @throws java.io.IOException */ - private void grabFilesAndDirs( String file, List dirs, List files ) - throws IOException - { - File zipFile = new File( file ); - if ( !zipFile.exists() ) - { - getLogger().error( "JarArchive skipping non-existing file: " + zipFile.getAbsolutePath() ); - } - else if ( zipFile.isDirectory() ) - { - getLogger().info( "JarArchiver skipping indexJar " + zipFile + " because it is not a jar" ); - } - else - { - try ( ZipFile zf = new ZipFile( file, "utf-8" ) ) - { + private void grabFilesAndDirs(String file, List dirs, List files) throws IOException { + File zipFile = new File(file); + if (!zipFile.exists()) { + getLogger().error("JarArchive skipping non-existing file: " + zipFile.getAbsolutePath()); + } else if (zipFile.isDirectory()) { + getLogger().info("JarArchiver skipping indexJar " + zipFile + " because it is not a jar"); + } else { + try (ZipFile zf = new ZipFile(file, "utf-8")) { Enumeration entries = zf.getEntries(); HashSet dirSet = new HashSet<>(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipArchiveEntry ze = entries.nextElement(); String name = ze.getName(); // avoid index for manifest-only jars. - if ( !name.equals( META_INF_NAME ) && !name.equals( META_INF_NAME + '/' ) && !name.equals( - INDEX_NAME ) && !name.equals( MANIFEST_NAME ) ) - { - if ( ze.isDirectory() ) - { - dirSet.add( name ); - } - else if ( !name.contains( "/" ) ) - { - files.add( name ); - } - else - { + if (!name.equals(META_INF_NAME) + && !name.equals(META_INF_NAME + '/') + && !name.equals(INDEX_NAME) + && !name.equals(MANIFEST_NAME)) { + if (ze.isDirectory()) { + dirSet.add(name); + } else if (!name.contains("/")) { + files.add(name); + } else { // a file, not in the root // since the jar may be one without directory // entries, add the parent dir of this file as // well. - dirSet.add( name.substring( 0, name.lastIndexOf( "/" ) + 1 ) ); + dirSet.add(name.substring(0, name.lastIndexOf("/") + 1)); } } } - dirs.addAll( dirSet ); + dirs.addAll(dirSet); } } } @@ -833,15 +708,12 @@ else if ( !name.contains( "/" ) ) * @param lastModifiedTime to set in the zip entry only if {@link #getLastModifiedTime()} returns null */ @Override - protected void setZipEntryTime( ZipArchiveEntry zipEntry, long lastModifiedTime ) - { - if ( getLastModifiedTime() != null ) - { + protected void setZipEntryTime(ZipArchiveEntry zipEntry, long lastModifiedTime) { + if (getLastModifiedTime() != null) { lastModifiedTime = getLastModifiedTime().toMillis(); } // The JAR tool does not round up, so we keep that behavior here (JDK-8277755). - zipEntry.setTime( lastModifiedTime ); + zipEntry.setTime(lastModifiedTime); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiver.java index 54e6f9d8b..b936ed318 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiver.java @@ -60,15 +60,11 @@ * archive created by {@link JarArchiver} * is left unchanged. */ -@Named( "mjar" ) -public class JarToolModularJarArchiver - extends ModularJarArchiver -{ - private static final String MODULE_DESCRIPTOR_FILE_NAME - = "module-info.class"; +@Named("mjar") +public class JarToolModularJarArchiver extends ModularJarArchiver { + private static final String MODULE_DESCRIPTOR_FILE_NAME = "module-info.class"; - private static final Pattern MRJAR_VERSION_AREA - = Pattern.compile( "META-INF/versions/\\d+/" ); + private static final Pattern MRJAR_VERSION_AREA = Pattern.compile("META-INF/versions/\\d+/"); private Object jarTool; @@ -76,140 +72,113 @@ public class JarToolModularJarArchiver private boolean hasJarDateOption; - public JarToolModularJarArchiver() - { - try - { - Class toolProviderClass = - Class.forName( "java.util.spi.ToolProvider" ); - Object jarToolOptional = toolProviderClass - .getMethod( "findFirst", String.class ) - .invoke( null, "jar" ); - - jarTool = jarToolOptional.getClass().getMethod( "get" ) - .invoke( jarToolOptional ); - } - catch ( ReflectiveOperationException | SecurityException e ) - { + public JarToolModularJarArchiver() { + try { + Class toolProviderClass = Class.forName("java.util.spi.ToolProvider"); + Object jarToolOptional = + toolProviderClass.getMethod("findFirst", String.class).invoke(null, "jar"); + + jarTool = jarToolOptional.getClass().getMethod("get").invoke(jarToolOptional); + } catch (ReflectiveOperationException | SecurityException e) { // Ignore. It is expected that the jar tool // may not be available. } } @Override - protected void zipFile( InputStreamSupplier is, ConcurrentJarCreator zOut, - String vPath, long lastModified, File fromArchive, - int mode, String symlinkDestination, - boolean addInParallel ) - throws IOException, ArchiverException - { - if ( jarTool != null && isModuleDescriptor( vPath ) ) - { - getLogger().debug( "Module descriptor found: " + vPath ); + protected void zipFile( + InputStreamSupplier is, + ConcurrentJarCreator zOut, + String vPath, + long lastModified, + File fromArchive, + int mode, + String symlinkDestination, + boolean addInParallel) + throws IOException, ArchiverException { + if (jarTool != null && isModuleDescriptor(vPath)) { + getLogger().debug("Module descriptor found: " + vPath); moduleDescriptorFound = true; } - super.zipFile( is, zOut, vPath, lastModified, - fromArchive, mode, symlinkDestination, addInParallel ); + super.zipFile(is, zOut, vPath, lastModified, fromArchive, mode, symlinkDestination, addInParallel); } @Override - protected void postCreateArchive() - throws ArchiverException - { - if ( !moduleDescriptorFound ) - { + protected void postCreateArchive() throws ArchiverException { + if (!moduleDescriptorFound) { // no need to update the JAR archive return; } - try - { - getLogger().debug( "Using the jar tool to " + - "update the archive to modular JAR." ); + try { + getLogger().debug("Using the jar tool to " + "update the archive to modular JAR."); - final Method jarRun = jarTool.getClass() - .getMethod( "run", PrintStream.class, PrintStream.class, String[].class ); + final Method jarRun = + jarTool.getClass().getMethod("run", PrintStream.class, PrintStream.class, String[].class); - if ( getLastModifiedTime() != null ) - { - hasJarDateOption = isJarDateOptionSupported( jarRun ); - getLogger().debug( "jar tool --date option is supported: " + hasJarDateOption ); + if (getLastModifiedTime() != null) { + hasJarDateOption = isJarDateOptionSupported(jarRun); + getLogger().debug("jar tool --date option is supported: " + hasJarDateOption); } - Integer result = (Integer) jarRun.invoke( jarTool, System.out, System.err, getJarToolArguments() ); + Integer result = (Integer) jarRun.invoke(jarTool, System.out, System.err, getJarToolArguments()); - if ( result != null && result != 0 ) - { - throw new ArchiverException( "Could not create modular JAR file. " + - "The JDK jar tool exited with " + result ); + if (result != null && result != 0) { + throw new ArchiverException( + "Could not create modular JAR file. " + "The JDK jar tool exited with " + result); } - if ( !hasJarDateOption && getLastModifiedTime() != null ) - { - getLogger().debug( "Fix last modified time zip entries." ); + if (!hasJarDateOption && getLastModifiedTime() != null) { + getLogger().debug("Fix last modified time zip entries."); // --date option not supported, fallback to rewrite the JAR file // https://github.com/codehaus-plexus/plexus-archiver/issues/164 fixLastModifiedTimeZipEntries(); } - } - catch ( IOException | ReflectiveOperationException | SecurityException e ) - { - throw new ArchiverException( "Exception occurred " + - "while creating modular JAR file", e ); + } catch (IOException | ReflectiveOperationException | SecurityException e) { + throw new ArchiverException("Exception occurred " + "while creating modular JAR file", e); } } /** * Fallback to rewrite the JAR file with the correct timestamp if the {@code --date} option is not available. */ - private void fixLastModifiedTimeZipEntries() - throws IOException - { + private void fixLastModifiedTimeZipEntries() throws IOException { long timeMillis = getLastModifiedTime().toMillis(); Path destFile = getDestFile().toPath(); - Path tmpZip = Files.createTempFile( destFile.getParent(), null, null ); - try ( ZipFile zipFile = new ZipFile( getDestFile() ); - ZipOutputStream out = new ZipOutputStream( Files.newOutputStream( tmpZip ) ) ) - { + Path tmpZip = Files.createTempFile(destFile.getParent(), null, null); + try (ZipFile zipFile = new ZipFile(getDestFile()); + ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(tmpZip))) { Enumeration entries = zipFile.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); // Not using setLastModifiedTime(FileTime) as it sets the extended timestamp // which is not compatible with the jar tool output. - entry.setTime( timeMillis ); - out.putNextEntry( entry ); - if ( !entry.isDirectory() ) - { - IOUtil.copy( zipFile.getInputStream( entry ), out ); + entry.setTime(timeMillis); + out.putNextEntry(entry); + if (!entry.isDirectory()) { + IOUtil.copy(zipFile.getInputStream(entry), out); } out.closeEntry(); } } - Files.move( tmpZip, destFile, StandardCopyOption.REPLACE_EXISTING ); + Files.move(tmpZip, destFile, StandardCopyOption.REPLACE_EXISTING); } /** * Returns {@code true} if {@code path} * is a module descriptor. */ - private boolean isModuleDescriptor( String path ) - { - if ( path.endsWith( MODULE_DESCRIPTOR_FILE_NAME ) ) - { - String prefix = path.substring( 0, - path.lastIndexOf( MODULE_DESCRIPTOR_FILE_NAME ) ); + private boolean isModuleDescriptor(String path) { + if (path.endsWith(MODULE_DESCRIPTOR_FILE_NAME)) { + String prefix = path.substring(0, path.lastIndexOf(MODULE_DESCRIPTOR_FILE_NAME)); // the path is a module descriptor if it located // into the root of the archive or into the // version area of a multi-release JAR file - return prefix.isEmpty() || - MRJAR_VERSION_AREA.matcher( prefix ).matches(); - } - else - { + return prefix.isEmpty() || MRJAR_VERSION_AREA.matcher(prefix).matches(); + } else { return false; } } @@ -219,9 +188,7 @@ private boolean isModuleDescriptor( String path ) * It takes into account the module version, * main class, etc. */ - private String[] getJarToolArguments() - throws IOException - { + private String[] getJarToolArguments() throws IOException { // We add empty temporary directory to the JAR file. // It may look strange at first, but to update a JAR file // you need to add new files[1]. If we add empty directory @@ -231,58 +198,51 @@ private String[] getJarToolArguments() // [1] There are some exceptions (such as when the main class // is updated) but we need at least empty directory // to ensure it will work in all cases. - File tempEmptyDir = Files.createTempDirectory( null ).toFile(); + File tempEmptyDir = Files.createTempDirectory(null).toFile(); tempEmptyDir.deleteOnExit(); List args = new ArrayList<>(); - args.add( "--update" ); - args.add( "--file" ); - args.add( getDestFile().getAbsolutePath() ); + args.add("--update"); + args.add("--file"); + args.add(getDestFile().getAbsolutePath()); - String mainClass = getModuleMainClass() != null - ? getModuleMainClass() - : getManifestMainClass(); + String mainClass = getModuleMainClass() != null ? getModuleMainClass() : getManifestMainClass(); - if ( mainClass != null ) - { - args.add( "--main-class" ); - args.add( mainClass ); + if (mainClass != null) { + args.add("--main-class"); + args.add(mainClass); } - if ( getModuleVersion() != null ) - { - args.add( "--module-version" ); - args.add( getModuleVersion() ); + if (getModuleVersion() != null) { + args.add("--module-version"); + args.add(getModuleVersion()); } - if ( !isCompress() ) - { - args.add( "--no-compress" ); + if (!isCompress()) { + args.add("--no-compress"); } - if ( hasJarDateOption ) - { + if (hasJarDateOption) { // The --date option already normalize the time, so revert to the local time - FileTime localTime = revertToLocalTime( getLastModifiedTime() ); - args.add( "--date" ); - args.add( localTime.toString() ); + FileTime localTime = revertToLocalTime(getLastModifiedTime()); + args.add("--date"); + args.add(localTime.toString()); } - args.add( "-C" ); - args.add( tempEmptyDir.getAbsolutePath() ); - args.add( "." ); + args.add("-C"); + args.add(tempEmptyDir.getAbsolutePath()); + args.add("."); - return args.toArray( new String[0] ); + return args.toArray(new String[0]); } - private static FileTime revertToLocalTime( FileTime time ) - { + private static FileTime revertToLocalTime(FileTime time) { long restoreToLocalTime = time.toMillis(); - Calendar cal = Calendar.getInstance( TimeZone.getDefault(), Locale.ROOT ); - cal.setTimeInMillis( restoreToLocalTime ); - restoreToLocalTime = restoreToLocalTime + ( cal.get( Calendar.ZONE_OFFSET ) + cal.get( Calendar.DST_OFFSET ) ); - return FileTime.fromMillis( restoreToLocalTime ); + Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.ROOT); + cal.setTimeInMillis(restoreToLocalTime); + restoreToLocalTime = restoreToLocalTime + (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)); + return FileTime.fromMillis(restoreToLocalTime); } /** @@ -290,22 +250,17 @@ private static FileTime revertToLocalTime( FileTime time ) * * @return true if the JAR tool supports the {@code --date} option */ - private boolean isJarDateOptionSupported( Method runMethod ) - { - try - { + private boolean isJarDateOptionSupported(Method runMethod) { + try { // Test the output code validating the --date option. - String[] args = { "--date", "2099-12-31T23:59:59Z", "--version" }; + String[] args = {"--date", "2099-12-31T23:59:59Z", "--version"}; PrintStream nullPrintStream = NullPrintStream.NULL_PRINT_STREAM; - Integer result = (Integer) runMethod.invoke( jarTool, nullPrintStream, nullPrintStream, args ); + Integer result = (Integer) runMethod.invoke(jarTool, nullPrintStream, nullPrintStream, args); return result != null && result.intValue() == 0; - } - catch ( ReflectiveOperationException | SecurityException e ) - { + } catch (ReflectiveOperationException | SecurityException e) { return false; } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/JarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/jar/JarUnArchiver.java index 46bcb8c6f..54b0feb7a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/JarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/JarUnArchiver.java @@ -20,24 +20,17 @@ import java.io.File; -import org.codehaus.plexus.archiver.zip.AbstractZipUnArchiver; import org.codehaus.plexus.archiver.zip.ZipUnArchiver; /** * Alias for {@link ZipUnArchiver}. */ -@Named( "jar" ) -public class JarUnArchiver - extends ZipUnArchiver -{ +@Named("jar") +public class JarUnArchiver extends ZipUnArchiver { - public JarUnArchiver() - { - } + public JarUnArchiver() {} - public JarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public JarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/JdkManifestFactory.java b/src/main/java/org/codehaus/plexus/archiver/jar/JdkManifestFactory.java index 52234aeda..bec1dde1f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/JdkManifestFactory.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/JdkManifestFactory.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.Properties; import java.util.jar.Attributes; + import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.util.PropertyUtils; @@ -28,75 +29,55 @@ * * @author Kristian Rosenvold */ -class JdkManifestFactory -{ +class JdkManifestFactory { - public static java.util.jar.Manifest getDefaultManifest() - throws ArchiverException - { + public static java.util.jar.Manifest getDefaultManifest() throws ArchiverException { final java.util.jar.Manifest defaultManifest = new java.util.jar.Manifest(); - defaultManifest.getMainAttributes().putValue( "Manifest-Version", "1.0" ); + defaultManifest.getMainAttributes().putValue("Manifest-Version", "1.0"); String createdBy = "Plexus Archiver"; final String plexusArchiverVersion = getArchiverVersion(); - if ( plexusArchiverVersion != null ) - { + if (plexusArchiverVersion != null) { createdBy += " " + plexusArchiverVersion; } - defaultManifest.getMainAttributes().putValue( "Created-By", createdBy ); + defaultManifest.getMainAttributes().putValue("Created-By", createdBy); return defaultManifest; } - static String getArchiverVersion() - { - try - { - final Properties properties = PropertyUtils.loadProperties( JdkManifestFactory.class.getResourceAsStream( - "/META-INF/maven/org.codehaus.plexus/plexus-archiver/pom.properties" ) ); + static String getArchiverVersion() { + try { + final Properties properties = PropertyUtils.loadProperties(JdkManifestFactory.class.getResourceAsStream( + "/META-INF/maven/org.codehaus.plexus/plexus-archiver/pom.properties")); - return properties != null - ? properties.getProperty( "version" ) - : null; + return properties != null ? properties.getProperty("version") : null; - } - catch ( final IOException e ) - { - throw new AssertionError( e ); + } catch (final IOException e) { + throw new AssertionError(e); } } - public static void merge( java.util.jar.Manifest target, java.util.jar.Manifest other, boolean overwriteMain ) - { - if ( other != null ) - { + public static void merge(java.util.jar.Manifest target, java.util.jar.Manifest other, boolean overwriteMain) { + if (other != null) { final Attributes mainAttributes = target.getMainAttributes(); - if ( overwriteMain ) - { + if (overwriteMain) { mainAttributes.clear(); - mainAttributes.putAll( other.getMainAttributes() ); - } - else - { - mergeAttributes( mainAttributes, other.getMainAttributes() ); + mainAttributes.putAll(other.getMainAttributes()); + } else { + mergeAttributes(mainAttributes, other.getMainAttributes()); } - for ( Map.Entry o : other.getEntries().entrySet() ) - { - Attributes ourSection = target.getAttributes( o.getKey() ); + for (Map.Entry o : other.getEntries().entrySet()) { + Attributes ourSection = target.getAttributes(o.getKey()); Attributes otherSection = o.getValue(); - if ( ourSection == null ) - { - if ( otherSection != null ) - { - target.getEntries().put( o.getKey(), (Attributes) otherSection.clone() ); + if (ourSection == null) { + if (otherSection != null) { + target.getEntries().put(o.getKey(), (Attributes) otherSection.clone()); } - } - else - { - mergeAttributes( ourSection, otherSection ); + } else { + mergeAttributes(ourSection, otherSection); } } } @@ -108,15 +89,12 @@ public static void merge( java.util.jar.Manifest target, java.util.jar.Manifest * @param target The target manifest of the merge * @param section the section to be merged with this one. */ - public static void mergeAttributes( java.util.jar.Attributes target, java.util.jar.Attributes section ) - { - for ( Object o : section.keySet() ) - { + public static void mergeAttributes(java.util.jar.Attributes target, java.util.jar.Attributes section) { + for (Object o : section.keySet()) { java.util.jar.Attributes.Name key = (Attributes.Name) o; - final Object value = section.get( o ); + final Object value = section.get(o); // the merge file always wins - target.put( key, value ); + target.put(key, value); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/Manifest.java b/src/main/java/org/codehaus/plexus/archiver/jar/Manifest.java index 587bdebb1..db6534fa5 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/Manifest.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/Manifest.java @@ -32,6 +32,7 @@ import java.util.StringTokenizer; import java.util.Vector; import java.util.jar.Attributes; + import org.codehaus.plexus.archiver.ArchiverException; /** @@ -49,9 +50,7 @@ * * @since Ant 1.4 */ -public class Manifest - extends java.util.jar.Manifest implements Iterable -{ +public class Manifest extends java.util.jar.Manifest implements Iterable { /** * The Name Attribute is the first in a named section @@ -84,8 +83,7 @@ public class Manifest */ static final String EOL = "\r\n"; - public static class BaseAttribute - { + public static class BaseAttribute { /** * The attribute's name @@ -97,44 +95,35 @@ public static class BaseAttribute * * @return the attribute's name. */ - public String getName() - { + public String getName() { return name; } @Override - public boolean equals( Object o ) - { - if ( this == o ) - { + public boolean equals(Object o) { + if (this == o) { return true; } - if ( !( o instanceof BaseAttribute ) ) - { + if (!(o instanceof BaseAttribute)) { return false; } BaseAttribute that = (BaseAttribute) o; - return !( name != null ? !name.equals( that.name ) : that.name != null ); - + return !(name != null ? !name.equals(that.name) : that.name != null); } @Override - public int hashCode() - { + public int hashCode() { return name != null ? name.hashCode() : 0; } - } /** * An attribute for the manifest. * Those attributes that are not nested into a section will be added to the "Main" section. */ - public static class Attribute - extends BaseAttribute implements Iterable - { + public static class Attribute extends BaseAttribute implements Iterable { /** * The attribute's value @@ -150,9 +139,7 @@ public static class Attribute /** * Construct an empty attribute */ - public Attribute() - { - } + public Attribute() {} /** * Construct a manifest by specifying its name and value @@ -160,15 +147,13 @@ public Attribute() * @param name the attribute's name * @param value the Attribute's value */ - public Attribute( String name, String value ) - { + public Attribute(String name, String value) { this.name = name; - setValue( value ); + setValue(value); } @Override - public Iterator iterator() - { + public Iterator iterator() { return values.iterator(); } @@ -176,8 +161,7 @@ public Iterator iterator() * @see java.lang.Object#hashCode */ @Override - public int hashCode() - { + public int hashCode() { int hashCode = super.hashCode(); hashCode += values.hashCode(); return hashCode; @@ -187,19 +171,15 @@ public int hashCode() * @see java.lang.Object#equals */ @Override - public boolean equals( Object rhs ) - { - if ( super.equals( rhs ) ) - { + public boolean equals(Object rhs) { + if (super.equals(rhs)) { return false; } - if ( rhs == null || rhs.getClass() != getClass() ) - { + if (rhs == null || rhs.getClass() != getClass()) { return false; } - if ( rhs == this ) - { + if (rhs == this) { return true; } @@ -207,13 +187,11 @@ public boolean equals( Object rhs ) String lhsKey = getKey(); String rhsKey = rhsAttribute.getKey(); //noinspection SimplifiableIfStatement,ConstantConditions - if ( ( lhsKey == null && rhsKey != null ) || ( lhsKey != null && rhsKey == null ) || !lhsKey.equals( - rhsKey ) ) - { + if ((lhsKey == null && rhsKey != null) || (lhsKey != null && rhsKey == null) || !lhsKey.equals(rhsKey)) { return false; } - return rhsAttribute.values != null && values.equals( rhsAttribute.values ); + return rhsAttribute.values != null && values.equals(rhsAttribute.values); } /** @@ -221,8 +199,7 @@ public boolean equals( Object rhs ) * * @param name the attribute's name */ - public void setName( String name ) - { + public void setName(String name) { this.name = name; } @@ -231,9 +208,8 @@ public void setName( String name ) * * @return the attribute's key. */ - public String getKey() - { - return getKey( name ); + public String getKey() { + return getKey(name); } /** @@ -241,13 +217,11 @@ public String getKey() * * @return the attribute's key. */ - private static String getKey( String name ) - { - if ( name == null ) - { + private static String getKey(String name) { + if (name == null) { return null; } - return name.toLowerCase( Locale.ENGLISH ); + return name.toLowerCase(Locale.ENGLISH); } /** @@ -255,16 +229,12 @@ private static String getKey( String name ) * * @param value the attribute's value */ - public void setValue( String value ) - { - if ( currentIndex >= values.size() ) - { - values.addElement( value ); + public void setValue(String value) { + if (currentIndex >= values.size()) { + values.addElement(value); currentIndex = values.size() - 1; - } - else - { - values.setElementAt( value, currentIndex ); + } else { + values.setElementAt(value, currentIndex); } } @@ -273,16 +243,13 @@ public void setValue( String value ) * * @return the attribute's value. */ - public String getValue() - { - if ( values.size() == 0 ) - { + public String getValue() { + if (values.size() == 0) { return null; } String fullValue = ""; - for ( String value : values ) - { + for (String value : values) { fullValue += value + " "; } return fullValue.trim(); @@ -293,10 +260,9 @@ public String getValue() * * @param value the attribute's additional value */ - public void addValue( String value ) - { + public void addValue(String value) { currentIndex++; - setValue( value ); + setValue(value); } /** @@ -306,12 +272,9 @@ public void addValue( String value ) * * @throws IOException if the attribute value cannot be written */ - void write( Writer writer ) - throws IOException - { - for ( String value : values ) - { - writeValue( writer, value ); + void write(Writer writer) throws IOException { + for (String value : values) { + writeValue(writer, value); } } @@ -323,18 +286,15 @@ void write( Writer writer ) * * @throws IOException if the attribute value cannot be written */ - private void writeValue( Writer writer, String value ) - throws IOException - { + private void writeValue(Writer writer, String value) throws IOException { String nameValue = name + ": " + value; - StringTokenizer tokenizer = new StringTokenizer( nameValue, "\n\r" ); + StringTokenizer tokenizer = new StringTokenizer(nameValue, "\n\r"); String prefix = ""; - while ( tokenizer.hasMoreTokens() ) - { - writeLine( writer, prefix + tokenizer.nextToken() ); + while (tokenizer.hasMoreTokens()) { + writeLine(writer, prefix + tokenizer.nextToken()); prefix = " "; } } @@ -347,99 +307,79 @@ private void writeValue( Writer writer, String value ) * * @throws java.io.IOException when Io excepts */ - private void writeLine( Writer writer, String line ) - throws IOException - { + private void writeLine(Writer writer, String line) throws IOException { // Make sure we have at most 70 bytes in UTF-8 as specified excluding line break - while ( line.getBytes( "UTF-8" ).length > MAX_SECTION_LENGTH ) - { + while (line.getBytes("UTF-8").length > MAX_SECTION_LENGTH) { // Try to find a MAX_SECTION_LENGTH // Use the minimum because we operate on at most chars and not bytes here otherwise // if we have more bytes than chars we will die in an IndexOutOfBoundsException. - int breakIndex = Math.min( line.length(), MAX_SECTION_LENGTH ); - String section = line.substring( 0, breakIndex ); - while ( section.getBytes( "UTF-8" ).length > MAX_SECTION_LENGTH && breakIndex > 0 ) - { + int breakIndex = Math.min(line.length(), MAX_SECTION_LENGTH); + String section = line.substring(0, breakIndex); + while (section.getBytes("UTF-8").length > MAX_SECTION_LENGTH && breakIndex > 0) { breakIndex--; - section = line.substring( 0, breakIndex ); + section = line.substring(0, breakIndex); } - if ( breakIndex == 0 ) - { - throw new IOException( "Unable to write manifest line " + line ); + if (breakIndex == 0) { + throw new IOException("Unable to write manifest line " + line); } - writer.write( section + EOL ); - line = " " + line.substring( breakIndex ); + writer.write(section + EOL); + line = " " + line.substring(breakIndex); } - writer.write( line + EOL ); + writer.write(line + EOL); } - } - public class ExistingAttribute - extends Attribute implements Iterable - { + public class ExistingAttribute extends Attribute implements Iterable { private final Attributes attributes; - public ExistingAttribute( Attributes attributes, String name ) - { + public ExistingAttribute(Attributes attributes, String name) { this.attributes = attributes; this.name = name; } @Override - public Iterator iterator() - { - return getKeys( attributes ).iterator(); + public Iterator iterator() { + return getKeys(attributes).iterator(); } @Override - public void setName( String name ) - { - throw new UnsupportedOperationException( "Cant do this" ); + public void setName(String name) { + throw new UnsupportedOperationException("Cant do this"); } @Override - public String getKey() - { + public String getKey() { return name; } @Override - public void setValue( String value ) - { - attributes.putValue( name, value ); + public void setValue(String value) { + attributes.putValue(name, value); } @Override - public String getValue() - { - return attributes.getValue( name ); + public String getValue() { + return attributes.getValue(name); } @Override - public void addValue( String value ) - { + public void addValue(String value) { String value1 = getValue(); - value1 = ( value1 != null ) ? " " + value : value; - setValue( value1 ); + value1 = (value1 != null) ? " " + value : value; + setValue(value1); } @Override - void write( Writer writer ) - throws IOException - { - throw new UnsupportedOperationException( "Cant do this" ); + void write(Writer writer) throws IOException { + throw new UnsupportedOperationException("Cant do this"); } - } - private static Collection getKeys( Attributes attributes ) - { + private static Collection getKeys(Attributes attributes) { Collection result = new ArrayList(); - for ( Object objectObjectEntry : attributes.keySet() ) - { - result.add( objectObjectEntry.toString() ); + for (Object objectObjectEntry : attributes.keySet()) { + result.add(objectObjectEntry.toString()); } return result; } @@ -449,8 +389,7 @@ private static Collection getKeys( Attributes attributes ) * A section consists of a set of attribute values, * separated from other sections by a blank line. */ - public static class Section implements Iterable - { + public static class Section implements Iterable { /** * Warnings for this section @@ -478,8 +417,7 @@ public static class Section implements Iterable * * @param name the section's name */ - public void setName( String name ) - { + public void setName(String name) { this.name = name; } @@ -488,14 +426,12 @@ public void setName( String name ) * * @return the section's name. */ - public String getName() - { + public String getName() { return name; } @Override - public Iterator iterator() - { + public Iterator iterator() { return attributes.keySet().iterator(); } @@ -508,9 +444,8 @@ public Iterator iterator() * single-valued, otherwise a Vector of Manifest.Attribute * instances. */ - public Attribute getAttribute( String attributeName ) - { - return attributes.get( attributeName.toLowerCase( Locale.ENGLISH ) ); + public Attribute getAttribute(String attributeName) { + return attributes.get(attributeName.toLowerCase(Locale.ENGLISH)); } /** @@ -520,15 +455,12 @@ public Attribute getAttribute( String attributeName ) * * @throws ManifestException if the attribute is not valid. */ - public void addConfiguredAttribute( Attribute attribute ) - throws ManifestException - { - String check = addAttributeAndCheck( attribute ); - if ( check != null ) - { + public void addConfiguredAttribute(Attribute attribute) throws ManifestException { + String check = addAttributeAndCheck(attribute); + if (check != null) { throw new ManifestException( - "Specify the section name using " + "the \"name\" attribute of the
element rather " - + "than using a \"Name\" manifest attribute" ); + "Specify the section name using " + "the \"name\" attribute of the
element rather " + + "than using a \"Name\" manifest attribute"); } } @@ -543,59 +475,43 @@ public void addConfiguredAttribute( Attribute attribute ) * @throws ManifestException if the attribute already * exists in this section. */ - public String addAttributeAndCheck( Attribute attribute ) - throws ManifestException - { - if ( attribute.getName() == null || attribute.getValue() == null ) - { - throw new ManifestException( "Attributes must have name and value" ); + public String addAttributeAndCheck(Attribute attribute) throws ManifestException { + if (attribute.getName() == null || attribute.getValue() == null) { + throw new ManifestException("Attributes must have name and value"); } - if ( attribute.getKey().equalsIgnoreCase( ATTRIBUTE_NAME ) ) - { - warnings.addElement( - "\"" + ATTRIBUTE_NAME + "\" attributes " + "should not occur in the main section and must be the " + if (attribute.getKey().equalsIgnoreCase(ATTRIBUTE_NAME)) { + warnings.addElement("\"" + ATTRIBUTE_NAME + "\" attributes " + + "should not occur in the main section and must be the " + "first element in all other sections: \"" + attribute.getName() + ": " + attribute.getValue() - + "\"" ); + + "\""); return attribute.getValue(); } - if ( attribute.getKey().startsWith( Attribute.getKey( ATTRIBUTE_FROM ) ) ) - { - warnings.addElement( "Manifest attributes should not start " + "with \"" + ATTRIBUTE_FROM + "\" in \"" - + attribute.getName() + ": " + attribute.getValue() + "\"" ); - } - else - { + if (attribute.getKey().startsWith(Attribute.getKey(ATTRIBUTE_FROM))) { + warnings.addElement("Manifest attributes should not start " + "with \"" + ATTRIBUTE_FROM + "\" in \"" + + attribute.getName() + ": " + attribute.getValue() + "\""); + } else { // classpath attributes go into a vector String attributeKey = attribute.getKey(); - if ( attributeKey.equalsIgnoreCase( ManifestConstants.ATTRIBUTE_CLASSPATH ) ) - { - Attribute classpathAttribute = attributes.get( attributeKey ); - - if ( classpathAttribute == null ) - { - storeAttribute( attribute ); - } - else - { - warnings.addElement( "Multiple Class-Path attributes " + "are supported but violate the Jar " - + "specification and may not be correctly " - + "processed in all environments" ); - - for ( String value : attribute ) - { - classpathAttribute.addValue( value ); + if (attributeKey.equalsIgnoreCase(ManifestConstants.ATTRIBUTE_CLASSPATH)) { + Attribute classpathAttribute = attributes.get(attributeKey); + + if (classpathAttribute == null) { + storeAttribute(attribute); + } else { + warnings.addElement("Multiple Class-Path attributes " + "are supported but violate the Jar " + + "specification and may not be correctly " + + "processed in all environments"); + + for (String value : attribute) { + classpathAttribute.addValue(value); } } - } - else if ( attributes.containsKey( attributeKey ) ) - { - throw new ManifestException( "The attribute \"" + attribute.getName() + "\" may not occur more " - + "than once in the same section" ); - } - else - { - storeAttribute( attribute ); + } else if (attributes.containsKey(attributeKey)) { + throw new ManifestException("The attribute \"" + attribute.getName() + "\" may not occur more " + + "than once in the same section"); + } else { + storeAttribute(attribute); } } return null; @@ -606,18 +522,15 @@ else if ( attributes.containsKey( attributeKey ) ) * * @param attribute the attribute to be stored */ - protected void storeAttribute( Attribute attribute ) - { - if ( attribute == null ) - { + protected void storeAttribute(Attribute attribute) { + if (attribute == null) { return; } String attributeKey = attribute.getKey(); - attributes.put( attributeKey, attribute ); - if ( !attributeIndex.contains( attributeKey ) ) - { - attributeIndex.addElement( attributeKey ); + attributes.put(attributeKey, attribute); + if (!attributeIndex.contains(attributeKey)) { + attributeIndex.addElement(attributeKey); } } @@ -626,8 +539,7 @@ protected void storeAttribute( Attribute attribute ) * * @return an Enumeration of warning strings. */ - public Enumeration getWarnings() - { + public Enumeration getWarnings() { return warnings.elements(); } @@ -635,12 +547,10 @@ public Enumeration getWarnings() * @see java.lang.Object#hashCode */ @Override - public int hashCode() - { + public int hashCode() { int hashCode = 0; - if ( name != null ) - { + if (name != null) { hashCode += name.hashCode(); } @@ -652,98 +562,76 @@ public int hashCode() * @see java.lang.Object#equals */ @Override - public boolean equals( Object rhs ) - { - if ( rhs == null || rhs.getClass() != getClass() ) - { + public boolean equals(Object rhs) { + if (rhs == null || rhs.getClass() != getClass()) { return false; } - if ( rhs == this ) - { + if (rhs == this) { return true; } Section rhsSection = (Section) rhs; - return rhsSection.attributes != null && attributes.equals( rhsSection.attributes ); + return rhsSection.attributes != null && attributes.equals(rhsSection.attributes); } - } - public class ExistingSection implements Iterable - { + public class ExistingSection implements Iterable { private final Attributes backingAttributes; private final String sectionName; - public ExistingSection( Attributes backingAttributes, String sectionName ) - { + public ExistingSection(Attributes backingAttributes, String sectionName) { this.backingAttributes = backingAttributes; this.sectionName = sectionName; } @Override - public Iterator iterator() - { - return getKeys( backingAttributes ).iterator(); + public Iterator iterator() { + return getKeys(backingAttributes).iterator(); } - public ExistingAttribute getAttribute( String attributeName ) - { - Attributes.Name name = new Attributes.Name( attributeName ); - return backingAttributes.containsKey( name ) - ? new ExistingAttribute( backingAttributes, attributeName ) - : null; - + public ExistingAttribute getAttribute(String attributeName) { + Attributes.Name name = new Attributes.Name(attributeName); + return backingAttributes.containsKey(name) ? new ExistingAttribute(backingAttributes, attributeName) : null; } - public String getName() - { + public String getName() { return sectionName; } - public String getAttributeValue( String attributeName ) - { - return backingAttributes.getValue( attributeName ); + public String getAttributeValue(String attributeName) { + return backingAttributes.getValue(attributeName); } - public void removeAttribute( String attributeName ) - { - backingAttributes.remove( new Attributes.Name( attributeName ) ); + public void removeAttribute(String attributeName) { + backingAttributes.remove(new Attributes.Name(attributeName)); } - public void addConfiguredAttribute( Attribute attribute ) - throws ManifestException - { - backingAttributes.putValue( attribute.getName(), attribute.getValue() ); + public void addConfiguredAttribute(Attribute attribute) throws ManifestException { + backingAttributes.putValue(attribute.getName(), attribute.getValue()); } - public String addAttributeAndCheck( Attribute attribute ) - throws ManifestException - { - return remap( backingAttributes, attribute ); + public String addAttributeAndCheck(Attribute attribute) throws ManifestException { + return remap(backingAttributes, attribute); } @Override - public int hashCode() - { + public int hashCode() { return backingAttributes.hashCode(); } @Override - public boolean equals( Object rhs ) - { - return rhs instanceof ExistingSection && backingAttributes.equals( - ( (ExistingSection) rhs ).backingAttributes ); + public boolean equals(Object rhs) { + return rhs instanceof ExistingSection + && backingAttributes.equals(((ExistingSection) rhs).backingAttributes); } - } @Override - public Iterator iterator() - { + public Iterator iterator() { return getEntries().keySet().iterator(); } @@ -764,24 +652,20 @@ public Iterator iterator() * @throws ArchiverException * if there is a problem loading the default manifest */ - public static Manifest getDefaultManifest( boolean minimalDefaultManifest ) - throws ArchiverException - { + public static Manifest getDefaultManifest(boolean minimalDefaultManifest) throws ArchiverException { final Manifest defaultManifest = new Manifest(); - defaultManifest.getMainAttributes().putValue( "Manifest-Version", "1.0" ); + defaultManifest.getMainAttributes().putValue("Manifest-Version", "1.0"); - if ( !minimalDefaultManifest ) - { + if (!minimalDefaultManifest) { String createdBy = "Plexus Archiver"; final String plexusArchiverVersion = JdkManifestFactory.getArchiverVersion(); - if ( plexusArchiverVersion != null ) - { + if (plexusArchiverVersion != null) { createdBy += " " + plexusArchiverVersion; } - defaultManifest.getMainAttributes().putValue( "Created-By", createdBy ); + defaultManifest.getMainAttributes().putValue("Created-By", createdBy); } return defaultManifest; @@ -790,23 +674,19 @@ public static Manifest getDefaultManifest( boolean minimalDefaultManifest ) /** * @see #getDefaultManifest(boolean) */ - public static Manifest getDefaultManifest() - throws ArchiverException - { - return getDefaultManifest( false ); + public static Manifest getDefaultManifest() throws ArchiverException { + return getDefaultManifest(false); } /** * Construct an empty manifest */ - public Manifest() - { + public Manifest() { setManifestVersion(); } - private void setManifestVersion() - { - getMainAttributes().put( Attributes.Name.MANIFEST_VERSION, "1.0" ); + private void setManifestVersion() { + getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); } /** @@ -821,17 +701,13 @@ private void setManifestVersion() * {@link #Manifest(InputStream)}. Will be removed in 4.0. */ @Deprecated - public Manifest( Reader r ) - throws ManifestException, IOException - { - super( getInputStream( r ) ); + public Manifest(Reader r) throws ManifestException, IOException { + super(getInputStream(r)); setManifestVersion(); } - public Manifest( InputStream is ) - throws IOException - { - super( is ); + public Manifest(InputStream is) throws IOException { + super(is); setManifestVersion(); } @@ -842,30 +718,24 @@ public Manifest( InputStream is ) * * @throws ManifestException if the secti0on is not valid. */ - public void addConfiguredSection( Section section ) - throws ManifestException - { + public void addConfiguredSection(Section section) throws ManifestException { String sectionName = section.getName(); - if ( sectionName == null ) - { - throw new ManifestException( "Sections must have a name" ); + if (sectionName == null) { + throw new ManifestException("Sections must have a name"); } - Attributes attributes = getOrCreateAttributes( sectionName ); - for ( String s : section.attributes.keySet() ) - { + Attributes attributes = getOrCreateAttributes(sectionName); + for (String s : section.attributes.keySet()) { - Attribute attribute = section.getAttribute( s ); - attributes.putValue( attribute.getName(), attribute.getValue() ); + Attribute attribute = section.getAttribute(s); + attributes.putValue(attribute.getName(), attribute.getValue()); } } - private Attributes getOrCreateAttributes( String name ) - { - Attributes attributes = getAttributes( name ); - if ( attributes == null ) - { + private Attributes getOrCreateAttributes(String name) { + Attributes attributes = getAttributes(name); + if (attributes == null) { attributes = new Attributes(); - getEntries().put( name, attributes ); + getEntries().put(name, attributes); } return attributes; } @@ -877,10 +747,8 @@ private Attributes getOrCreateAttributes( String name ) * * @throws ManifestException if the attribute is not valid. */ - public void addConfiguredAttribute( Attribute attribute ) - throws ManifestException - { - remap( getMainAttributes(), attribute ); + public void addConfiguredAttribute(Attribute attribute) throws ManifestException { + remap(getMainAttributes(), attribute); } /** @@ -890,13 +758,11 @@ public void addConfiguredAttribute( Attribute attribute ) * * @throws IOException if the manifest cannot be written */ - public void write( Writer writer ) - throws IOException - { + public void write(Writer writer) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); - super.write( byteArrayOutputStream ); + super.write(byteArrayOutputStream); // We know that UTF-8 is the encoding of the JAR file specification - writer.write( byteArrayOutputStream.toString( "UTF-8" ) ); + writer.write(byteArrayOutputStream.toString("UTF-8")); } /** @@ -906,15 +772,11 @@ public void write( Writer writer ) * appears in a Manifest file. */ @Override - public String toString() - { + public String toString() { StringWriter sw = new StringWriter(); - try - { - write( sw ); - } - catch ( IOException e ) - { + try { + write(sw); + } catch (IOException e) { return null; } return sw.toString(); @@ -925,14 +787,12 @@ public String toString() * * @return an enumeration of warning strings */ - Enumeration getWarnings() - { + Enumeration getWarnings() { Vector warnings = new Vector(); Enumeration warnEnum = mainSection.getWarnings(); - while ( warnEnum.hasMoreElements() ) - { - warnings.addElement( warnEnum.nextElement() ); + while (warnEnum.hasMoreElements()) { + warnings.addElement(warnEnum.nextElement()); } return warnings.elements(); @@ -943,11 +803,10 @@ Enumeration getWarnings() * * @return the manifest's version string */ - public String getManifestVersion() - { + public String getManifestVersion() { /* - The version of this manifest - */ + The version of this manifest + */ return DEFAULT_MANIFEST_VERSION; } @@ -956,9 +815,8 @@ public String getManifestVersion() * * @return the main section of the manifest */ - public ExistingSection getMainSection() - { - return new ExistingSection( getMainAttributes(), null ); + public ExistingSection getMainSection() { + return new ExistingSection(getMainAttributes(), null); } /** @@ -969,62 +827,45 @@ public ExistingSection getMainSection() * @return the specified section or null if that section * does not exist in the manifest */ - public ExistingSection getSection( String name ) - { - Attributes attributes = getAttributes( name ); - if ( attributes != null ) - { - return new ExistingSection( attributes, name ); + public ExistingSection getSection(String name) { + Attributes attributes = getAttributes(name); + if (attributes != null) { + return new ExistingSection(attributes, name); } return null; } @Deprecated - private static InputStream getInputStream( Reader r ) - throws IOException - { + private static InputStream getInputStream(Reader r) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int read; - while ( ( read = r.read() ) != -1 ) - { - byteArrayOutputStream.write( read ); + while ((read = r.read()) != -1) { + byteArrayOutputStream.write(read); } - return new ByteArrayInputStream( byteArrayOutputStream.toByteArray() ); + return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } - public static String remap( Attributes backingAttributes, Attribute attribute ) - throws ManifestException - { - if ( attribute.getKey() == null || attribute.getValue() == null ) - { - throw new ManifestException( "Attributes must have name and value" ); + public static String remap(Attributes backingAttributes, Attribute attribute) throws ManifestException { + if (attribute.getKey() == null || attribute.getValue() == null) { + throw new ManifestException("Attributes must have name and value"); } String attributeKey = attribute.getKey(); - if ( attributeKey.equalsIgnoreCase( ManifestConstants.ATTRIBUTE_CLASSPATH ) ) - { - String classpathAttribute = backingAttributes.getValue( attributeKey ); + if (attributeKey.equalsIgnoreCase(ManifestConstants.ATTRIBUTE_CLASSPATH)) { + String classpathAttribute = backingAttributes.getValue(attributeKey); - if ( classpathAttribute == null ) - { + if (classpathAttribute == null) { classpathAttribute = attribute.getValue(); - } - else - { + } else { classpathAttribute += " " + attribute.getValue(); } - backingAttributes.putValue( ManifestConstants.ATTRIBUTE_CLASSPATH, classpathAttribute ); - } - else - { - backingAttributes.putValue( attribute.getName(), attribute.getValue() ); - if ( attribute.getKey().equalsIgnoreCase( ATTRIBUTE_NAME ) ) - { + backingAttributes.putValue(ManifestConstants.ATTRIBUTE_CLASSPATH, classpathAttribute); + } else { + backingAttributes.putValue(attribute.getName(), attribute.getValue()); + if (attribute.getKey().equalsIgnoreCase(ATTRIBUTE_NAME)) { return attribute.getValue(); } } return null; - } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/ManifestConstants.java b/src/main/java/org/codehaus/plexus/archiver/jar/ManifestConstants.java index eeb9b10a4..348891a4d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/ManifestConstants.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/ManifestConstants.java @@ -20,8 +20,7 @@ * Manifest constants * Not part of any public API */ -class ManifestConstants -{ +class ManifestConstants { /** * The standard manifest version header @@ -52,5 +51,4 @@ class ManifestConstants * Default Manifest version if one is not specified */ public static final String DEFAULT_MANIFEST_VERSION = "1.0"; - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/ManifestException.java b/src/main/java/org/codehaus/plexus/archiver/jar/ManifestException.java index 9ed2c650e..cddc8771e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/ManifestException.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/ManifestException.java @@ -19,18 +19,14 @@ /** * Exception thrown indicating problems in a JAR Manifest */ -public class ManifestException - extends Exception -{ +public class ManifestException extends Exception { /** * Constructs an exception with the given descriptive message. * * @param msg Description of or information about the exception. */ - public ManifestException( String msg ) - { - super( msg ); + public ManifestException(String msg) { + super(msg); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/ModularJarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/jar/ModularJarArchiver.java index 89cd6c963..93719ca29 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/ModularJarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/ModularJarArchiver.java @@ -36,17 +36,14 @@ * * @since 3.6 */ -public abstract class ModularJarArchiver - extends JarArchiver -{ +public abstract class ModularJarArchiver extends JarArchiver { private String moduleMainClass; private String manifestMainClass; private String moduleVersion; - public String getModuleMainClass() - { + public String getModuleMainClass() { return moduleMainClass; } @@ -60,13 +57,11 @@ public String getModuleMainClass() * * @param moduleMainClass the module main class. */ - public void setModuleMainClass( String moduleMainClass ) - { + public void setModuleMainClass(String moduleMainClass) { this.moduleMainClass = moduleMainClass; } - public String getModuleVersion() - { + public String getModuleVersion() { return moduleVersion; } @@ -77,8 +72,7 @@ public String getModuleVersion() * * @param moduleVersion the module version. */ - public void setModuleVersion( String moduleVersion ) - { + public void setModuleVersion(String moduleVersion) { this.moduleVersion = moduleVersion; } @@ -91,28 +85,23 @@ public void setModuleVersion( String moduleVersion ) * * @return the "Main-Class" attribute of the manifest */ - protected String getManifestMainClass() - { + protected String getManifestMainClass() { return manifestMainClass; } @Override - protected Manifest createManifest() - { + protected Manifest createManifest() { Manifest manifest = super.createManifest(); - if ( manifest != null ) - { - manifestMainClass = manifest.getMainAttributes() - .getValue( "Main-Class" ); + if (manifest != null) { + manifestMainClass = manifest.getMainAttributes().getValue("Main-Class"); } return manifest; } @Override - public void reset() - { + public void reset() { // We want to be sure that on multiple run // the latest manifest is used, so lets // reset it to null diff --git a/src/main/java/org/codehaus/plexus/archiver/jar/PlexusIoJarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/jar/PlexusIoJarFileResourceCollection.java index 5f59aefee..6e88c8d4f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/jar/PlexusIoJarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/jar/PlexusIoJarFileResourceCollection.java @@ -17,32 +17,10 @@ import javax.inject.Named; -import java.io.Closeable; -import java.io.File; -import java.io.IOException; -import java.io.InputStream; -import java.net.URL; -import java.net.URLClassLoader; -import java.nio.charset.Charset; -import java.nio.charset.StandardCharsets; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.jar.JarFile; - -import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; -import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.archiver.zip.PlexusIoZipFileResourceCollection; -import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; -import org.codehaus.plexus.components.io.resources.AbstractPlexusIoArchiveResourceCollection; -import org.codehaus.plexus.components.io.resources.EncodingSupported; -import org.codehaus.plexus.components.io.resources.PlexusIoResource; -import org.codehaus.plexus.components.io.resources.PlexusIoURLResource; /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "jar" ) -public class PlexusIoJarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("jar") +public class PlexusIoJarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/manager/ArchiverManager.java b/src/main/java/org/codehaus/plexus/archiver/manager/ArchiverManager.java index 49e969e76..b2eb4abb5 100644 --- a/src/main/java/org/codehaus/plexus/archiver/manager/ArchiverManager.java +++ b/src/main/java/org/codehaus/plexus/archiver/manager/ArchiverManager.java @@ -16,10 +16,11 @@ */ package org.codehaus.plexus.archiver.manager; +import javax.annotation.Nonnull; + import java.io.File; import java.util.Collection; -import javax.annotation.Nonnull; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; @@ -27,37 +28,30 @@ /** * @author dantran */ -public interface ArchiverManager -{ +public interface ArchiverManager { @Nonnull - Archiver getArchiver( @Nonnull String archiverName ) - throws NoSuchArchiverException; + Archiver getArchiver(@Nonnull String archiverName) throws NoSuchArchiverException; @Nonnull - Archiver getArchiver( @Nonnull File file ) - throws NoSuchArchiverException; + Archiver getArchiver(@Nonnull File file) throws NoSuchArchiverException; @Nonnull Collection getAvailableArchivers(); @Nonnull - UnArchiver getUnArchiver( @Nonnull String unArchiverName ) - throws NoSuchArchiverException; + UnArchiver getUnArchiver(@Nonnull String unArchiverName) throws NoSuchArchiverException; @Nonnull - UnArchiver getUnArchiver( @Nonnull File file ) - throws NoSuchArchiverException; + UnArchiver getUnArchiver(@Nonnull File file) throws NoSuchArchiverException; @Nonnull Collection getAvailableUnArchivers(); @Nonnull - PlexusIoResourceCollection getResourceCollection( @Nonnull File file ) - throws NoSuchArchiverException; + PlexusIoResourceCollection getResourceCollection(@Nonnull File file) throws NoSuchArchiverException; @Nonnull - PlexusIoResourceCollection getResourceCollection( String unArchiverName ) - throws NoSuchArchiverException; + PlexusIoResourceCollection getResourceCollection(String unArchiverName) throws NoSuchArchiverException; @Nonnull Collection getAvailableResourceCollections(); diff --git a/src/main/java/org/codehaus/plexus/archiver/manager/DefaultArchiverManager.java b/src/main/java/org/codehaus/plexus/archiver/manager/DefaultArchiverManager.java index 1d8ec82e0..1ba38b459 100644 --- a/src/main/java/org/codehaus/plexus/archiver/manager/DefaultArchiverManager.java +++ b/src/main/java/org/codehaus/plexus/archiver/manager/DefaultArchiverManager.java @@ -16,17 +16,17 @@ */ package org.codehaus.plexus.archiver.manager; -import java.io.File; -import java.util.Collection; -import java.util.Locale; -import java.util.Map; - import javax.annotation.Nonnull; import javax.inject.Inject; import javax.inject.Named; import javax.inject.Provider; import javax.inject.Singleton; +import java.io.File; +import java.util.Collection; +import java.util.Locale; +import java.util.Map; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection; @@ -39,9 +39,7 @@ */ @Singleton @Named -public class DefaultArchiverManager - implements ArchiverManager -{ +public class DefaultArchiverManager implements ArchiverManager { private final Map> archivers; @@ -50,118 +48,99 @@ public class DefaultArchiverManager private final Map> plexusIoResourceCollections; @Inject - public DefaultArchiverManager( Map> archivers, - Map> unArchivers, - Map> plexusIoResourceCollections ) - { - this.archivers = requireNonNull( archivers ); - this.unArchivers = requireNonNull( unArchivers ); - this.plexusIoResourceCollections = requireNonNull( plexusIoResourceCollections ); + public DefaultArchiverManager( + Map> archivers, + Map> unArchivers, + Map> plexusIoResourceCollections) { + this.archivers = requireNonNull(archivers); + this.unArchivers = requireNonNull(unArchivers); + this.plexusIoResourceCollections = requireNonNull(plexusIoResourceCollections); } @Override - @Nonnull public Archiver getArchiver( @Nonnull String archiverName ) - throws NoSuchArchiverException - { - requireNonNull( archiverName ); - Provider archiver = archivers.get( archiverName ); - if ( archiver == null ) - { - throw new NoSuchArchiverException( archiverName ); + @Nonnull + public Archiver getArchiver(@Nonnull String archiverName) throws NoSuchArchiverException { + requireNonNull(archiverName); + Provider archiver = archivers.get(archiverName); + if (archiver == null) { + throw new NoSuchArchiverException(archiverName); } return archiver.get(); } @Override - @Nonnull public UnArchiver getUnArchiver( @Nonnull String unArchiverName ) - throws NoSuchArchiverException - { - requireNonNull( unArchiverName ); - Provider unArchiver = unArchivers.get( unArchiverName ); - if ( unArchiver == null ) - { - throw new NoSuchArchiverException( unArchiverName ); + @Nonnull + public UnArchiver getUnArchiver(@Nonnull String unArchiverName) throws NoSuchArchiverException { + requireNonNull(unArchiverName); + Provider unArchiver = unArchivers.get(unArchiverName); + if (unArchiver == null) { + throw new NoSuchArchiverException(unArchiverName); } return unArchiver.get(); } @Override - public @Nonnull - PlexusIoResourceCollection getResourceCollection( String resourceCollectionName ) - throws NoSuchArchiverException - { - requireNonNull( resourceCollectionName ); + public @Nonnull PlexusIoResourceCollection getResourceCollection(String resourceCollectionName) + throws NoSuchArchiverException { + requireNonNull(resourceCollectionName); Provider resourceCollection = - plexusIoResourceCollections.get( resourceCollectionName ); - if ( resourceCollection == null ) - { - throw new NoSuchArchiverException( resourceCollectionName ); + plexusIoResourceCollections.get(resourceCollectionName); + if (resourceCollection == null) { + throw new NoSuchArchiverException(resourceCollectionName); } return resourceCollection.get(); } - private static @Nonnull - String getFileExtension( @Nonnull File file ) - { + private static @Nonnull String getFileExtension(@Nonnull File file) { - String fileName = file.getName().toLowerCase( Locale.ROOT ); - String[] tokens = StringUtils.split( fileName, "." ); + String fileName = file.getName().toLowerCase(Locale.ROOT); + String[] tokens = StringUtils.split(fileName, "."); String archiveExt = ""; - if ( tokens.length == 2 ) { + if (tokens.length == 2) { archiveExt = tokens[1]; - } - else if ( tokens.length > 2 && "tar".equals( tokens[tokens.length - 2] ) ) - { + } else if (tokens.length > 2 && "tar".equals(tokens[tokens.length - 2])) { archiveExt = "tar." + tokens[tokens.length - 1]; - } - else if ( tokens.length > 2 ) { - archiveExt = tokens[tokens.length-1]; + } else if (tokens.length > 2) { + archiveExt = tokens[tokens.length - 1]; } return archiveExt; } @Override - @Nonnull public Archiver getArchiver( @Nonnull File file ) - throws NoSuchArchiverException - { - return getArchiver( getFileExtension( file ) ); + @Nonnull + public Archiver getArchiver(@Nonnull File file) throws NoSuchArchiverException { + return getArchiver(getFileExtension(file)); } @Override - public Collection getAvailableArchivers() - { + public Collection getAvailableArchivers() { return archivers.keySet(); } @Override - @Nonnull public UnArchiver getUnArchiver( @Nonnull File file ) - throws NoSuchArchiverException - { - return getUnArchiver( getFileExtension( file ) ); + @Nonnull + public UnArchiver getUnArchiver(@Nonnull File file) throws NoSuchArchiverException { + return getUnArchiver(getFileExtension(file)); } @Nonnull @Override - public Collection getAvailableUnArchivers() - { + public Collection getAvailableUnArchivers() { return unArchivers.keySet(); } @Override - @Nonnull public PlexusIoResourceCollection getResourceCollection( @Nonnull File file ) - throws NoSuchArchiverException - { - return getResourceCollection( getFileExtension( file ) ); + @Nonnull + public PlexusIoResourceCollection getResourceCollection(@Nonnull File file) throws NoSuchArchiverException { + return getResourceCollection(getFileExtension(file)); } @Nonnull @Override - public Collection getAvailableResourceCollections() - { + public Collection getAvailableResourceCollections() { return plexusIoResourceCollections.keySet(); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/manager/NoSuchArchiverException.java b/src/main/java/org/codehaus/plexus/archiver/manager/NoSuchArchiverException.java index 79f19d971..a9328605e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/manager/NoSuchArchiverException.java +++ b/src/main/java/org/codehaus/plexus/archiver/manager/NoSuchArchiverException.java @@ -19,22 +19,17 @@ /** * @author dantran */ -public class NoSuchArchiverException - extends Exception -{ +public class NoSuchArchiverException extends Exception { private final String archiverName; - public NoSuchArchiverException( String archiverName ) - { - super( "No such archiver: '" + archiverName + "'." ); + public NoSuchArchiverException(String archiverName) { + super("No such archiver: '" + archiverName + "'."); this.archiverName = archiverName; } - public String getArchiver() - { + public String getArchiver() { return archiverName; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/nar/NarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/nar/NarUnArchiver.java index 184d00c4d..d5ecee83f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/nar/NarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/nar/NarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "nar" ) -public class NarUnArchiver - extends ZipUnArchiver -{ +@Named("nar") +public class NarUnArchiver extends ZipUnArchiver { - public NarUnArchiver() - { - } + public NarUnArchiver() {} - public NarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public NarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/nar/PlexusIoNarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/nar/PlexusIoNarFileResourceCollection.java index 0235086e4..f6b6723b3 100644 --- a/src/main/java/org/codehaus/plexus/archiver/nar/PlexusIoNarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/nar/PlexusIoNarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "nar" ) -public class PlexusIoNarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("nar") +public class PlexusIoNarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/par/ParUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/par/ParUnArchiver.java index 0b28c5c37..5ced2b867 100644 --- a/src/main/java/org/codehaus/plexus/archiver/par/ParUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/par/ParUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "par" ) -public class ParUnArchiver - extends ZipUnArchiver -{ +@Named("par") +public class ParUnArchiver extends ZipUnArchiver { - public ParUnArchiver() - { - } + public ParUnArchiver() {} - public ParUnArchiver( File sourceFile ) - { - super( sourceFile ); + public ParUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/par/PlexusIoJarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/par/PlexusIoJarFileResourceCollection.java index 40751c93d..76ec6944a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/par/PlexusIoJarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/par/PlexusIoJarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "par" ) -public class PlexusIoJarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("par") +public class PlexusIoJarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/rar/PlexusIoRarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/rar/PlexusIoRarFileResourceCollection.java index 01e3d4cdd..ae0f8748b 100644 --- a/src/main/java/org/codehaus/plexus/archiver/rar/PlexusIoRarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/rar/PlexusIoRarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "rar" ) -public class PlexusIoRarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("rar") +public class PlexusIoRarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/rar/RarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/rar/RarArchiver.java index 39b17d258..f8706f0de 100644 --- a/src/main/java/org/codehaus/plexus/archiver/rar/RarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/rar/RarArchiver.java @@ -18,22 +18,12 @@ import javax.inject.Named; -import java.io.File; -import java.io.IOException; - -import org.codehaus.plexus.archiver.ArchiveEntry; -import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.jar.JarArchiver; -import org.codehaus.plexus.archiver.util.ResourceUtils; -import org.codehaus.plexus.archiver.zip.ConcurrentJarCreator; /** * Rar archiver. * * @see JarArchiver */ -@Named( "rar" ) -public class RarArchiver - extends JarArchiver -{ -} +@Named("rar") +public class RarArchiver extends JarArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/rar/RarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/rar/RarUnArchiver.java index f1c702905..ff13611ec 100644 --- a/src/main/java/org/codehaus/plexus/archiver/rar/RarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/rar/RarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "rar" ) -public class RarUnArchiver - extends ZipUnArchiver -{ +@Named("rar") +public class RarUnArchiver extends ZipUnArchiver { - public RarUnArchiver() - { - } + public RarUnArchiver() {} - public RarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public RarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualFileResource.java b/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualFileResource.java index 3c641a198..807ee1d2c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualFileResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualFileResource.java @@ -15,12 +15,13 @@ */ package org.codehaus.plexus.archiver.resources; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import javax.annotation.Nonnull; import org.codehaus.plexus.components.io.attributes.AttributeUtils; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; @@ -29,93 +30,73 @@ /** * A file resource that does not necessarily exist (anywhere). */ -public class PlexusIoVirtualFileResource - extends AbstractPlexusIoResource - implements ResourceAttributeSupplier -{ +public class PlexusIoVirtualFileResource extends AbstractPlexusIoResource implements ResourceAttributeSupplier { private final File file; - protected PlexusIoVirtualFileResource( File file, String name ) - { - super( name, file.lastModified(), file.length(), file.isFile(), file.isDirectory(), file.exists() ); + protected PlexusIoVirtualFileResource(File file, String name) { + super(name, file.lastModified(), file.length(), file.isFile(), file.isDirectory(), file.exists()); this.file = file; } - protected static String getName( File file ) - { - return file.getPath().replace( '\\', '/' ); + protected static String getName(File file) { + return file.getPath().replace('\\', '/'); } /** * Returns the resources file. */ - public File getFile() - { + public File getFile() { return file; } @Nonnull @Override - public InputStream getContents() - throws IOException - { - throw new UnsupportedOperationException( "We're not really sure we can do this" ); + public InputStream getContents() throws IOException { + throw new UnsupportedOperationException("We're not really sure we can do this"); } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return getFile().toURI().toURL(); } @Override - public long getSize() - { + public long getSize() { return getFile().length(); } @Override - public boolean isDirectory() - { + public boolean isDirectory() { return getFile().isDirectory(); } @Override - public boolean isExisting() - { + public boolean isExisting() { return getFile().exists(); } @Override - public boolean isFile() - { + public boolean isFile() { return getFile().isFile(); } @Override - public PlexusIoResourceAttributes getAttributes() - { + public PlexusIoResourceAttributes getAttributes() { return null; } @Override - public long getLastModified() - { - if ( file.exists() ) - { - return AttributeUtils.getLastModified( getFile() ); - } - else - { + public long getLastModified() { + if (file.exists()) { + return AttributeUtils.getLastModified(getFile()); + } else { return System.currentTimeMillis(); } } - @Override public boolean isSymbolicLink() - { + @Override + public boolean isSymbolicLink() { return getAttributes().isSymbolicLink(); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualSymlinkResource.java b/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualSymlinkResource.java index a41ba8f54..65918d633 100644 --- a/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualSymlinkResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/resources/PlexusIoVirtualSymlinkResource.java @@ -17,37 +17,31 @@ import java.io.File; import java.io.IOException; + import org.codehaus.plexus.components.io.attributes.SymlinkUtils; import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; /** * A symlink that does not necessarily exist (anywhere). */ -public class PlexusIoVirtualSymlinkResource extends PlexusIoVirtualFileResource - implements SymlinkDestinationSupplier -{ +public class PlexusIoVirtualSymlinkResource extends PlexusIoVirtualFileResource implements SymlinkDestinationSupplier { private final String symnlinkDestination; - public PlexusIoVirtualSymlinkResource( File symlinkFile, String symnlinkDestination ) - { - super( symlinkFile, getName( symlinkFile ) ); + public PlexusIoVirtualSymlinkResource(File symlinkFile, String symnlinkDestination) { + super(symlinkFile, getName(symlinkFile)); this.symnlinkDestination = symnlinkDestination; } @Override - public String getSymlinkDestination() - throws IOException - { + public String getSymlinkDestination() throws IOException { return symnlinkDestination == null - ? SymlinkUtils.readSymbolicLink( getFile() ).toString() - : symnlinkDestination; - + ? SymlinkUtils.readSymbolicLink(getFile()).toString() + : symnlinkDestination; } - @Override public boolean isSymbolicLink() - { + @Override + public boolean isSymbolicLink() { return true; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/sar/PlexusIoSarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/sar/PlexusIoSarFileResourceCollection.java index 5bea8ab49..650fb7e0a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/sar/PlexusIoSarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/sar/PlexusIoSarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "sar" ) -public class PlexusIoSarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("sar") +public class PlexusIoSarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/sar/SarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/sar/SarUnArchiver.java index 565e22e0e..64d92dd70 100644 --- a/src/main/java/org/codehaus/plexus/archiver/sar/SarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/sar/SarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "sar" ) -public class SarUnArchiver - extends ZipUnArchiver -{ +@Named("sar") +public class SarUnArchiver extends ZipUnArchiver { - public SarUnArchiver() - { - } + public SarUnArchiver() {} - public SarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public SarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/snappy/PlexusIoSnappyResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/snappy/PlexusIoSnappyResourceCollection.java index 9a973644f..a7f8d7156 100644 --- a/src/main/java/org/codehaus/plexus/archiver/snappy/PlexusIoSnappyResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/snappy/PlexusIoSnappyResourceCollection.java @@ -1,14 +1,14 @@ package org.codehaus.plexus.archiver.snappy; +import javax.annotation.Nonnull; +import javax.annotation.WillNotClose; +import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.HashMap; -import javax.annotation.Nonnull; -import javax.annotation.WillNotClose; -import javax.inject.Named; - import org.codehaus.plexus.archiver.util.Streams; import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; @@ -18,29 +18,22 @@ * Implementation of {@link org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection} for * snappy compressed files. */ -@Named( "snappy" ) -public class PlexusIoSnappyResourceCollection - extends PlexusIoCompressedFileResourceCollection -{ +@Named("snappy") +public class PlexusIoSnappyResourceCollection extends PlexusIoCompressedFileResourceCollection { @Nonnull @Override - protected @WillNotClose - InputStream getInputStream( File file ) - throws IOException - { - return SnappyUnArchiver.getSnappyInputStream( Streams.fileInputStream( file ) ); + protected @WillNotClose InputStream getInputStream(File file) throws IOException { + return SnappyUnArchiver.getSnappyInputStream(Streams.fileInputStream(file)); } - @Override protected PlexusIoResourceAttributes getAttributes( File file ) throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + @Override + protected PlexusIoResourceAttributes getAttributes(File file) throws IOException { + return new FileAttributes(file, new HashMap(), new HashMap()); } @Override - protected String getDefaultExtension() - { + protected String getDefaultExtension() { return ".snappy"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyArchiver.java b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyArchiver.java index ad5f33bb5..41b21a496 100644 --- a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyArchiver.java @@ -19,6 +19,7 @@ import javax.inject.Named; import java.io.IOException; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; @@ -28,53 +29,42 @@ /** * Snappy archiver. */ -@Named( "snappy" ) -public class SnappyArchiver - extends AbstractArchiver -{ +@Named("snappy") +public class SnappyArchiver extends AbstractArchiver { private final SnappyCompressor compressor = new SnappyCompressor(); @Override - public void execute() - throws ArchiverException, IOException - { - if ( !checkForced() ) - { + public void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } ArchiveEntry entry = iter.next(); - if ( iter.hasNext() ) - { - throw new ArchiverException( "There is more than one file in input." ); + if (iter.hasNext()) { + throw new ArchiverException("There is more than one file in input."); } - compressor.setSource( entry.getResource() ); - compressor.setDestFile( getDestFile() ); + compressor.setSource(entry.getResource()); + compressor.setDestFile(getDestFile()); compressor.compress(); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void close() - { + protected void close() { compressor.close(); } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "snappy"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyCompressor.java b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyCompressor.java index b24113815..3e932ad63 100644 --- a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyCompressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyCompressor.java @@ -17,18 +17,18 @@ package org.codehaus.plexus.archiver.snappy; import java.io.IOException; + import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Compressor; import org.iq80.snappy.SnappyFramedOutputStream; + import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; /** * Snappy compression */ -public class SnappyCompressor - extends Compressor -{ +public class SnappyCompressor extends Compressor { private SnappyFramedOutputStream zOut; @@ -36,36 +36,25 @@ public class SnappyCompressor * perform the Snappy compression operation. */ @Override - public void compress() - throws ArchiverException - { - try - { - zOut = new SnappyFramedOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) ); - compress( getSource(), zOut ); - } - catch ( IOException ioe ) - { + public void compress() throws ArchiverException { + try { + zOut = new SnappyFramedOutputStream(bufferedOutputStream(fileOutputStream(getDestFile()))); + compress(getSource(), zOut); + } catch (IOException ioe) { String msg = "Problem creating snappy " + ioe.getMessage(); - throw new ArchiverException( msg, ioe ); + throw new ArchiverException(msg, ioe); } } @Override - public void close() - { - try - { - if ( this.zOut != null ) - { + public void close() { + try { + if (this.zOut != null) { this.zOut.close(); zOut = null; } - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure closing target.", e ); + } catch (final IOException e) { + throw new ArchiverException("Failure closing target.", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyUnArchiver.java index ad0bbaef9..24c837ca7 100644 --- a/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/snappy/SnappyUnArchiver.java @@ -16,15 +16,17 @@ */ package org.codehaus.plexus.archiver.snappy; +import javax.annotation.Nonnull; +import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import javax.annotation.Nonnull; -import javax.inject.Named; import org.codehaus.plexus.archiver.AbstractUnArchiver; import org.codehaus.plexus.archiver.ArchiverException; import org.iq80.snappy.SnappyFramedInputStream; + import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.copyFully; @@ -34,56 +36,41 @@ /** * Unarchiver for snappy-compressed files. */ -@Named( "snappy" ) -public class SnappyUnArchiver - extends AbstractUnArchiver -{ +@Named("snappy") +public class SnappyUnArchiver extends AbstractUnArchiver { - private final static String OPERATION_SNAPPY = "snappy"; + private static final String OPERATION_SNAPPY = "snappy"; - public SnappyUnArchiver() - { - } + public SnappyUnArchiver() {} - public SnappyUnArchiver( File sourceFile ) - { - super( sourceFile ); + public SnappyUnArchiver(File sourceFile) { + super(sourceFile); } @Override - protected void execute() - throws ArchiverException - { - if ( getSourceFile().lastModified() > getDestFile().lastModified() ) - { - getLogger().info( - "Expanding " + getSourceFile().getAbsolutePath() + " to " + getDestFile().getAbsolutePath() ); + protected void execute() throws ArchiverException { + if (getSourceFile().lastModified() > getDestFile().lastModified()) { + getLogger() + .info("Expanding " + getSourceFile().getAbsolutePath() + " to " + + getDestFile().getAbsolutePath()); copyFully( - getSnappyInputStream( bufferedInputStream( fileInputStream( getSourceFile(), OPERATION_SNAPPY ) ) ), - bufferedOutputStream( fileOutputStream( getDestFile(), OPERATION_SNAPPY ) ), OPERATION_SNAPPY ); - + getSnappyInputStream(bufferedInputStream(fileInputStream(getSourceFile(), OPERATION_SNAPPY))), + bufferedOutputStream(fileOutputStream(getDestFile(), OPERATION_SNAPPY)), + OPERATION_SNAPPY); } } - public static @Nonnull - SnappyFramedInputStream getSnappyInputStream( InputStream bis ) - throws ArchiverException - { - try - { - return new SnappyFramedInputStream( bis, true ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Trouble creating Snappy compressor, invalid file ?", e ); + public static @Nonnull SnappyFramedInputStream getSnappyInputStream(InputStream bis) throws ArchiverException { + try { + return new SnappyFramedInputStream(bis, true); + } catch (IOException e) { + throw new ArchiverException("Trouble creating Snappy compressor, invalid file ?", e); } } @Override - protected void execute( String path, File outputDirectory ) - { - throw new UnsupportedOperationException( "Targeted extraction not supported in Snappy format." ); + protected void execute(String path, File outputDirectory) { + throw new UnsupportedOperationException("Targeted extraction not supported in Snappy format."); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/swc/PlexusIoSwcFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/swc/PlexusIoSwcFileResourceCollection.java index d83f73a82..96fd9df25 100644 --- a/src/main/java/org/codehaus/plexus/archiver/swc/PlexusIoSwcFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/swc/PlexusIoSwcFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "swc" ) -public class PlexusIoSwcFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("swc") +public class PlexusIoSwcFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/swc/SwcUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/swc/SwcUnArchiver.java index dc3b0d10e..dedf97135 100644 --- a/src/main/java/org/codehaus/plexus/archiver/swc/SwcUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/swc/SwcUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "swc" ) -public class SwcUnArchiver - extends ZipUnArchiver -{ +@Named("swc") +public class SwcUnArchiver extends ZipUnArchiver { - public SwcUnArchiver() - { - } + public SwcUnArchiver() {} - public SwcUnArchiver( File sourceFile ) - { - super( sourceFile ); + public SwcUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/BZip2TarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/BZip2TarFile.java index 5c9362021..3db1a7428 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/BZip2TarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/BZip2TarFile.java @@ -3,27 +3,23 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; + import org.codehaus.plexus.archiver.bzip2.BZip2UnArchiver; /** * Extension of {@link TarFile} for bzip2 compressed files. */ -public class BZip2TarFile extends TarFile -{ +public class BZip2TarFile extends TarFile { /** * Creates a new instance with the given file. */ - public BZip2TarFile( File file ) - { - super( file ); + public BZip2TarFile(File file) { + super(file); } @Override - protected InputStream getInputStream( File file ) - throws IOException - { - return BZip2UnArchiver.getBZip2InputStream( super.getInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return BZip2UnArchiver.getBZip2InputStream(super.getInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/GZipTarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/GZipTarFile.java index 8d4bdc675..25c54eefa 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/GZipTarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/GZipTarFile.java @@ -4,28 +4,23 @@ import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; + import org.codehaus.plexus.archiver.util.Streams; /** * Extension of {@link TarFile} for gzip compressed files. */ -public class GZipTarFile - extends TarFile -{ +public class GZipTarFile extends TarFile { /** * Creates a new instance with the given file. */ - public GZipTarFile( File file ) - { - super( file ); + public GZipTarFile(File file) { + super(file); } @Override - protected InputStream getInputStream( File file ) - throws IOException - { - return Streams.bufferedInputStream( new GZIPInputStream( super.getInputStream( file ) ) ); + protected InputStream getInputStream(File file) throws IOException { + return Streams.bufferedInputStream(new GZIPInputStream(super.getInputStream(file))); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTBZ2FileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTBZ2FileResourceCollection.java index b05bd661f..be5154a21 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTBZ2FileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTBZ2FileResourceCollection.java @@ -5,8 +5,5 @@ /** * Alias for {@link PlexusIoTarBZip2FileResourceCollection} */ -@Named( "tbz2" ) -public class PlexusIoTBZ2FileResourceCollection - extends PlexusIoTarBZip2FileResourceCollection -{ -} +@Named("tbz2") +public class PlexusIoTBZ2FileResourceCollection extends PlexusIoTarBZip2FileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTGZFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTGZFileResourceCollection.java index 450afbcdb..d903d85db 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTGZFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTGZFileResourceCollection.java @@ -5,8 +5,5 @@ /** * Alias for {@link PlexusIoTarGZipFileResourceCollection} */ -@Named( "tgz" ) -public class PlexusIoTGZFileResourceCollection - extends PlexusIoTarGZipFileResourceCollection -{ -} +@Named("tgz") +public class PlexusIoTGZFileResourceCollection extends PlexusIoTarGZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTXZFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTXZFileResourceCollection.java index 59ec6a9c2..9c82f7f7a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTXZFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTXZFileResourceCollection.java @@ -20,7 +20,5 @@ /** * Alias for {@link PlexusIoTarXZFileResourceCollection} */ -@Named( "txz" ) -public class PlexusIoTXZFileResourceCollection extends PlexusIoTarXZFileResourceCollection -{ -} +@Named("txz") +public class PlexusIoTXZFileResourceCollection extends PlexusIoTarXZFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTZstdFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTZstdFileResourceCollection.java index b8606b26d..9f0de16a9 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTZstdFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTZstdFileResourceCollection.java @@ -22,7 +22,5 @@ * * @since 4.7.2 */ -@Named( "tzst" ) -public class PlexusIoTZstdFileResourceCollection extends PlexusIoTarZstdFileResourceCollection -{ -} +@Named("tzst") +public class PlexusIoTZstdFileResourceCollection extends PlexusIoTarZstdFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarBZip2FileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarBZip2FileResourceCollection.java index a6e6cba38..0da8bd647 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarBZip2FileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarBZip2FileResourceCollection.java @@ -4,15 +4,11 @@ import java.io.File; -@Named( "tar.bz2" ) -public class PlexusIoTarBZip2FileResourceCollection - extends PlexusIoTarFileResourceCollection -{ +@Named("tar.bz2") +public class PlexusIoTarBZip2FileResourceCollection extends PlexusIoTarFileResourceCollection { @Override - protected TarFile newTarFile( File file ) - { - return new BZip2TarFile( file ); + protected TarFile newTarFile(File file) { + return new BZip2TarFile(file); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarFileResourceCollection.java index a12014737..3b390064b 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarFileResourceCollection.java @@ -28,73 +28,56 @@ import org.codehaus.plexus.components.io.resources.AbstractPlexusIoArchiveResourceCollection; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -@Named( "tar" ) -public class PlexusIoTarFileResourceCollection - extends AbstractPlexusIoArchiveResourceCollection implements Closeable -{ +@Named("tar") +public class PlexusIoTarFileResourceCollection extends AbstractPlexusIoArchiveResourceCollection implements Closeable { - protected TarFile newTarFile( File file ) - { - return new TarFile( file ); + protected TarFile newTarFile(File file) { + return new TarFile(file); } TarFile tarFile = null; @Override - public void close() - throws IOException - { - if ( tarFile != null ) - { + public void close() throws IOException { + if (tarFile != null) { tarFile.close(); } } @Override - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { return false; } @Override - protected Iterator getEntries() - throws IOException - { + protected Iterator getEntries() throws IOException { final File f = getFile(); - if ( f == null ) - { - throw new IOException( "The tar archive file has not been set." ); + if (f == null) { + throw new IOException("The tar archive file has not been set."); } - if ( tarFile == null ) - { - tarFile = newTarFile( f ); + if (tarFile == null) { + tarFile = newTarFile(f); } final Enumeration en = tarFile.getEntries(); - return new Iterator() - { + return new Iterator() { @Override - public boolean hasNext() - { + public boolean hasNext() { return en.hasMoreElements(); } @Override - public PlexusIoResource next() - { + public PlexusIoResource next() { final TarArchiveEntry entry = (TarArchiveEntry) en.nextElement(); return entry.isSymbolicLink() - ? new TarSymlinkResource( tarFile, entry ) - : new TarResource( tarFile, entry ); + ? new TarSymlinkResource(tarFile, entry) + : new TarResource(tarFile, entry); } @Override - public void remove() - { - throw new UnsupportedOperationException( "Removing isn't implemented." ); + public void remove() { + throw new UnsupportedOperationException("Removing isn't implemented."); } - }; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarGZipFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarGZipFileResourceCollection.java index ee689e949..43d58aa9d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarGZipFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarGZipFileResourceCollection.java @@ -4,15 +4,11 @@ import java.io.File; -@Named( "tar.gz" ) -public class PlexusIoTarGZipFileResourceCollection - extends PlexusIoTarFileResourceCollection -{ +@Named("tar.gz") +public class PlexusIoTarGZipFileResourceCollection extends PlexusIoTarFileResourceCollection { @Override - protected TarFile newTarFile( File file ) - { - return new GZipTarFile( file ); + protected TarFile newTarFile(File file) { + return new GZipTarFile(file); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarSnappyFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarSnappyFileResourceCollection.java index 139adadeb..b2923b6c5 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarSnappyFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarSnappyFileResourceCollection.java @@ -4,15 +4,11 @@ import java.io.File; -@Named( "tar.snappy" ) -public class PlexusIoTarSnappyFileResourceCollection - extends PlexusIoTarFileResourceCollection -{ +@Named("tar.snappy") +public class PlexusIoTarSnappyFileResourceCollection extends PlexusIoTarFileResourceCollection { @Override - protected TarFile newTarFile( File file ) - { - return new SnappyTarFile( file ); + protected TarFile newTarFile(File file) { + return new SnappyTarFile(file); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarXZFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarXZFileResourceCollection.java index 588e0342d..43e617c00 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarXZFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarXZFileResourceCollection.java @@ -24,18 +24,13 @@ * @author philip.lourandos * @since 3.3 */ -@Named( "tar.xz" ) -public class PlexusIoTarXZFileResourceCollection extends PlexusIoTarFileResourceCollection -{ +@Named("tar.xz") +public class PlexusIoTarXZFileResourceCollection extends PlexusIoTarFileResourceCollection { - public PlexusIoTarXZFileResourceCollection() - { - } + public PlexusIoTarXZFileResourceCollection() {} @Override - protected TarFile newTarFile( File file ) - { - return new XZTarFile( file ); + protected TarFile newTarFile(File file) { + return new XZTarFile(file); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarZstdFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarZstdFileResourceCollection.java index aa084c10d..2394e500f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarZstdFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/PlexusIoTarZstdFileResourceCollection.java @@ -16,23 +16,19 @@ package org.codehaus.plexus.archiver.tar; import javax.inject.Named; + import java.io.File; /** * Alias for {@link PlexusIoTarFileResourceCollection} */ -@Named( "tar.zst" ) -public class PlexusIoTarZstdFileResourceCollection extends PlexusIoTarFileResourceCollection -{ +@Named("tar.zst") +public class PlexusIoTarZstdFileResourceCollection extends PlexusIoTarFileResourceCollection { - public PlexusIoTarZstdFileResourceCollection() - { - } + public PlexusIoTarZstdFileResourceCollection() {} @Override - protected TarFile newTarFile( File file ) - { - return new ZstdTarFile( file ); + protected TarFile newTarFile(File file) { + return new ZstdTarFile(file); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/SnappyTarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/SnappyTarFile.java index feb889313..df9daec36 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/SnappyTarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/SnappyTarFile.java @@ -3,27 +3,23 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; + import org.codehaus.plexus.archiver.snappy.SnappyUnArchiver; /** * Extension of {@link org.codehaus.plexus.archiver.tar.TarFile} for snappy compressed files. */ -public class SnappyTarFile extends TarFile -{ +public class SnappyTarFile extends TarFile { /** * Creates a new instance with the given file. */ - public SnappyTarFile( File file ) - { - super( file ); + public SnappyTarFile(File file) { + super(file); } @Override - protected InputStream getInputStream( File file ) - throws IOException - { - return SnappyUnArchiver.getSnappyInputStream( super.getInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return SnappyUnArchiver.getSnappyInputStream(super.getInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2Archiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2Archiver.java index 5f6f53162..ab74e004f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2Archiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2Archiver.java @@ -23,8 +23,5 @@ * * @since 4.7.0 */ -@Named( "tbz2" ) -public class TBZ2Archiver - extends TarBZip2Archiver -{ -} +@Named("tbz2") +public class TBZ2Archiver extends TarBZip2Archiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2UnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2UnArchiver.java index 31d154e96..28b525e65 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2UnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TBZ2UnArchiver.java @@ -18,13 +18,8 @@ import javax.inject.Named; -import java.io.File; - /** * Alias for {@link TarBZip2UnArchiver}. */ -@Named( "tbz2" ) -public class TBZ2UnArchiver - extends TarBZip2UnArchiver -{ -} +@Named("tbz2") +public class TBZ2UnArchiver extends TarBZip2UnArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TGZArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TGZArchiver.java index 5d5d8b554..0284ab2e4 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TGZArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TGZArchiver.java @@ -23,8 +23,5 @@ * * @since 4.7.0 */ -@Named( "tgz" ) -public class TGZArchiver - extends TarGZipArchiver -{ -} +@Named("tgz") +public class TGZArchiver extends TarGZipArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TGZUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TGZUnArchiver.java index ce26b89bb..601c91d27 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TGZUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TGZUnArchiver.java @@ -18,13 +18,8 @@ import javax.inject.Named; -import java.io.File; - /** * Alias for {@link TarGZipUnArchiver}. */ -@Named( "tgz" ) -public class TGZUnArchiver - extends TarGZipUnArchiver -{ -} +@Named("tgz") +public class TGZUnArchiver extends TarGZipUnArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TXZArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TXZArchiver.java index abc6fc3b7..fb55d7424 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TXZArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TXZArchiver.java @@ -22,7 +22,5 @@ * * @since 4.7.0 */ -@Named( "txz" ) -public class TXZArchiver extends TarXZArchiver -{ -} +@Named("txz") +public class TXZArchiver extends TarXZArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TXZUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TXZUnArchiver.java index 5b80be224..b7f54a41e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TXZUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TXZUnArchiver.java @@ -17,12 +17,8 @@ import javax.inject.Named; -import java.io.File; - /** * Alias for {@link TarXZUnArchiver}. */ -@Named( "txz" ) -public class TXZUnArchiver extends TarXZUnArchiver -{ -} +@Named("txz") +public class TXZUnArchiver extends TarXZUnArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TZstdArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TZstdArchiver.java index 37ce36ac4..ad48a26ef 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TZstdArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TZstdArchiver.java @@ -22,7 +22,5 @@ * * @since 4.7.2 */ -@Named( "tzst" ) -public class TZstdArchiver extends TarZstdArchiver -{ -} +@Named("tzst") +public class TZstdArchiver extends TarZstdArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TZstdUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TZstdUnArchiver.java index 22ce49eab..867a5d261 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TZstdUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TZstdUnArchiver.java @@ -22,7 +22,5 @@ * * @since 4.7.2 */ -@Named( "tzst" ) -public class TZstdUnArchiver extends TarZstdUnArchiver -{ -} +@Named("tzst") +public class TZstdUnArchiver extends TarZstdUnArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarArchiver.java index f63e0e5f4..cae07804c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarArchiver.java @@ -18,8 +18,6 @@ import javax.inject.Named; -import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -46,13 +44,13 @@ import org.codehaus.plexus.util.StringUtils; import org.iq80.snappy.SnappyOutputStream; +import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; + /** * @author Emmanuel Venisse */ -@Named( "tar" ) -public class TarArchiver - extends AbstractArchiver -{ +@Named("tar") +public class TarArchiver extends AbstractArchiver { /** * Indicates whether the user has been warned about long files already. @@ -84,8 +82,7 @@ public class TarArchiver * * @param mode the mode to handle long file names. */ - public void setLongfile( TarLongFileMode mode ) - { + public void setLongfile(TarLongFileMode mode) { this.longFileMode = mode; } @@ -100,86 +97,66 @@ public void setLongfile( TarLongFileMode mode ) * * @param mode the compression method. */ - public void setCompression( TarCompressionMethod mode ) - { + public void setCompression(TarCompressionMethod mode) { this.compression = mode; } @Override - protected void execute() - throws ArchiverException, IOException - { - if ( !checkForced() ) - { + protected void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } File tarFile = getDestFile(); - if ( tarFile == null ) - { - throw new ArchiverException( "You must set the destination tar file." ); + if (tarFile == null) { + throw new ArchiverException("You must set the destination tar file."); } - if ( tarFile.exists() && !tarFile.isFile() ) - { - throw new ArchiverException( tarFile + " isn't a file." ); + if (tarFile.exists() && !tarFile.isFile()) { + throw new ArchiverException(tarFile + " isn't a file."); } - if ( tarFile.exists() && !tarFile.canWrite() ) - { - throw new ArchiverException( tarFile + " is read-only." ); + if (tarFile.exists() && !tarFile.canWrite()) { + throw new ArchiverException(tarFile + " is read-only."); } - getLogger().info( "Building tar: " + tarFile.getAbsolutePath() ); + getLogger().info("Building tar: " + tarFile.getAbsolutePath()); - try - { - tOut = new TarArchiveOutputStream( compress( compression, Files.newOutputStream( tarFile.toPath() ) ), "UTF8" ); - if ( longFileMode.isTruncateMode() ) - { - tOut.setLongFileMode( TarArchiveOutputStream.LONGFILE_TRUNCATE ); - } - else if ( longFileMode.isPosixMode() || longFileMode.isPosixWarnMode() ) - { - tOut.setLongFileMode( TarArchiveOutputStream.LONGFILE_POSIX ); + try { + tOut = new TarArchiveOutputStream(compress(compression, Files.newOutputStream(tarFile.toPath())), "UTF8"); + if (longFileMode.isTruncateMode()) { + tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_TRUNCATE); + } else if (longFileMode.isPosixMode() || longFileMode.isPosixWarnMode()) { + tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_POSIX); // Todo: Patch 2.5.1 for this fix. Also make closeable fix on 2.5.1 - tOut.setBigNumberMode( TarArchiveOutputStream.BIGNUMBER_POSIX ); - } - else if ( longFileMode.isFailMode() || longFileMode.isOmitMode() ) - { - tOut.setLongFileMode( TarArchiveOutputStream.LONGFILE_ERROR ); - } - else - { + tOut.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_POSIX); + } else if (longFileMode.isFailMode() || longFileMode.isOmitMode()) { + tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_ERROR); + } else { // warn or GNU - tOut.setLongFileMode( TarArchiveOutputStream.LONGFILE_GNU ); + tOut.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); } longWarningGiven = false; - while ( iter.hasNext() ) - { + while (iter.hasNext()) { ArchiveEntry entry = iter.next(); // Check if we don't add tar file in itself - if ( ResourceUtils.isSame( entry.getResource(), tarFile ) ) - { - throw new ArchiverException( "A tar file cannot include itself." ); + if (ResourceUtils.isSame(entry.getResource(), tarFile)) { + throw new ArchiverException("A tar file cannot include itself."); } String fileName = entry.getName(); - String name = StringUtils.replace( fileName, File.separatorChar, '/' ); + String name = StringUtils.replace(fileName, File.separatorChar, '/'); - tarFile( entry, tOut, name ); + tarFile(entry, tOut, name); } tOut.close(); - } - finally - { - IOUtil.close( tOut ); + } finally { + IOUtil.close(tOut); } } @@ -192,180 +169,146 @@ else if ( longFileMode.isFailMode() || longFileMode.isOmitMode() ) * * @throws IOException on error */ - protected void tarFile( ArchiveEntry entry, TarArchiveOutputStream tOut, String vPath ) - throws ArchiverException, IOException - { + protected void tarFile(ArchiveEntry entry, TarArchiveOutputStream tOut, String vPath) + throws ArchiverException, IOException { // don't add "" to the archive - if ( vPath.length() <= 0 ) - { + if (vPath.length() <= 0) { return; } - if ( entry.getResource().isDirectory() && !vPath.endsWith( "/" ) ) - { + if (entry.getResource().isDirectory() && !vPath.endsWith("/")) { vPath += "/"; } - if ( vPath.startsWith( "/" ) && !options.getPreserveLeadingSlashes() ) - { + if (vPath.startsWith("/") && !options.getPreserveLeadingSlashes()) { int l = vPath.length(); - if ( l <= 1 ) - { + if (l <= 1) { // we would end up adding "" to the archive return; } - vPath = vPath.substring( 1, l ); + vPath = vPath.substring(1, l); } int pathLength = vPath.length(); InputStream fIn = null; - try - { + try { TarArchiveEntry te; - if ( !longFileMode.isGnuMode() - && pathLength >= org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN ) - { + if (!longFileMode.isGnuMode() + && pathLength >= org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN) { int maxPosixPathLen = org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN - + org.apache.commons.compress.archivers.tar.TarConstants.PREFIXLEN; - if ( longFileMode.isPosixMode() ) - { - } - else if ( longFileMode.isPosixWarnMode() ) - { - if ( pathLength > maxPosixPathLen ) - { - getLogger().warn( "Entry: " + vPath + " longer than " + maxPosixPathLen + " characters." ); - if ( !longWarningGiven ) - { - getLogger().warn( "Resulting tar file can only be processed " - + "successfully by GNU compatible tar commands" ); + + org.apache.commons.compress.archivers.tar.TarConstants.PREFIXLEN; + if (longFileMode.isPosixMode()) { + } else if (longFileMode.isPosixWarnMode()) { + if (pathLength > maxPosixPathLen) { + getLogger().warn("Entry: " + vPath + " longer than " + maxPosixPathLen + " characters."); + if (!longWarningGiven) { + getLogger() + .warn("Resulting tar file can only be processed " + + "successfully by GNU compatible tar commands"); longWarningGiven = true; } } - } - else if ( longFileMode.isOmitMode() ) - { - getLogger().info( "Omitting: " + vPath ); + } else if (longFileMode.isOmitMode()) { + getLogger().info("Omitting: " + vPath); return; - } - else if ( longFileMode.isWarnMode() ) - { - getLogger().warn( "Entry: " + vPath + " longer than " - + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN - + " characters." ); - if ( !longWarningGiven ) - { - getLogger().warn( "Resulting tar file can only be processed " - + "successfully by GNU compatible tar commands" ); + } else if (longFileMode.isWarnMode()) { + getLogger() + .warn("Entry: " + vPath + " longer than " + + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + + " characters."); + if (!longWarningGiven) { + getLogger() + .warn("Resulting tar file can only be processed " + + "successfully by GNU compatible tar commands"); longWarningGiven = true; } - } - else if ( longFileMode.isFailMode() ) - { - throw new ArchiverException( "Entry: " + vPath + " longer than " - + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN - + " characters." ); - } - else - { - throw new IllegalStateException( "Non gnu mode should never get here?" ); + } else if (longFileMode.isFailMode()) { + throw new ArchiverException("Entry: " + vPath + " longer than " + + org.apache.commons.compress.archivers.tar.TarConstants.NAMELEN + + " characters."); + } else { + throw new IllegalStateException("Non gnu mode should never get here?"); } } - if ( entry.getType() == ArchiveEntry.SYMLINK ) - { + if (entry.getType() == ArchiveEntry.SYMLINK) { final SymlinkDestinationSupplier plexusIoSymlinkResource = - (SymlinkDestinationSupplier) entry.getResource(); + (SymlinkDestinationSupplier) entry.getResource(); - te = new TarArchiveEntry( vPath, TarArchiveEntry.LF_SYMLINK ); - te.setLinkName( plexusIoSymlinkResource.getSymlinkDestination() ); - } - else - { - te = new TarArchiveEntry( vPath ); + te = new TarArchiveEntry(vPath, TarArchiveEntry.LF_SYMLINK); + te.setLinkName(plexusIoSymlinkResource.getSymlinkDestination()); + } else { + te = new TarArchiveEntry(vPath); } - if ( getLastModifiedTime() == null ) - { + if (getLastModifiedTime() == null) { long teLastModified = entry.getResource().getLastModified(); - te.setModTime( teLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE - ? System.currentTimeMillis() - : teLastModified ); - } - else - { - te.setModTime( getLastModifiedTime().toMillis() ); + te.setModTime( + teLastModified == PlexusIoResource.UNKNOWN_MODIFICATION_DATE + ? System.currentTimeMillis() + : teLastModified); + } else { + te.setModTime(getLastModifiedTime().toMillis()); } - if ( entry.getType() == ArchiveEntry.SYMLINK ) - { - te.setSize( 0 ); + if (entry.getType() == ArchiveEntry.SYMLINK) { + te.setSize(0); - } - else if ( !entry.getResource().isDirectory() ) - { + } else if (!entry.getResource().isDirectory()) { final long size = entry.getResource().getSize(); - te.setSize( size == PlexusIoResource.UNKNOWN_RESOURCE_SIZE ? 0 : size ); + te.setSize(size == PlexusIoResource.UNKNOWN_RESOURCE_SIZE ? 0 : size); } - te.setMode( entry.getMode() ); + te.setMode(entry.getMode()); PlexusIoResourceAttributes attributes = entry.getResourceAttributes(); - te.setUserName( ( attributes != null && attributes.getUserName() != null ) - ? attributes.getUserName() - : options.getUserName() ); - te.setGroupName( ( attributes != null && attributes.getGroupName() != null ) - ? attributes.getGroupName() - : options.getGroup() ); + te.setUserName( + (attributes != null && attributes.getUserName() != null) + ? attributes.getUserName() + : options.getUserName()); + te.setGroupName( + (attributes != null && attributes.getGroupName() != null) + ? attributes.getGroupName() + : options.getGroup()); final int userId = - ( attributes != null && attributes.getUserId() != null ) ? attributes.getUserId() : options.getUid(); - if ( userId >= 0 ) - { - te.setUserId( userId ); + (attributes != null && attributes.getUserId() != null) ? attributes.getUserId() : options.getUid(); + if (userId >= 0) { + te.setUserId(userId); } - final int groupId = - ( attributes != null && attributes.getGroupId() != null ) ? attributes.getGroupId() : options.getGid(); - if ( groupId >= 0 ) - { - te.setGroupId( groupId ); + final int groupId = (attributes != null && attributes.getGroupId() != null) + ? attributes.getGroupId() + : options.getGid(); + if (groupId >= 0) { + te.setGroupId(groupId); } - tOut.putArchiveEntry( te ); + tOut.putArchiveEntry(te); - try - { - if ( entry.getResource().isFile() && !( entry.getType() == ArchiveEntry.SYMLINK ) ) - { + try { + if (entry.getResource().isFile() && !(entry.getType() == ArchiveEntry.SYMLINK)) { fIn = entry.getInputStream(); - Streams.copyFullyDontCloseOutput( fIn, tOut, "xAR" ); + Streams.copyFullyDontCloseOutput(fIn, tOut, "xAR"); } - } - catch ( Throwable e ) - { - getLogger().warn( "When creating tar entry", e ); - } - finally - { + } catch (Throwable e) { + getLogger().warn("When creating tar entry", e); + } finally { tOut.closeArchiveEntry(); } - } - finally - { - IOUtil.close( fIn ); + } finally { + IOUtil.close(fIn); } } /** * Valid Modes for Compression attribute to Tar Task */ - public class TarOptions - { + public class TarOptions { private String userName = ""; @@ -383,16 +326,14 @@ public class TarOptions * * @param userName the user name for the tar entry. */ - public void setUserName( String userName ) - { + public void setUserName(String userName) { this.userName = userName; } /** * @return the user name for the tar entry */ - public String getUserName() - { + public String getUserName() { return userName; } @@ -402,16 +343,14 @@ public String getUserName() * * @param uid the id of the user for the tar entry. */ - public void setUid( int uid ) - { + public void setUid(int uid) { this.uid = uid; } /** * @return the uid for the tar entry */ - public int getUid() - { + public int getUid() { return uid; } @@ -421,16 +360,14 @@ public int getUid() * * @param groupName the group name string. */ - public void setGroup( String groupName ) - { + public void setGroup(String groupName) { this.groupName = groupName; } /** * @return the group name string. */ - public String getGroup() - { + public String getGroup() { return groupName; } @@ -440,24 +377,21 @@ public String getGroup() * * @param gid the group id. */ - public void setGid( int gid ) - { + public void setGid(int gid) { this.gid = gid; } /** * @return the group identifier. */ - public int getGid() - { + public int getGid() { return gid; } /** * @return the leading slashes flag. */ - public boolean getPreserveLeadingSlashes() - { + public boolean getPreserveLeadingSlashes() { return preserveLeadingSlashes; } @@ -468,86 +402,62 @@ public boolean getPreserveLeadingSlashes() * * @param preserveLeadingSlashes the leading slashes flag. */ - public void setPreserveLeadingSlashes( boolean preserveLeadingSlashes ) - { + public void setPreserveLeadingSlashes(boolean preserveLeadingSlashes) { this.preserveLeadingSlashes = preserveLeadingSlashes; } - } /** * Valid Modes for Compression attribute to Tar Task */ - public enum TarCompressionMethod - { - + public enum TarCompressionMethod { none, gzip, bzip2, snappy, xz, zstd - } - private OutputStream compress( TarCompressionMethod tarCompressionMethod, final OutputStream ostream ) - throws IOException - { - if ( TarCompressionMethod.gzip.equals( tarCompressionMethod ) ) - { - return bufferedOutputStream( new GZIPOutputStream( ostream ) ); - } - else if ( TarCompressionMethod.bzip2.equals( tarCompressionMethod ) ) - { - return new BZip2CompressorOutputStream( bufferedOutputStream( ostream ) ); - } - else if ( TarCompressionMethod.snappy.equals( tarCompressionMethod ) ) - { - return new SnappyOutputStream( bufferedOutputStream( ostream ) ); - } - else if ( TarCompressionMethod.xz.equals( tarCompressionMethod ) ) - { - return new XZCompressorOutputStream( bufferedOutputStream( ostream ) ); - } - else if ( TarCompressionMethod.zstd.equals( tarCompressionMethod ) ) - { - return new ZstdCompressorOutputStream( bufferedOutputStream( ostream ) ); + private OutputStream compress(TarCompressionMethod tarCompressionMethod, final OutputStream ostream) + throws IOException { + if (TarCompressionMethod.gzip.equals(tarCompressionMethod)) { + return bufferedOutputStream(new GZIPOutputStream(ostream)); + } else if (TarCompressionMethod.bzip2.equals(tarCompressionMethod)) { + return new BZip2CompressorOutputStream(bufferedOutputStream(ostream)); + } else if (TarCompressionMethod.snappy.equals(tarCompressionMethod)) { + return new SnappyOutputStream(bufferedOutputStream(ostream)); + } else if (TarCompressionMethod.xz.equals(tarCompressionMethod)) { + return new XZCompressorOutputStream(bufferedOutputStream(ostream)); + } else if (TarCompressionMethod.zstd.equals(tarCompressionMethod)) { + return new ZstdCompressorOutputStream(bufferedOutputStream(ostream)); } return ostream; } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { super.cleanUp(); - if ( this.tOut != null ) - { + if (this.tOut != null) { this.tOut.close(); } } @Override - protected void close() - throws IOException - { - if ( this.tOut != null ) - { + protected void close() throws IOException { + if (this.tOut != null) { this.tOut.close(); } } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "TAR"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2Archiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2Archiver.java index 16a031eb8..9d661d91a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2Archiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2Archiver.java @@ -23,19 +23,14 @@ * * @since 4.7.0 */ -@Named( "tar.bz2" ) -public class TarBZip2Archiver - extends TarArchiver -{ +@Named("tar.bz2") +public class TarBZip2Archiver extends TarArchiver { - public TarBZip2Archiver() - { + public TarBZip2Archiver() { this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( TarCompressionMethod.bzip2 ); + private void setupCompressionMethod() { + this.setCompression(TarCompressionMethod.bzip2); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiver.java index 3cb84c918..5cc14299f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiver.java @@ -25,25 +25,19 @@ * * @author Dan Tran */ -@Named( "tar.bz2" ) -public class TarBZip2UnArchiver - extends TarUnArchiver -{ +@Named("tar.bz2") +public class TarBZip2UnArchiver extends TarUnArchiver { - public TarBZip2UnArchiver() - { + public TarBZip2UnArchiver() { this.setupCompressionMethod(); } - public TarBZip2UnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarBZip2UnArchiver(File sourceFile) { + super(sourceFile); this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( UntarCompressionMethod.BZIP2 ); + private void setupCompressionMethod() { + this.setCompression(UntarCompressionMethod.BZIP2); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarFile.java index a9b262d37..becbe3113 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarFile.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.archiver.tar; -import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; - import java.io.File; import java.io.FilterInputStream; import java.io.IOException; @@ -15,6 +13,8 @@ import org.codehaus.plexus.archiver.ArchiveFile; import org.codehaus.plexus.archiver.util.Streams; +import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; + /** *

* Implementation of {@link ArchiveFile} for tar files.

@@ -36,9 +36,7 @@ * The advantage of this class is that you may write code for the * {@link ArchiveFile}, which is valid for both tar files and zip files.

*/ -public class TarFile - implements ArchiveFile -{ +public class TarFile implements ArchiveFile { private final java.io.File file; @@ -49,8 +47,7 @@ public class TarFile /** * Creates a new instance with the given file. */ - public TarFile( File file ) - { + public TarFile(File file) { this.file = file; } @@ -62,65 +59,48 @@ public TarFile( File file ) * current entry, then entries may be skipped. */ @Override - public Enumeration getEntries() - throws IOException - { - if ( inputStream != null ) - { + public Enumeration getEntries() throws IOException { + if (inputStream != null) { close(); } open(); - return new Enumeration() - { + return new Enumeration() { boolean currentEntryValid; @Override - public boolean hasMoreElements() - { - if ( !currentEntryValid ) - { - try - { + public boolean hasMoreElements() { + if (!currentEntryValid) { + try { currentEntry = inputStream.getNextTarEntry(); - } - catch ( IOException e ) - { - throw new UndeclaredThrowableException( e ); + } catch (IOException e) { + throw new UndeclaredThrowableException(e); } } return currentEntry != null; } @Override - public org.apache.commons.compress.archivers.ArchiveEntry nextElement() - { - if ( currentEntry == null ) - { + public org.apache.commons.compress.archivers.ArchiveEntry nextElement() { + if (currentEntry == null) { throw new NoSuchElementException(); } currentEntryValid = false; return currentEntry; } - }; } - public void close() - throws IOException - { - if ( inputStream != null ) - { + public void close() throws IOException { + if (inputStream != null) { inputStream.close(); inputStream = null; } } @Override - public InputStream getInputStream( org.apache.commons.compress.archivers.ArchiveEntry entry ) - throws IOException - { - return getInputStream( new TarArchiveEntry( entry.getName() ) ); + public InputStream getInputStream(org.apache.commons.compress.archivers.ArchiveEntry entry) throws IOException { + return getInputStream(new TarArchiveEntry(entry.getName())); } /** @@ -129,86 +109,59 @@ public InputStream getInputStream( org.apache.commons.compress.archivers.Archive * happens in that case, because an actual close would invalidate * the underlying {@link TarArchiveInputStream}. */ - public InputStream getInputStream( TarArchiveEntry entry ) - throws IOException - { - if ( entry.equals( (Object) currentEntry ) && inputStream != null ) - { - return new FilterInputStream( inputStream ) - { - - public void close() - throws IOException - { + public InputStream getInputStream(TarArchiveEntry entry) throws IOException { + if (entry.equals((Object) currentEntry) && inputStream != null) { + return new FilterInputStream(inputStream) { + + public void close() throws IOException { // Does nothing. } - }; } - return getInputStream( entry, currentEntry ); + return getInputStream(entry, currentEntry); } - protected InputStream getInputStream( File file ) - throws IOException - { - return Streams.fileInputStream( file ); + protected InputStream getInputStream(File file) throws IOException { + return Streams.fileInputStream(file); } - private InputStream getInputStream( TarArchiveEntry entry, TarArchiveEntry currentEntry ) - throws IOException - { - if ( currentEntry == null || inputStream == null ) - { + private InputStream getInputStream(TarArchiveEntry entry, TarArchiveEntry currentEntry) throws IOException { + if (currentEntry == null || inputStream == null) { // Search for the entry from the beginning of the file to the end. - if ( inputStream != null ) - { + if (inputStream != null) { close(); } open(); - if ( !findEntry( entry, null ) ) - { - throw new IOException( "Unknown entry: " + entry.getName() ); + if (!findEntry(entry, null)) { + throw new IOException("Unknown entry: " + entry.getName()); } - } - else - { + } else { // Search for the entry from the current position to the end of the file. - if ( findEntry( entry, null ) ) - { - return getInputStream( entry ); + if (findEntry(entry, null)) { + return getInputStream(entry); } close(); open(); - if ( !findEntry( entry, currentEntry ) ) - { - throw new IOException( "No such entry: " + entry.getName() ); + if (!findEntry(entry, currentEntry)) { + throw new IOException("No such entry: " + entry.getName()); } } - return getInputStream( entry ); + return getInputStream(entry); } - private void open() - throws IOException - { - inputStream = new TarArchiveInputStream( bufferedInputStream( getInputStream( file ) ), "UTF8" ); + private void open() throws IOException { + inputStream = new TarArchiveInputStream(bufferedInputStream(getInputStream(file)), "UTF8"); } - private boolean findEntry( TarArchiveEntry entry, TarArchiveEntry currentEntry ) - throws IOException - { - for ( ;; ) - { + private boolean findEntry(TarArchiveEntry entry, TarArchiveEntry currentEntry) throws IOException { + for (; ; ) { this.currentEntry = inputStream.getNextTarEntry(); - if ( this.currentEntry == null - || ( currentEntry != null && this.currentEntry.equals( currentEntry ) ) ) - { + if (this.currentEntry == null || (currentEntry != null && this.currentEntry.equals(currentEntry))) { return false; } - if ( this.currentEntry.equals( entry ) ) - { + if (this.currentEntry.equals(entry)) { return true; } } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipArchiver.java index 1ee308dab..7dea3cc20 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipArchiver.java @@ -23,19 +23,14 @@ * * @since 4.7.0 */ -@Named( "tar.gz" ) -public class TarGZipArchiver - extends TarArchiver -{ +@Named("tar.gz") +public class TarGZipArchiver extends TarArchiver { - public TarGZipArchiver() - { + public TarGZipArchiver() { this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( TarCompressionMethod.gzip ); + private void setupCompressionMethod() { + this.setCompression(TarCompressionMethod.gzip); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiver.java index 879c8f0dc..b59f46e3d 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiver.java @@ -25,25 +25,19 @@ * * @author Dan Tran */ -@Named( "tar.gz" ) -public class TarGZipUnArchiver - extends TarUnArchiver -{ +@Named("tar.gz") +public class TarGZipUnArchiver extends TarUnArchiver { - public TarGZipUnArchiver() - { + public TarGZipUnArchiver() { this.setupCompressionMethod(); } - public TarGZipUnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarGZipUnArchiver(File sourceFile) { + super(sourceFile); this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( UntarCompressionMethod.GZIP ); + private void setupCompressionMethod() { + this.setCompression(UntarCompressionMethod.GZIP); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarLongFileMode.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarLongFileMode.java index 76c1ac50b..8f312cd67 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarLongFileMode.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarLongFileMode.java @@ -19,9 +19,7 @@ /** * Set of options for long file handling in the task. */ -public enum TarLongFileMode -{ - +public enum TarLongFileMode { warn, fail, truncate, @@ -33,57 +31,49 @@ public enum TarLongFileMode /** * @return true if value is "truncate". */ - public boolean isTruncateMode() - { - return truncate.equals( this ); + public boolean isTruncateMode() { + return truncate.equals(this); } /** * @return true if value is "warn". */ - public boolean isWarnMode() - { - return warn.equals( this ); + public boolean isWarnMode() { + return warn.equals(this); } /** * @return true if value is "gnu". */ - public boolean isGnuMode() - { - return gnu.equals( this ); + public boolean isGnuMode() { + return gnu.equals(this); } /** * @return true if value is "fail". */ - public boolean isFailMode() - { - return fail.equals( this ); + public boolean isFailMode() { + return fail.equals(this); } /** * @return true if value is "omit". */ - public boolean isOmitMode() - { - return omit.equals( this ); + public boolean isOmitMode() { + return omit.equals(this); } /** * @return true if value is "posix". */ - public boolean isPosixMode() - { - return posix.equals( this ); + public boolean isPosixMode() { + return posix.equals(this); } /** * @return true if value is "posix_warn". */ - public boolean isPosixWarnMode() - { - return posix_warn.equals( this ); + public boolean isPosixWarnMode() { + return posix_warn.equals(this); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarResource.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarResource.java index 46541cbad..dc6617d42 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarResource.java @@ -1,9 +1,11 @@ package org.codehaus.plexus.archiver.tar; +import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; import java.net.URL; -import javax.annotation.Nonnull; + import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.codehaus.plexus.components.io.attributes.PlexusIoResourceAttributes; import org.codehaus.plexus.components.io.attributes.SimpleResourceAttributes; @@ -11,10 +13,7 @@ import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -public class TarResource - extends AbstractPlexusIoResource - implements ResourceAttributeSupplier -{ +public class TarResource extends AbstractPlexusIoResource implements ResourceAttributeSupplier { private final TarFile tarFile; @@ -22,53 +21,46 @@ public class TarResource private PlexusIoResourceAttributes attributes; - public TarResource( TarFile tarFile, TarArchiveEntry entry ) - { - super( entry.getName(), getLastModifiedTime( entry ), - entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), !entry.isDirectory(), - entry.isDirectory(), true ); + public TarResource(TarFile tarFile, TarArchiveEntry entry) { + super( + entry.getName(), + getLastModifiedTime(entry), + entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), + !entry.isDirectory(), + entry.isDirectory(), + true); this.tarFile = tarFile; this.entry = entry; } - private static long getLastModifiedTime( TarArchiveEntry entry ) - { + private static long getLastModifiedTime(TarArchiveEntry entry) { long l = entry.getModTime().getTime(); return l == -1 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : l; } @Override - public synchronized PlexusIoResourceAttributes getAttributes() - { - if ( attributes == null ) - { - attributes = new SimpleResourceAttributes( entry.getUserId(), entry.getUserName(), entry.getGroupId(), - entry.getGroupName(), entry.getMode() ); - + public synchronized PlexusIoResourceAttributes getAttributes() { + if (attributes == null) { + attributes = new SimpleResourceAttributes( + entry.getUserId(), entry.getUserName(), entry.getGroupId(), entry.getGroupName(), entry.getMode()); } return attributes; } - public synchronized void setAttributes( PlexusIoResourceAttributes attributes ) - { + public synchronized void setAttributes(PlexusIoResourceAttributes attributes) { this.attributes = attributes; } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return null; } @Nonnull @Override - public InputStream getContents() - throws IOException - { - return tarFile.getInputStream( entry ); + public InputStream getContents() throws IOException { + return tarFile.getInputStream(entry); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyArchiver.java index 22afff0b9..f6d7b133f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyArchiver.java @@ -23,19 +23,14 @@ * * @since 4.7.0 */ -@Named( "tar.snappy" ) -public class TarSnappyArchiver - extends TarArchiver -{ +@Named("tar.snappy") +public class TarSnappyArchiver extends TarArchiver { - public TarSnappyArchiver() - { + public TarSnappyArchiver() { this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( TarCompressionMethod.snappy ); + private void setupCompressionMethod() { + this.setCompression(TarCompressionMethod.snappy); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiver.java index e20cdfe6e..0d1958e2e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiver.java @@ -24,25 +24,19 @@ * Extract files in tar with snappy compression * */ -@Named( "tar.snappy" ) -public class TarSnappyUnArchiver - extends TarUnArchiver -{ +@Named("tar.snappy") +public class TarSnappyUnArchiver extends TarUnArchiver { - public TarSnappyUnArchiver() - { + public TarSnappyUnArchiver() { this.setupCompressionMethod(); } - public TarSnappyUnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarSnappyUnArchiver(File sourceFile) { + super(sourceFile); this.setupCompressionMethod(); } - private void setupCompressionMethod() - { - this.setCompression( UntarCompressionMethod.SNAPPY ); + private void setupCompressionMethod() { + this.setCompression(UntarCompressionMethod.SNAPPY); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarSymlinkResource.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarSymlinkResource.java index edfbd5966..5310872a7 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarSymlinkResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarSymlinkResource.java @@ -16,36 +16,29 @@ package org.codehaus.plexus.archiver.tar; import java.io.IOException; + import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; /** * A {@link TarResource} that represents symbolic link. */ -public class TarSymlinkResource - extends TarResource - implements SymlinkDestinationSupplier -{ +public class TarSymlinkResource extends TarResource implements SymlinkDestinationSupplier { private final String symlinkDestination; - public TarSymlinkResource( TarFile tarFile, TarArchiveEntry entry ) - { - super( tarFile, entry ); + public TarSymlinkResource(TarFile tarFile, TarArchiveEntry entry) { + super(tarFile, entry); symlinkDestination = entry.getLinkName(); } @Override - public String getSymlinkDestination() - throws IOException - { + public String getSymlinkDestination() throws IOException { return symlinkDestination; } @Override - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return true; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java index d88c3dd11..1b0b79509 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarUnArchiver.java @@ -18,9 +18,6 @@ import javax.inject.Named; -import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -37,21 +34,19 @@ import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.iq80.snappy.SnappyFramedInputStream; +import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileInputStream; + /** * @author Emmanuel Venisse */ -@Named( "tar" ) -public class TarUnArchiver - extends AbstractUnArchiver -{ +@Named("tar") +public class TarUnArchiver extends AbstractUnArchiver { - public TarUnArchiver() - { - } + public TarUnArchiver() {} - public TarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarUnArchiver(File sourceFile) { + super(sourceFile); } /** @@ -73,60 +68,54 @@ public TarUnArchiver( File sourceFile ) * * @param method compression method */ - public void setCompression( UntarCompressionMethod method ) - { + public void setCompression(UntarCompressionMethod method) { compression = method; } /** * No encoding support in Untar. */ - public void setEncoding( String encoding ) - { - getLogger().warn( "The TarUnArchiver doesn't support the encoding attribute" ); + public void setEncoding(String encoding) { + getLogger().warn("The TarUnArchiver doesn't support the encoding attribute"); } @Override - protected void execute() - throws ArchiverException - { - execute( getSourceFile(), getDestDirectory(), getFileMappers() ); + protected void execute() throws ArchiverException { + execute(getSourceFile(), getDestDirectory(), getFileMappers()); } @Override - protected void execute( String path, File outputDirectory ) - { - execute( new File( path ), getDestDirectory(), getFileMappers() ); + protected void execute(String path, File outputDirectory) { + execute(new File(path), getDestDirectory(), getFileMappers()); } - protected void execute( File sourceFile, File destDirectory, FileMapper[] fileMappers ) - throws ArchiverException - { - try - { - getLogger().info( "Expanding: " + sourceFile + " into " + destDirectory ); - TarFile tarFile = new TarFile( sourceFile ); - try ( TarArchiveInputStream tis = new TarArchiveInputStream( - decompress( compression, sourceFile, bufferedInputStream( fileInputStream( sourceFile ) ) ) ) ) - { + protected void execute(File sourceFile, File destDirectory, FileMapper[] fileMappers) throws ArchiverException { + try { + getLogger().info("Expanding: " + sourceFile + " into " + destDirectory); + TarFile tarFile = new TarFile(sourceFile); + try (TarArchiveInputStream tis = new TarArchiveInputStream( + decompress(compression, sourceFile, bufferedInputStream(fileInputStream(sourceFile))))) { TarArchiveEntry te; - while ( ( te = tis.getNextTarEntry() ) != null ) - { - TarResource fileInfo = new TarResource( tarFile, te ); - if ( isSelected( te.getName(), fileInfo ) ) - { + while ((te = tis.getNextTarEntry()) != null) { + TarResource fileInfo = new TarResource(tarFile, te); + if (isSelected(te.getName(), fileInfo)) { final String symlinkDestination = te.isSymbolicLink() ? te.getLinkName() : null; - extractFile( sourceFile, destDirectory, tis, te.getName(), te.getModTime(), te.isDirectory(), - te.getMode() != 0 ? te.getMode() : null, symlinkDestination, fileMappers ); - + extractFile( + sourceFile, + destDirectory, + tis, + te.getName(), + te.getModTime(), + te.isDirectory(), + te.getMode() != 0 ? te.getMode() : null, + symlinkDestination, + fileMappers); } } - getLogger().debug( "expand complete" ); + getLogger().debug("expand complete"); } - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Error while expanding " + sourceFile.getAbsolutePath(), ioe ); + } catch (IOException ioe) { + throw new ArchiverException("Error while expanding " + sourceFile.getAbsolutePath(), ioe); } } @@ -141,28 +130,18 @@ protected void execute( File sourceFile, File destDirectory, FileMapper[] fileMa * * @throws IOException thrown by GZIPInputStream constructor */ - private InputStream decompress( UntarCompressionMethod compression, final File file, final InputStream istream ) - throws IOException, ArchiverException - { - if ( compression == UntarCompressionMethod.GZIP ) - { - return Streams.bufferedInputStream( new GZIPInputStream( istream ) ); - } - else if ( compression == UntarCompressionMethod.BZIP2 ) - { - return new BZip2CompressorInputStream( istream ); - } - else if ( compression == UntarCompressionMethod.SNAPPY ) - { - return new SnappyFramedInputStream( istream, true ); - } - else if ( compression == UntarCompressionMethod.XZ ) - { - return new XZCompressorInputStream( istream ); - } - else if ( compression == UntarCompressionMethod.ZSTD ) - { - return new ZstdCompressorInputStream( istream ); + private InputStream decompress(UntarCompressionMethod compression, final File file, final InputStream istream) + throws IOException, ArchiverException { + if (compression == UntarCompressionMethod.GZIP) { + return Streams.bufferedInputStream(new GZIPInputStream(istream)); + } else if (compression == UntarCompressionMethod.BZIP2) { + return new BZip2CompressorInputStream(istream); + } else if (compression == UntarCompressionMethod.SNAPPY) { + return new SnappyFramedInputStream(istream, true); + } else if (compression == UntarCompressionMethod.XZ) { + return new XZCompressorInputStream(istream); + } else if (compression == UntarCompressionMethod.ZSTD) { + return new ZstdCompressorInputStream(istream); } return istream; } @@ -170,26 +149,21 @@ else if ( compression == UntarCompressionMethod.ZSTD ) /** * Valid Modes for Compression attribute to Untar Task */ - public enum UntarCompressionMethod - { - - NONE( "none" ), - GZIP( "gzip" ), - BZIP2( "bzip2" ), - SNAPPY( "snappy" ), - XZ( "xz" ), - ZSTD( "zstd" ); + public enum UntarCompressionMethod { + NONE("none"), + GZIP("gzip"), + BZIP2("bzip2"), + SNAPPY("snappy"), + XZ("xz"), + ZSTD("zstd"); final String value; /** * Constructor */ - UntarCompressionMethod( String value ) - { + UntarCompressionMethod(String value) { this.value = value; } - } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarXZArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarXZArchiver.java index 754c35ddd..59ef920d2 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarXZArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarXZArchiver.java @@ -22,18 +22,14 @@ * * @since 4.7.0 */ -@Named( "tar.xz" ) -public class TarXZArchiver extends TarArchiver -{ +@Named("tar.xz") +public class TarXZArchiver extends TarArchiver { - public TarXZArchiver() - { + public TarXZArchiver() { setupCompressionMethod(); } - private void setupCompressionMethod() - { - setCompression( TarCompressionMethod.xz ); + private void setupCompressionMethod() { + setCompression(TarCompressionMethod.xz); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarXZUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarXZUnArchiver.java index 0c6160070..eba2fc154 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarXZUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarXZUnArchiver.java @@ -24,25 +24,20 @@ * @author philip.lourandos * @since 3.3 */ -@Named( "tar.xz" ) -public class TarXZUnArchiver extends TarUnArchiver -{ +@Named("tar.xz") +public class TarXZUnArchiver extends TarUnArchiver { - public TarXZUnArchiver() - { + public TarXZUnArchiver() { setupCompressionMethod(); } - public TarXZUnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarXZUnArchiver(File sourceFile) { + super(sourceFile); setupCompressionMethod(); } - private void setupCompressionMethod() - { - setCompression( TarUnArchiver.UntarCompressionMethod.XZ ); + private void setupCompressionMethod() { + setCompression(TarUnArchiver.UntarCompressionMethod.XZ); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdArchiver.java index 28c43c172..c1800174c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdArchiver.java @@ -22,17 +22,14 @@ * * @since 4.7.0 */ -@Named( "tar.zst" ) -public class TarZstdArchiver extends TarArchiver -{ +@Named("tar.zst") +public class TarZstdArchiver extends TarArchiver { - public TarZstdArchiver() - { + public TarZstdArchiver() { setupCompressionMethod(); } - private final void setupCompressionMethod() - { - setCompression( TarCompressionMethod.zstd ); + private final void setupCompressionMethod() { + setCompression(TarCompressionMethod.zstd); } } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiver.java index b144ccfcc..8902bdb37 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiver.java @@ -16,30 +16,26 @@ package org.codehaus.plexus.archiver.tar; import javax.inject.Named; + import java.io.File; /** * Extract files in tar with zstd compression */ -@Named( "tar.zst" ) -public class TarZstdUnArchiver extends TarUnArchiver -{ +@Named("tar.zst") +public class TarZstdUnArchiver extends TarUnArchiver { - public TarZstdUnArchiver() - { + public TarZstdUnArchiver() { setupCompressionMethod(); } - public TarZstdUnArchiver( File sourceFile ) - { - super( sourceFile ); + public TarZstdUnArchiver(File sourceFile) { + super(sourceFile); setupCompressionMethod(); } - private final void setupCompressionMethod() - { - setCompression( UntarCompressionMethod.ZSTD ); + private final void setupCompressionMethod() { + setCompression(UntarCompressionMethod.ZSTD); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/XZTarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/XZTarFile.java index c35bd96c0..95fcef949 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/XZTarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/XZTarFile.java @@ -18,6 +18,7 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; + import org.codehaus.plexus.archiver.xz.XZUnArchiver; /** @@ -25,18 +26,14 @@ * @author philip.lourandos * @since 3.3 */ -public class XZTarFile extends TarFile -{ +public class XZTarFile extends TarFile { - public XZTarFile( File file ) - { - super( file ); + public XZTarFile(File file) { + super(file); } @Override - protected InputStream getInputStream( File file ) throws IOException - { - return XZUnArchiver.getXZInputStream( super.getInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return XZUnArchiver.getXZInputStream(super.getInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/tar/ZstdTarFile.java b/src/main/java/org/codehaus/plexus/archiver/tar/ZstdTarFile.java index 9a65686c8..97404565c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/tar/ZstdTarFile.java +++ b/src/main/java/org/codehaus/plexus/archiver/tar/ZstdTarFile.java @@ -15,27 +15,23 @@ */ package org.codehaus.plexus.archiver.tar; -import org.codehaus.plexus.archiver.zstd.ZstdUnArchiver; - import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.codehaus.plexus.archiver.zstd.ZstdUnArchiver; + /** * Extension of {@link org.codehaus.plexus.archiver.tar.TarFile} for zst compressed files. */ -public class ZstdTarFile extends TarFile -{ +public class ZstdTarFile extends TarFile { - public ZstdTarFile( File file ) - { - super( file ); + public ZstdTarFile(File file) { + super(file); } @Override - protected InputStream getInputStream( File file ) throws IOException - { - return ZstdUnArchiver.getZstdInputStream( super.getInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return ZstdUnArchiver.getZstdInputStream(super.getInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/AbstractFileSet.java b/src/main/java/org/codehaus/plexus/archiver/util/AbstractFileSet.java index 0ec6d5966..5c2cde548 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/AbstractFileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/AbstractFileSet.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.archiver.util; import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.BaseFileSet; import org.codehaus.plexus.components.io.filemappers.FileMapper; import org.codehaus.plexus.components.io.fileselectors.FileSelector; @@ -26,9 +27,7 @@ * * @since 1.0-alpha-9 */ -public abstract class AbstractFileSet - implements BaseFileSet -{ +public abstract class AbstractFileSet implements BaseFileSet { private String prefix; @@ -52,14 +51,12 @@ public abstract class AbstractFileSet * Sets a string of patterns, which excluded files * should match. */ - public void setExcludes( String[] excludes ) - { + public void setExcludes(String[] excludes) { this.excludes = excludes; } @Override - public String[] getExcludes() - { + public String[] getExcludes() { return excludes; } @@ -67,14 +64,12 @@ 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; } @Override - public FileSelector[] getFileSelectors() - { + public FileSelector[] getFileSelectors() { return fileSelectors; } @@ -82,14 +77,12 @@ public FileSelector[] getFileSelectors() * Sets a string of patterns, which included files * should match. */ - public void setIncludes( String[] includes ) - { + public void setIncludes(String[] includes) { this.includes = includes; } @Override - public String[] getIncludes() - { + public String[] getIncludes() { return includes; } @@ -97,14 +90,12 @@ 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; } @Override - public String getPrefix() - { + public String getPrefix() { return prefix; } @@ -112,14 +103,12 @@ 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; } @Override - public boolean isCaseSensitive() - { + public boolean isCaseSensitive() { return caseSensitive; } @@ -127,14 +116,12 @@ 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; } @Override - public boolean isUsingDefaultExcludes() - { + public boolean isUsingDefaultExcludes() { return usingDefaultExcludes; } @@ -142,54 +129,45 @@ 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; } @Override - public boolean isIncludingEmptyDirectories() - { + public boolean isIncludingEmptyDirectories() { return includingEmptyDirectories; } - public T prefixed( String prefix ) - { - setPrefix( prefix ); + public T prefixed(String prefix) { + setPrefix(prefix); return (T) this; } - public T include( String[] includes ) - { - setIncludes( includes ); + public T include(String[] includes) { + setIncludes(includes); return (T) this; } - public T exclude( String[] excludes ) - { - setExcludes( excludes ); + public T exclude(String[] excludes) { + setExcludes(excludes); return (T) this; } - public T includeExclude( String[] includes, String[] excludes ) - { - return (T) include( includes ).exclude( excludes ); + public T includeExclude(String[] includes, String[] excludes) { + return (T) include(includes).exclude(excludes); } - public T includeEmptyDirs( boolean includeEmptyDirectories ) - { - setIncludingEmptyDirectories( includeEmptyDirectories ); + public T includeEmptyDirs(boolean includeEmptyDirectories) { + setIncludingEmptyDirectories(includeEmptyDirectories); return (T) this; } - public void setStreamTransformer( @Nonnull InputStreamTransformer streamTransformer ) - { + public void setStreamTransformer(@Nonnull InputStreamTransformer streamTransformer) { this.streamTransformer = streamTransformer; } @Override - public InputStreamTransformer getStreamTransformer() - { + public InputStreamTransformer getStreamTransformer() { return streamTransformer; } @@ -197,15 +175,12 @@ public InputStreamTransformer getStreamTransformer() * Sets a set of file mappers, which should be used * to change the filename of the included files. */ - public void setFileMappers( FileMapper[] fileMappers ) - { + public void setFileMappers(FileMapper[] fileMappers) { this.fileMappers = fileMappers; } @Override - public FileMapper[] getFileMappers() - { + public FileMapper[] getFileMappers() { return fileMappers; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java b/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java index c4960024a..2bfa36dc2 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtils.java @@ -17,17 +17,16 @@ import java.io.File; import java.io.IOException; + import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.components.io.attributes.AttributeUtils; import org.codehaus.plexus.util.Os; import org.slf4j.Logger; -@SuppressWarnings( "JavaDoc" ) -public final class ArchiveEntryUtils -{ +@SuppressWarnings("JavaDoc") +public final class ArchiveEntryUtils { - private ArchiveEntryUtils() - { + private ArchiveEntryUtils() { // no op } @@ -40,10 +39,9 @@ private ArchiveEntryUtils() * @deprecated Use {@link #chmod(File, int)} */ @Deprecated - public static void chmod( final File file, final int mode, final Logger logger, boolean useJvmChmod ) - throws ArchiverException - { - chmod( file, mode ); + public static void chmod(final File file, final int mode, final Logger logger, boolean useJvmChmod) + throws ArchiverException { + chmod(file, mode); } /** @@ -54,28 +52,19 @@ public static void chmod( final File file, final int mode, final Logger logger, * @deprecated Use {@link #chmod(File, int)} */ @Deprecated - public static void chmod( final File file, final int mode, final Logger logger ) - throws ArchiverException - { - chmod( file, mode ); + public static void chmod(final File file, final int mode, final Logger logger) throws ArchiverException { + chmod(file, mode); } - public static void chmod( final File file, final int mode ) - throws ArchiverException - { - if ( !Os.isFamily( Os.FAMILY_UNIX ) ) - { + public static void chmod(final File file, final int mode) throws ArchiverException { + if (!Os.isFamily(Os.FAMILY_UNIX)) { return; } - try - { - AttributeUtils.chmod( file, mode ); - } - catch ( IOException e ) - { - throw new ArchiverException( "Failed setting file attributes", e ); + try { + AttributeUtils.chmod(file, mode); + } catch (IOException e) { + throw new ArchiverException("Failed setting file attributes", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/Compressor.java b/src/main/java/org/codehaus/plexus/archiver/util/Compressor.java index 31e801073..79d41af54 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/Compressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/Compressor.java @@ -20,17 +20,16 @@ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; + import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -public abstract class Compressor -{ - private final Logger logger = LoggerFactory.getLogger( getClass() ); +public abstract class Compressor { + private final Logger logger = LoggerFactory.getLogger(getClass()); - protected Logger getLogger() - { + protected Logger getLogger() { return logger; } @@ -43,29 +42,25 @@ protected Logger getLogger() * * @param compressFile */ - public void setDestFile( File compressFile ) - { + public void setDestFile(File compressFile) { this.destFile = compressFile; } - public File getDestFile() - { + public File getDestFile() { return destFile; } /** * The resource to compress; required. */ - public void setSource( PlexusIoResource source ) - { + public void setSource(PlexusIoResource source) { this.source = source; } /** * The resource to compress; required. */ - public PlexusIoResource getSource() - { + public PlexusIoResource getSource() { return source; } @@ -77,28 +72,21 @@ public PlexusIoResource getSource() * * @throws IOException */ - private void compressFile( InputStream in, OutputStream zOut ) - throws IOException - { - byte[] buffer = new byte[ 8 * 1024 ]; + private void compressFile(InputStream in, OutputStream zOut) throws IOException { + byte[] buffer = new byte[8 * 1024]; int count = 0; - do - { - zOut.write( buffer, 0, count ); - count = in.read( buffer, 0, buffer.length ); - } - while ( count != -1 ); + do { + zOut.write(buffer, 0, count); + count = in.read(buffer, 0, buffer.length); + } while (count != -1); } /** * compress a resource to an output stream */ - protected void compress( PlexusIoResource resource, OutputStream zOut ) - throws IOException - { - try ( InputStream in = Streams.bufferedInputStream( resource.getContents() ) ) - { - compressFile( in, zOut ); + protected void compress(PlexusIoResource resource, OutputStream zOut) throws IOException { + try (InputStream in = Streams.bufferedInputStream(resource.getContents())) { + compressFile(in, zOut); } } @@ -107,15 +95,12 @@ protected void compress( PlexusIoResource resource, OutputStream zOut ) * * this is public so the process of compression and closing can be dealt with separately. */ - public abstract void compress() - throws ArchiverException; + public abstract void compress() throws ArchiverException; /** * subclasses must implement this method to cleanup after compression * * this is public so the process of compression and closing can be dealt with separately. */ - public abstract void close() - throws ArchiverException; - + public abstract void close() throws ArchiverException; } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/DefaultArchivedFileSet.java b/src/main/java/org/codehaus/plexus/archiver/util/DefaultArchivedFileSet.java index dc59ce1a8..1574e624a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/DefaultArchivedFileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/DefaultArchivedFileSet.java @@ -1,7 +1,9 @@ package org.codehaus.plexus.archiver.util; -import java.io.File; import javax.annotation.Nonnull; + +import java.io.File; + import org.codehaus.plexus.archiver.ArchivedFileSet; /** @@ -9,31 +11,23 @@ * * @since 1.0-alpha-9 */ -public class DefaultArchivedFileSet - extends AbstractFileSet - implements ArchivedFileSet -{ +public class DefaultArchivedFileSet extends AbstractFileSet implements ArchivedFileSet { private final File archive; - public DefaultArchivedFileSet( @Nonnull File archive ) - { + public DefaultArchivedFileSet(@Nonnull File archive) { this.archive = archive; } @Override - public File getArchive() - { + public File getArchive() { return archive; } - public static DefaultArchivedFileSet archivedFileSet( File archiveFile ) - { - if ( archiveFile == null ) - { - throw new IllegalArgumentException( "Archive File cannot be null" ); + public static DefaultArchivedFileSet archivedFileSet(File archiveFile) { + if (archiveFile == null) { + throw new IllegalArgumentException("Archive File cannot be null"); } - return new DefaultArchivedFileSet( archiveFile ); + return new DefaultArchivedFileSet(archiveFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/DefaultFileSet.java b/src/main/java/org/codehaus/plexus/archiver/util/DefaultFileSet.java index 6b5f55883..158473d44 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/DefaultFileSet.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/DefaultFileSet.java @@ -1,7 +1,9 @@ package org.codehaus.plexus.archiver.util; -import java.io.File; import javax.annotation.Nonnull; + +import java.io.File; + import org.codehaus.plexus.archiver.FileSet; /** @@ -9,39 +11,30 @@ * * @since 1.0-alpha-9 */ -public class DefaultFileSet - extends AbstractFileSet - implements FileSet -{ +public class DefaultFileSet extends AbstractFileSet implements FileSet { private File directory; - public DefaultFileSet( File directory ) - { + public DefaultFileSet(File directory) { this.directory = directory; } - public DefaultFileSet() - { - } + public DefaultFileSet() {} /** * Sets the file sets base directory. */ - public void setDirectory( @Nonnull File directory ) - { + public void setDirectory(@Nonnull File directory) { this.directory = directory; } - @Nonnull public File getDirectory() - { + @Nonnull + public File getDirectory() { return directory; } - public static DefaultFileSet fileSet( File directory ) - { - final DefaultFileSet defaultFileSet = new DefaultFileSet( directory ); + public static DefaultFileSet fileSet(File directory) { + final DefaultFileSet defaultFileSet = new DefaultFileSet(directory); return defaultFileSet; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/FilePermission.java b/src/main/java/org/codehaus/plexus/archiver/util/FilePermission.java index 830645173..f8a0bae6e 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/FilePermission.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/FilePermission.java @@ -23,8 +23,7 @@ * @since 1.1 * */ -public class FilePermission -{ +public class FilePermission { private final boolean executable; @@ -38,9 +37,13 @@ public class FilePermission private final boolean writable; - public FilePermission( boolean executable, boolean ownerOnlyExecutable, boolean ownerOnlyReadable, - boolean readable, boolean ownerOnlyWritable, boolean writable ) - { + public FilePermission( + boolean executable, + boolean ownerOnlyExecutable, + boolean ownerOnlyReadable, + boolean readable, + boolean ownerOnlyWritable, + boolean writable) { this.executable = executable; this.ownerOnlyExecutable = ownerOnlyExecutable; this.ownerOnlyReadable = ownerOnlyReadable; @@ -49,43 +52,34 @@ public FilePermission( boolean executable, boolean ownerOnlyExecutable, boolean this.writable = writable; } - public boolean isExecutable() - { + public boolean isExecutable() { return executable; } - public boolean isOwnerOnlyExecutable() - { + public boolean isOwnerOnlyExecutable() { return ownerOnlyExecutable; } - public boolean isOwnerOnlyReadable() - { + public boolean isOwnerOnlyReadable() { return ownerOnlyReadable; } - public boolean isReadable() - { + public boolean isReadable() { return readable; } - public boolean isOwnerOnlyWritable() - { + public boolean isOwnerOnlyWritable() { return ownerOnlyWritable; } - public boolean isWritable() - { + public boolean isWritable() { return writable; } @Override - public String toString() - { + public String toString() { return "FilePermission [executable=" + executable + ", ownerOnlyExecutable=" + ownerOnlyExecutable - + ", ownerOnlyReadable=" + ownerOnlyReadable + ", readable=" + readable + ", ownerOnlyWritable=" - + ownerOnlyWritable + ", writable=" + writable + "]"; - + + ", ownerOnlyReadable=" + ownerOnlyReadable + ", readable=" + readable + ", ownerOnlyWritable=" + + ownerOnlyWritable + ", writable=" + writable + "]"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/FilePermissionUtils.java b/src/main/java/org/codehaus/plexus/archiver/util/FilePermissionUtils.java index c83f5d806..3ac9f54b9 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/FilePermissionUtils.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/FilePermissionUtils.java @@ -20,6 +20,7 @@ import java.util.ArrayList; import java.util.List; + import org.codehaus.plexus.util.StringUtils; import org.slf4j.Logger; @@ -27,11 +28,9 @@ * @author Olivier Lamy * @since 1.0.1 */ -public class FilePermissionUtils -{ +public class FilePermissionUtils { - private FilePermissionUtils() - { + private FilePermissionUtils() { // no op } @@ -40,33 +39,31 @@ private FilePermissionUtils() * * @return FilePermission associated to the mode (group permission are ignored here) */ - public static FilePermission getFilePermissionFromMode( String mode, Logger logger ) - { - if ( StringUtils.isBlank( mode ) ) - { - throw new IllegalArgumentException( " file mode cannot be empty" ); + public static FilePermission getFilePermissionFromMode(String mode, Logger logger) { + if (StringUtils.isBlank(mode)) { + throw new IllegalArgumentException(" file mode cannot be empty"); } // 4 characters works on some unix (ie solaris) - if ( mode.length() != 3 && mode.length() != 4 ) - { - throw new IllegalArgumentException( " file mode must be 3 or 4 characters" ); + if (mode.length() != 3 && mode.length() != 4) { + throw new IllegalArgumentException(" file mode must be 3 or 4 characters"); } - List modes = new ArrayList<>( mode.length() ); - for ( int i = 0, size = mode.length(); i < size; i++ ) - { - modes.add( String.valueOf( mode.charAt( i ) ) ); + List modes = new ArrayList<>(mode.length()); + for (int i = 0, size = mode.length(); i < size; i++) { + modes.add(String.valueOf(mode.charAt(i))); } - boolean executable = false, ownerOnlyExecutable = true, ownerOnlyReadable = true, readable = false, - ownerOnlyWritable = true, writable = false; + boolean executable = false, + ownerOnlyExecutable = true, + ownerOnlyReadable = true, + readable = false, + ownerOnlyWritable = true, + writable = false; // handle user perm - try - { - int userMode = Integer.parseInt( modes.get( mode.length() == 4 ? 1 : 0 ) ); - switch ( userMode ) - { + try { + int userMode = Integer.parseInt(modes.get(mode.length() == 4 ? 1 : 0)); + switch (userMode) { case 0: break; case 1: @@ -96,20 +93,16 @@ public static FilePermission getFilePermissionFromMode( String mode, Logger logg executable = true; break; default: - logger.warn( "ignore file mode " + userMode ); + logger.warn("ignore file mode " + userMode); } - } - catch ( NumberFormatException e ) - { - throw new IllegalArgumentException( " file mode must contains only number " + mode ); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(" file mode must contains only number " + mode); } // handle all perm - try - { - int allMode = Integer.parseInt( modes.get( mode.length() == 4 ? 3 : 2 ) ); - switch ( allMode ) - { + try { + int allMode = Integer.parseInt(modes.get(mode.length() == 4 ? 3 : 2)); + switch (allMode) { case 0: break; case 1: @@ -151,17 +144,13 @@ public static FilePermission getFilePermissionFromMode( String mode, Logger logg ownerOnlyWritable = false; break; default: - logger.warn( "ignore file mode " + allMode ); + logger.warn("ignore file mode " + allMode); } - } - catch ( NumberFormatException e ) - { - throw new IllegalArgumentException( " file mode must contains only number " + mode ); + } catch (NumberFormatException e) { + throw new IllegalArgumentException(" file mode must contains only number " + mode); } - return new FilePermission( executable, ownerOnlyExecutable, ownerOnlyReadable, readable, ownerOnlyWritable, - writable ); - + return new FilePermission( + executable, ownerOnlyExecutable, ownerOnlyReadable, readable, ownerOnlyWritable, writable); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/FilterSupport.java b/src/main/java/org/codehaus/plexus/archiver/util/FilterSupport.java index bc0cd31c4..09b016858 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/FilterSupport.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/FilterSupport.java @@ -2,6 +2,7 @@ import java.io.InputStream; import java.util.List; + import org.codehaus.plexus.archiver.ArchiveFileFilter; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.components.io.fileselectors.FileSelector; @@ -11,36 +12,28 @@ * @deprecated Use {@link FileSelector} and {@link Archiver#addFileSet}. */ @Deprecated -public class FilterSupport -{ +public class FilterSupport { private final List filters; private final Logger logger; - public FilterSupport( List filters, Logger logger ) - { + public FilterSupport(List filters, Logger logger) { this.filters = filters; this.logger = logger; } - public boolean include( InputStream dataStream, String entryName ) - { + public boolean include(InputStream dataStream, String entryName) { boolean included = true; - if ( filters != null && !filters.isEmpty() ) - { - for ( ArchiveFileFilter filter : filters ) - { - included = filter.include( dataStream, entryName ); - - if ( !included ) - { - if ( logger.isDebugEnabled() ) - { - logger.debug( "Entry: \'" + entryName + "\' excluded by filter: " - + filter.getClass().getName() ); + if (filters != null && !filters.isEmpty()) { + for (ArchiveFileFilter filter : filters) { + included = filter.include(dataStream, entryName); + if (!included) { + if (logger.isDebugEnabled()) { + logger.debug("Entry: \'" + entryName + "\' excluded by filter: " + + filter.getClass().getName()); } break; @@ -50,5 +43,4 @@ public boolean include( InputStream dataStream, String entryName ) return included; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/ResourceUtils.java b/src/main/java/org/codehaus/plexus/archiver/util/ResourceUtils.java index 4c36792e2..1bd25e01f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/ResourceUtils.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/ResourceUtils.java @@ -13,14 +13,12 @@ /** * Utility class for work with {@link PlexusIoResource} instances. */ -public class ResourceUtils -{ +public class ResourceUtils { /** * Private constructor, to prevent accidental implementation. */ - private ResourceUtils() - { + private ResourceUtils() { // Does nothing } @@ -28,25 +26,21 @@ private ResourceUtils() * Queries, whether the given source is up-to-date relative to * the given destination. */ - public static boolean isUptodate( PlexusIoResource source, File destination ) - { - return isUptodate( source, destination.lastModified() ); + public static boolean isUptodate(PlexusIoResource source, File destination) { + return isUptodate(source, destination.lastModified()); } /** * Queries, whether the given source is up-to-date relative to * the given modification date. */ - public static boolean isUptodate( PlexusIoResource source, long destinationDate ) - { + public static boolean isUptodate(PlexusIoResource source, long destinationDate) { final long s = source.getLastModified(); - if ( s == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ) - { + if (s == PlexusIoResource.UNKNOWN_MODIFICATION_DATE) { return false; } - if ( destinationDate == 0 ) - { + if (destinationDate == 0) { return false; } @@ -57,15 +51,12 @@ public static boolean isUptodate( PlexusIoResource source, long destinationDate * Queries, whether the given source is up-to-date relative to * the given modification date. */ - public static boolean isUptodate( long sourceDate, long destinationDate ) - { - if ( sourceDate == PlexusIoResource.UNKNOWN_MODIFICATION_DATE ) - { + public static boolean isUptodate(long sourceDate, long destinationDate) { + if (sourceDate == PlexusIoResource.UNKNOWN_MODIFICATION_DATE) { return false; } - if ( destinationDate == 0 ) - { + if (destinationDate == 0) { return false; } @@ -75,47 +66,38 @@ public static boolean isUptodate( long sourceDate, long destinationDate ) /** * Copies the sources contents to the given destination file. */ - public static void copyFile( PlexusIoResource in, File outFile ) - throws IOException - { - try ( InputStream input = in.getContents(); OutputStream output = Files.newOutputStream( outFile.toPath() ) ) - { - IOUtil.copy( input, output ); + public static void copyFile(PlexusIoResource in, File outFile) throws IOException { + try (InputStream input = in.getContents(); + OutputStream output = Files.newOutputStream(outFile.toPath())) { + IOUtil.copy(input, output); } } /** * Copies the sources contents to the given destination file. */ - public static void copyFile( InputStream input, File outFile ) - throws IOException - { + public static void copyFile(InputStream input, File outFile) throws IOException { OutputStream output = null; - try - { - output = Files.newOutputStream( outFile.toPath() ); - IOUtil.copy( input, output ); + try { + output = Files.newOutputStream(outFile.toPath()); + IOUtil.copy(input, output); output.close(); output = null; input.close(); input = null; - } - finally - { - IOUtil.close( input ); - IOUtil.close( output ); + } finally { + IOUtil.close(input); + IOUtil.close(output); } } /** * Checks, whether the resource and the file are identical. */ - public static boolean isSame( PlexusIoResource resource, File file ) - { - if ( resource instanceof FileSupplier ) - { - File resourceFile = ( (FileSupplier) resource ).getFile(); - return file.equals( resourceFile ); + public static boolean isSame(PlexusIoResource resource, File file) { + if (resource instanceof FileSupplier) { + File resourceFile = ((FileSupplier) resource).getFile(); + return file.equals(resourceFile); } return false; } @@ -125,15 +107,11 @@ public static boolean isSame( PlexusIoResource resource, File file ) * Uses {@link File#getCanonicalFile()} for comparison, which is much * slower than comparing the files. */ - public static boolean isCanonicalizedSame( PlexusIoResource resource, File file ) - throws IOException - { - if ( resource instanceof FileSupplier ) - { - File resourceFile = ( (FileSupplier) resource ).getFile(); - return file.getCanonicalFile().equals( resourceFile.getCanonicalFile() ); + public static boolean isCanonicalizedSame(PlexusIoResource resource, File file) throws IOException { + if (resource instanceof FileSupplier) { + File resourceFile = ((FileSupplier) resource).getFile(); + return file.getCanonicalFile().equals(resourceFile.getCanonicalFile()); } return false; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/util/Streams.java b/src/main/java/org/codehaus/plexus/archiver/util/Streams.java index b37689afe..dbdd71f77 100644 --- a/src/main/java/org/codehaus/plexus/archiver/util/Streams.java +++ b/src/main/java/org/codehaus/plexus/archiver/util/Streams.java @@ -15,6 +15,9 @@ */ package org.codehaus.plexus.archiver.util; +import javax.annotation.WillClose; +import javax.annotation.WillNotClose; + import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; @@ -24,137 +27,87 @@ import java.io.OutputStream; import java.nio.file.Files; -import javax.annotation.WillClose; -import javax.annotation.WillNotClose; - import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.util.IOUtil; -public class Streams -{ - - public static final InputStream EMPTY_INPUTSTREAM = new ByteArrayInputStream( new byte[0] ); +public class Streams { - public static BufferedInputStream bufferedInputStream( InputStream is ) - { - return is instanceof BufferedInputStream - ? (BufferedInputStream) is - : new BufferedInputStream( is, 65536 ); + public static final InputStream EMPTY_INPUTSTREAM = new ByteArrayInputStream(new byte[0]); + public static BufferedInputStream bufferedInputStream(InputStream is) { + return is instanceof BufferedInputStream ? (BufferedInputStream) is : new BufferedInputStream(is, 65536); } - public static BufferedOutputStream bufferedOutputStream( OutputStream os ) - { - return os instanceof BufferedOutputStream - ? (BufferedOutputStream) os - : new BufferedOutputStream( os, 65536 ); - + public static BufferedOutputStream bufferedOutputStream(OutputStream os) { + return os instanceof BufferedOutputStream ? (BufferedOutputStream) os : new BufferedOutputStream(os, 65536); } - public static byte[] cacheBuffer() - { - return new byte[ 8 * 1024 ]; + public static byte[] cacheBuffer() { + return new byte[8 * 1024]; } - public static InputStream fileInputStream( File file ) - throws IOException - { - return Files.newInputStream( file.toPath() ); + public static InputStream fileInputStream(File file) throws IOException { + return Files.newInputStream(file.toPath()); } - public static InputStream fileInputStream( File file, String operation ) - throws ArchiverException - { - try - { - return Files.newInputStream( file.toPath() ); - } - catch ( IOException e ) - { + public static InputStream fileInputStream(File file, String operation) throws ArchiverException { + try { + return Files.newInputStream(file.toPath()); + } catch (IOException e) { throw new ArchiverException( - "Problem reading input file for " + operation + " " + file.getParent() + ", " + e.getMessage() ); - + "Problem reading input file for " + operation + " " + file.getParent() + ", " + e.getMessage()); } } - public static OutputStream fileOutputStream( File file ) - throws IOException - { - return Files.newOutputStream( file.toPath() ); + public static OutputStream fileOutputStream(File file) throws IOException { + return Files.newOutputStream(file.toPath()); } - public static OutputStream fileOutputStream( File file, String operation ) - throws ArchiverException - { - try - { - return Files.newOutputStream( file.toPath() ); - } - catch ( IOException e ) - { + public static OutputStream fileOutputStream(File file, String operation) throws ArchiverException { + try { + return Files.newOutputStream(file.toPath()); + } catch (IOException e) { throw new ArchiverException( - "Problem creating output file for " + operation + " " + file.getParent() + ", " + e.getMessage() ); - + "Problem creating output file for " + operation + " " + file.getParent() + ", " + e.getMessage()); } } - public static void copyFully( @WillClose InputStream zIn, @WillClose OutputStream out, String gzip ) - throws ArchiverException - { + public static void copyFully(@WillClose InputStream zIn, @WillClose OutputStream out, String gzip) + throws ArchiverException { // There must be 1 million libs out there that do this - try - { - copyFullyDontCloseOutput( zIn, out, gzip ); + try { + copyFullyDontCloseOutput(zIn, out, gzip); out.close(); out = null; - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure copying.", e ); - } - finally - { - IOUtil.close( out ); + } catch (final IOException e) { + throw new ArchiverException("Failure copying.", e); + } finally { + IOUtil.close(out); } } - public static void copyFullyDontCloseOutput( @WillClose InputStream zIn, @WillNotClose OutputStream out, - String gzip ) - throws ArchiverException - { + public static void copyFullyDontCloseOutput(@WillClose InputStream zIn, @WillNotClose OutputStream out, String gzip) + throws ArchiverException { // There must be 1 million libs out there that do this - try - { + try { byte[] buffer = cacheBuffer(); int count = 0; - do - { - try - { - out.write( buffer, 0, count ); - } - catch ( IOException e ) - { + do { + try { + out.write(buffer, 0, count); + } catch (IOException e) { throw new ArchiverException( - "Problem writing to output in " + gzip + " operation " + e.getMessage() ); - + "Problem writing to output in " + gzip + " operation " + e.getMessage()); } - count = zIn.read( buffer, 0, buffer.length ); - } - while ( count != -1 ); + count = zIn.read(buffer, 0, buffer.length); + } while (count != -1); zIn.close(); zIn = null; - } - catch ( IOException e ) - { - throw new ArchiverException( - "Problem reading from source file in " + gzip + " operation " + e.getMessage() ); + } catch (IOException e) { + throw new ArchiverException("Problem reading from source file in " + gzip + " operation " + e.getMessage()); - } - finally - { - IOUtil.close( zIn ); + } finally { + IOUtil.close(zIn); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/war/PlexusIoWarFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/war/PlexusIoWarFileResourceCollection.java index 360a0f40c..60e76df67 100644 --- a/src/main/java/org/codehaus/plexus/archiver/war/PlexusIoWarFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/war/PlexusIoWarFileResourceCollection.java @@ -22,8 +22,5 @@ /** * Alias for {@link PlexusIoZipFileResourceCollection}. */ -@Named( "war" ) -public class PlexusIoWarFileResourceCollection - extends PlexusIoZipFileResourceCollection -{ -} +@Named("war") +public class PlexusIoWarFileResourceCollection extends PlexusIoZipFileResourceCollection {} diff --git a/src/main/java/org/codehaus/plexus/archiver/war/WarArchiver.java b/src/main/java/org/codehaus/plexus/archiver/war/WarArchiver.java index befce726c..2ee06f362 100644 --- a/src/main/java/org/codehaus/plexus/archiver/war/WarArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/war/WarArchiver.java @@ -20,6 +20,7 @@ import java.io.File; import java.io.IOException; + import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.jar.JarArchiver; @@ -42,10 +43,8 @@ * * @see JarArchiver */ -@Named( "war" ) -public class WarArchiver - extends JarArchiver -{ +@Named("war") +public class WarArchiver extends JarArchiver { /** * our web.xml deployment descriptor @@ -67,8 +66,7 @@ public class WarArchiver * @param excpectWebXml true if web xml is *expected* from the client */ @Deprecated - public void setIgnoreWebxml( boolean excpectWebXml ) - { + public void setIgnoreWebxml(boolean excpectWebXml) { expectWebXml = excpectWebXml; } @@ -77,13 +75,11 @@ public void setIgnoreWebxml( boolean excpectWebXml ) * * @param expectWebXml true if web xml is *expected* from the client */ - public void setExpectWebXml( boolean expectWebXml ) - { + public void setExpectWebXml(boolean expectWebXml) { this.expectWebXml = expectWebXml; } - public WarArchiver() - { + public WarArchiver() { super(); archiveType = "war"; } @@ -92,71 +88,48 @@ public WarArchiver() * set the deployment descriptor to use (WEB-INF/web.xml); * required unless update=true */ - public void setWebxml( File descr ) - throws ArchiverException - { + public void setWebxml(File descr) throws ArchiverException { deploymentDescriptor = descr; - if ( !deploymentDescriptor.exists() ) - { - throw new ArchiverException( "Deployment descriptor: " + deploymentDescriptor + " does not exist." ); + if (!deploymentDescriptor.exists()) { + throw new ArchiverException("Deployment descriptor: " + deploymentDescriptor + " does not exist."); } - addFile( descr, "WEB-INF" + File.separatorChar + "web.xml" ); + addFile(descr, "WEB-INF" + File.separatorChar + "web.xml"); } /** * add a file under WEB-INF/lib/ */ - public void addLib( File fileName ) - throws ArchiverException - { - addDirectory( fileName.getParentFile(), "WEB-INF/lib/", - new String[] - { - fileName.getName() - }, null ); - + public void addLib(File fileName) throws ArchiverException { + addDirectory(fileName.getParentFile(), "WEB-INF/lib/", new String[] {fileName.getName()}, null); } /** * add files under WEB-INF/lib/ */ - public void addLibs( File directoryName, String[] includes, String[] excludes ) - throws ArchiverException - { - addDirectory( directoryName, "WEB-INF/lib/", includes, excludes ); + public void addLibs(File directoryName, String[] includes, String[] excludes) throws ArchiverException { + addDirectory(directoryName, "WEB-INF/lib/", includes, excludes); } /** * add a file under WEB-INF/lib/ */ - public void addClass( File fileName ) - throws ArchiverException - { - addDirectory( fileName.getParentFile(), "WEB-INF/classes/", - new String[] - { - fileName.getName() - }, null ); - + public void addClass(File fileName) throws ArchiverException { + addDirectory(fileName.getParentFile(), "WEB-INF/classes/", new String[] {fileName.getName()}, null); } /** * add files under WEB-INF/classes */ - public void addClasses( File directoryName, String[] includes, String[] excludes ) - throws ArchiverException - { - addDirectory( directoryName, "WEB-INF/classes/", includes, excludes ); + public void addClasses(File directoryName, String[] includes, String[] excludes) throws ArchiverException { + addDirectory(directoryName, "WEB-INF/classes/", includes, excludes); } /** * files to add under WEB-INF; */ - public void addWebinf( File directoryName, String[] includes, String[] excludes ) - throws ArchiverException - { - addDirectory( directoryName, "WEB-INF/", includes, excludes ); + public void addWebinf(File directoryName, String[] includes, String[] excludes) throws ArchiverException { + addDirectory(directoryName, "WEB-INF/", includes, excludes); } /** @@ -166,52 +139,43 @@ public void addWebinf( File directoryName, String[] includes, String[] excludes * @param zOut */ @Override - protected void initZipOutputStream( ConcurrentJarCreator zOut ) - throws ArchiverException, IOException - { + protected void initZipOutputStream(ConcurrentJarCreator zOut) throws ArchiverException, IOException { // If no webxml file is specified, it's an error. - if ( expectWebXml && deploymentDescriptor == null && !isInUpdateMode() ) - { + if (expectWebXml && deploymentDescriptor == null && !isInUpdateMode()) { throw new ArchiverException( - "webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)" ); - + "webxml attribute is required (or pre-existing WEB-INF/web.xml if executing in update mode)"); } - super.initZipOutputStream( zOut ); + super.initZipOutputStream(zOut); } /** * Overridden from ZipArchiver class to deal with web.xml */ @Override - protected void zipFile( ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath ) - throws IOException, ArchiverException - { + protected void zipFile(ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath) + throws IOException, ArchiverException { // If the file being added is WEB-INF/web.xml, we warn if it's // not the one specified in the "webxml" attribute - or if // it's being added twice, meaning the same file is specified // by the "webxml" attribute and in a element. - if ( vPath.equalsIgnoreCase( "WEB-INF/web.xml" ) ) - { - if ( descriptorAdded || ( expectWebXml - && ( deploymentDescriptor == null - || !ResourceUtils.isCanonicalizedSame( entry.getResource(), - deploymentDescriptor ) ) ) ) - { - getLogger().warn( "Warning: selected " + archiveType - + " files include a WEB-INF/web.xml which will be ignored " - + "\n(webxml attribute is missing from " - + archiveType + " task, or ignoreWebxml attribute is specified as 'true')" ); - } - else - { - super.zipFile( entry, zOut, vPath ); + if (vPath.equalsIgnoreCase("WEB-INF/web.xml")) { + if (descriptorAdded + || (expectWebXml + && (deploymentDescriptor == null + || !ResourceUtils.isCanonicalizedSame( + entry.getResource(), deploymentDescriptor)))) { + getLogger() + .warn("Warning: selected " + archiveType + + " files include a WEB-INF/web.xml which will be ignored " + + "\n(webxml attribute is missing from " + + archiveType + " task, or ignoreWebxml attribute is specified as 'true')"); + } else { + super.zipFile(entry, zOut, vPath); descriptorAdded = true; } - } - else - { - super.zipFile( entry, zOut, vPath ); + } else { + super.zipFile(entry, zOut, vPath); } } @@ -220,12 +184,9 @@ protected void zipFile( ArchiveEntry entry, ConcurrentJarCreator zOut, String vP * gets executed. */ @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { descriptorAdded = false; expectWebXml = true; super.cleanUp(); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/war/WarUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/war/WarUnArchiver.java index 5cc7afc61..c49a82cfa 100644 --- a/src/main/java/org/codehaus/plexus/archiver/war/WarUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/war/WarUnArchiver.java @@ -25,18 +25,12 @@ /** * Alias for {@link ZipUnArchiver}. */ -@Named( "war" ) -public class WarUnArchiver - extends ZipUnArchiver -{ +@Named("war") +public class WarUnArchiver extends ZipUnArchiver { - public WarUnArchiver() - { - } + public WarUnArchiver() {} - public WarUnArchiver( File sourceFile ) - { - super( sourceFile ); + public WarUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/xz/PlexusIoXZResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/xz/PlexusIoXZResourceCollection.java index cf7666524..b6b39c6e9 100644 --- a/src/main/java/org/codehaus/plexus/archiver/xz/PlexusIoXZResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/xz/PlexusIoXZResourceCollection.java @@ -31,26 +31,21 @@ * @author lore * @since 3.3 */ -@Named( "xz" ) -public class PlexusIoXZResourceCollection extends PlexusIoCompressedFileResourceCollection -{ +@Named("xz") +public class PlexusIoXZResourceCollection extends PlexusIoCompressedFileResourceCollection { @Override - protected PlexusIoResourceAttributes getAttributes( File file ) throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + protected PlexusIoResourceAttributes getAttributes(File file) throws IOException { + return new FileAttributes(file, new HashMap(), new HashMap()); } @Override - protected String getDefaultExtension() - { + protected String getDefaultExtension() { return ".xz"; } @Override - protected InputStream getInputStream( File file ) throws IOException - { - return XZUnArchiver.getXZInputStream( Streams.fileInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return XZUnArchiver.getXZInputStream(Streams.fileInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/xz/XZArchiver.java b/src/main/java/org/codehaus/plexus/archiver/xz/XZArchiver.java index 79b7f2ed1..2a778f6e6 100644 --- a/src/main/java/org/codehaus/plexus/archiver/xz/XZArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/xz/XZArchiver.java @@ -18,6 +18,7 @@ import javax.inject.Named; import java.io.IOException; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; @@ -28,55 +29,44 @@ * @author philiplourandos * @since 3.3 */ -@Named( "xz" ) -public class XZArchiver extends AbstractArchiver -{ +@Named("xz") +public class XZArchiver extends AbstractArchiver { private final XZCompressor compressor = new XZCompressor(); - public XZArchiver() - { - } + public XZArchiver() {} @Override - protected void execute() throws ArchiverException, IOException - { - if ( !checkForced() ) - { + protected void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } ArchiveEntry entry = iter.next(); - if ( iter.hasNext() ) - { - throw new ArchiverException( "There is more than one file in input." ); + if (iter.hasNext()) { + throw new ArchiverException("There is more than one file in input."); } - compressor.setSource( entry.getResource() ); - compressor.setDestFile( getDestFile() ); + compressor.setSource(entry.getResource()); + compressor.setDestFile(getDestFile()); compressor.compress(); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void close() throws IOException - { + protected void close() throws IOException { compressor.close(); } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "xz"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/xz/XZCompressor.java b/src/main/java/org/codehaus/plexus/archiver/xz/XZCompressor.java index 4f70b00b3..c2bab4d7f 100644 --- a/src/main/java/org/codehaus/plexus/archiver/xz/XZCompressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/xz/XZCompressor.java @@ -16,9 +16,11 @@ package org.codehaus.plexus.archiver.xz; import java.io.IOException; + import org.apache.commons.compress.compressors.xz.XZCompressorOutputStream; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Compressor; + import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; @@ -26,44 +28,31 @@ * @author philip.lourandos * @since 3.3 */ -public class XZCompressor extends Compressor -{ +public class XZCompressor extends Compressor { private XZCompressorOutputStream xzOut; - public XZCompressor() - { - } + public XZCompressor() {} @Override - public void compress() throws ArchiverException - { - try - { - xzOut = new XZCompressorOutputStream( bufferedOutputStream( fileOutputStream( getDestFile() ) ) ); - compress( getSource(), xzOut ); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Problem creating xz " + ioe.getMessage(), ioe ); + public void compress() throws ArchiverException { + try { + xzOut = new XZCompressorOutputStream(bufferedOutputStream(fileOutputStream(getDestFile()))); + compress(getSource(), xzOut); + } catch (IOException ioe) { + throw new ArchiverException("Problem creating xz " + ioe.getMessage(), ioe); } } @Override - public void close() - { - try - { - if ( this.xzOut != null ) - { + public void close() { + try { + if (this.xzOut != null) { this.xzOut.close(); xzOut = null; } - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure closing target.", e ); + } catch (final IOException e) { + throw new ArchiverException("Failure closing target.", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/xz/XZUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/xz/XZUnArchiver.java index a52324dbe..c55fa3ae3 100644 --- a/src/main/java/org/codehaus/plexus/archiver/xz/XZUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/xz/XZUnArchiver.java @@ -15,15 +15,17 @@ */ package org.codehaus.plexus.archiver.xz; +import javax.annotation.Nonnull; +import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.io.InputStream; -import javax.annotation.Nonnull; -import javax.inject.Named; import org.apache.commons.compress.compressors.xz.XZCompressorInputStream; import org.codehaus.plexus.archiver.AbstractUnArchiver; import org.codehaus.plexus.archiver.ArchiverException; + import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.copyFully; @@ -34,54 +36,41 @@ * @author philip.lourandos * @since 3.3 */ -@Named( "xz" ) -public class XZUnArchiver extends AbstractUnArchiver -{ +@Named("xz") +public class XZUnArchiver extends AbstractUnArchiver { private static final String OPERATION_XZ = "xz"; - public XZUnArchiver() - { - } + public XZUnArchiver() {} - public XZUnArchiver( File source ) - { - super( source ); + public XZUnArchiver(File source) { + super(source); } @Override - protected void execute() throws ArchiverException - { - if ( getSourceFile().lastModified() > getDestFile().lastModified() ) - { - getLogger().info( "Expanding " + getSourceFile().getAbsolutePath() + " to " - + getDestFile().getAbsolutePath() ); - - copyFully( getXZInputStream( bufferedInputStream( fileInputStream( getSourceFile(), OPERATION_XZ ) ) ), - bufferedOutputStream( fileOutputStream( getDestFile(), OPERATION_XZ ) ), OPERATION_XZ ); + protected void execute() throws ArchiverException { + if (getSourceFile().lastModified() > getDestFile().lastModified()) { + getLogger() + .info("Expanding " + getSourceFile().getAbsolutePath() + " to " + + getDestFile().getAbsolutePath()); + copyFully( + getXZInputStream(bufferedInputStream(fileInputStream(getSourceFile(), OPERATION_XZ))), + bufferedOutputStream(fileOutputStream(getDestFile(), OPERATION_XZ)), + OPERATION_XZ); } } - public static @Nonnull - XZCompressorInputStream getXZInputStream( InputStream in ) - throws ArchiverException - { - try - { - return new XZCompressorInputStream( in ); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Trouble creating BZIP2 compressor, invalid file ?", ioe ); + public static @Nonnull XZCompressorInputStream getXZInputStream(InputStream in) throws ArchiverException { + try { + return new XZCompressorInputStream(in); + } catch (IOException ioe) { + throw new ArchiverException("Trouble creating BZIP2 compressor, invalid file ?", ioe); } } @Override - protected void execute( String path, File outputDirectory ) throws ArchiverException - { - throw new UnsupportedOperationException( "Targeted execution not supported in xz format" ); - + protected void execute(String path, File outputDirectory) throws ArchiverException { + throw new UnsupportedOperationException("Targeted execution not supported in xz format"); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipArchiver.java index f1df19cd6..44e9f2ebb 100755 --- a/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipArchiver.java @@ -16,9 +16,6 @@ */ package org.codehaus.plexus.archiver.zip; -import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; -import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; - import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; @@ -55,10 +52,11 @@ import org.codehaus.plexus.components.io.resources.PlexusIoResource; import org.codehaus.plexus.util.FileUtils; -@SuppressWarnings( { "UnusedDeclaration" } ) -public abstract class AbstractZipArchiver - extends AbstractArchiver -{ +import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; +import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; + +@SuppressWarnings({"UnusedDeclaration"}) +public abstract class AbstractZipArchiver extends AbstractArchiver { private String comment; @@ -114,54 +112,44 @@ public abstract class AbstractZipArchiver protected ZipArchiveOutputStream zipArchiveOutputStream; - public String getComment() - { + public String getComment() { return comment; } - public void setComment( String comment ) - { + public void setComment(String comment) { this.comment = comment; } - public String getEncoding() - { + public String getEncoding() { return encoding; } - public void setEncoding( String encoding ) - { + public void setEncoding(String encoding) { this.encoding = encoding; } - public void setCompress( boolean compress ) - { + public void setCompress(boolean compress) { this.doCompress = compress; } - public boolean isCompress() - { + public boolean isCompress() { return doCompress; } - public boolean isRecompressAddedZips() - { + public boolean isRecompressAddedZips() { return recompressAddedZips; } - public void setRecompressAddedZips( boolean recompressAddedZips ) - { + public void setRecompressAddedZips(boolean recompressAddedZips) { this.recompressAddedZips = recompressAddedZips; } - public void setUpdateMode( boolean update ) - { + public void setUpdateMode(boolean update) { this.doUpdate = update; savedDoUpdate = doUpdate; } - public boolean isInUpdateMode() - { + public boolean isInUpdateMode() { return doUpdate; } @@ -171,140 +159,112 @@ public boolean isInUpdateMode() * * @param f true to emilate sun jar utility */ - public void setFilesonly( boolean f ) - { + public void setFilesonly(boolean f) { doFilesonly = f; } - public boolean isFilesonly() - { + public boolean isFilesonly() { return doFilesonly; } @Override - protected void execute() - throws ArchiverException, IOException - { - if ( !checkForced() ) - { + protected void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } - if ( doubleFilePass ) - { + if (doubleFilePass) { skipWriting = true; createArchiveMain(); skipWriting = false; createArchiveMain(); - } - else - { + } else { createArchiveMain(); } - finalizeZipOutputStream( zOut ); + finalizeZipOutputStream(zOut); } - protected void finalizeZipOutputStream( ConcurrentJarCreator zOut ) - throws IOException, ArchiverException - { - } + protected void finalizeZipOutputStream(ConcurrentJarCreator zOut) throws IOException, ArchiverException {} - private void createArchiveMain() - throws ArchiverException, IOException - { + private void createArchiveMain() throws ArchiverException, IOException { //noinspection deprecation - if ( !Archiver.DUPLICATES_SKIP.equals( duplicate ) ) - { + if (!Archiver.DUPLICATES_SKIP.equals(duplicate)) { //noinspection deprecation - setDuplicateBehavior( duplicate ); + setDuplicateBehavior(duplicate); } ResourceIterator iter = getResources(); - if ( !iter.hasNext() && !hasVirtualFiles() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext() && !hasVirtualFiles()) { + throw new EmptyArchiveException("archive cannot be empty"); } zipFile = getDestFile(); - if ( zipFile == null ) - { - throw new ArchiverException( "You must set the destination " + archiveType + "file." ); + if (zipFile == null) { + throw new ArchiverException("You must set the destination " + archiveType + "file."); } - if ( zipFile.exists() && !zipFile.isFile() ) - { - throw new ArchiverException( zipFile + " isn't a file." ); + if (zipFile.exists() && !zipFile.isFile()) { + throw new ArchiverException(zipFile + " isn't a file."); } - if ( zipFile.exists() && !zipFile.canWrite() ) - { - throw new ArchiverException( zipFile + " is read-only." ); + if (zipFile.exists() && !zipFile.canWrite()) { + throw new ArchiverException(zipFile + " is read-only."); } // Whether or not an actual update is required - // we don't need to update if the original file doesn't exist addingNewFiles = true; - if ( doUpdate && !zipFile.exists() ) - { + if (doUpdate && !zipFile.exists()) { doUpdate = false; - getLogger().debug( "ignoring update attribute as " + archiveType + " doesn't exist." ); + getLogger().debug("ignoring update attribute as " + archiveType + " doesn't exist."); } success = false; - if ( doUpdate ) - { - renamedFile = FileUtils.createTempFile( "zip", ".tmp", zipFile.getParentFile() ); + if (doUpdate) { + renamedFile = FileUtils.createTempFile("zip", ".tmp", zipFile.getParentFile()); renamedFile.deleteOnExit(); - try - { - FileUtils.rename( zipFile, renamedFile ); - } - catch ( SecurityException e ) - { - getLogger().debug( e.toString() ); + try { + FileUtils.rename(zipFile, renamedFile); + } catch (SecurityException e) { + getLogger().debug(e.toString()); throw new ArchiverException( - "Not allowed to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e ); - } - catch ( IOException e ) - { - getLogger().debug( e.toString() ); + "Not allowed to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e); + } catch (IOException e) { + getLogger().debug(e.toString()); throw new ArchiverException( - "Unable to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e ); + "Unable to rename old file (" + zipFile.getAbsolutePath() + ") to temporary file", e); } } String action = doUpdate ? "Updating " : "Building "; - getLogger().info( action + archiveType + ": " + zipFile.getAbsolutePath() ); + getLogger().info(action + archiveType + ": " + zipFile.getAbsolutePath()); - if ( !skipWriting ) - { - zipArchiveOutputStream = - new ZipArchiveOutputStream( bufferedOutputStream( fileOutputStream( zipFile, "zip" ) ) ); - zipArchiveOutputStream.setEncoding( encoding ); - zipArchiveOutputStream.setCreateUnicodeExtraFields( this.getUnicodeExtraFieldPolicy() ); + if (!skipWriting) { + zipArchiveOutputStream = new ZipArchiveOutputStream(bufferedOutputStream(fileOutputStream(zipFile, "zip"))); + zipArchiveOutputStream.setEncoding(encoding); + zipArchiveOutputStream.setCreateUnicodeExtraFields(this.getUnicodeExtraFieldPolicy()); zipArchiveOutputStream.setMethod( - doCompress ? ZipArchiveOutputStream.DEFLATED : ZipArchiveOutputStream.STORED ); + doCompress ? ZipArchiveOutputStream.DEFLATED : ZipArchiveOutputStream.STORED); - zOut = new ConcurrentJarCreator( recompressAddedZips, Runtime.getRuntime().availableProcessors() ); + zOut = new ConcurrentJarCreator( + recompressAddedZips, Runtime.getRuntime().availableProcessors()); } - initZipOutputStream( zOut ); + initZipOutputStream(zOut); // Add the new files to the archive. - addResources( iter, zOut ); + addResources(iter, zOut); // If we've been successful on an update, delete the // temporary file - if ( doUpdate ) - { - if ( !renamedFile.delete() ) - { - getLogger().warn( "Warning: unable to delete temporary file " + renamedFile.getName() ); + if (doUpdate) { + if (!renamedFile.delete()) { + getLogger().warn("Warning: unable to delete temporary file " + renamedFile.getName()); } } success = true; @@ -319,24 +279,19 @@ private void createArchiveMain() * * @see #getEncoding() */ - private ZipArchiveOutputStream.UnicodeExtraFieldPolicy getUnicodeExtraFieldPolicy() - { + private ZipArchiveOutputStream.UnicodeExtraFieldPolicy getUnicodeExtraFieldPolicy() { // Copied from ZipEncodingHelper.isUTF8() String effectiveEncoding = this.getEncoding(); - if ( effectiveEncoding == null ) - { + if (effectiveEncoding == null) { effectiveEncoding = Charset.defaultCharset().name(); } - boolean utf8 = StandardCharsets.UTF_8.name().equalsIgnoreCase( effectiveEncoding ); + boolean utf8 = StandardCharsets.UTF_8.name().equalsIgnoreCase(effectiveEncoding); - if ( !utf8 ) - { - for ( String alias : StandardCharsets.UTF_8.aliases() ) - { - if ( alias.equalsIgnoreCase( effectiveEncoding ) ) - { + if (!utf8) { + for (String alias : StandardCharsets.UTF_8.aliases()) { + if (alias.equalsIgnoreCase(effectiveEncoding)) { utf8 = true; break; } @@ -348,9 +303,8 @@ private ZipArchiveOutputStream.UnicodeExtraFieldPolicy getUnicodeExtraFieldPolic // is not encodeable as well. If the effective encoding is not UTF-8, we always add the extra field. If it is // UTF-8, we never add the extra field. return utf8 - ? ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NEVER - : ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS; - + ? ZipArchiveOutputStream.UnicodeExtraFieldPolicy.NEVER + : ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS; } /** @@ -359,38 +313,28 @@ private ZipArchiveOutputStream.UnicodeExtraFieldPolicy getUnicodeExtraFieldPolic * @param resources the resources to add * @param zOut the stream to write to */ - @SuppressWarnings( - { - "JavaDoc" - } ) - protected final void addResources( ResourceIterator resources, ConcurrentJarCreator zOut ) - throws IOException, ArchiverException - { - while ( resources.hasNext() ) - { + @SuppressWarnings({"JavaDoc"}) + protected final void addResources(ResourceIterator resources, ConcurrentJarCreator zOut) + throws IOException, ArchiverException { + while (resources.hasNext()) { ArchiveEntry entry = resources.next(); String name = entry.getName(); - name = name.replace( File.separatorChar, '/' ); + name = name.replace(File.separatorChar, '/'); - if ( "".equals( name ) ) - { + if ("".equals(name)) { continue; } - if ( entry.getResource().isDirectory() && !name.endsWith( "/" ) ) - { + if (entry.getResource().isDirectory() && !name.endsWith("/")) { name = name + "/"; } - addParentDirs( entry, null, name, zOut ); + addParentDirs(entry, null, name, zOut); - if ( entry.getResource().isFile() ) - { - zipFile( entry, zOut, name ); - } - else - { - zipDir( entry.getResource(), zOut, name, entry.getMode(), encoding ); + if (entry.getResource().isFile()) { + zipFile(entry, zOut, name); + } else { + zipDir(entry.getResource(), zOut, name, entry.getMode(), encoding); } } } @@ -402,33 +346,24 @@ protected final void addResources( ResourceIterator resources, ConcurrentJarCrea * we do not *relly* know the entry's connection to the file system so establishing the attributes of the parents can * be impossible and is not really supported. */ - @SuppressWarnings( - { - "JavaDoc" - } ) - private void addParentDirs( ArchiveEntry archiveEntry, File baseDir, String entry, ConcurrentJarCreator zOut ) - throws IOException - { - if ( !doFilesonly && getIncludeEmptyDirs() ) - { - Deque directories = addedDirs.asStringDeque( entry ); - - while ( !directories.isEmpty() ) - { + @SuppressWarnings({"JavaDoc"}) + private void addParentDirs(ArchiveEntry archiveEntry, File baseDir, String entry, ConcurrentJarCreator zOut) + throws IOException { + if (!doFilesonly && getIncludeEmptyDirs()) { + Deque directories = addedDirs.asStringDeque(entry); + + while (!directories.isEmpty()) { String dir = directories.pop(); File f; - if ( baseDir != null ) - { - f = new File( baseDir, dir ); - } - else - { - f = new File( dir ); + if (baseDir != null) { + f = new File(baseDir, dir); + } else { + f = new File(dir); } // the // At this point we could do something like read the atr - final PlexusIoResource res = new AnonymousResource( f ); - zipDir( res, zOut, dir, archiveEntry.getDefaultDirMode(), encoding ); + final PlexusIoResource res = new AnonymousResource(f); + zipDir(res, zOut, dir, archiveEntry.getDefaultDirMode(), encoding); } } } @@ -446,36 +381,34 @@ private void addParentDirs( ArchiveEntry archiveEntry, File baseDir, String entr * If set to {@code false} it is added synchronously. * If the entry is symbolic link this parameter is ignored. */ - @SuppressWarnings( - { - "JavaDoc" - } ) - protected void zipFile( InputStreamSupplier in, ConcurrentJarCreator zOut, String vPath, - long lastModified, - File fromArchive, int mode, String symlinkDestination, boolean addInParallel ) - throws IOException, ArchiverException - { - getLogger().debug( "adding entry " + vPath ); - - entries.put( vPath, vPath ); - - if ( !skipWriting ) - { - ZipArchiveEntry ze = new ZipArchiveEntry( vPath ); - setZipEntryTime( ze, lastModified ); - - ze.setMethod( doCompress ? ZipArchiveEntry.DEFLATED : ZipArchiveEntry.STORED ); - ze.setUnixMode( UnixStat.FILE_FLAG | mode ); - - if ( ze.isUnixSymlink() ) - { - final byte[] bytes = encodeArchiveEntry( symlinkDestination, getEncoding() ); - InputStreamSupplier payload = () -> new ByteArrayInputStream( bytes ); - zOut.addArchiveEntry( ze, payload, true ); - } - else - { - zOut.addArchiveEntry( ze, in, addInParallel ); + @SuppressWarnings({"JavaDoc"}) + protected void zipFile( + InputStreamSupplier in, + ConcurrentJarCreator zOut, + String vPath, + long lastModified, + File fromArchive, + int mode, + String symlinkDestination, + boolean addInParallel) + throws IOException, ArchiverException { + getLogger().debug("adding entry " + vPath); + + entries.put(vPath, vPath); + + if (!skipWriting) { + ZipArchiveEntry ze = new ZipArchiveEntry(vPath); + setZipEntryTime(ze, lastModified); + + ze.setMethod(doCompress ? ZipArchiveEntry.DEFLATED : ZipArchiveEntry.STORED); + ze.setUnixMode(UnixStat.FILE_FLAG | mode); + + if (ze.isUnixSymlink()) { + final byte[] bytes = encodeArchiveEntry(symlinkDestination, getEncoding()); + InputStreamSupplier payload = () -> new ByteArrayInputStream(bytes); + zOut.addArchiveEntry(ze, payload, true); + } else { + zOut.addArchiveEntry(ze, in, addInParallel); } } } @@ -489,39 +422,35 @@ protected void zipFile( InputStreamSupplier in, ConcurrentJarCreator zOut, Strin * @param zOut the stream to write to * @param vPath the name this entry shall have in the archive */ - @SuppressWarnings( - { - "JavaDoc" - } ) - protected void zipFile( final ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath ) - throws IOException, ArchiverException - { + @SuppressWarnings({"JavaDoc"}) + protected void zipFile(final ArchiveEntry entry, ConcurrentJarCreator zOut, String vPath) + throws IOException, ArchiverException { final PlexusIoResource resource = entry.getResource(); - if ( ResourceUtils.isSame( resource, getDestFile() ) ) - { - throw new ArchiverException( "A zip file cannot include itself" ); + if (ResourceUtils.isSame(resource, getDestFile())) { + throw new ArchiverException("A zip file cannot include itself"); } final boolean b = entry.getResource() instanceof SymlinkDestinationSupplier; - String symlinkTarget = b ? ( (SymlinkDestinationSupplier) entry.getResource() ).getSymlinkDestination() : null; + String symlinkTarget = b ? ((SymlinkDestinationSupplier) entry.getResource()).getSymlinkDestination() : null; InputStreamSupplier in = () -> { - try - { + try { return entry.getInputStream(); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + } catch (IOException e) { + throw new UncheckedIOException(e); } }; - try - { - zipFile( in, zOut, vPath, resource.getLastModified(), null, entry.getMode(), symlinkTarget, - !entry.shouldAddSynchronously() ); - } - catch ( IOException e ) - { - throw new ArchiverException( "IOException when zipping r" + entry.getName() + ": " + e.getMessage(), e ); + try { + zipFile( + in, + zOut, + vPath, + resource.getLastModified(), + null, + entry.getMode(), + symlinkTarget, + !entry.shouldAddSynchronously()); + } catch (IOException e) { + throw new ArchiverException("IOException when zipping r" + entry.getName() + ": " + e.getMessage(), e); } } @@ -537,37 +466,30 @@ protected void zipFile( final ArchiveEntry entry, ConcurrentJarCreator zOut, Str * @param zipEntry to set the last modified time * @param lastModifiedTime to set in the zip entry only if {@link #getLastModifiedTime()} returns null */ - protected void setZipEntryTime( ZipArchiveEntry zipEntry, long lastModifiedTime ) - { - if ( getLastModifiedTime() != null ) - { + protected void setZipEntryTime(ZipArchiveEntry zipEntry, long lastModifiedTime) { + if (getLastModifiedTime() != null) { lastModifiedTime = getLastModifiedTime().toMillis(); } - zipEntry.setTime( lastModifiedTime + 1999 ); + zipEntry.setTime(lastModifiedTime + 1999); } - protected void zipDir( PlexusIoResource dir, ConcurrentJarCreator zOut, String vPath, int mode, - String encodingToUse ) - throws IOException - { - if ( addedDirs.update( vPath ) ) - { + protected void zipDir(PlexusIoResource dir, ConcurrentJarCreator zOut, String vPath, int mode, String encodingToUse) + throws IOException { + if (addedDirs.update(vPath)) { return; } - getLogger().debug( "adding directory " + vPath ); + getLogger().debug("adding directory " + vPath); - if ( !skipWriting ) - { + if (!skipWriting) { final boolean isSymlink = dir instanceof SymlinkDestinationSupplier; - if ( isSymlink && vPath.endsWith( File.separator ) ) - { - vPath = vPath.substring( 0, vPath.length() - 1 ); + if (isSymlink && vPath.endsWith(File.separator)) { + vPath = vPath.substring(0, vPath.length() - 1); } - ZipArchiveEntry ze = new ZipArchiveEntry( vPath ); + ZipArchiveEntry ze = new ZipArchiveEntry(vPath); /* * ZipOutputStream.putNextEntry expects the ZipEntry to @@ -576,50 +498,40 @@ protected void zipDir( PlexusIoResource dir, ConcurrentJarCreator zOut, String v * * This forces us to process the data twice. */ - if ( isSymlink ) - { + if (isSymlink) { mode = UnixStat.LINK_FLAG | mode; } - if ( dir != null && dir.isExisting() ) - { - setZipEntryTime( ze, dir.getLastModified() ); - } - else - { + if (dir != null && dir.isExisting()) { + setZipEntryTime(ze, dir.getLastModified()); + } else { // ZIPs store time with a granularity of 2 seconds, round up - setZipEntryTime( ze, System.currentTimeMillis() ); + setZipEntryTime(ze, System.currentTimeMillis()); } - if ( !isSymlink ) - { - ze.setSize( 0 ); - ze.setMethod( ZipArchiveEntry.STORED ); + if (!isSymlink) { + ze.setSize(0); + ze.setMethod(ZipArchiveEntry.STORED); // This is faintly ridiculous: - ze.setCrc( EMPTY_CRC ); - } - ze.setUnixMode( mode ); - - if ( !isSymlink ) - { - zOut.addArchiveEntry( ze, () -> Streams.EMPTY_INPUTSTREAM, true ); + ze.setCrc(EMPTY_CRC); } - else - { - String symlinkDestination = ( (SymlinkDestinationSupplier) dir ).getSymlinkDestination(); - final byte[] bytes = encodeArchiveEntry( symlinkDestination, encodingToUse ); - ze.setMethod( ZipArchiveEntry.DEFLATED ); - zOut.addArchiveEntry( ze, () -> new ByteArrayInputStream( bytes ), true ); + ze.setUnixMode(mode); + + if (!isSymlink) { + zOut.addArchiveEntry(ze, () -> Streams.EMPTY_INPUTSTREAM, true); + } else { + String symlinkDestination = ((SymlinkDestinationSupplier) dir).getSymlinkDestination(); + final byte[] bytes = encodeArchiveEntry(symlinkDestination, encodingToUse); + ze.setMethod(ZipArchiveEntry.DEFLATED); + zOut.addArchiveEntry(ze, () -> new ByteArrayInputStream(bytes), true); } } } - private byte[] encodeArchiveEntry( String payload, String encoding ) - throws IOException - { - ZipEncoding enc = ZipEncodingHelper.getZipEncoding( encoding ); - ByteBuffer encodedPayloadByteBuffer = enc.encode( payload ); + private byte[] encodeArchiveEntry(String payload, String encoding) throws IOException { + ZipEncoding enc = ZipEncodingHelper.getZipEncoding(encoding); + ByteBuffer encodedPayloadByteBuffer = enc.encode(payload); byte[] encodedPayloadBytes = new byte[encodedPayloadByteBuffer.limit()]; - encodedPayloadByteBuffer.get( encodedPayloadBytes ); + encodedPayloadByteBuffer.get(encodedPayloadBytes); return encodedPayloadBytes; } @@ -631,32 +543,24 @@ private byte[] encodeArchiveEntry( String payload, String encoding ) * * @return true for historic reasons */ - @SuppressWarnings( - { - "JavaDoc" - } ) - protected boolean createEmptyZip( File zipFile ) - throws ArchiverException - { + @SuppressWarnings({"JavaDoc"}) + protected boolean createEmptyZip(File zipFile) throws ArchiverException { // In this case using java.util.zip will not work // because it does not permit a zero-entry archive. // Must create it manually. - getLogger().info( "Note: creating empty " + archiveType + " archive " + zipFile ); + getLogger().info("Note: creating empty " + archiveType + " archive " + zipFile); - try ( OutputStream os = Files.newOutputStream( zipFile.toPath() ) ) - { + try (OutputStream os = Files.newOutputStream(zipFile.toPath())) { // Cf. PKZIP specification. - byte[] empty = new byte[ 22 ]; + byte[] empty = new byte[22]; empty[0] = 80; // P empty[1] = 75; // K empty[2] = 5; empty[3] = 6; // remainder zeros - os.write( empty ); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe ); + os.write(empty); + } catch (IOException ioe) { + throw new ArchiverException("Could not create empty ZIP archive " + "(" + ioe.getMessage() + ")", ioe); } return true; } @@ -676,9 +580,7 @@ protected boolean createEmptyZip( File zipFile ) * @see #reset */ @Override - protected void cleanUp() - throws IOException - { + protected void cleanUp() throws IOException { super.cleanUp(); addedDirs.clear(); entries.clear(); @@ -696,10 +598,9 @@ protected void cleanUp() * * @see #cleanUp */ - public void reset() - { - setDestFile( null ); -// duplicate = "add"; + public void reset() { + setDestFile(null); + // duplicate = "add"; archiveType = "zip"; doCompress = true; doUpdate = false; @@ -712,42 +613,32 @@ public void reset() * * @param zOut The output stream */ - protected void initZipOutputStream( ConcurrentJarCreator zOut ) - throws ArchiverException, IOException - { - } + protected void initZipOutputStream(ConcurrentJarCreator zOut) throws ArchiverException, IOException {} /** * method for subclasses to override */ @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected boolean revert( StringBuffer messageBuffer ) - { + protected boolean revert(StringBuffer messageBuffer) { int initLength = messageBuffer.length(); // delete a bogus ZIP file (but only if it's not the original one) - if ( ( !doUpdate || renamedFile != null ) && !zipFile.delete() ) - { - messageBuffer.append( " (and the archive is probably corrupt but I could not delete it)" ); + if ((!doUpdate || renamedFile != null) && !zipFile.delete()) { + messageBuffer.append(" (and the archive is probably corrupt but I could not delete it)"); } - if ( doUpdate && renamedFile != null ) - { - try - { - FileUtils.rename( renamedFile, zipFile ); - } - catch ( IOException e ) - { - messageBuffer.append( " (and I couldn't rename the temporary file " ); - messageBuffer.append( renamedFile.getName() ); - messageBuffer.append( " back)" ); + if (doUpdate && renamedFile != null) { + try { + FileUtils.rename(renamedFile, zipFile); + } catch (IOException e) { + messageBuffer.append(" (and I couldn't rename the temporary file "); + messageBuffer.append(renamedFile.getName()); + messageBuffer.append(" back)"); } } @@ -755,23 +646,16 @@ protected boolean revert( StringBuffer messageBuffer ) } @Override - protected void close() - throws IOException - { + protected void close() throws IOException { // Close the output stream. - try - { - if ( zipArchiveOutputStream != null ) - { - if ( zOut != null ) - { - zOut.writeTo( zipArchiveOutputStream ); + try { + if (zipArchiveOutputStream != null) { + if (zOut != null) { + zOut.writeTo(zipArchiveOutputStream); } zipArchiveOutputStream.close(); } - } - catch ( IOException ex ) - { + } catch (IOException ex) { // If we're in this finally clause because of an // exception, we don't really care if there's an // exception when closing the stream. E.g. if it @@ -781,39 +665,32 @@ protected void close() // exception. Otherwise, the error that's reported // will be the close() error, which is not the // real cause of the problem. - if ( success ) - { + if (success) { throw ex; } - } - catch ( InterruptedException e ) - { - IOException ex = new IOException( "InterruptedException exception" ); - ex.initCause( e.getCause() ); + } catch (InterruptedException e) { + IOException ex = new IOException("InterruptedException exception"); + ex.initCause(e.getCause()); throw ex; - } - catch ( ExecutionException e ) - { - IOException ex = new IOException( "Execution exception" ); - ex.initCause( e.getCause() ); + } catch (ExecutionException e) { + IOException ex = new IOException("Execution exception"); + ex.initCause(e.getCause()); throw ex; } } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return archiveType; } @Override - protected FileTime normalizeLastModifiedTime( FileTime lastModifiedTime ) - { + protected FileTime normalizeLastModifiedTime(FileTime lastModifiedTime) { // timestamp of zip entries at zip storage level ignores timezone: managed in ZipEntry.setTime, // that turns javaToDosTime: need to revert the operation here to get reproducible // zip entry time - return FileTime.fromMillis( dosToJavaTime( lastModifiedTime.toMillis() ) ); + return FileTime.fromMillis(dosToJavaTime(lastModifiedTime.toMillis())); } /** @@ -822,10 +699,9 @@ protected FileTime normalizeLastModifiedTime( FileTime lastModifiedTime ) * @see java.util.zip.ZipEntry#setTime * @see java.util.zip.ZipUtils#dosToJavaTime */ - private static long dosToJavaTime( long dosTime ) - { - Calendar cal = Calendar.getInstance( TimeZone.getDefault(), Locale.ROOT ); - cal.setTimeInMillis( dosTime ); - return dosTime - ( cal.get( Calendar.ZONE_OFFSET ) + cal.get( Calendar.DST_OFFSET ) ); + private static long dosToJavaTime(long dosTime) { + Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.ROOT); + cal.setTimeInMillis(dosTime); + return dosTime - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)); } } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipUnArchiver.java index c5b046ece..4b2219de8 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/AbstractZipUnArchiver.java @@ -16,13 +16,15 @@ */ package org.codehaus.plexus.archiver.zip; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.Enumeration; -import javax.annotation.Nonnull; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.apache.commons.io.input.BoundedInputStream; @@ -34,9 +36,7 @@ /** * @author Emmanuel Venisse */ -public abstract class AbstractZipUnArchiver - extends AbstractUnArchiver -{ +public abstract class AbstractZipUnArchiver extends AbstractUnArchiver { private static final String NATIVE_ENCODING = "native-encoding"; @@ -44,13 +44,10 @@ public abstract class AbstractZipUnArchiver private long maxOutputSize = Long.MAX_VALUE; - public AbstractZipUnArchiver() - { - } + public AbstractZipUnArchiver() {} - public AbstractZipUnArchiver( final File sourceFile ) - { - super( sourceFile ); + public AbstractZipUnArchiver(final File sourceFile) { + super(sourceFile); } /** @@ -59,10 +56,8 @@ public AbstractZipUnArchiver( final File sourceFile ) * Set to native-encoding if you want your platform's native encoding, defaults to UTF8. *

*/ - public void setEncoding( String encoding ) - { - if ( NATIVE_ENCODING.equals( encoding ) ) - { + public void setEncoding(String encoding) { + if (NATIVE_ENCODING.equals(encoding)) { encoding = null; } this.encoding = encoding; @@ -76,152 +71,126 @@ public void setEncoding( String encoding ) * @param maxOutputSize max size of the produced output, in bytes. Must be greater than 0 * @throws IllegalArgumentException if specified output size is less or equal to 0 */ - public void setMaxOutputSize( long maxOutputSize ) { - if ( maxOutputSize <= 0 ) { - throw new IllegalArgumentException( "Invalid max output size specified: " + maxOutputSize ); + public void setMaxOutputSize(long maxOutputSize) { + if (maxOutputSize <= 0) { + throw new IllegalArgumentException("Invalid max output size specified: " + maxOutputSize); } this.maxOutputSize = maxOutputSize; } - private static class ZipEntryFileInfo - implements PlexusIoResource - { + private static class ZipEntryFileInfo implements PlexusIoResource { private final org.apache.commons.compress.archivers.zip.ZipFile zipFile; private final ZipArchiveEntry zipEntry; - ZipEntryFileInfo( final org.apache.commons.compress.archivers.zip.ZipFile zipFile, - final ZipArchiveEntry zipEntry ) - { + ZipEntryFileInfo( + final org.apache.commons.compress.archivers.zip.ZipFile zipFile, final ZipArchiveEntry zipEntry) { this.zipFile = zipFile; this.zipEntry = zipEntry; } - public String getName() - { + public String getName() { return zipEntry.getName(); } @Override - public boolean isDirectory() - { + public boolean isDirectory() { return zipEntry.isDirectory(); } @Override - public boolean isFile() - { + public boolean isFile() { return !zipEntry.isDirectory() && !zipEntry.isUnixSymlink(); } @Override - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return zipEntry.isUnixSymlink(); } @Nonnull @Override - public InputStream getContents() - throws IOException - { - return zipFile.getInputStream( zipEntry ); + public InputStream getContents() throws IOException { + return zipFile.getInputStream(zipEntry); } @Override - public long getLastModified() - { + public long getLastModified() { final long l = zipEntry.getTime(); return l == 0 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : l; } @Override - public long getSize() - { + public long getSize() { final long l = zipEntry.getSize(); return l == -1 ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : l; } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return null; } @Override - public boolean isExisting() - { + public boolean isExisting() { return true; } - } @Override - protected void execute() - throws ArchiverException - { - execute( "", getDestDirectory() ); + protected void execute() throws ArchiverException { + execute("", getDestDirectory()); } - private String resolveSymlink( ZipFile zf, ZipArchiveEntry ze ) - throws IOException - { - if ( ze.isUnixSymlink() ) - { - return zf.getUnixSymlink( ze ); - } - else - { + private String resolveSymlink(ZipFile zf, ZipArchiveEntry ze) throws IOException { + if (ze.isUnixSymlink()) { + return zf.getUnixSymlink(ze); + } else { return null; } } @Override - protected void execute( final String path, final File outputDirectory ) - throws ArchiverException - { - getLogger().debug( "Expanding: " + getSourceFile() + " into " + outputDirectory ); - try ( ZipFile zipFile = new ZipFile( getSourceFile(), encoding, true ) ) - { + protected void execute(final String path, final File outputDirectory) throws ArchiverException { + getLogger().debug("Expanding: " + getSourceFile() + " into " + outputDirectory); + try (ZipFile zipFile = new ZipFile(getSourceFile(), encoding, true)) { long remainingSpace = maxOutputSize; final Enumeration e = zipFile.getEntriesInPhysicalOrder(); - while ( e.hasMoreElements() ) - { + while (e.hasMoreElements()) { final ZipArchiveEntry ze = e.nextElement(); - final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo( zipFile, ze ); - if ( !isSelected( ze.getName(), fileInfo ) ) - { + final ZipEntryFileInfo fileInfo = new ZipEntryFileInfo(zipFile, ze); + if (!isSelected(ze.getName(), fileInfo)) { continue; } - if ( ze.getName().startsWith( path ) ) - { - try ( InputStream in = zipFile.getInputStream( ze ) ) - { - BoundedInputStream bis = new BoundedInputStream( in, remainingSpace + 1 ); - CountingInputStream cis = new CountingInputStream( bis ); - extractFile( getSourceFile(), outputDirectory, cis, - ze.getName(), new Date( ze.getTime() ), ze.isDirectory(), - ze.getUnixMode() != 0 ? ze.getUnixMode() : null, - resolveSymlink( zipFile, ze ), getFileMappers() ); + if (ze.getName().startsWith(path)) { + try (InputStream in = zipFile.getInputStream(ze)) { + BoundedInputStream bis = new BoundedInputStream(in, remainingSpace + 1); + CountingInputStream cis = new CountingInputStream(bis); + extractFile( + getSourceFile(), + outputDirectory, + cis, + ze.getName(), + new Date(ze.getTime()), + ze.isDirectory(), + ze.getUnixMode() != 0 ? ze.getUnixMode() : null, + resolveSymlink(zipFile, ze), + getFileMappers()); remainingSpace -= cis.getByteCount(); - if ( remainingSpace < 0 ) - { - throw new ArchiverException( "Maximum output size limit reached" ); + if (remainingSpace < 0) { + throw new ArchiverException("Maximum output size limit reached"); } } } } - getLogger().debug( "expand complete" ); - } - catch ( final IOException ioe ) - { - throw new ArchiverException( "Error while expanding " + getSourceFile().getAbsolutePath(), ioe ); + getLogger().debug("expand complete"); + } catch (final IOException ioe) { + throw new ArchiverException( + "Error while expanding " + getSourceFile().getAbsolutePath(), ioe); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/AddedDirs.java b/src/main/java/org/codehaus/plexus/archiver/zip/AddedDirs.java index 4d5438364..00d547630 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/AddedDirs.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/AddedDirs.java @@ -25,8 +25,7 @@ /** * A list of directories that have been added to an archive. */ -public class AddedDirs -{ +public class AddedDirs { private final Set addedDirs = new HashSet(); @@ -34,52 +33,45 @@ public class AddedDirs * @deprecated use {@link #asStringDeque(String)} instead. */ @Deprecated - public Stack asStringStack( String entry ) - { + public Stack asStringStack(String entry) { Stack directories = new Stack<>(); // Don't include the last entry itself if it's // a dir; it will be added on its own. - int slashPos = entry.length() - ( entry.endsWith( "/" ) ? 1 : 0 ); + int slashPos = entry.length() - (entry.endsWith("/") ? 1 : 0); - while ( ( slashPos = entry.lastIndexOf( '/', slashPos - 1 ) ) != -1 ) - { - String dir = entry.substring( 0, slashPos + 1 ); + while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) { + String dir = entry.substring(0, slashPos + 1); - if ( addedDirs.contains( dir ) ) - { + if (addedDirs.contains(dir)) { break; } - directories.push( dir ); + directories.push(dir); } return directories; } - public Deque asStringDeque( String entry ) - { + public Deque asStringDeque(String entry) { Deque directories = new ArrayDeque<>(); // Don't include the last entry itself if it's // a dir; it will be added on its own. - int slashPos = entry.length() - ( entry.endsWith( "/" ) ? 1 : 0 ); + int slashPos = entry.length() - (entry.endsWith("/") ? 1 : 0); - while ( ( slashPos = entry.lastIndexOf( '/', slashPos - 1 ) ) != -1 ) - { - String dir = entry.substring( 0, slashPos + 1 ); + while ((slashPos = entry.lastIndexOf('/', slashPos - 1)) != -1) { + String dir = entry.substring(0, slashPos + 1); - if ( addedDirs.contains( dir ) ) - { + if (addedDirs.contains(dir)) { break; } - directories.push( dir ); + directories.push(dir); } return directories; } - public void clear() - { + public void clear() { addedDirs.clear(); } @@ -90,14 +82,11 @@ public void clear() * * @return true if the path was already present, false if it has been added. */ - public boolean update( String vPath ) - { - return !addedDirs.add( vPath ); + public boolean update(String vPath) { + return !addedDirs.add(vPath); } - public Set allAddedDirs() - { - return new HashSet( addedDirs ); + public Set allAddedDirs() { + return new HashSet(addedDirs); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/AnonymousResource.java b/src/main/java/org/codehaus/plexus/archiver/zip/AnonymousResource.java index 65de3dd90..9affe55d7 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/AnonymousResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/AnonymousResource.java @@ -1,47 +1,39 @@ package org.codehaus.plexus.archiver.zip; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; -import javax.annotation.Nonnull; import org.codehaus.plexus.components.io.resources.AbstractPlexusIoResource; -public class AnonymousResource extends AbstractPlexusIoResource -{ +public class AnonymousResource extends AbstractPlexusIoResource { private final File file; - public AnonymousResource( File file ) - { - this( file, getName( file ) ); + public AnonymousResource(File file) { + this(file, getName(file)); } - public AnonymousResource( File file, String name ) - { - super( name, file.lastModified(), file.length(), file.isFile(), file.isDirectory(), file.exists() ); + public AnonymousResource(File file, String name) { + super(name, file.lastModified(), file.length(), file.isFile(), file.isDirectory(), file.exists()); this.file = file; } @Nonnull @Override - public InputStream getContents() - throws IOException - { - throw new UnsupportedOperationException( "not supp" ); + public InputStream getContents() throws IOException { + throw new UnsupportedOperationException("not supp"); } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return file.toURI().toURL(); } - private static String getName( File file ) - { - return file.getPath().replace( '\\', '/' ); + private static String getName(File file) { + return file.getPath().replace('\\', '/'); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ByteArrayOutputStream.java b/src/main/java/org/codehaus/plexus/archiver/zip/ByteArrayOutputStream.java index 5f62ab9fc..41a26f0c0 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ByteArrayOutputStream.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ByteArrayOutputStream.java @@ -26,6 +26,7 @@ import java.util.ArrayList; import java.util.Collections; import java.util.List; + import org.apache.commons.io.input.ClosedInputStream; /** @@ -49,13 +50,12 @@ * designed to behave exactly like the original. The only exception is the * deprecated toString(int) method that has been ignored. */ -public class ByteArrayOutputStream extends OutputStream -{ +public class ByteArrayOutputStream extends OutputStream { /** * A singleton empty byte array. */ - private static final byte[] EMPTY_BYTE_ARRAY = new byte[ 0 ]; + private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * The list of buffers, which grows and never reduces. @@ -91,9 +91,8 @@ public class ByteArrayOutputStream extends OutputStream * Creates a new byte array output stream. The buffer capacity is * initially 1024 bytes, though its size increases if necessary. */ - public ByteArrayOutputStream() - { - this( 1024 ); + public ByteArrayOutputStream() { + this(1024); } /** @@ -104,15 +103,12 @@ public ByteArrayOutputStream() * * @throws IllegalArgumentException if size is negative */ - public ByteArrayOutputStream( final int size ) - { - if ( size < 0 ) - { - throw new IllegalArgumentException( "Negative initial size: " + size ); + public ByteArrayOutputStream(final int size) { + if (size < 0) { + throw new IllegalArgumentException("Negative initial size: " + size); } - synchronized ( this ) - { - needNewBuffer( size ); + synchronized (this) { + needNewBuffer(size); } } @@ -122,36 +118,27 @@ public ByteArrayOutputStream( final int size ) * * @param newcount the size of the buffer if one is created */ - private void needNewBuffer( final int newcount ) - { - if ( currentBufferIndex < buffers.size() - 1 ) - { - //Recycling old buffer + private void needNewBuffer(final int newcount) { + if (currentBufferIndex < buffers.size() - 1) { + // Recycling old buffer filledBufferSum += currentBuffer.length; currentBufferIndex++; - currentBuffer = buffers.get( currentBufferIndex ); - } - else - { - //Creating new buffer + currentBuffer = buffers.get(currentBufferIndex); + } else { + // Creating new buffer int newBufferSize; - if ( currentBuffer == null ) - { + if (currentBuffer == null) { newBufferSize = newcount; filledBufferSum = 0; - } - else - { - newBufferSize = Math.max( - currentBuffer.length << 1, - newcount - filledBufferSum ); + } else { + newBufferSize = Math.max(currentBuffer.length << 1, newcount - filledBufferSum); filledBufferSum += currentBuffer.length; } currentBufferIndex++; - currentBuffer = new byte[ newBufferSize ]; - buffers.add( currentBuffer ); + currentBuffer = new byte[newBufferSize]; + buffers.add(currentBuffer); } } @@ -163,33 +150,22 @@ private void needNewBuffer( final int newcount ) * @param len The number of bytes to write */ @Override - public void write( final byte[] b, final int off, final int len ) - { - if ( ( off < 0 ) - || ( off > b.length ) - || ( len < 0 ) - || ( ( off + len ) > b.length ) - || ( ( off + len ) < 0 ) ) - { + public void write(final byte[] b, final int off, final int len) { + if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) > b.length) || ((off + len) < 0)) { throw new IndexOutOfBoundsException(); - } - else if ( len == 0 ) - { + } else if (len == 0) { return; } - synchronized ( this ) - { + synchronized (this) { final int newcount = count + len; int remaining = len; int inBufferPos = count - filledBufferSum; - while ( remaining > 0 ) - { - final int part = Math.min( remaining, currentBuffer.length - inBufferPos ); - System.arraycopy( b, off + len - remaining, currentBuffer, inBufferPos, part ); + while (remaining > 0) { + final int part = Math.min(remaining, currentBuffer.length - inBufferPos); + System.arraycopy(b, off + len - remaining, currentBuffer, inBufferPos, part); remaining -= part; - if ( remaining > 0 ) - { - needNewBuffer( newcount ); + if (remaining > 0) { + needNewBuffer(newcount); inBufferPos = 0; } } @@ -203,12 +179,10 @@ else if ( len == 0 ) * @param b the byte to write */ @Override - public synchronized void write( final int b ) - { + public synchronized void write(final int b) { int inBufferPos = count - filledBufferSum; - if ( inBufferPos == currentBuffer.length ) - { - needNewBuffer( count + 1 ); + if (inBufferPos == currentBuffer.length) { + needNewBuffer(count + 1); inBufferPos = 0; } currentBuffer[inBufferPos] = (byte) b; @@ -228,22 +202,19 @@ public synchronized void write( final int b ) * @throws java.io.IOException if an I/O error occurs while reading the input stream * @since 1.4 */ - public synchronized int write( final InputStream in ) throws IOException - { + public synchronized int write(final InputStream in) throws IOException { int readCount = 0; int inBufferPos = count - filledBufferSum; - int n = in.read( currentBuffer, inBufferPos, currentBuffer.length - inBufferPos ); - while ( n != -1 ) - { + int n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); + while (n != -1) { readCount += n; inBufferPos += n; count += n; - if ( inBufferPos == currentBuffer.length ) - { - needNewBuffer( currentBuffer.length ); + if (inBufferPos == currentBuffer.length) { + needNewBuffer(currentBuffer.length); inBufferPos = 0; } - n = in.read( currentBuffer, inBufferPos, currentBuffer.length - inBufferPos ); + n = in.read(currentBuffer, inBufferPos, currentBuffer.length - inBufferPos); } return readCount; } @@ -253,8 +224,7 @@ public synchronized int write( final InputStream in ) throws IOException * * @return the current size of the byte array */ - public synchronized int size() - { + public synchronized int size() { return count; } @@ -267,30 +237,25 @@ public synchronized int size() * but it has to now due to backwards compatibility) */ @Override - public void close() throws IOException - { - //nop + public void close() throws IOException { + // nop } /** * @see java.io.ByteArrayOutputStream#reset() */ - public synchronized void reset() - { + public synchronized void reset() { count = 0; filledBufferSum = 0; currentBufferIndex = 0; - if ( reuseBuffers ) - { - currentBuffer = buffers.get( currentBufferIndex ); - } - else - { - //Throw away old buffers + if (reuseBuffers) { + currentBuffer = buffers.get(currentBufferIndex); + } else { + // Throw away old buffers currentBuffer = null; - int size = buffers.get( 0 ).length; + int size = buffers.get(0).length; buffers.clear(); - needNewBuffer( size ); + needNewBuffer(size); reuseBuffers = true; } } @@ -304,16 +269,13 @@ public synchronized void reset() * @throws java.io.IOException if an I/O error occurs, such as if the stream is closed * @see java.io.ByteArrayOutputStream#writeTo(java.io.OutputStream) */ - public synchronized void writeTo( final OutputStream out ) throws IOException - { + public synchronized void writeTo(final OutputStream out) throws IOException { int remaining = count; - for ( final byte[] buf : buffers ) - { - final int c = Math.min( buf.length, remaining ); - out.write( buf, 0, c ); + for (final byte[] buf : buffers) { + final int c = Math.min(buf.length, remaining); + out.write(buf, 0, c); remaining -= c; - if ( remaining == 0 ) - { + if (remaining == 0) { break; } } @@ -342,10 +304,8 @@ public synchronized void writeTo( final OutputStream out ) throws IOException * @throws java.io.IOException if an I/O error occurs * @since 2.0 */ - public static InputStream toBufferedInputStream( final InputStream input ) - throws IOException - { - return toBufferedInputStream( input, 1024 ); + public static InputStream toBufferedInputStream(final InputStream input) throws IOException { + return toBufferedInputStream(input, 1024); } /** @@ -372,13 +332,11 @@ public static InputStream toBufferedInputStream( final InputStream input ) * @throws java.io.IOException if an I/O error occurs * @since 2.5 */ - public static InputStream toBufferedInputStream( final InputStream input, int size ) - throws IOException - { + public static InputStream toBufferedInputStream(final InputStream input, int size) throws IOException { // It does not matter if a ByteArrayOutputStream is not closed as close() is a no-op - @SuppressWarnings( "resource" ) - final ByteArrayOutputStream output = new ByteArrayOutputStream( size ); - output.write( input ); + @SuppressWarnings("resource") + final ByteArrayOutputStream output = new ByteArrayOutputStream(size); + output.write(input); return output.toInputStream(); } @@ -393,26 +351,22 @@ public static InputStream toBufferedInputStream( final InputStream input, int si * @see #reset() * @since 2.5 */ - public synchronized InputStream toInputStream() - { + public synchronized InputStream toInputStream() { int remaining = count; - if ( remaining == 0 ) - { + if (remaining == 0) { return new ClosedInputStream(); } - final List list = new ArrayList( buffers.size() ); - for ( final byte[] buf : buffers ) - { - final int c = Math.min( buf.length, remaining ); - list.add( new ByteArrayInputStream( buf, 0, c ) ); + final List list = new ArrayList(buffers.size()); + for (final byte[] buf : buffers) { + final int c = Math.min(buf.length, remaining); + list.add(new ByteArrayInputStream(buf, 0, c)); remaining -= c; - if ( remaining == 0 ) - { + if (remaining == 0) { break; } } reuseBuffers = false; - return new SequenceInputStream( Collections.enumeration( list ) ); + return new SequenceInputStream(Collections.enumeration(list)); } /** @@ -423,23 +377,19 @@ public synchronized InputStream toInputStream() * * @see java.io.ByteArrayOutputStream#toByteArray() */ - public synchronized byte[] toByteArray() - { + public synchronized byte[] toByteArray() { int remaining = count; - if ( remaining == 0 ) - { + if (remaining == 0) { return EMPTY_BYTE_ARRAY; } - final byte newbuf[] = new byte[ remaining ]; + final byte newbuf[] = new byte[remaining]; int pos = 0; - for ( final byte[] buf : buffers ) - { - final int c = Math.min( buf.length, remaining ); - System.arraycopy( buf, 0, newbuf, pos, c ); + for (final byte[] buf : buffers) { + final int c = Math.min(buf.length, remaining); + System.arraycopy(buf, 0, newbuf, pos, c); pos += c; remaining -= c; - if ( remaining == 0 ) - { + if (remaining == 0) { break; } } @@ -457,10 +407,9 @@ public synchronized byte[] toByteArray() */ @Override @Deprecated - public String toString() - { + public String toString() { // make explicit the use of the default charset - return new String( toByteArray(), Charset.defaultCharset() ); + return new String(toByteArray(), Charset.defaultCharset()); } /** @@ -474,9 +423,8 @@ public String toString() * @throws java.io.UnsupportedEncodingException if the encoding is not supported * @see java.io.ByteArrayOutputStream#toString(String) */ - public String toString( final String enc ) throws UnsupportedEncodingException - { - return new String( toByteArray(), enc ); + public String toString(final String enc) throws UnsupportedEncodingException { + return new String(toByteArray(), enc); } /** @@ -490,9 +438,7 @@ public String toString( final String enc ) throws UnsupportedEncodingException * @see java.io.ByteArrayOutputStream#toString(String) * @since 2.5 */ - public String toString( final Charset charset ) - { - return new String( toByteArray(), charset ); + public String toString(final Charset charset) { + return new String(toByteArray(), charset); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreator.java b/src/main/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreator.java index ecd99f927..5a3c32c5a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreator.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreator.java @@ -26,6 +26,7 @@ import java.util.concurrent.Executors; import java.util.zip.Deflater; import java.util.zip.ZipEntry; + import org.apache.commons.compress.archivers.zip.ParallelScatterZipCreator; import org.apache.commons.compress.archivers.zip.ScatterZipOutputStream; import org.apache.commons.compress.archivers.zip.StreamCompressor; @@ -40,8 +41,7 @@ import static org.apache.commons.compress.archivers.zip.ZipArchiveEntryRequest.createZipArchiveEntryRequest; -public class ConcurrentJarCreator -{ +public class ConcurrentJarCreator { private final boolean compressAddedZips; @@ -57,33 +57,25 @@ public class ConcurrentJarCreator private long zipCloseElapsed; - private static class DeferredSupplier - implements ScatterGatherBackingStoreSupplier - { + private static class DeferredSupplier implements ScatterGatherBackingStoreSupplier { private int threshold; - DeferredSupplier( int threshold ) - { + DeferredSupplier(int threshold) { this.threshold = threshold; } @Override - public ScatterGatherBackingStore get() - throws IOException - { - return new DeferredScatterOutputStream( threshold ); + public ScatterGatherBackingStore get() throws IOException { + return new DeferredScatterOutputStream(threshold); } - } public static ScatterZipOutputStream createDeferred( - ScatterGatherBackingStoreSupplier scatterGatherBackingStoreSupplier ) - throws IOException - { + ScatterGatherBackingStoreSupplier scatterGatherBackingStoreSupplier) throws IOException { ScatterGatherBackingStore bs = scatterGatherBackingStoreSupplier.get(); - StreamCompressor sc = StreamCompressor.create( Deflater.DEFAULT_COMPRESSION, bs ); - return new ScatterZipOutputStream( bs, sc ); + StreamCompressor sc = StreamCompressor.create(Deflater.DEFAULT_COMPRESSION, bs); + return new ScatterZipOutputStream(bs, sc); } /** @@ -98,9 +90,8 @@ public static ScatterZipOutputStream createDeferred( * * @throws IOException */ - public ConcurrentJarCreator( int nThreads ) throws IOException - { - this( true, nThreads ); + public ConcurrentJarCreator(int nThreads) throws IOException { + this(true, nThreads); } /** @@ -121,17 +112,15 @@ public ConcurrentJarCreator( int nThreads ) throws IOException * * @throws IOException */ - public ConcurrentJarCreator( boolean compressAddedZips, int nThreads ) throws IOException - { + public ConcurrentJarCreator(boolean compressAddedZips, int nThreads) throws IOException { this.compressAddedZips = compressAddedZips; - ScatterGatherBackingStoreSupplier defaultSupplier = new DeferredSupplier( 100000000 / nThreads ); - metaInfDir = createDeferred( defaultSupplier ); - manifest = createDeferred( defaultSupplier ); - directories = createDeferred( defaultSupplier ); - synchronousEntries = createDeferred( defaultSupplier ); - parallelScatterZipCreator = new ParallelScatterZipCreator( Executors.newFixedThreadPool( nThreads ), - defaultSupplier ); - + ScatterGatherBackingStoreSupplier defaultSupplier = new DeferredSupplier(100000000 / nThreads); + metaInfDir = createDeferred(defaultSupplier); + manifest = createDeferred(defaultSupplier); + directories = createDeferred(defaultSupplier); + synchronousEntries = createDeferred(defaultSupplier); + parallelScatterZipCreator = + new ParallelScatterZipCreator(Executors.newFixedThreadPool(nThreads), defaultSupplier); } /** @@ -146,51 +135,38 @@ public ConcurrentJarCreator( boolean compressAddedZips, int nThreads ) throws IO * * @throws java.io.IOException */ - public void addArchiveEntry( final ZipArchiveEntry zipArchiveEntry, final InputStreamSupplier source, - final boolean addInParallel ) throws IOException - { + public void addArchiveEntry( + final ZipArchiveEntry zipArchiveEntry, final InputStreamSupplier source, final boolean addInParallel) + throws IOException { final int method = zipArchiveEntry.getMethod(); - if ( method == -1 ) - { - throw new IllegalArgumentException( "Method must be set on the supplied zipArchiveEntry" ); + if (method == -1) { + throw new IllegalArgumentException("Method must be set on the supplied zipArchiveEntry"); } final String zipEntryName = zipArchiveEntry.getName(); - if ( "META-INF".equals( zipEntryName ) || "META-INF/".equals( zipEntryName ) ) - { + if ("META-INF".equals(zipEntryName) || "META-INF/".equals(zipEntryName)) { // TODO This should be enforced because META-INF non-directory does not make any sense?! - if ( zipArchiveEntry.isDirectory() ) - { - zipArchiveEntry.setMethod( ZipEntry.STORED ); + if (zipArchiveEntry.isDirectory()) { + zipArchiveEntry.setMethod(ZipEntry.STORED); } - metaInfDir.addArchiveEntry( createZipArchiveEntryRequest( zipArchiveEntry, source ) ); - } - else if ( "META-INF/MANIFEST.MF".equals( zipEntryName ) ) - { - manifest.addArchiveEntry( createZipArchiveEntryRequest( zipArchiveEntry, source ) ); - } - else if ( zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink() ) - { - directories.addArchiveEntry( createZipArchiveEntryRequest( zipArchiveEntry, - () -> Streams.EMPTY_INPUTSTREAM ) ); - } - else if ( addInParallel ) - { - parallelScatterZipCreator.addArchiveEntry( () -> createEntry( zipArchiveEntry, source ) ); - } - else - { - synchronousEntries.addArchiveEntry( createEntry( zipArchiveEntry, source ) ); + metaInfDir.addArchiveEntry(createZipArchiveEntryRequest(zipArchiveEntry, source)); + } else if ("META-INF/MANIFEST.MF".equals(zipEntryName)) { + manifest.addArchiveEntry(createZipArchiveEntryRequest(zipArchiveEntry, source)); + } else if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink()) { + directories.addArchiveEntry(createZipArchiveEntryRequest(zipArchiveEntry, () -> Streams.EMPTY_INPUTSTREAM)); + } else if (addInParallel) { + parallelScatterZipCreator.addArchiveEntry(() -> createEntry(zipArchiveEntry, source)); + } else { + synchronousEntries.addArchiveEntry(createEntry(zipArchiveEntry, source)); } } - public void writeTo( ZipArchiveOutputStream targetStream ) throws IOException, ExecutionException, - InterruptedException - { - metaInfDir.writeTo( targetStream ); - manifest.writeTo( targetStream ); - directories.writeTo( targetStream ); - synchronousEntries.writeTo( targetStream ); - parallelScatterZipCreator.writeTo( targetStream ); + public void writeTo(ZipArchiveOutputStream targetStream) + throws IOException, ExecutionException, InterruptedException { + metaInfDir.writeTo(targetStream); + manifest.writeTo(targetStream); + directories.writeTo(targetStream); + synchronousEntries.writeTo(targetStream); + parallelScatterZipCreator.writeTo(targetStream); long startAt = System.currentTimeMillis(); targetStream.close(); zipCloseElapsed = System.currentTimeMillis() - startAt; @@ -205,51 +181,41 @@ public void writeTo( ZipArchiveOutputStream targetStream ) throws IOException, E * * @return A string */ - public String getStatisticsMessage() - { + public String getStatisticsMessage() { return parallelScatterZipCreator.getStatisticsMessage() + " Zip Close: " + zipCloseElapsed + "ms"; } - private ZipArchiveEntryRequest createEntry( final ZipArchiveEntry zipArchiveEntry, - final InputStreamSupplier inputStreamSupplier ) - { + private ZipArchiveEntryRequest createEntry( + final ZipArchiveEntry zipArchiveEntry, final InputStreamSupplier inputStreamSupplier) { // if we re-compress the zip files there is no need to look at the input stream - if ( compressAddedZips ) - { - return createZipArchiveEntryRequest( zipArchiveEntry, inputStreamSupplier ); + if (compressAddedZips) { + return createZipArchiveEntryRequest(zipArchiveEntry, inputStreamSupplier); } InputStream is = inputStreamSupplier.get(); // otherwise we should inspect the first four bytes to see if the input stream is zip file or not byte[] header = new byte[4]; - try - { - int read = is.read( header ); + try { + int read = is.read(header); int compressionMethod = zipArchiveEntry.getMethod(); - if ( isZipHeader( header ) ) - { + if (isZipHeader(header)) { compressionMethod = ZipEntry.STORED; } - zipArchiveEntry.setMethod( compressionMethod ); + zipArchiveEntry.setMethod(compressionMethod); - return createZipArchiveEntryRequest( zipArchiveEntry, prependBytesToStream( header, read, is ) ); - } - catch ( IOException e ) - { - IOUtils.closeQuietly( is ); - throw new UncheckedIOException( e ); + return createZipArchiveEntryRequest(zipArchiveEntry, prependBytesToStream(header, read, is)); + } catch (IOException e) { + IOUtils.closeQuietly(is); + throw new UncheckedIOException(e); } } - private boolean isZipHeader( byte[] header ) - { + private boolean isZipHeader(byte[] header) { return header[0] == 0x50 && header[1] == 0x4b && header[2] == 3 && header[3] == 4; } - private InputStreamSupplier prependBytesToStream( final byte[] bytes, final int len, final InputStream stream ) - { - return () -> len > 0 ? new SequenceInputStream( new ByteArrayInputStream( bytes, 0, len ), stream ) : stream; + private InputStreamSupplier prependBytesToStream(final byte[] bytes, final int len, final InputStream stream) { + return () -> len > 0 ? new SequenceInputStream(new ByteArrayInputStream(bytes, 0, len), stream) : stream; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/DeferredScatterOutputStream.java b/src/main/java/org/codehaus/plexus/archiver/zip/DeferredScatterOutputStream.java index 730fa6dbe..dda5eb2fe 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/DeferredScatterOutputStream.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/DeferredScatterOutputStream.java @@ -20,44 +20,37 @@ import java.io.File; import java.io.IOException; import java.io.InputStream; + import org.apache.commons.compress.parallel.ScatterGatherBackingStore; -public class DeferredScatterOutputStream implements ScatterGatherBackingStore -{ +public class DeferredScatterOutputStream implements ScatterGatherBackingStore { private final OffloadingOutputStream dfos; - public DeferredScatterOutputStream( int threshold ) - { - dfos = new OffloadingOutputStream( threshold, "scatterzipfragment", "zip" ); + public DeferredScatterOutputStream(int threshold) { + dfos = new OffloadingOutputStream(threshold, "scatterzipfragment", "zip"); } @Override - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { return dfos.getInputStream(); } @Override - public void writeOut( byte[] data, int offset, int length ) throws IOException - { - dfos.write( data, offset, length ); + public void writeOut(byte[] data, int offset, int length) throws IOException { + dfos.write(data, offset, length); } @Override - public void closeForWriting() throws IOException - { + public void closeForWriting() throws IOException { dfos.close(); } @Override - public void close() throws IOException - { + public void close() throws IOException { File file = dfos.getFile(); - if ( file != null ) - { + if (file != null) { file.delete(); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStream.java b/src/main/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStream.java index be56fa274..4fc0abffa 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStream.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStream.java @@ -30,8 +30,7 @@ /** * Offloads to disk when a given memory consumption has been reached */ -class OffloadingOutputStream extends ThresholdingOutputStream -{ +class OffloadingOutputStream extends ThresholdingOutputStream { // ----------------------------------------------------------- Data members @@ -74,16 +73,14 @@ class OffloadingOutputStream extends ThresholdingOutputStream * @param suffix Suffix to use for the temporary file. * @since 1.4 */ - public OffloadingOutputStream( int threshold, String prefix, String suffix ) - { - super( threshold ); + public OffloadingOutputStream(int threshold, String prefix, String suffix) { + super(threshold); - if ( prefix == null ) - { - throw new IllegalArgumentException( "Temporary file prefix is missing" ); + if (prefix == null) { + throw new IllegalArgumentException("Temporary file prefix is missing"); } - memoryOutputStream = new ByteArrayOutputStream( threshold / 10 ); + memoryOutputStream = new ByteArrayOutputStream(threshold / 10); currentOutputStream = memoryOutputStream; this.prefix = prefix; this.suffix = suffix; @@ -99,8 +96,7 @@ public OffloadingOutputStream( int threshold, String prefix, String suffix ) * @throws java.io.IOException if an error occurs. */ @Override - protected OutputStream getStream() throws IOException - { + protected OutputStream getStream() throws IOException { return currentOutputStream; } @@ -113,21 +109,18 @@ protected OutputStream getStream() throws IOException * @throws java.io.IOException if an error occurs. */ @Override - protected void thresholdReached() throws IOException - { - outputPath = Files.createTempFile( prefix, suffix ); - currentOutputStream = Files.newOutputStream( outputPath ); + protected void thresholdReached() throws IOException { + outputPath = Files.createTempFile(prefix, suffix); + currentOutputStream = Files.newOutputStream(outputPath); } - public InputStream getInputStream() throws IOException - { + public InputStream getInputStream() throws IOException { InputStream memoryAsInput = memoryOutputStream.toInputStream(); - if ( outputPath == null ) - { + if (outputPath == null) { return memoryAsInput; } - return new SequenceInputStream( memoryAsInput, Files.newInputStream( outputPath ) ); + return new SequenceInputStream(memoryAsInput, Files.newInputStream(outputPath)); } // --------------------------------------------------------- Public methods @@ -140,10 +133,8 @@ public InputStream getInputStream() throws IOException * @return The data for this output stream, or null if no such * data is available. */ - public byte[] getData() - { - if ( memoryOutputStream != null ) - { + public byte[] getData() { + if (memoryOutputStream != null) { return memoryOutputStream.toByteArray(); } return null; @@ -163,8 +154,7 @@ public byte[] getData() * @return The file for this output stream, or null if no such * file exists. */ - public File getFile() - { + public File getFile() { return outputPath != null ? outputPath.toFile() : null; } @@ -174,8 +164,7 @@ public File getFile() * @throws java.io.IOException if an error occurs. */ @Override - public void close() throws IOException - { + public void close() throws IOException { super.close(); currentOutputStream.close(); } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollection.java index dfb2c7608..c0d729554 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollection.java @@ -9,88 +9,72 @@ import java.nio.charset.StandardCharsets; import java.util.Enumeration; import java.util.Iterator; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.components.io.resources.AbstractPlexusIoArchiveResourceCollection; import org.codehaus.plexus.components.io.resources.EncodingSupported; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -@Named( "zip" ) -public class PlexusArchiverZipFileResourceCollection - extends AbstractPlexusIoArchiveResourceCollection implements EncodingSupported -{ +@Named("zip") +public class PlexusArchiverZipFileResourceCollection extends AbstractPlexusIoArchiveResourceCollection + implements EncodingSupported { private Charset charset = StandardCharsets.UTF_8; @Override - protected Iterator getEntries() - throws IOException - { + protected Iterator getEntries() throws IOException { final File f = getFile(); - if ( f == null ) - { - throw new IOException( "The tar archive file has not been set." ); + if (f == null) { + throw new IOException("The tar archive file has not been set."); } - final ZipFile zipFile = new ZipFile( f, charset != null ? charset.name() : "UTF8" ); - return new CloseableIterator( zipFile ); + final ZipFile zipFile = new ZipFile(f, charset != null ? charset.name() : "UTF8"); + return new CloseableIterator(zipFile); } @Override - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { // Well maybe someday investigate if we can do concurrent zip return false; } - class CloseableIterator - implements Iterator, Closeable - { + class CloseableIterator implements Iterator, Closeable { final Enumeration en; private final ZipFile zipFile; - public CloseableIterator( ZipFile zipFile ) - { + public CloseableIterator(ZipFile zipFile) { this.en = zipFile.getEntriesInPhysicalOrder(); this.zipFile = zipFile; } @Override - public boolean hasNext() - { + public boolean hasNext() { return en.hasMoreElements(); } @Override - public PlexusIoResource next() - { + public PlexusIoResource next() { final ZipArchiveEntry entry = en.nextElement(); return entry.isUnixSymlink() - ? new ZipSymlinkResource( zipFile, entry, getStreamTransformer() ) - : new ZipResource( zipFile, entry, getStreamTransformer() ); - + ? new ZipSymlinkResource(zipFile, entry, getStreamTransformer()) + : new ZipResource(zipFile, entry, getStreamTransformer()); } @Override - public void remove() - { - throw new UnsupportedOperationException( "Removing isn't implemented." ); + public void remove() { + throw new UnsupportedOperationException("Removing isn't implemented."); } @Override - public void close() - throws IOException - { + public void close() throws IOException { zipFile.close(); } - } @Override - public void setEncoding( Charset charset ) - { + public void setEncoding(Charset charset) { this.charset = charset; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollection.java index 92dd8d37b..b4767ddca 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollection.java @@ -15,8 +15,6 @@ */ package org.codehaus.plexus.archiver.zip; -import javax.inject.Named; - import java.io.Closeable; import java.io.File; import java.io.IOException; @@ -28,6 +26,7 @@ import java.util.Enumeration; import java.util.Iterator; import java.util.jar.JarFile; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; @@ -38,70 +37,54 @@ // TODO: there were two components for same name! // @Named( "zip" ) -public class PlexusIoZipFileResourceCollection - extends AbstractPlexusIoArchiveResourceCollection - implements EncodingSupported -{ +public class PlexusIoZipFileResourceCollection extends AbstractPlexusIoArchiveResourceCollection + implements EncodingSupported { private Charset charset = StandardCharsets.UTF_8; - public PlexusIoZipFileResourceCollection() - { - - } + public PlexusIoZipFileResourceCollection() {} @Override - public boolean isConcurrentAccessSupported() - { + public boolean isConcurrentAccessSupported() { // Maybe we could support concurrent some time in the future return false; } @Override - protected Iterator getEntries() - throws IOException - { + protected Iterator getEntries() throws IOException { final File f = getFile(); - if ( f == null ) - { - throw new IOException( "The zip file has not been set." ); + if (f == null) { + throw new IOException("The zip file has not been set."); } - final URLClassLoader urlClassLoader = new URLClassLoader( new URL[] - { - f.toURI().toURL() - }, null ) - { - - @Override - public URL getResource( String name ) - { - return findResource( name ); - } - - }; - - final URL url = new URL( "jar:" + f.toURI().toURL() + "!/" ); - final JarFile jarFile = new JarFile( f ); - final ZipFile zipFile = new ZipFile( f, charset != null ? charset.name() : "UTF8" ); + final URLClassLoader urlClassLoader = + new URLClassLoader(new URL[] {f.toURI().toURL()}, null) { + + @Override + public URL getResource(String name) { + return findResource(name); + } + }; + + final URL url = new URL("jar:" + f.toURI().toURL() + "!/"); + final JarFile jarFile = new JarFile(f); + final ZipFile zipFile = new ZipFile(f, charset != null ? charset.name() : "UTF8"); final Enumeration en = zipFile.getEntriesInPhysicalOrder(); - return new ZipFileResourceIterator( en, url, jarFile, zipFile, urlClassLoader ); + return new ZipFileResourceIterator(en, url, jarFile, zipFile, urlClassLoader); } - private static class ZipFileResourceIterator - implements Iterator, Closeable - { + private static class ZipFileResourceIterator implements Iterator, Closeable { - private class ZipFileResource - extends PlexusIoURLResource - { + private class ZipFileResource extends PlexusIoURLResource { private final JarFile jarFile; - private ZipFileResource( JarFile jarFile, ZipArchiveEntry entry ) - { - super( entry.getName(), - entry.getTime() == -1 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : entry.getTime(), - entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), - !entry.isDirectory(), entry.isDirectory(), true ); + private ZipFileResource(JarFile jarFile, ZipArchiveEntry entry) { + super( + entry.getName(), + entry.getTime() == -1 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : entry.getTime(), + entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), + !entry.isDirectory(), + entry.isDirectory(), + true); this.jarFile = jarFile; } @@ -122,54 +105,42 @@ public InputStream getContents() throws IOException { // would not be a problem. // And we know the URL returned by getURL is part of the JAR // because that is how we constructed it. - return jarFile.getInputStream( jarFile.getEntry( getName() ) ); + return jarFile.getInputStream(jarFile.getEntry(getName())); } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { String spec = getName(); - if ( spec.startsWith( "/" ) ) - { + if (spec.startsWith("/")) { // Code path for PLXCOMP-170. Note that urlClassloader does not seem to produce correct // urls for this. Which again means files loaded via this path cannot have file names // requiring url encoding spec = "./" + spec; - return new URL( url, spec ); + return new URL(url, spec); } - return urlClassLoader.getResource( spec ); + return urlClassLoader.getResource(spec); } - } - private class ZipFileSymlinkResource - extends ZipFileResource - implements SymlinkDestinationSupplier - { + private class ZipFileSymlinkResource extends ZipFileResource implements SymlinkDestinationSupplier { private final ZipArchiveEntry entry; - private ZipFileSymlinkResource( JarFile jarFile, ZipArchiveEntry entry ) - { - super( jarFile, entry ); + private ZipFileSymlinkResource(JarFile jarFile, ZipArchiveEntry entry) { + super(jarFile, entry); this.entry = entry; } @Override - public String getSymlinkDestination() - throws IOException - { - return zipFile.getUnixSymlink( entry ); + public String getSymlinkDestination() throws IOException { + return zipFile.getUnixSymlink(entry); } @Override - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return true; } - } private final Enumeration en; @@ -182,9 +153,12 @@ public boolean isSymbolicLink() private final URLClassLoader urlClassLoader; - public ZipFileResourceIterator( Enumeration en, URL url, JarFile jarFile, ZipFile zipFile, - URLClassLoader urlClassLoader ) - { + public ZipFileResourceIterator( + Enumeration en, + URL url, + JarFile jarFile, + ZipFile zipFile, + URLClassLoader urlClassLoader) { this.en = en; this.url = url; this.jarFile = jarFile; @@ -193,54 +167,39 @@ public ZipFileResourceIterator( Enumeration en, URL url, JarFil } @Override - public boolean hasNext() - { + public boolean hasNext() { return en.hasMoreElements(); } @Override - public PlexusIoResource next() - { + public PlexusIoResource next() { final ZipArchiveEntry entry = en.nextElement(); return entry.isUnixSymlink() - ? new ZipFileSymlinkResource( jarFile, entry ) - : new ZipFileResource( jarFile, entry ); - + ? new ZipFileSymlinkResource(jarFile, entry) + : new ZipFileResource(jarFile, entry); } @Override - public void remove() - { - throw new UnsupportedOperationException( "Removing isn't implemented." ); + public void remove() { + throw new UnsupportedOperationException("Removing isn't implemented."); } @Override - public void close() - throws IOException - { - try - { + public void close() throws IOException { + try { urlClassLoader.close(); - } - finally - { - try - { + } finally { + try { zipFile.close(); - } finally - { + } finally { jarFile.close(); } - } } - } @Override - public void setEncoding( Charset charset ) - { + public void setEncoding(Charset charset) { this.charset = charset; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java index b19b681e8..6a85ba3ee 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java @@ -18,8 +18,5 @@ import javax.inject.Named; -@Named( "zip" ) -public class ZipArchiver - extends AbstractZipArchiver -{ -} +@Named("zip") +public class ZipArchiver extends AbstractZipArchiver {} diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ZipResource.java b/src/main/java/org/codehaus/plexus/archiver/zip/ZipResource.java index 2df6ac012..c51f6b6a6 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ZipResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ZipResource.java @@ -1,9 +1,11 @@ package org.codehaus.plexus.archiver.zip; +import javax.annotation.Nonnull; + import java.io.IOException; import java.io.InputStream; import java.net.URL; -import javax.annotation.Nonnull; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.archiver.UnixStat; @@ -15,9 +17,7 @@ import org.codehaus.plexus.components.io.resources.ClosingInputStream; import org.codehaus.plexus.components.io.resources.PlexusIoResource; -public class ZipResource extends AbstractPlexusIoResource - implements ResourceAttributeSupplier -{ +public class ZipResource extends AbstractPlexusIoResource implements ResourceAttributeSupplier { private final org.apache.commons.compress.archivers.zip.ZipFile zipFile; @@ -27,67 +27,57 @@ public class ZipResource extends AbstractPlexusIoResource private PlexusIoResourceAttributes attributes; - public ZipResource( ZipFile zipFile, ZipArchiveEntry entry, InputStreamTransformer streamTransformer ) - { - super( entry.getName(), getLastModified( entry ), - entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), !entry.isDirectory(), - entry.isDirectory(), true ); + public ZipResource(ZipFile zipFile, ZipArchiveEntry entry, InputStreamTransformer streamTransformer) { + super( + entry.getName(), + getLastModified(entry), + entry.isDirectory() ? PlexusIoResource.UNKNOWN_RESOURCE_SIZE : entry.getSize(), + !entry.isDirectory(), + entry.isDirectory(), + true); this.zipFile = zipFile; this.entry = entry; this.streamTransformer = streamTransformer; } - private static long getLastModified( ZipArchiveEntry entry ) - { + private static long getLastModified(ZipArchiveEntry entry) { long time = entry.getTime(); return time == -1 ? PlexusIoResource.UNKNOWN_MODIFICATION_DATE : time; } @Override - public synchronized PlexusIoResourceAttributes getAttributes() - { + public synchronized PlexusIoResourceAttributes getAttributes() { int mode = PlexusIoResourceAttributes.UNKNOWN_OCTAL_MODE; - if ( entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX ) - { + if (entry.getPlatform() == ZipArchiveEntry.PLATFORM_UNIX) { mode = entry.getUnixMode(); - if ( ( mode & UnixStat.FILE_FLAG ) == UnixStat.FILE_FLAG ) - { + if ((mode & UnixStat.FILE_FLAG) == UnixStat.FILE_FLAG) { mode = mode & ~UnixStat.FILE_FLAG; - } - else - { + } else { mode = mode & ~UnixStat.DIR_FLAG; } } - if ( attributes == null ) - { - attributes = new SimpleResourceAttributes( null, null, null, null, mode ); + if (attributes == null) { + attributes = new SimpleResourceAttributes(null, null, null, null, mode); } return attributes; } - public synchronized void setAttributes( PlexusIoResourceAttributes attributes ) - { + public synchronized void setAttributes(PlexusIoResourceAttributes attributes) { this.attributes = attributes; } @Override - public URL getURL() - throws IOException - { + public URL getURL() throws IOException { return null; } @Nonnull @Override - public InputStream getContents() - throws IOException - { - final InputStream inputStream = zipFile.getInputStream( entry ); - return new ClosingInputStream( streamTransformer.transform( this, inputStream ), inputStream ); + public InputStream getContents() throws IOException { + final InputStream inputStream = zipFile.getInputStream(entry); + return new ClosingInputStream(streamTransformer.transform(this, inputStream), inputStream); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ZipSymlinkResource.java b/src/main/java/org/codehaus/plexus/archiver/zip/ZipSymlinkResource.java index 1ea6f7c36..9338cba6a 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ZipSymlinkResource.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ZipSymlinkResource.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.archiver.zip; import java.io.IOException; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.components.io.functions.InputStreamTransformer; @@ -24,37 +25,26 @@ /** * A {@link ZipResource} that represents symbolic link. */ -public class ZipSymlinkResource - extends ZipResource - implements SymlinkDestinationSupplier -{ +public class ZipSymlinkResource extends ZipResource implements SymlinkDestinationSupplier { private final String symlinkDestination; - public ZipSymlinkResource( ZipFile zipFile, ZipArchiveEntry entry, InputStreamTransformer streamTransformer ) - { - super( zipFile, entry, streamTransformer ); - try - { - symlinkDestination = zipFile.getUnixSymlink( entry ); - } - catch ( IOException e ) - { - throw new RuntimeException( e ); + public ZipSymlinkResource(ZipFile zipFile, ZipArchiveEntry entry, InputStreamTransformer streamTransformer) { + super(zipFile, entry, streamTransformer); + try { + symlinkDestination = zipFile.getUnixSymlink(entry); + } catch (IOException e) { + throw new RuntimeException(e); } } @Override - public String getSymlinkDestination() - throws IOException - { + public String getSymlinkDestination() throws IOException { return symlinkDestination; } @Override - public boolean isSymbolicLink() - { + public boolean isSymbolicLink() { return true; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zip/ZipUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zip/ZipUnArchiver.java index 4041b6fdf..49af6717c 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zip/ZipUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zip/ZipUnArchiver.java @@ -23,18 +23,12 @@ /** * @author Emmanuel Venisse */ -@Named( "zip" ) -public class ZipUnArchiver - extends AbstractZipUnArchiver -{ +@Named("zip") +public class ZipUnArchiver extends AbstractZipUnArchiver { - public ZipUnArchiver() - { - } + public ZipUnArchiver() {} - public ZipUnArchiver( File sourceFile ) - { - super( sourceFile ); + public ZipUnArchiver(File sourceFile) { + super(sourceFile); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zstd/PlexusIoZstdResourceCollection.java b/src/main/java/org/codehaus/plexus/archiver/zstd/PlexusIoZstdResourceCollection.java index 84a9d0e62..d0ce8ec31 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zstd/PlexusIoZstdResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/archiver/zstd/PlexusIoZstdResourceCollection.java @@ -31,26 +31,21 @@ * Implementation of {@link org.codehaus.plexus.components.io.resources.PlexusIoResourceCollection} for * zstd compressed files. */ -@Named( "zst" ) -public class PlexusIoZstdResourceCollection extends PlexusIoCompressedFileResourceCollection -{ +@Named("zst") +public class PlexusIoZstdResourceCollection extends PlexusIoCompressedFileResourceCollection { @Override - protected PlexusIoResourceAttributes getAttributes( File file ) throws IOException - { - return new FileAttributes( file, new HashMap(), new HashMap() ); + protected PlexusIoResourceAttributes getAttributes(File file) throws IOException { + return new FileAttributes(file, new HashMap(), new HashMap()); } @Override - protected String getDefaultExtension() - { + protected String getDefaultExtension() { return ".zst"; } @Override - protected InputStream getInputStream( File file ) throws IOException - { - return ZstdUnArchiver.getZstdInputStream( Streams.fileInputStream( file ) ); + protected InputStream getInputStream(File file) throws IOException { + return ZstdUnArchiver.getZstdInputStream(Streams.fileInputStream(file)); } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdArchiver.java index f2484d746..549740a45 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdArchiver.java @@ -18,6 +18,7 @@ import javax.inject.Named; import java.io.IOException; + import org.codehaus.plexus.archiver.AbstractArchiver; import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.ArchiverException; @@ -27,64 +28,51 @@ /** * Zstd archiver. */ -@Named( "zst" ) -public class ZstdArchiver extends AbstractArchiver -{ +@Named("zst") +public class ZstdArchiver extends AbstractArchiver { private final ZstdCompressor compressor = new ZstdCompressor(); - public ZstdArchiver() - { - } + public ZstdArchiver() {} /** * Set compression level */ - public void setLevel( Integer level ) - throws ArchiverException - { - compressor.setLevel( level ); + public void setLevel(Integer level) throws ArchiverException { + compressor.setLevel(level); } @Override - protected void execute() throws ArchiverException, IOException - { - if ( !checkForced() ) - { + protected void execute() throws ArchiverException, IOException { + if (!checkForced()) { return; } ResourceIterator iter = getResources(); - if ( !iter.hasNext() ) - { - throw new EmptyArchiveException( "archive cannot be empty" ); + if (!iter.hasNext()) { + throw new EmptyArchiveException("archive cannot be empty"); } ArchiveEntry entry = iter.next(); - if ( iter.hasNext() ) - { - throw new ArchiverException( "There is more than one file in input." ); + if (iter.hasNext()) { + throw new ArchiverException("There is more than one file in input."); } - compressor.setSource( entry.getResource() ); - compressor.setDestFile( getDestFile() ); + compressor.setSource(entry.getResource()); + compressor.setDestFile(getDestFile()); compressor.compress(); } @Override - public boolean isSupportingForced() - { + public boolean isSupportingForced() { return true; } @Override - protected void close() throws IOException - { + protected void close() throws IOException { compressor.close(); } @Override - protected String getArchiveType() - { + protected String getArchiveType() { return "zstd"; } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdCompressor.java b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdCompressor.java index 4dc06d2ea..c41557ab2 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdCompressor.java +++ b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdCompressor.java @@ -15,72 +15,55 @@ */ package org.codehaus.plexus.archiver.zstd; +import java.io.BufferedOutputStream; +import java.io.IOException; + import org.apache.commons.compress.compressors.zstandard.ZstdCompressorOutputStream; import org.codehaus.plexus.archiver.ArchiverException; import org.codehaus.plexus.archiver.util.Compressor; -import java.io.BufferedOutputStream; -import java.io.IOException; - import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.fileOutputStream; /** * Zstd compression */ -public class ZstdCompressor extends Compressor -{ +public class ZstdCompressor extends Compressor { private Integer level; private ZstdCompressorOutputStream zstdOut; - public ZstdCompressor() - { - } + public ZstdCompressor() {} - public void setLevel( Integer level ) - { + public void setLevel(Integer level) { this.level = level; } @Override - public void compress() throws ArchiverException - { - try - { - BufferedOutputStream outStream = bufferedOutputStream( fileOutputStream( getDestFile() ) ); - if (level == null) - { - zstdOut = new ZstdCompressorOutputStream( outStream ); - } - else - { - zstdOut = new ZstdCompressorOutputStream( outStream, level ); + public void compress() throws ArchiverException { + try { + BufferedOutputStream outStream = bufferedOutputStream(fileOutputStream(getDestFile())); + if (level == null) { + zstdOut = new ZstdCompressorOutputStream(outStream); + } else { + zstdOut = new ZstdCompressorOutputStream(outStream, level); } - compress( getSource(), zstdOut); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Problem creating zstd " + ioe.getMessage(), ioe ); + compress(getSource(), zstdOut); + } catch (IOException ioe) { + throw new ArchiverException("Problem creating zstd " + ioe.getMessage(), ioe); } } @Override - public void close() - { - try - { - if ( this.zstdOut != null ) - { + public void close() { + try { + if (this.zstdOut != null) { this.zstdOut.close(); zstdOut = null; } - } - catch ( final IOException e ) - { - throw new ArchiverException( "Failure closing target.", e ); + } catch (final IOException e) { + throw new ArchiverException("Failure closing target.", e); } } - } diff --git a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdUnArchiver.java b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdUnArchiver.java index 7dcf6c1f5..2a6d4cd96 100644 --- a/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdUnArchiver.java +++ b/src/main/java/org/codehaus/plexus/archiver/zstd/ZstdUnArchiver.java @@ -15,16 +15,17 @@ */ package org.codehaus.plexus.archiver.zstd; -import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream; -import org.codehaus.plexus.archiver.AbstractUnArchiver; -import org.codehaus.plexus.archiver.ArchiverException; - import javax.annotation.Nonnull; import javax.inject.Named; + import java.io.File; import java.io.IOException; import java.io.InputStream; +import org.apache.commons.compress.compressors.zstandard.ZstdCompressorInputStream; +import org.codehaus.plexus.archiver.AbstractUnArchiver; +import org.codehaus.plexus.archiver.ArchiverException; + import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; import static org.codehaus.plexus.archiver.util.Streams.bufferedOutputStream; import static org.codehaus.plexus.archiver.util.Streams.copyFully; @@ -34,53 +35,41 @@ /** * Unarchiver for zstd-compressed files. */ -@Named( "zst" ) -public class ZstdUnArchiver extends AbstractUnArchiver -{ +@Named("zst") +public class ZstdUnArchiver extends AbstractUnArchiver { private static final String OPERATION_ZSTD = "zstd"; - public ZstdUnArchiver() - { - } + public ZstdUnArchiver() {} - public ZstdUnArchiver( File source ) - { - super( source ); + public ZstdUnArchiver(File source) { + super(source); } @Override - protected void execute() throws ArchiverException - { - if ( getSourceFile().lastModified() > getDestFile().lastModified() ) - { - getLogger().info( "Expanding " + getSourceFile().getAbsolutePath() + " to " - + getDestFile().getAbsolutePath() ); - - copyFully( getZstdInputStream( bufferedInputStream( fileInputStream( getSourceFile(), OPERATION_ZSTD) ) ), - bufferedOutputStream( fileOutputStream( getDestFile(), OPERATION_ZSTD) ), OPERATION_ZSTD); + protected void execute() throws ArchiverException { + if (getSourceFile().lastModified() > getDestFile().lastModified()) { + getLogger() + .info("Expanding " + getSourceFile().getAbsolutePath() + " to " + + getDestFile().getAbsolutePath()); + copyFully( + getZstdInputStream(bufferedInputStream(fileInputStream(getSourceFile(), OPERATION_ZSTD))), + bufferedOutputStream(fileOutputStream(getDestFile(), OPERATION_ZSTD)), + OPERATION_ZSTD); } } - public static @Nonnull - ZstdCompressorInputStream getZstdInputStream( InputStream in ) - throws ArchiverException - { - try - { - return new ZstdCompressorInputStream( in ); - } - catch ( IOException ioe ) - { - throw new ArchiverException( "Trouble creating Zstd compressor, invalid file ?", ioe ); + public static @Nonnull ZstdCompressorInputStream getZstdInputStream(InputStream in) throws ArchiverException { + try { + return new ZstdCompressorInputStream(in); + } catch (IOException ioe) { + throw new ArchiverException("Trouble creating Zstd compressor, invalid file ?", ioe); } } @Override - protected void execute( String path, File outputDirectory ) throws ArchiverException - { - throw new UnsupportedOperationException( "Targeted execution not supported in zstd format" ); + protected void execute(String path, File outputDirectory) throws ArchiverException { + throw new UnsupportedOperationException("Targeted execution not supported in zstd format"); } - } diff --git a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoZipFileResourceCollection.java b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoZipFileResourceCollection.java index 3b1e017ad..6825717e0 100644 --- a/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoZipFileResourceCollection.java +++ b/src/main/java/org/codehaus/plexus/components/io/resources/PlexusIoZipFileResourceCollection.java @@ -20,8 +20,4 @@ * Make sure maven-assembly-plugin IT's work when you do :) */ public class PlexusIoZipFileResourceCollection - extends org.codehaus.plexus.archiver.zip.PlexusIoZipFileResourceCollection - -{ - -} + extends org.codehaus.plexus.archiver.zip.PlexusIoZipFileResourceCollection {} diff --git a/src/test/java/org/codehaus/plexus/archiver/AbstractArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/AbstractArchiverTest.java index 081607916..b709ba0a8 100644 --- a/src/test/java/org/codehaus/plexus/archiver/AbstractArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/AbstractArchiverTest.java @@ -8,100 +8,86 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -public class AbstractArchiverTest -{ +public class AbstractArchiverTest { private AbstractArchiver archiver; @BeforeEach - public void setUp() throws Exception - { - this.archiver = new AbstractArchiver() - { + public void setUp() throws Exception { + this.archiver = new AbstractArchiver() { @Override - protected String getArchiveType() - { + protected String getArchiveType() { throw new UnsupportedOperationException(); } @Override - protected void execute() throws ArchiverException, IOException - { + protected void execute() throws ArchiverException, IOException { throw new UnsupportedOperationException(); } @Override - protected void close() throws IOException - { + protected void close() throws IOException { throw new UnsupportedOperationException(); } - }; } @Test - public void testModesAndOverridesAreUnsetByDefault() - { - assertEquals( -1, archiver.getDefaultFileMode() ); - assertEquals( -1, archiver.getOverrideFileMode() ); + public void testModesAndOverridesAreUnsetByDefault() { + assertEquals(-1, archiver.getDefaultFileMode()); + assertEquals(-1, archiver.getOverrideFileMode()); - assertEquals( Archiver.DEFAULT_DIR_MODE, archiver.getDefaultDirectoryMode() ); - assertEquals( -1, archiver.getOverrideDirectoryMode() ); + assertEquals(Archiver.DEFAULT_DIR_MODE, archiver.getDefaultDirectoryMode()); + assertEquals(-1, archiver.getOverrideDirectoryMode()); } @Test - public void testWhenUnsetModeUsesDefault() - { - assertEquals( Archiver.DEFAULT_FILE_MODE, archiver.getFileMode() ); - assertEquals( Archiver.DEFAULT_DIR_MODE, archiver.getDirectoryMode() ); + public void testWhenUnsetModeUsesDefault() { + assertEquals(Archiver.DEFAULT_FILE_MODE, archiver.getFileMode()); + assertEquals(Archiver.DEFAULT_DIR_MODE, archiver.getDirectoryMode()); } @Test - public void testSetModeIsUsedWithFlagsForType() - { - archiver.setFileMode( 0400 ); - assertEquals( 0100400, archiver.getFileMode() ); + public void testSetModeIsUsedWithFlagsForType() { + archiver.setFileMode(0400); + assertEquals(0100400, archiver.getFileMode()); - archiver.setDirectoryMode( 0600 ); - assertEquals( 040600, archiver.getDirectoryMode() ); + archiver.setDirectoryMode(0600); + assertEquals(040600, archiver.getDirectoryMode()); } @Test - public void testSetDefaultIncludesFlagsForType() - { - archiver.setDefaultFileMode( 0400 ); - assertEquals( 0100400, archiver.getDefaultFileMode() ); + public void testSetDefaultIncludesFlagsForType() { + archiver.setDefaultFileMode(0400); + assertEquals(0100400, archiver.getDefaultFileMode()); - archiver.setDefaultDirectoryMode( 0600 ); - assertEquals( 040600, archiver.getDefaultDirectoryMode() ); + archiver.setDefaultDirectoryMode(0600); + assertEquals(040600, archiver.getDefaultDirectoryMode()); } @Test - public void testDefaultIsUsedWhenModeIsUnset() - { - archiver.setDefaultFileMode( 0400 ); - assertEquals( 0100400, archiver.getFileMode() ); + public void testDefaultIsUsedWhenModeIsUnset() { + archiver.setDefaultFileMode(0400); + assertEquals(0100400, archiver.getFileMode()); - archiver.setDefaultDirectoryMode( 0600 ); - assertEquals( 040600, archiver.getDirectoryMode() ); + archiver.setDefaultDirectoryMode(0600); + assertEquals(040600, archiver.getDirectoryMode()); } @Test - public void testOverridesCanBeReset() - { - archiver.setFileMode( 0400 ); - archiver.setFileMode( -1 ); - assertEquals( -1, archiver.getOverrideFileMode() ); - - archiver.setDirectoryMode( 0600 ); - archiver.setDirectoryMode( -1 ); - assertEquals( -1, archiver.getOverrideDirectoryMode() ); + public void testOverridesCanBeReset() { + archiver.setFileMode(0400); + archiver.setFileMode(-1); + assertEquals(-1, archiver.getOverrideFileMode()); + + archiver.setDirectoryMode(0600); + archiver.setDirectoryMode(-1); + assertEquals(-1, archiver.getOverrideDirectoryMode()); } @Test public void testSetDestFileInTheWorkingDir() { - archiver.setDestFile( new File( "archive" ) ); + archiver.setDestFile(new File("archive")); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/AbstractUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/AbstractUnArchiverTest.java index b7698aa1f..372d14fb3 100644 --- a/src/test/java/org/codehaus/plexus/archiver/AbstractUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/AbstractUnArchiverTest.java @@ -36,172 +36,157 @@ * * @author Markus KARG */ -public class AbstractUnArchiverTest -{ +public class AbstractUnArchiverTest { private AbstractUnArchiver abstractUnArchiver; @BeforeEach - public void setUp() - { - this.abstractUnArchiver = new AbstractUnArchiver() - { + public void setUp() { + this.abstractUnArchiver = new AbstractUnArchiver() { @Override - protected void execute( final String path, final File outputDirectory ) - throws ArchiverException - { + protected void execute(final String path, final File outputDirectory) throws ArchiverException { // unused } @Override - protected void execute() - throws ArchiverException - { + protected void execute() throws ArchiverException { // unused } }; } @AfterEach - public void tearDown() - { + public void tearDown() { this.abstractUnArchiver = null; } @Test - public void shouldThrowExceptionBecauseRewrittenPathIsOutOfDirectory( @TempDir File targetFolder ) - throws ArchiverException - { + public void shouldThrowExceptionBecauseRewrittenPathIsOutOfDirectory(@TempDir File targetFolder) + throws ArchiverException { // given // The prefix includes the target directory name to make sure we catch cases when the paths // are compared as strings. For example /opt/directory starts with /opt/dir but it is // sibling and not inside /opt/dir. String prefix = "../" + targetFolder.getName() + "PREFIX/"; - final FileMapper[] fileMappers = new FileMapper[] { pName -> prefix + pName, pName -> pName + ".SUFFIX"}; + final FileMapper[] fileMappers = new FileMapper[] {pName -> prefix + pName, pName -> pName + ".SUFFIX"}; // when - Exception exception = assertThrows( ArchiverException.class, () -> - abstractUnArchiver.extractFile( null, targetFolder, null, "ENTRYNAME", null, false, null, null, fileMappers ) ); + Exception exception = assertThrows( + ArchiverException.class, + () -> abstractUnArchiver.extractFile( + null, targetFolder, null, "ENTRYNAME", null, false, null, null, fileMappers)); // then // ArchiverException is thrown providing the rewritten path - assertEquals( "Entry is outside of the target directory (" + prefix + "ENTRYNAME.SUFFIX)", exception.getMessage() ); + assertEquals( + "Entry is outside of the target directory (" + prefix + "ENTRYNAME.SUFFIX)", exception.getMessage()); } @Test - public void shouldExtractWhenFileOnDiskDoesNotExist( @TempDir File temporaryFolder ) throws IOException - { + public void shouldExtractWhenFileOnDiskDoesNotExist(@TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); // does not create the file! + File file = new File(temporaryFolder, "whatever.txt"); // does not create the file! String entryname = file.getName(); Date entryDate = new Date(); // when & then // always extract the file if it does not exist - assertTrue( abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - abstractUnArchiver.setOverwrite( false ); - assertTrue( abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); + assertTrue(abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + abstractUnArchiver.setOverwrite(false); + assertTrue(abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); } @Test - public void shouldExtractWhenFileOnDiskIsNewerThanEntryInArchive( @TempDir File temporaryFolder ) throws IOException - { + public void shouldExtractWhenFileOnDiskIsNewerThanEntryInArchive(@TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); + File file = new File(temporaryFolder, "whatever.txt"); file.createNewFile(); - file.setLastModified( System.currentTimeMillis() ); + file.setLastModified(System.currentTimeMillis()); String entryname = file.getName(); - Date entryDate = new Date( 0 ); + Date entryDate = new Date(0); // when & then // if the file is newer than archive entry, extract only if overwrite is true (default) - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - abstractUnArchiver.setOverwrite( false ); - assertFalse( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + abstractUnArchiver.setOverwrite(false); + assertFalse(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); } @Test - public void shouldExtractWhenFileOnDiskIsNewerThanEntryInArchive_andWarnAboutDifferentCasing( @TempDir File temporaryFolder ) - throws IOException - { + public void shouldExtractWhenFileOnDiskIsNewerThanEntryInArchive_andWarnAboutDifferentCasing( + @TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); + File file = new File(temporaryFolder, "whatever.txt"); file.createNewFile(); - file.setLastModified( System.currentTimeMillis() ); + file.setLastModified(System.currentTimeMillis()); String entryname = file.getName().toUpperCase(); - Date entryDate = new Date( 0 ); + Date entryDate = new Date(0); // when & then - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - assertTrue( this.abstractUnArchiver.casingMessageEmitted.get() > 0 ); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + assertTrue(this.abstractUnArchiver.casingMessageEmitted.get() > 0); } @Test - public void shouldExtractWhenEntryInArchiveIsNewerThanFileOnDisk( @TempDir File temporaryFolder ) throws IOException - { + public void shouldExtractWhenEntryInArchiveIsNewerThanFileOnDisk(@TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); + File file = new File(temporaryFolder, "whatever.txt"); file.createNewFile(); - file.setLastModified( 0 ); + file.setLastModified(0); String entryname = file.getName().toUpperCase(); - Date entryDate = new Date( System.currentTimeMillis() ); + Date entryDate = new Date(System.currentTimeMillis()); // when & then // always extract the file if the archive entry is newer than the file on disk - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - this.abstractUnArchiver.setOverwrite( false ); - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + this.abstractUnArchiver.setOverwrite(false); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); } @Test - public void shouldExtractWhenEntryInArchiveIsNewerThanFileOnDiskAndWarnAboutDifferentCasing( @TempDir File temporaryFolder ) - throws IOException - { + public void shouldExtractWhenEntryInArchiveIsNewerThanFileOnDiskAndWarnAboutDifferentCasing( + @TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); + File file = new File(temporaryFolder, "whatever.txt"); file.createNewFile(); - file.setLastModified( 0 ); + file.setLastModified(0); String entryname = file.getName().toUpperCase(); - Date entryDate = new Date( System.currentTimeMillis() ); + Date entryDate = new Date(System.currentTimeMillis()); // when & then - this.abstractUnArchiver.setOverwrite( true ); - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - this.abstractUnArchiver.setOverwrite( false ); - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - assertTrue( this.abstractUnArchiver.casingMessageEmitted.get() > 0 ); + this.abstractUnArchiver.setOverwrite(true); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + this.abstractUnArchiver.setOverwrite(false); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + assertTrue(this.abstractUnArchiver.casingMessageEmitted.get() > 0); } @Test - public void shouldNotWarnAboutDifferentCasingForDirectoryEntries( @TempDir File temporaryFolder ) - throws IOException - { + public void shouldNotWarnAboutDifferentCasingForDirectoryEntries(@TempDir File temporaryFolder) throws IOException { // given - File file = new File( temporaryFolder, "whatever.txt" ); + File file = new File(temporaryFolder, "whatever.txt"); file.createNewFile(); - file.setLastModified( 0 ); + file.setLastModified(0); String entryname = file.getName() + '/'; // archive entries for directories end with a '/' Date entryDate = new Date(); // when & then - this.abstractUnArchiver.setOverwrite( true ); - assertTrue( this.abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryname, entryDate ) ); - assertEquals( 0, this.abstractUnArchiver.casingMessageEmitted.get() ); + this.abstractUnArchiver.setOverwrite(true); + assertTrue(this.abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryname, entryDate)); + assertEquals(0, this.abstractUnArchiver.casingMessageEmitted.get()); } @Test - public void shouldExtractWhenCasingDifferOnlyInEntryNamePath( @TempDir File temporaryFolder) - throws IOException - { + public void shouldExtractWhenCasingDifferOnlyInEntryNamePath(@TempDir File temporaryFolder) throws IOException { // given String entryName = "directory/whatever.txt"; - File file = new File( temporaryFolder, entryName ); // does not create the file! + File file = new File(temporaryFolder, entryName); // does not create the file! file.mkdirs(); file.createNewFile(); Date entryDate = new Date(System.currentTimeMillis() + 5000); // when & then - abstractUnArchiver.setOverwrite( true ); - assertTrue( abstractUnArchiver.shouldExtractEntry( temporaryFolder, file, entryName, entryDate ) ); + abstractUnArchiver.setOverwrite(true); + assertTrue(abstractUnArchiver.shouldExtractEntry(temporaryFolder, file, entryName, entryDate)); assertEquals(0, abstractUnArchiver.casingMessageEmitted.get()); } } diff --git a/src/test/java/org/codehaus/plexus/archiver/BasePlexusArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/BasePlexusArchiverTest.java index f779ced80..a2262d381 100644 --- a/src/test/java/org/codehaus/plexus/archiver/BasePlexusArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/BasePlexusArchiverTest.java @@ -34,8 +34,7 @@ * Base abstract class that all the test-cases for different archivers * extend so that they can use its helpful methods. */ -public abstract class BasePlexusArchiverTest extends TestSupport -{ +public abstract class BasePlexusArchiverTest extends TestSupport { /** * Ensure that the last modified timestamp of a file will be greater @@ -47,12 +46,10 @@ public abstract class BasePlexusArchiverTest extends TestSupport * * @throws IOException if the timestamp could not be modified */ - protected void waitUntilNewTimestamp( File outputFile, long timestampReference ) - throws IOException - { + protected void waitUntilNewTimestamp(File outputFile, long timestampReference) throws IOException { long startTime = System.currentTimeMillis(); - File tmpFile = Files.createTempFile( - "BasePlexusArchiverTest.waitUntilNewTimestamp", null ).toFile(); + File tmpFile = Files.createTempFile("BasePlexusArchiverTest.waitUntilNewTimestamp", null) + .toFile(); long newTimestamp; // We could easily just set the last modified time using @@ -64,28 +61,24 @@ protected void waitUntilNewTimestamp( File outputFile, long timestampReference ) // Otherwise the build may fail because when the test overrides // `outputFile` it will have timestamp that is equal // to `timestampReference`. - do - { - FileUtils.fileWrite( tmpFile, "waitUntilNewTimestamp" ); + do { + FileUtils.fileWrite(tmpFile, "waitUntilNewTimestamp"); newTimestamp = tmpFile.lastModified(); Thread.yield(); - } - while ( timestampReference >= newTimestamp + } while (timestampReference >= newTimestamp // A simple guard to ensure that we'll not do this forever. // If the last modified timestamp is not changed to // a newer value after 10 seconds, probably it never will. - && System.currentTimeMillis() - startTime < 10_000 ); + && System.currentTimeMillis() - startTime < 10_000); tmpFile.delete(); - if ( timestampReference >= newTimestamp ) - { - throw new IOException("Could not modify the last modified timestamp " - + "to newer than the refence value." ); + if (timestampReference >= newTimestamp) { + throw new IOException("Could not modify the last modified timestamp " + "to newer than the refence value."); } - FileTime newTimestampTime = FileTime.fromMillis( newTimestamp ); - Files.setLastModifiedTime( outputFile.toPath(), newTimestampTime ); + FileTime newTimestampTime = FileTime.fromMillis(newTimestamp); + Files.setLastModifiedTime(outputFile.toPath(), newTimestampTime); } /** @@ -97,17 +90,15 @@ protected void waitUntilNewTimestamp( File outputFile, long timestampReference ) * * @throws Exception */ - protected Archiver createArchiver( String format ) throws Exception - { + protected Archiver createArchiver(String format) throws Exception { - final File pomFile = new File( "pom.xml" ); - final File rarFile = new File( "target/output/pom.xml." + format ); + final File pomFile = new File("pom.xml"); + final File rarFile = new File("target/output/pom.xml." + format); - Archiver archiver = (Archiver) lookup( Archiver.class, format ); - archiver.setDestFile( rarFile ); - archiver.addFile( pomFile, "pom.xml" ); + Archiver archiver = (Archiver) lookup(Archiver.class, format); + archiver.setDestFile(rarFile); + archiver.addFile(pomFile, "pom.xml"); return archiver; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizerTest.java b/src/test/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizerTest.java index da1947930..4d1912e5b 100644 --- a/src/test/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizerTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/DotDirectiveArchiveFinalizerTest.java @@ -2,6 +2,7 @@ import java.io.File; import java.util.jar.JarFile; + import org.codehaus.plexus.archiver.jar.JarArchiver; import org.junit.jupiter.api.Test; @@ -10,63 +11,56 @@ /** * @author Jason van Zyl */ -public class DotDirectiveArchiveFinalizerTest - extends TestSupport -{ +public class DotDirectiveArchiveFinalizerTest extends TestSupport { @Test - public void testDotDirectiveArchiveFinalizer() - throws Exception - { + public void testDotDirectiveArchiveFinalizer() throws Exception { DotDirectiveArchiveFinalizer ddaf = - new DotDirectiveArchiveFinalizer( new File( getBasedir(), "src/test/dotfiles" ) ); + new DotDirectiveArchiveFinalizer(new File(getBasedir(), "src/test/dotfiles")); JarArchiver archiver = new JarArchiver(); - File jarFile = new File( getBasedir(), "target/dotfiles.jar" ); + File jarFile = new File(getBasedir(), "target/dotfiles.jar"); - archiver.setDestFile( jarFile ); + archiver.setDestFile(jarFile); - archiver.addArchiveFinalizer( ddaf ); + archiver.addArchiveFinalizer(ddaf); archiver.createArchive(); - JarFile jar = new JarFile( jarFile ); + JarFile jar = new JarFile(jarFile); - assertNotNull( jar.getEntry( "LICENSE.txt" ) ); + assertNotNull(jar.getEntry("LICENSE.txt")); - assertNotNull( jar.getEntry( "NOTICE.txt" ) ); + assertNotNull(jar.getEntry("NOTICE.txt")); - assertNotNull( jar.getEntry( "META-INF/maven/LICENSE.txt" ) ); + assertNotNull(jar.getEntry("META-INF/maven/LICENSE.txt")); - assertNotNull( jar.getEntry( "META-INF/maven/NOTICE.txt" ) ); + assertNotNull(jar.getEntry("META-INF/maven/NOTICE.txt")); } @Test - public void testDefaultDotDirectiveBehaviour() - throws Exception - { - File dotFileDirectory = new File( getBasedir(), "src/test/dotfiles" ); + public void testDefaultDotDirectiveBehaviour() throws Exception { + File dotFileDirectory = new File(getBasedir(), "src/test/dotfiles"); JarArchiver archiver = new JarArchiver(); - archiver.setDotFileDirectory( dotFileDirectory ); + archiver.setDotFileDirectory(dotFileDirectory); - File jarFile = new File( getBasedir(), "target/default-dotfiles.jar" ); + File jarFile = new File(getBasedir(), "target/default-dotfiles.jar"); - archiver.setDestFile( jarFile ); + archiver.setDestFile(jarFile); archiver.createArchive(); - JarFile jar = new JarFile( jarFile ); + JarFile jar = new JarFile(jarFile); - assertNotNull( jar.getEntry( "LICENSE.txt" ) ); + assertNotNull(jar.getEntry("LICENSE.txt")); - assertNotNull( jar.getEntry( "NOTICE.txt" ) ); + assertNotNull(jar.getEntry("NOTICE.txt")); - assertNotNull( jar.getEntry( "META-INF/maven/LICENSE.txt" ) ); + assertNotNull(jar.getEntry("META-INF/maven/LICENSE.txt")); - assertNotNull( jar.getEntry( "META-INF/maven/NOTICE.txt" ) ); + assertNotNull(jar.getEntry("META-INF/maven/NOTICE.txt")); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/DuplicateFilesTest.java b/src/test/java/org/codehaus/plexus/archiver/DuplicateFilesTest.java index 3a9e9cc5e..565b4724f 100644 --- a/src/test/java/org/codehaus/plexus/archiver/DuplicateFilesTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/DuplicateFilesTest.java @@ -20,134 +20,110 @@ /** * @author Erik Engstrom */ -public class DuplicateFilesTest - extends TestSupport -{ +public class DuplicateFilesTest extends TestSupport { - private static final File file1 = getTestFile( "src/test/resources/group-writable/foo.txt" ); + private static final File file1 = getTestFile("src/test/resources/group-writable/foo.txt"); - private static final File file2 = getTestFile( "src/test/resources/world-writable/foo.txt" ); - - private static final File destination = getTestFile( "target/output/duplicateFiles" ); + private static final File file2 = getTestFile("src/test/resources/world-writable/foo.txt"); + private static final File destination = getTestFile("target/output/duplicateFiles"); @Test - public void testZipArchiver() - throws Exception - { - Archiver archiver = lookup( Archiver.class, "zip" ); - archiver.setDuplicateBehavior( Archiver.DUPLICATES_SKIP ); + public void testZipArchiver() throws Exception { + Archiver archiver = lookup(Archiver.class, "zip"); + archiver.setDuplicateBehavior(Archiver.DUPLICATES_SKIP); - File archive = createArchive( archiver, "zip" ); + File archive = createArchive(archiver, "zip"); org.apache.commons.compress.archivers.zip.ZipFile zf = - new org.apache.commons.compress.archivers.zip.ZipFile( archive ); + new org.apache.commons.compress.archivers.zip.ZipFile(archive); Enumeration e = zf.getEntries(); int entryCount = 0; - while ( e.hasMoreElements() ) - { + while (e.hasMoreElements()) { ZipArchiveEntry entry = e.nextElement(); - System.out.println( entry.getName() ); + System.out.println(entry.getName()); entryCount++; } zf.close(); // Zip file should have 2 entries, 1 for the directory and one for foo.txt - assertEquals( 2, entryCount ); - testArchive( archive, "zip" ); + assertEquals(2, entryCount); + testArchive(archive, "zip"); } @Test - public void testDirArchiver() - throws Exception - { - Archiver archiver = lookup( Archiver.class, "dir" ); - createArchive( archiver, "dir" ); - testFinalFile( "target/output/duplicateFiles.dir/duplicateFiles/foo.txt" ); - + public void testDirArchiver() throws Exception { + Archiver archiver = lookup(Archiver.class, "dir"); + createArchive(archiver, "dir"); + testFinalFile("target/output/duplicateFiles.dir/duplicateFiles/foo.txt"); } @Test - public void testTarArchiver() - throws Exception - { - TarArchiver archiver = (TarArchiver) lookup( Archiver.class, "tar" ); - archiver.setLongfile( TarLongFileMode.posix ); - archiver.setDuplicateBehavior( Archiver.DUPLICATES_SKIP ); - - File archive = createArchive( archiver, "tar" ); + public void testTarArchiver() throws Exception { + TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar"); + archiver.setLongfile(TarLongFileMode.posix); + archiver.setDuplicateBehavior(Archiver.DUPLICATES_SKIP); + + File archive = createArchive(archiver, "tar"); TarArchiveInputStream tis; - tis = new TarArchiveInputStream( new BufferedInputStream( Files.newInputStream( archive.toPath() ) ) ); + tis = new TarArchiveInputStream(new BufferedInputStream(Files.newInputStream(archive.toPath()))); int entryCount = 0; - while ( ( tis.getNextEntry() ) != null ) - { + while ((tis.getNextEntry()) != null) { entryCount++; } - assertEquals( 1, entryCount ); - testArchive( archive, "tar" ); + assertEquals(1, entryCount); + testArchive(archive, "tar"); tis.close(); } - private File createArchive( Archiver archiver, String outputFileExt ) - throws Exception - { - archiver.addFile( file1, "duplicateFiles/foo.txt" ); - archiver.addFile( file2, "duplicateFiles/foo.txt" ); + private File createArchive(Archiver archiver, String outputFileExt) throws Exception { + archiver.addFile(file1, "duplicateFiles/foo.txt"); + archiver.addFile(file2, "duplicateFiles/foo.txt"); // delete it if it exists to ensure it is actually empty - if ( destination.exists() ) - { + if (destination.exists()) { destination.delete(); } - File archive = getTestFile( "target/output/duplicateFiles." + outputFileExt ); - if ( archive.exists() ) - { - if ( archive.isDirectory() ) - { - FileUtils.deleteDirectory( archive ); - } - else - { + File archive = getTestFile("target/output/duplicateFiles." + outputFileExt); + if (archive.exists()) { + if (archive.isDirectory()) { + FileUtils.deleteDirectory(archive); + } else { archive.delete(); } } - archiver.setDestFile( archive ); + archiver.setDestFile(archive); archiver.createArchive(); return archive; } - private void testArchive( File archive, String role ) - throws Exception - { + private void testArchive(File archive, String role) throws Exception { // Check the content of the archive by extracting it - UnArchiver unArchiver = lookup( UnArchiver.class, role ); - unArchiver.setSourceFile( archive ); + UnArchiver unArchiver = lookup(UnArchiver.class, role); + unArchiver.setSourceFile(archive); - unArchiver.setDestDirectory( getTestFile( "target/output/" ) ); + unArchiver.setDestDirectory(getTestFile("target/output/")); unArchiver.extract(); - assertTrue( destination.exists() ); - assertTrue( destination.isDirectory() ); - testFinalFile( "target/output/duplicateFiles/foo.txt" ); + assertTrue(destination.exists()); + assertTrue(destination.isDirectory()); + testFinalFile("target/output/duplicateFiles/foo.txt"); } - private void testFinalFile( String path ) - throws Exception - { - File outputFile = getTestFile( path ); - assertTrue( outputFile.exists() ); - BufferedReader reader = Files.newBufferedReader( outputFile.toPath(), StandardCharsets.UTF_8 ); + private void testFinalFile(String path) throws Exception { + File outputFile = getTestFile(path); + assertTrue(outputFile.exists()); + BufferedReader reader = Files.newBufferedReader(outputFile.toPath(), StandardCharsets.UTF_8); String firstLine = reader.readLine(); reader.close(); - reader = Files.newBufferedReader( file2.toPath(), StandardCharsets.UTF_8 ); + reader = Files.newBufferedReader(file2.toPath(), StandardCharsets.UTF_8); String expectedFirstLine = reader.readLine(); reader.close(); - assertEquals( expectedFirstLine, firstLine ); + assertEquals(expectedFirstLine, firstLine); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/EmptyDirectoryTest.java b/src/test/java/org/codehaus/plexus/archiver/EmptyDirectoryTest.java index 4f27a7d97..0d7009684 100644 --- a/src/test/java/org/codehaus/plexus/archiver/EmptyDirectoryTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/EmptyDirectoryTest.java @@ -24,6 +24,7 @@ package org.codehaus.plexus.archiver; import java.io.File; + import org.codehaus.plexus.archiver.tar.TarArchiver; import org.codehaus.plexus.archiver.tar.TarLongFileMode; import org.junit.jupiter.api.Test; @@ -33,73 +34,60 @@ /** * @author Daniel Krisher */ -public class EmptyDirectoryTest - extends TestSupport -{ +public class EmptyDirectoryTest extends TestSupport { @Test - public void testZipArchiver() - throws Exception - { - testEmptyDirectory( "zip", lookup( Archiver.class, "zip" ) ); + public void testZipArchiver() throws Exception { + testEmptyDirectory("zip", lookup(Archiver.class, "zip")); } @Test - public void testJarArchiver() - throws Exception - { + public void testJarArchiver() throws Exception { // No JAR UnArchiver implementation :( -// testEmptyDirectory( "jar" ); + // testEmptyDirectory( "jar" ); } @Test - public void testTarArchiver() - throws Exception - { - final TarArchiver tar = (TarArchiver) lookup( Archiver.class, "tar" ); - tar.setLongfile( TarLongFileMode.posix ); - testEmptyDirectory( "tar", tar ); + public void testTarArchiver() throws Exception { + final TarArchiver tar = (TarArchiver) lookup(Archiver.class, "tar"); + tar.setLongfile(TarLongFileMode.posix); + testEmptyDirectory("tar", tar); } - private void testEmptyDirectory( String role, Archiver archiver ) - throws Exception - { + private void testEmptyDirectory(String role, Archiver archiver) throws Exception { // Should default to true... - assertTrue( archiver.getIncludeEmptyDirs() ); + assertTrue(archiver.getIncludeEmptyDirs()); // create an empty directory to store in the zip archive - File emptyDir = getTestFile( "target/output/emptyTest/TmpEmptyDir" ); + File emptyDir = getTestFile("target/output/emptyTest/TmpEmptyDir"); // delete it if it exists to ensure it is actually empty - if ( emptyDir.exists() ) - { + if (emptyDir.exists()) { emptyDir.delete(); } emptyDir.mkdirs(); - archiver.addDirectory( emptyDir.getParentFile() ); + archiver.addDirectory(emptyDir.getParentFile()); - File archive = getTestFile( "target/output/emptyDirArchive.zip" ); - if ( archive.exists() ) - { + File archive = getTestFile("target/output/emptyDirArchive.zip"); + if (archive.exists()) { archive.delete(); } - archiver.setDestFile( archive ); + archiver.setDestFile(archive); archiver.createArchive(); // delete the empty dir, we will extract it from the archive emptyDir.delete(); // Check the content of the archive by extracting it - UnArchiver unArchiver = lookup( UnArchiver.class, role ); - unArchiver.setSourceFile( archive ); + UnArchiver unArchiver = lookup(UnArchiver.class, role); + unArchiver.setSourceFile(archive); - unArchiver.setDestDirectory( getTestFile( "target/output/emptyTest" ) ); + unArchiver.setDestDirectory(getTestFile("target/output/emptyTest")); unArchiver.extract(); - assertTrue( emptyDir.exists() ); - assertTrue( emptyDir.isDirectory() ); + assertTrue(emptyDir.exists()); + assertTrue(emptyDir.isDirectory()); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/SymlinkTest.java b/src/test/java/org/codehaus/plexus/archiver/SymlinkTest.java index d2ebd4c55..7b8a4ebee 100644 --- a/src/test/java/org/codehaus/plexus/archiver/SymlinkTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/SymlinkTest.java @@ -3,6 +3,7 @@ import java.io.File; import java.io.IOException; import java.nio.file.Files; + import org.codehaus.plexus.archiver.dir.DirectoryArchiver; import org.codehaus.plexus.archiver.tar.TarArchiver; import org.codehaus.plexus.archiver.tar.TarLongFileMode; @@ -19,101 +20,87 @@ /** * @author Kristian Rosenvold */ -public class SymlinkTest - extends TestSupport -{ +public class SymlinkTest extends TestSupport { @Test - @DisabledOnOs( OS.WINDOWS ) - public void testSymlinkDir() - throws IOException - { - File dummyContent = getTestFile( "src/test/resources/symlinks/src/symDir" ); - assertTrue( dummyContent.isDirectory() ); - assertTrue( Files.isSymbolicLink( dummyContent.toPath() ) ); + @DisabledOnOs(OS.WINDOWS) + public void testSymlinkDir() throws IOException { + File dummyContent = getTestFile("src/test/resources/symlinks/src/symDir"); + assertTrue(dummyContent.isDirectory()); + assertTrue(Files.isSymbolicLink(dummyContent.toPath())); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testSymlinkDirWithSlash() - throws IOException - { - File dummyContent = getTestFile( "src/test/resources/symlinks/src/symDir/" ); - assertTrue( dummyContent.isDirectory() ); - assertTrue( Files.isSymbolicLink( dummyContent.toPath() ) ); + @DisabledOnOs(OS.WINDOWS) + public void testSymlinkDirWithSlash() throws IOException { + File dummyContent = getTestFile("src/test/resources/symlinks/src/symDir/"); + assertTrue(dummyContent.isDirectory()); + assertTrue(Files.isSymbolicLink(dummyContent.toPath())); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testSymlinkFile() - { - File dummyContent = getTestFile( "src/test/resources/symlinks/src/symR" ); - assertFalse( dummyContent.isDirectory() ); - assertTrue( Files.isSymbolicLink( dummyContent.toPath() ) ); + @DisabledOnOs(OS.WINDOWS) + public void testSymlinkFile() { + File dummyContent = getTestFile("src/test/resources/symlinks/src/symR"); + assertFalse(dummyContent.isDirectory()); + assertTrue(Files.isSymbolicLink(dummyContent.toPath())); } @Test - public void testSymlinkTar() - throws Exception - { - TarArchiver archiver = (TarArchiver) lookup( Archiver.class, "tar" ); - archiver.setLongfile( TarLongFileMode.posix ); - - File dummyContent = getTestFile( "src/test/resources/symlinks/src" ); - archiver.addDirectory( dummyContent ); - final File archiveFile = new File( "target/output/symlinks.tar" ); - archiver.setDestFile( archiveFile ); + public void testSymlinkTar() throws Exception { + TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar"); + archiver.setLongfile(TarLongFileMode.posix); + + File dummyContent = getTestFile("src/test/resources/symlinks/src"); + archiver.addDirectory(dummyContent); + final File archiveFile = new File("target/output/symlinks.tar"); + archiver.setDestFile(archiveFile); archiver.createArchive(); - File output = getTestFile( "target/output/untaredSymlinks" ); + File output = getTestFile("target/output/untaredSymlinks"); output.mkdirs(); - TarUnArchiver unarchiver = (TarUnArchiver) lookup( UnArchiver.class, "tar" ); - unarchiver.setSourceFile( archiveFile ); - unarchiver.setDestFile( output ); + TarUnArchiver unarchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar"); + unarchiver.setSourceFile(archiveFile); + unarchiver.setDestFile(output); unarchiver.extract(); } @Test - public void testSymlinkZip() - throws Exception - { - ZipArchiver archiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - - File dummyContent = getTestFile( "src/test/resources/symlinks/src" ); - archiver.addDirectory( dummyContent ); - final File archiveFile = new File( "target/output/symlinks.zip" ); + public void testSymlinkZip() throws Exception { + ZipArchiver archiver = (ZipArchiver) lookup(Archiver.class, "zip"); + + File dummyContent = getTestFile("src/test/resources/symlinks/src"); + archiver.addDirectory(dummyContent); + final File archiveFile = new File("target/output/symlinks.zip"); archiveFile.delete(); - archiver.setDestFile( archiveFile ); + archiver.setDestFile(archiveFile); archiver.createArchive(); - File output = getTestFile( "target/output/unzippedSymlinks" ); + File output = getTestFile("target/output/unzippedSymlinks"); output.mkdirs(); - ZipUnArchiver unarchiver = (ZipUnArchiver) lookup( UnArchiver.class, "zip" ); - unarchiver.setSourceFile( archiveFile ); - unarchiver.setDestFile( output ); + ZipUnArchiver unarchiver = (ZipUnArchiver) lookup(UnArchiver.class, "zip"); + unarchiver.setSourceFile(archiveFile); + unarchiver.setDestFile(output); unarchiver.extract(); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testSymlinkDirArchiver() - throws Exception - { - DirectoryArchiver archiver = (DirectoryArchiver) lookup( Archiver.class, "dir" ); - - File dummyContent = getTestFile( "src/test/resources/symlinks/src" ); - archiver.addDirectory( dummyContent ); - final File archiveFile = new File( "target/output/dirarchiver-symlink" ); + @DisabledOnOs(OS.WINDOWS) + public void testSymlinkDirArchiver() throws Exception { + DirectoryArchiver archiver = (DirectoryArchiver) lookup(Archiver.class, "dir"); + + File dummyContent = getTestFile("src/test/resources/symlinks/src"); + archiver.addDirectory(dummyContent); + final File archiveFile = new File("target/output/dirarchiver-symlink"); archiveFile.mkdirs(); - archiver.setDestFile( archiveFile ); - archiver.addSymlink( "target/output/dirarchiver-symlink/aNewDir/symlink", "." ); + archiver.setDestFile(archiveFile); + archiver.addSymlink("target/output/dirarchiver-symlink/aNewDir/symlink", "."); archiver.createArchive(); - File symbolicLink = new File( "target/output/dirarchiver-symlink/symR" ); - assertTrue( Files.isSymbolicLink( symbolicLink.toPath() ) ); + File symbolicLink = new File("target/output/dirarchiver-symlink/symR"); + assertTrue(Files.isSymbolicLink(symbolicLink.toPath())); - symbolicLink = new File( "target/output/dirarchiver-symlink/aDirWithALink/backOutsideToFileX" ); - assertTrue( Files.isSymbolicLink( symbolicLink.toPath() ) ); + symbolicLink = new File("target/output/dirarchiver-symlink/aDirWithALink/backOutsideToFileX"); + assertTrue(Files.isSymbolicLink(symbolicLink.toPath())); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/TestSupport.java b/src/test/java/org/codehaus/plexus/archiver/TestSupport.java index f4c65df76..0b2d65d31 100644 --- a/src/test/java/org/codehaus/plexus/archiver/TestSupport.java +++ b/src/test/java/org/codehaus/plexus/archiver/TestSupport.java @@ -11,9 +11,7 @@ /** * Test support class. */ -public abstract class TestSupport - extends InjectedTest -{ +public abstract class TestSupport extends InjectedTest { @Override @BeforeEach public void setUp() throws Exception { @@ -26,18 +24,15 @@ public void tearDown() throws Exception { super.tearDown(); } - private static Path basedir() - { - return Paths.get( System.getProperty( "basedir", ( new File( "" ) ).getAbsolutePath() ) ); + private static Path basedir() { + return Paths.get(System.getProperty("basedir", (new File("")).getAbsolutePath())); } - protected static File getTestFile( final String path ) - { - return basedir().resolve( path ).toFile(); + protected static File getTestFile(final String path) { + return basedir().resolve(path).toFile(); } - protected static File getTestFile( final String basedir, final String path ) - { - return basedir().resolve( basedir ).resolve( path ).toFile(); + protected static File getTestFile(final String basedir, final String path) { + return basedir().resolve(basedir).resolve(path).toFile(); } } diff --git a/src/test/java/org/codehaus/plexus/archiver/bzip2/BZip2ArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/bzip2/BZip2ArchiverTest.java index 212ae3d93..71f4e1ba5 100644 --- a/src/test/java/org/codehaus/plexus/archiver/bzip2/BZip2ArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/bzip2/BZip2ArchiverTest.java @@ -24,12 +24,12 @@ package org.codehaus.plexus.archiver.bzip2; import java.io.File; -import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.BasePlexusArchiverTest; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; @@ -46,70 +46,59 @@ /** * @author Emmanuel Venisse */ -public class BZip2ArchiverTest - extends BasePlexusArchiverTest -{ +public class BZip2ArchiverTest extends BasePlexusArchiverTest { @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.addDirectory( getTestFile( "src" ) ); - zipArchiver.setDestFile( getTestFile( "target/output/archiveForbz2.zip" ) ); + public void testCreateArchive() throws Exception { + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.addDirectory(getTestFile("src")); + zipArchiver.setDestFile(getTestFile("target/output/archiveForbz2.zip")); zipArchiver.createArchive(); - BZip2Archiver archiver = (BZip2Archiver) lookup( Archiver.class, "bzip2" ); - String[] inputFiles = new String[ 1 ]; + BZip2Archiver archiver = (BZip2Archiver) lookup(Archiver.class, "bzip2"); + String[] inputFiles = new String[1]; inputFiles[0] = "archiveForbz2.zip"; - archiver.addDirectory( getTestFile( "target/output" ), inputFiles, null ); - archiver.setDestFile( getTestFile( "target/output/archive.bz2" ) ); + archiver.addDirectory(getTestFile("target/output"), inputFiles, null); + archiver.setDestFile(getTestFile("target/output/archive.bz2")); archiver.createArchive(); } @Test - public void testCreateEmptyArchive() - throws Exception - { - BZip2Archiver archiver = (BZip2Archiver) lookup( Archiver.class, "bzip2" ); - archiver.setDestFile( getTestFile( "target/output/empty.bz2" ) ); - try - { + public void testCreateEmptyArchive() throws Exception { + BZip2Archiver archiver = (BZip2Archiver) lookup(Archiver.class, "bzip2"); + archiver.setDestFile(getTestFile("target/output/empty.bz2")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testCreateResourceCollection() - throws Exception - { - final File pomFile = new File( "pom.xml" ); - final File bz2File = new File( "target/output/pom.xml.bz2" ); - BZip2Archiver bzip2Archiver = (BZip2Archiver) lookup( Archiver.class, "bzip2" ); - bzip2Archiver.setDestFile( bz2File ); - bzip2Archiver.addFile( pomFile, "pom.xml" ); - FileUtils.removePath( bz2File.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File pomFile = new File("pom.xml"); + final File bz2File = new File("target/output/pom.xml.bz2"); + BZip2Archiver bzip2Archiver = (BZip2Archiver) lookup(Archiver.class, "bzip2"); + bzip2Archiver.setDestFile(bz2File); + bzip2Archiver.addFile(pomFile, "pom.xml"); + FileUtils.removePath(bz2File.getPath()); bzip2Archiver.createArchive(); - System.out.println( "Created: " + bz2File.getAbsolutePath() ); + System.out.println("Created: " + bz2File.getAbsolutePath()); - final File zipFile = new File( "target/output/pom.zip" ); - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.setDestFile( zipFile ); - zipArchiver.addArchivedFileSet( bz2File, "prfx/" ); - FileUtils.removePath( zipFile.getPath() ); + final File zipFile = new File("target/output/pom.zip"); + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.setDestFile(zipFile); + zipArchiver.addArchivedFileSet(bz2File, "prfx/"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final ZipFile juZipFile = new ZipFile( zipFile ); - final ZipEntry zipEntry = juZipFile.getEntry( "prfx/target/output/pom.xml" ); - final InputStream archivePom = juZipFile.getInputStream( zipEntry ); - final InputStream pom = Files.newInputStream( pomFile.toPath() ); + final ZipFile juZipFile = new ZipFile(zipFile); + final ZipEntry zipEntry = juZipFile.getEntry("prfx/target/output/pom.xml"); + final InputStream archivePom = juZipFile.getInputStream(zipEntry); + final InputStream pom = Files.newInputStream(pomFile.toPath()); - assertTrue( Arrays.equals( IOUtil.toByteArray( pom ), IOUtil.toByteArray( archivePom ) ) ); + assertTrue(Arrays.equals(IOUtil.toByteArray(pom), IOUtil.toByteArray(archivePom))); archivePom.close(); pom.close(); juZipFile.close(); @@ -122,34 +111,32 @@ public void testCreateResourceCollection() * @throws Exception */ @Test - public void testBz2IsForcedBehaviour() throws Exception - { - BZip2Archiver bZip2Archiver = (BZip2Archiver) createArchiver( "bzip2" ); + public void testBz2IsForcedBehaviour() throws Exception { + BZip2Archiver bZip2Archiver = (BZip2Archiver) createArchiver("bzip2"); - assertTrue( bZip2Archiver.isSupportingForced() ); + assertTrue(bZip2Archiver.isSupportingForced()); bZip2Archiver.createArchive(); final long creationTime = bZip2Archiver.getDestFile().lastModified(); - waitUntilNewTimestamp( bZip2Archiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(bZip2Archiver.getDestFile(), creationTime); - bZip2Archiver = (BZip2Archiver) createArchiver( "bzip2" ); + bZip2Archiver = (BZip2Archiver) createArchiver("bzip2"); - bZip2Archiver.setForced( true ); + bZip2Archiver.setForced(true); bZip2Archiver.createArchive(); final long firstRunTime = bZip2Archiver.getDestFile().lastModified(); - assertFalse( creationTime == firstRunTime ); + assertFalse(creationTime == firstRunTime); - bZip2Archiver = (BZip2Archiver) createArchiver( "bzip2" ); + bZip2Archiver = (BZip2Archiver) createArchiver("bzip2"); - bZip2Archiver.setForced( false ); + bZip2Archiver.setForced(false); bZip2Archiver.createArchive(); final long secondRunTime = bZip2Archiver.getDestFile().lastModified(); - assertEquals( firstRunTime, secondRunTime ); + assertEquals(firstRunTime, secondRunTime); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/gzip/GZipArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/gzip/GZipArchiverTest.java index 7b5d2506b..d6a433df0 100644 --- a/src/test/java/org/codehaus/plexus/archiver/gzip/GZipArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/gzip/GZipArchiverTest.java @@ -46,67 +46,56 @@ /** * @author Emmanuel Venisse */ -public class GZipArchiverTest - extends BasePlexusArchiverTest -{ +public class GZipArchiverTest extends BasePlexusArchiverTest { @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.addDirectory( getTestFile( "src" ) ); - zipArchiver.setDestFile( getTestFile( "target/output/archiveForGzip.zip" ) ); + public void testCreateArchive() throws Exception { + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.addDirectory(getTestFile("src")); + zipArchiver.setDestFile(getTestFile("target/output/archiveForGzip.zip")); zipArchiver.createArchive(); - GZipArchiver archiver = (GZipArchiver) lookup( Archiver.class, "gzip" ); - String[] inputFiles = new String[ 1 ]; + GZipArchiver archiver = (GZipArchiver) lookup(Archiver.class, "gzip"); + String[] inputFiles = new String[1]; inputFiles[0] = "archiveForGzip.zip"; - archiver.addDirectory( getTestFile( "target/output" ), inputFiles, null ); - archiver.setDestFile( getTestFile( "target/output/archive.gzip" ) ); + archiver.addDirectory(getTestFile("target/output"), inputFiles, null); + archiver.setDestFile(getTestFile("target/output/archive.gzip")); archiver.createArchive(); } @Test - public void testCreateEmptyArchive() - throws Exception - { - GZipArchiver archiver = (GZipArchiver) lookup( Archiver.class, "gzip" ); - archiver.setDestFile( getTestFile( "target/output/empty.gz" ) ); - try - { + public void testCreateEmptyArchive() throws Exception { + GZipArchiver archiver = (GZipArchiver) lookup(Archiver.class, "gzip"); + archiver.setDestFile(getTestFile("target/output/empty.gz")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testCreateResourceCollection() - throws Exception - { - final File pomFile = new File( "pom.xml" ); - final File gzFile = new File( "target/output/pom.xml.gz" ); - GZipArchiver gzipArchiver = (GZipArchiver) lookup( Archiver.class, "gzip" ); - gzipArchiver.setDestFile( gzFile ); - gzipArchiver.addFile( pomFile, "pom.xml" ); - FileUtils.removePath( gzFile.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File pomFile = new File("pom.xml"); + final File gzFile = new File("target/output/pom.xml.gz"); + GZipArchiver gzipArchiver = (GZipArchiver) lookup(Archiver.class, "gzip"); + gzipArchiver.setDestFile(gzFile); + gzipArchiver.addFile(pomFile, "pom.xml"); + FileUtils.removePath(gzFile.getPath()); gzipArchiver.createArchive(); - final File zipFile = new File( "target/output/pom.zip" ); - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.setDestFile( zipFile ); - zipArchiver.addArchivedFileSet( gzFile, "prfx/" ); - FileUtils.removePath( zipFile.getPath() ); + final File zipFile = new File("target/output/pom.zip"); + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.setDestFile(zipFile); + zipArchiver.addArchivedFileSet(gzFile, "prfx/"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final ZipFile juZipFile = new ZipFile( zipFile ); - final ZipEntry zipEntry = juZipFile.getEntry( "prfx/target/output/pom.xml" ); - final InputStream archivePom = juZipFile.getInputStream( zipEntry ); - final InputStream pom = Files.newInputStream( pomFile.toPath() ); - assertTrue( Arrays.equals( IOUtil.toByteArray( pom ), IOUtil.toByteArray( archivePom ) ) ); + final ZipFile juZipFile = new ZipFile(zipFile); + final ZipEntry zipEntry = juZipFile.getEntry("prfx/target/output/pom.xml"); + final InputStream archivePom = juZipFile.getInputStream(zipEntry); + final InputStream pom = Files.newInputStream(pomFile.toPath()); + assertTrue(Arrays.equals(IOUtil.toByteArray(pom), IOUtil.toByteArray(archivePom))); archivePom.close(); pom.close(); juZipFile.close(); @@ -119,34 +108,32 @@ public void testCreateResourceCollection() * @throws Exception */ @Test - public void testTarGzIsForcedBehaviour() throws Exception - { - GZipArchiver gZipArchiver = (GZipArchiver) createArchiver( "gzip" ); + public void testTarGzIsForcedBehaviour() throws Exception { + GZipArchiver gZipArchiver = (GZipArchiver) createArchiver("gzip"); - assertTrue( gZipArchiver.isSupportingForced() ); + assertTrue(gZipArchiver.isSupportingForced()); gZipArchiver.createArchive(); final long creationTime = gZipArchiver.getDestFile().lastModified(); - waitUntilNewTimestamp( gZipArchiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(gZipArchiver.getDestFile(), creationTime); - gZipArchiver = (GZipArchiver) createArchiver( "gzip" ); + gZipArchiver = (GZipArchiver) createArchiver("gzip"); - gZipArchiver.setForced( true ); + gZipArchiver.setForced(true); gZipArchiver.createArchive(); final long firstRunTime = gZipArchiver.getDestFile().lastModified(); - assertNotEquals( creationTime, firstRunTime ); + assertNotEquals(creationTime, firstRunTime); - gZipArchiver = (GZipArchiver) createArchiver( "gzip" ); + gZipArchiver = (GZipArchiver) createArchiver("gzip"); - gZipArchiver.setForced( false ); + gZipArchiver.setForced(false); gZipArchiver.createArchive(); final long secondRunTime = gZipArchiver.getDestFile().lastModified(); - assertEquals( firstRunTime, secondRunTime ); + assertEquals(firstRunTime, secondRunTime); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/BaseJarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/BaseJarArchiverTest.java index b39233af9..902449ab6 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/BaseJarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/BaseJarArchiverTest.java @@ -16,9 +16,6 @@ */ package org.codehaus.plexus.archiver.jar; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertTrue; - import java.io.File; import java.io.IOException; import java.io.InputStream; @@ -35,52 +32,49 @@ import org.codehaus.plexus.util.IOUtil; import org.junit.jupiter.api.Test; -public abstract class BaseJarArchiverTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +public abstract class BaseJarArchiverTest { /* * Verify that the JarArchiver implementation * could create basic JAR file */ @Test - public void testCreateJar() - throws IOException, ArchiverException - { - File jarFile = new File( "target/output/testJar.jar" ); + public void testCreateJar() throws IOException, ArchiverException { + File jarFile = new File("target/output/testJar.jar"); jarFile.delete(); JarArchiver archiver = getJarArchiver(); - archiver.setDestFile( jarFile ); - archiver.addDirectory( new File( "src/test/resources/java-classes" ) ); + archiver.setDestFile(jarFile); + archiver.addDirectory(new File("src/test/resources/java-classes")); archiver.createArchive(); // verify that the JAR file is created and contains the expected files - try ( ZipFile resultingArchive = new ZipFile( jarFile ) ) - { + try (ZipFile resultingArchive = new ZipFile(jarFile)) { // verify that the JAR file contains manifest directory and file // and that those are the first two entries. Enumeration resultingEntries = resultingArchive.entries(); - assertEquals( "META-INF/", resultingEntries.nextElement().getName() ); - assertEquals( "META-INF/MANIFEST.MF", resultingEntries.nextElement().getName() ); + assertEquals("META-INF/", resultingEntries.nextElement().getName()); + assertEquals("META-INF/MANIFEST.MF", resultingEntries.nextElement().getName()); // verify the JAR contains the class and it is not corrupted - ZipEntry classFileEntry = resultingArchive.getEntry( "com/example/app/Main.class" ); - InputStream resultingClassFile = resultingArchive.getInputStream( classFileEntry ); + ZipEntry classFileEntry = resultingArchive.getEntry("com/example/app/Main.class"); + InputStream resultingClassFile = resultingArchive.getInputStream(classFileEntry); InputStream originalClassFile = - Files.newInputStream( Paths.get( "src/test/resources/java-classes/com/example/app/Main.class" ) ); + Files.newInputStream(Paths.get("src/test/resources/java-classes/com/example/app/Main.class")); - assertTrue( IOUtil.contentEquals( originalClassFile, resultingClassFile ) ); + assertTrue(IOUtil.contentEquals(originalClassFile, resultingClassFile)); } } - protected static long normalizeLastModifiedTime( long dosTime ) - { - Calendar cal = Calendar.getInstance( TimeZone.getDefault(), Locale.ROOT ); - cal.setTimeInMillis( dosTime ); - return dosTime - ( cal.get( Calendar.ZONE_OFFSET ) + cal.get( Calendar.DST_OFFSET ) ); + protected static long normalizeLastModifiedTime(long dosTime) { + Calendar cal = Calendar.getInstance(TimeZone.getDefault(), Locale.ROOT); + cal.setTimeInMillis(dosTime); + return dosTime - (cal.get(Calendar.ZONE_OFFSET) + cal.get(Calendar.DST_OFFSET)); } protected abstract JarArchiver getJarArchiver(); - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/DirectoryArchiverUnpackJarTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/DirectoryArchiverUnpackJarTest.java index f978bebde..416f4f702 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/DirectoryArchiverUnpackJarTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/DirectoryArchiverUnpackJarTest.java @@ -1,10 +1,12 @@ package org.codehaus.plexus.archiver.jar; +import javax.annotation.Nonnull; + import java.io.File; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; -import javax.annotation.Nonnull; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.util.ArchiveEntryUtils; @@ -15,58 +17,44 @@ import static org.junit.jupiter.api.Assertions.assertTrue; -public class DirectoryArchiverUnpackJarTest - extends TestSupport -{ +public class DirectoryArchiverUnpackJarTest extends TestSupport { - public static final String[] DEFAULT_INCLUDES_ARRAY = - { - "**/*" - }; + public static final String[] DEFAULT_INCLUDES_ARRAY = {"**/*"}; - static class IdentityTransformer - implements InputStreamTransformer - { + static class IdentityTransformer implements InputStreamTransformer { - IdentityTransformer() - { - } + IdentityTransformer() {} @Nonnull @Override - public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream ) - throws IOException - { + public InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream) + throws IOException { return inputStream; } - } @Test - public void test_dependency_sets_depSet_unpacked_rdonly() - throws Exception - { - File src = new File( "src/test/resources/unpack_issue.jar" ); - assertTrue( src.exists() ); - DefaultArchivedFileSet afs = DefaultArchivedFileSet.archivedFileSet( src ); - afs.setIncludes( DEFAULT_INCLUDES_ARRAY ); - afs.setExcludes( null ); - afs.setPrefix( "child-1/" ); - afs.setStreamTransformer( new IdentityTransformer() ); - Archiver archiver = (Archiver) lookup( Archiver.class, "dir" ); - archiver.setDefaultDirectoryMode( 0555 ); - archiver.setDirectoryMode( 0555 ); // causes permission denied if bug is not fixed. - archiver.setDestFile( new File( "target/depset_unpack" ) ); - archiver.addArchivedFileSet( afs, Charset.forName( "UTF-8" ) ); + public void test_dependency_sets_depSet_unpacked_rdonly() throws Exception { + File src = new File("src/test/resources/unpack_issue.jar"); + assertTrue(src.exists()); + DefaultArchivedFileSet afs = DefaultArchivedFileSet.archivedFileSet(src); + afs.setIncludes(DEFAULT_INCLUDES_ARRAY); + afs.setExcludes(null); + afs.setPrefix("child-1/"); + afs.setStreamTransformer(new IdentityTransformer()); + Archiver archiver = (Archiver) lookup(Archiver.class, "dir"); + archiver.setDefaultDirectoryMode(0555); + archiver.setDirectoryMode(0555); // causes permission denied if bug is not fixed. + archiver.setDestFile(new File("target/depset_unpack")); + archiver.addArchivedFileSet(afs, Charset.forName("UTF-8")); archiver.createArchive(); - assertTrue( new File( "target/depset_unpack/child-1/META-INF/MANIFEST.MF" ).exists() ); + assertTrue(new File("target/depset_unpack/child-1/META-INF/MANIFEST.MF").exists()); // make them writeable or mvn clean will fail - ArchiveEntryUtils.chmod( new File( "target/depset_unpack/child-1/META-INF" ), 0777 ); - ArchiveEntryUtils.chmod( new File( "target/depset_unpack/child-1/META-INF/maven" ), 0777 ); - ArchiveEntryUtils.chmod( new File( "target/depset_unpack/child-1/META-INF/maven/test" ), 0777 ); - ArchiveEntryUtils.chmod( new File( "target/depset_unpack/child-1/META-INF/maven/test/child1" ), 0777 ); - ArchiveEntryUtils.chmod( new File( "target/depset_unpack/child-1/assembly-resources" ), 0777 ); + ArchiveEntryUtils.chmod(new File("target/depset_unpack/child-1/META-INF"), 0777); + ArchiveEntryUtils.chmod(new File("target/depset_unpack/child-1/META-INF/maven"), 0777); + ArchiveEntryUtils.chmod(new File("target/depset_unpack/child-1/META-INF/maven/test"), 0777); + ArchiveEntryUtils.chmod(new File("target/depset_unpack/child-1/META-INF/maven/test/child1"), 0777); + ArchiveEntryUtils.chmod(new File("target/depset_unpack/child-1/assembly-resources"), 0777); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/IndexTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/IndexTest.java index b851d4c01..4a52e50e7 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/IndexTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/IndexTest.java @@ -17,6 +17,7 @@ package org.codehaus.plexus.archiver.jar; import java.io.InputStream; + import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; @@ -29,47 +30,44 @@ /** * @author Richard van der Hoff */ -public class IndexTest extends TestSupport -{ +public class IndexTest extends TestSupport { @Test - public void testCreateArchiveWithIndexedJars() - throws Exception - { + public void testCreateArchiveWithIndexedJars() throws Exception { /* create a dummy jar */ - JarArchiver archiver1 = (JarArchiver) lookup( Archiver.class, "jar" ); - archiver1.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "one.txt" ); - archiver1.setDestFile( getTestFile( "target/output/archive1.jar" ) ); + JarArchiver archiver1 = (JarArchiver) lookup(Archiver.class, "jar"); + archiver1.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "one.txt"); + archiver1.setDestFile(getTestFile("target/output/archive1.jar")); archiver1.createArchive(); /* now create another jar, with an index, and whose manifest includes a Class-Path entry for the first jar. */ Manifest m = new Manifest(); - Manifest.Attribute classpathAttr = new Manifest.Attribute( "Class-Path", "archive1.jar" ); - m.addConfiguredAttribute( classpathAttr ); - - JarArchiver archiver2 = (JarArchiver) lookup( Archiver.class, "jar" ); - archiver2.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "two.txt" ); - archiver2.setIndex( true ); - archiver2.addConfiguredIndexJars( archiver1.getDestFile() ); - archiver2.setDestFile( getTestFile( "target/output/archive2.jar" ) ); - archiver2.addConfiguredManifest( m ); + Manifest.Attribute classpathAttr = new Manifest.Attribute("Class-Path", "archive1.jar"); + m.addConfiguredAttribute(classpathAttr); + + JarArchiver archiver2 = (JarArchiver) lookup(Archiver.class, "jar"); + archiver2.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "two.txt"); + archiver2.setIndex(true); + archiver2.addConfiguredIndexJars(archiver1.getDestFile()); + archiver2.setDestFile(getTestFile("target/output/archive2.jar")); + archiver2.addConfiguredManifest(m); archiver2.createArchive(); // read the index file back and check it looks like it ought to org.apache.commons.compress.archivers.zip.ZipFile zf = - new org.apache.commons.compress.archivers.zip.ZipFile( archiver2.getDestFile() ); - - ZipArchiveEntry indexEntry = zf.getEntry( "META-INF/INDEX.LIST" ); - assertNotNull( indexEntry ); - InputStream bis = bufferedInputStream( zf.getInputStream( indexEntry ) ); - - byte buf[] = new byte[ 1024 ]; - int i = bis.read( buf ); - String res = new String( buf, 0, i ); - assertEquals( "JarIndex-Version: 1.0\n\narchive2.jar\ntwo.txt\n\narchive1.jar\none.txt\n\n", - res.replaceAll( "\r\n", "\n" ) ); - + new org.apache.commons.compress.archivers.zip.ZipFile(archiver2.getDestFile()); + + ZipArchiveEntry indexEntry = zf.getEntry("META-INF/INDEX.LIST"); + assertNotNull(indexEntry); + InputStream bis = bufferedInputStream(zf.getInputStream(indexEntry)); + + byte buf[] = new byte[1024]; + int i = bis.read(buf); + String res = new String(buf, 0, i); + assertEquals( + "JarIndex-Version: 1.0\n\narchive2.jar\ntwo.txt\n\narchive1.jar\none.txt\n\n", + res.replaceAll("\r\n", "\n")); } /** @@ -77,55 +75,54 @@ public void testCreateArchiveWithIndexedJars() * tests for files in META-INF */ @Test - public void testCreateArchiveWithIndexedJarsAndMetaInf() - throws Exception - { + public void testCreateArchiveWithIndexedJarsAndMetaInf() throws Exception { /* create a dummy jar */ - JarArchiver archiver1 = (JarArchiver) lookup( Archiver.class, "jar" ); - archiver1.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "one.txt" ); + JarArchiver archiver1 = (JarArchiver) lookup(Archiver.class, "jar"); + archiver1.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "one.txt"); // add a file in the META-INF directory, as this previously didn't make it into the index - archiver1.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "META-INF/foo" ); - archiver1.setDestFile( getTestFile( "target/output/archive1.jar" ) ); + archiver1.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "META-INF/foo"); + archiver1.setDestFile(getTestFile("target/output/archive1.jar")); archiver1.createArchive(); /* create another dummy jar, with an index but nothing else in META-INF. Also checks non-leaf files. */ - JarArchiver archiver3 = (JarArchiver) lookup( Archiver.class, "jar" ); - archiver3.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "org/apache/maven/one.txt" ); - archiver3.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "META-INF/INDEX.LIST" ); - archiver3.setDestFile( getTestFile( "target/output/archive3.jar" ) ); + JarArchiver archiver3 = (JarArchiver) lookup(Archiver.class, "jar"); + archiver3.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "org/apache/maven/one.txt"); + archiver3.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "META-INF/INDEX.LIST"); + archiver3.setDestFile(getTestFile("target/output/archive3.jar")); archiver3.createArchive(); /* now create another jar, with an index, and whose manifest includes a Class-Path entry for the first two jars. */ Manifest m = new Manifest(); - Manifest.Attribute classpathAttr = new Manifest.Attribute( "Class-Path", "archive1.jar archive3.jar" ); - m.addConfiguredAttribute( classpathAttr ); - - JarArchiver archiver2 = (JarArchiver) lookup( Archiver.class, "jar" ); - archiver2.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "two.txt" ); - archiver2.setIndex( true ); - archiver2.addConfiguredIndexJars( archiver1.getDestFile() ); - archiver2.addConfiguredIndexJars( archiver3.getDestFile() ); - archiver2.setDestFile( getTestFile( "target/output/archive2.jar" ) ); - archiver2.addConfiguredManifest( m ); + Manifest.Attribute classpathAttr = new Manifest.Attribute("Class-Path", "archive1.jar archive3.jar"); + m.addConfiguredAttribute(classpathAttr); + + JarArchiver archiver2 = (JarArchiver) lookup(Archiver.class, "jar"); + archiver2.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "two.txt"); + archiver2.setIndex(true); + archiver2.addConfiguredIndexJars(archiver1.getDestFile()); + archiver2.addConfiguredIndexJars(archiver3.getDestFile()); + archiver2.setDestFile(getTestFile("target/output/archive2.jar")); + archiver2.addConfiguredManifest(m); archiver2.createArchive(); // read the index file back and check it looks like it ought to org.apache.commons.compress.archivers.zip.ZipFile zf = - new org.apache.commons.compress.archivers.zip.ZipFile( archiver2.getDestFile() ); + new org.apache.commons.compress.archivers.zip.ZipFile(archiver2.getDestFile()); - ZipArchiveEntry indexEntry = zf.getEntry( "META-INF/INDEX.LIST" ); - assertNotNull( indexEntry ); - InputStream bis = bufferedInputStream( zf.getInputStream( indexEntry ) ); + ZipArchiveEntry indexEntry = zf.getEntry("META-INF/INDEX.LIST"); + assertNotNull(indexEntry); + InputStream bis = bufferedInputStream(zf.getInputStream(indexEntry)); - byte buf[] = new byte[ 1024 ]; - int i = bis.read( buf ); - String res = new String( buf, 0, i ); - //System.out.println(res); + byte buf[] = new byte[1024]; + int i = bis.read(buf); + String res = new String(buf, 0, i); + // System.out.println(res); - assertEquals( "JarIndex-Version: 1.0\n\n" + "archive2.jar\ntwo.txt\n\n" + "archive1.jar\nMETA-INF\none.txt\n\n" - + "archive3.jar\norg\norg/apache\norg/apache/maven\n\n", res.replaceAll( "\r\n", "\n" ) ); + assertEquals( + "JarIndex-Version: 1.0\n\n" + "archive2.jar\ntwo.txt\n\n" + "archive1.jar\nMETA-INF\none.txt\n\n" + + "archive3.jar\norg\norg/apache\norg/apache/maven\n\n", + res.replaceAll("\r\n", "\n")); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/JarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/JarArchiverTest.java index 3bcd86c77..dda773d46 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/JarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/JarArchiverTest.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.archiver.jar; -import static org.junit.jupiter.api.Assertions.assertEquals; - import java.io.File; import java.io.IOException; import java.io.OutputStream; @@ -20,134 +18,136 @@ import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; -public class JarArchiverTest - extends BaseJarArchiverTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class JarArchiverTest extends BaseJarArchiverTest { @TempDir private Path tempDir; @Test - public void testCreateManifestOnlyJar() - throws IOException, ManifestException, ArchiverException - { - File jarFile = Files.createTempFile( tempDir, "JarArchiverTest.", ".jar" ).toFile(); + public void testCreateManifestOnlyJar() throws IOException, ManifestException, ArchiverException { + File jarFile = Files.createTempFile(tempDir, "JarArchiverTest.", ".jar").toFile(); JarArchiver archiver = getJarArchiver(); - archiver.setDestFile( jarFile ); + archiver.setDestFile(jarFile); Manifest manifest = new Manifest(); - Manifest.Attribute attribute = new Manifest.Attribute( "Main-Class", getClass().getName() ); + Manifest.Attribute attribute = + new Manifest.Attribute("Main-Class", getClass().getName()); - manifest.addConfiguredAttribute( attribute ); + manifest.addConfiguredAttribute(attribute); - archiver.addConfiguredManifest( manifest ); + archiver.addConfiguredManifest(manifest); archiver.createArchive(); } @Test - public void testNonCompressed() - throws IOException, ManifestException, ArchiverException - { - File jarFile = new File( "target/output/jarArchiveNonCompressed.jar" ); + public void testNonCompressed() throws IOException, ManifestException, ArchiverException { + File jarFile = new File("target/output/jarArchiveNonCompressed.jar"); JarArchiver archiver = getJarArchiver(); - archiver.setDestFile( jarFile ); - archiver.setCompress( false ); - archiver.addDirectory( new File( "src/test/resources/mjar179" ) ); + archiver.setDestFile(jarFile); + archiver.setCompress(false); + archiver.addDirectory(new File("src/test/resources/mjar179")); archiver.createArchive(); } @Test - public void testVeryLargeJar() - throws IOException, ManifestException, ArchiverException - { + public void testVeryLargeJar() throws IOException, ManifestException, ArchiverException { // Generate some number of random files that is likely to be // two or three times the number of available file handles Random rand = new Random(); - for ( int i = 0; i < 45000; i++ ) - { - Path path = tempDir.resolve( "file" + i ); - OutputStream out = Files.newOutputStream( path ); - byte[] data = new byte[ 512 ]; // 512bytes per file - rand.nextBytes( data ); - out.write( data ); + for (int i = 0; i < 45000; i++) { + Path path = tempDir.resolve("file" + i); + OutputStream out = Files.newOutputStream(path); + byte[] data = new byte[512]; // 512bytes per file + rand.nextBytes(data); + out.write(data); out.flush(); out.close(); } - File jarFile = new File( "target/output/veryLargeJar.jar" ); + File jarFile = new File("target/output/veryLargeJar.jar"); JarArchiver archiver = getJarArchiver(); - archiver.setDestFile( jarFile ); - archiver.addDirectory( tempDir.toFile() ); + archiver.setDestFile(jarFile); + archiver.addDirectory(tempDir.toFile()); archiver.createArchive(); } @Test - public void testReproducibleBuild() - throws IOException, ManifestException, ParseException - { - String[] tzList = { "America/Managua", "America/New_York", "America/Buenos_Aires", "America/Sao_Paulo", - "America/Los_Angeles", "Africa/Cairo", "Africa/Lagos", "Africa/Nairobi", "Europe/Lisbon", "Europe/Madrid", - "Europe/Moscow", "Europe/Oslo", "Australia/Sydney", "Asia/Tokyo", "Asia/Singapore", "Asia/Qatar", - "Asia/Seoul", "Atlantic/Bermuda", "UTC", "GMT", "Etc/GMT-14" }; - for ( String tzId : tzList ) - { + public void testReproducibleBuild() throws IOException, ManifestException, ParseException { + String[] tzList = { + "America/Managua", + "America/New_York", + "America/Buenos_Aires", + "America/Sao_Paulo", + "America/Los_Angeles", + "Africa/Cairo", + "Africa/Lagos", + "Africa/Nairobi", + "Europe/Lisbon", + "Europe/Madrid", + "Europe/Moscow", + "Europe/Oslo", + "Australia/Sydney", + "Asia/Tokyo", + "Asia/Singapore", + "Asia/Qatar", + "Asia/Seoul", + "Atlantic/Bermuda", + "UTC", + "GMT", + "Etc/GMT-14" + }; + for (String tzId : tzList) { // Every single run with different Time Zone should set the same modification time. - createReproducibleBuild( tzId ); + createReproducibleBuild(tzId); } } - private void createReproducibleBuild( String timeZoneId ) - throws IOException, ManifestException, ParseException - { + private void createReproducibleBuild(String timeZoneId) throws IOException, ManifestException, ParseException { final TimeZone defaultTz = TimeZone.getDefault(); - TimeZone.setDefault( TimeZone.getTimeZone( timeZoneId ) ); - try - { - String tzName = timeZoneId.substring( timeZoneId.lastIndexOf( '/' ) + 1 ); - Path jarFile = Files.createTempFile( tempDir, "JarArchiverTest-" + tzName + "-", ".jar" ); + TimeZone.setDefault(TimeZone.getTimeZone(timeZoneId)); + try { + String tzName = timeZoneId.substring(timeZoneId.lastIndexOf('/') + 1); + Path jarFile = Files.createTempFile(tempDir, "JarArchiverTest-" + tzName + "-", ".jar"); Manifest manifest = new Manifest(); - Manifest.Attribute attribute = new Manifest.Attribute( "Main-Class", "com.example.app.Main" ); - manifest.addConfiguredAttribute( attribute ); + Manifest.Attribute attribute = new Manifest.Attribute("Main-Class", "com.example.app.Main"); + manifest.addConfiguredAttribute(attribute); JarArchiver archiver = getJarArchiver(); - archiver.setDestFile( jarFile.toFile() ); - archiver.addConfiguredManifest( manifest ); - archiver.addDirectory( new File( "src/test/resources/java-classes" ) ); + archiver.setDestFile(jarFile.toFile()); + archiver.addConfiguredManifest(manifest); + archiver.addDirectory(new File("src/test/resources/java-classes")); - SimpleDateFormat isoFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssXXX" ); - long parsedTime = isoFormat.parse( "2038-01-19T03:14:08Z" ).getTime(); - FileTime lastModTime = FileTime.fromMillis( parsedTime ); + SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + long parsedTime = isoFormat.parse("2038-01-19T03:14:08Z").getTime(); + FileTime lastModTime = FileTime.fromMillis(parsedTime); - archiver.configureReproducibleBuild( lastModTime ); + archiver.configureReproducibleBuild(lastModTime); archiver.createArchive(); // zip 2 seconds precision, normalized to UTC - long expectedTime = normalizeLastModifiedTime( parsedTime - ( parsedTime % 2000 ) ); - try ( ZipFile zip = new ZipFile( jarFile.toFile() ) ) - { + long expectedTime = normalizeLastModifiedTime(parsedTime - (parsedTime % 2000)); + try (ZipFile zip = new ZipFile(jarFile.toFile())) { Enumeration entries = zip.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); long time = entry.getTime(); - assertEquals( expectedTime, time, "last modification time does not match" ); + assertEquals(expectedTime, time, "last modification time does not match"); } } - } - finally - { - TimeZone.setDefault( defaultTz ); + } finally { + TimeZone.setDefault(defaultTz); } } @Override - protected JarArchiver getJarArchiver() - { + protected JarArchiver getJarArchiver() { return new JarArchiver(); } } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiverTest.java index 72d108b27..a8552c3e3 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/JarToolModularJarArchiverTest.java @@ -16,10 +16,6 @@ */ package org.codehaus.plexus.archiver.jar; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertThrows; - import java.io.File; import java.io.InputStream; import java.lang.reflect.Method; @@ -38,9 +34,11 @@ import org.junit.jupiter.api.condition.DisabledIf; import org.junit.jupiter.api.condition.EnabledIf; -public class JarToolModularJarArchiverTest - extends BaseJarArchiverTest -{ +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +public class JarToolModularJarArchiverTest extends BaseJarArchiverTest { private ModularJarArchiver archiver; @@ -48,34 +46,30 @@ public class JarToolModularJarArchiverTest * Configures the ModularJarArchiver for the test cases. */ @BeforeEach - public void setup() - throws Exception - { - File jarFile = new File( "target/output/modular.jar" ); + public void setup() throws Exception { + File jarFile = new File("target/output/modular.jar"); jarFile.delete(); archiver = getJarArchiver(); - archiver.setDestFile( jarFile ); - archiver.addDirectory( new File( "src/test/resources/java-classes" ) ); + archiver.setDestFile(jarFile); + archiver.addDirectory(new File("src/test/resources/java-classes")); } /* * Verify that the main class and the version are properly set for a modular JAR file. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testModularJarWithMainClassAndVersion() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); - archiver.setModuleVersion( "1.0.0" ); - archiver.setModuleMainClass( "com.example.app.Main" ); + @EnabledIf("modulesAreSupported") + public void testModularJarWithMainClassAndVersion() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); + archiver.setModuleVersion("1.0.0"); + archiver.setModuleMainClass("com.example.app.Main"); archiver.createArchive(); // verify that the proper version and main class are set - assertModularJarFile( archiver.getDestFile(), - "1.0.0", "com.example.app.Main", "com.example.app", "com.example.resources" ); + assertModularJarFile( + archiver.getDestFile(), "1.0.0", "com.example.app.Main", "com.example.app", "com.example.resources"); } /* @@ -84,24 +78,21 @@ public void testModularJarWithMainClassAndVersion() * value is overridden */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testModularJarWithManifestAndModuleMainClass() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); + @EnabledIf("modulesAreSupported") + public void testModularJarWithManifestAndModuleMainClass() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); Manifest manifest = new Manifest(); - manifest.addConfiguredAttribute( - new Manifest.Attribute( "Main-Class", "com.example.app.Main2" ) ); - archiver.addConfiguredManifest( manifest ); - archiver.setModuleMainClass( "com.example.app.Main" ); + manifest.addConfiguredAttribute(new Manifest.Attribute("Main-Class", "com.example.app.Main2")); + archiver.addConfiguredManifest(manifest); + archiver.setModuleMainClass("com.example.app.Main"); archiver.createArchive(); // Verify that the explicitly set module main class // overrides the manifest main - assertModularJarFile( archiver.getDestFile(), - null, "com.example.app.Main", "com.example.app", "com.example.resources" ); - assertManifestMainClass( archiver.getDestFile(), "com.example.app.Main" ); + assertModularJarFile( + archiver.getDestFile(), null, "com.example.app.Main", "com.example.app", "com.example.resources"); + assertManifestMainClass(archiver.getDestFile(), "com.example.app.Main"); } /** @@ -109,53 +100,45 @@ public void testModularJarWithManifestAndModuleMainClass() * the manifest main class attribute (if present) is used instead */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testModularJarWithManifestMainClassAttribute() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); + @EnabledIf("modulesAreSupported") + public void testModularJarWithManifestMainClassAttribute() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); Manifest manifest = new Manifest(); - manifest.addConfiguredAttribute( - new Manifest.Attribute( "Main-Class", "com.example.app.Main2" ) ); - archiver.addConfiguredManifest( manifest ); + manifest.addConfiguredAttribute(new Manifest.Attribute("Main-Class", "com.example.app.Main2")); + archiver.addConfiguredManifest(manifest); archiver.createArchive(); // Verify that the the manifest main class attribute is used as module main class - assertModularJarFile( archiver.getDestFile(), - null, "com.example.app.Main2", "com.example.app", "com.example.resources" ); - assertManifestMainClass( archiver.getDestFile(), "com.example.app.Main2" ); + assertModularJarFile( + archiver.getDestFile(), null, "com.example.app.Main2", "com.example.app", "com.example.resources"); + assertManifestMainClass(archiver.getDestFile(), "com.example.app.Main2"); } /* * Verify that a modular JAR file is created even when no additional attributes are set. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testModularJar() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); + @EnabledIf("modulesAreSupported") + public void testModularJar() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); archiver.createArchive(); // verify that the proper version and main class are set - assertModularJarFile( archiver.getDestFile(), - null, null, "com.example.app", "com.example.resources" ); + assertModularJarFile(archiver.getDestFile(), null, null, "com.example.app", "com.example.resources"); } /* * Verify that exception is thrown when the modular JAR is not valid. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testInvalidModularJar() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); + @EnabledIf("modulesAreSupported") + public void testInvalidModularJar() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); // Not a valid version - archiver.setModuleVersion( "notAValidVersion" ); + archiver.setModuleVersion("notAValidVersion"); - assertThrows( ArchiverException.class, () -> archiver.createArchive() ); + assertThrows(ArchiverException.class, () -> archiver.createArchive()); } /* @@ -163,20 +146,17 @@ public void testInvalidModularJar() * if the Java version does not support modules. */ @Test - @DisabledIf( "modulesAreSupported" ) - public void testModularJarPriorJava9() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); - archiver.setModuleVersion( "1.0.0" ); - archiver.setModuleMainClass( "com.example.app.Main" ); + @DisabledIf("modulesAreSupported") + public void testModularJarPriorJava9() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); + archiver.setModuleVersion("1.0.0"); + archiver.setModuleMainClass("com.example.app.Main"); archiver.createArchive(); // verify that the modular jar is created - try ( ZipFile resultingArchive = new ZipFile( archiver.getDestFile() ) ) - { - assertNotNull( resultingArchive.getEntry( "module-info.class" ) ); + try (ZipFile resultingArchive = new ZipFile(archiver.getDestFile())) { + assertNotNull(resultingArchive.getEntry("module-info.class")); } } @@ -184,25 +164,21 @@ public void testModularJarPriorJava9() * Verify that the compression flag is respected. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testNoCompression() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); - archiver.setCompress( false ); + @EnabledIf("modulesAreSupported") + public void testNoCompression() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); + archiver.setCompress(false); archiver.createArchive(); // verify that the entries are not compressed - try ( ZipFile resultingArchive = new ZipFile( archiver.getDestFile() ) ) - { + try (ZipFile resultingArchive = new ZipFile(archiver.getDestFile())) { Enumeration entries = resultingArchive.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - assertEquals( ZipEntry.STORED, entry.getMethod() ); + assertEquals(ZipEntry.STORED, entry.getMethod()); } } } @@ -212,29 +188,24 @@ public void testNoCompression() * is kept after it is updated to modular JAR file. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testCompression() - throws Exception - { - archiver.addDirectory( new File( "src/test/resources/java-module-descriptor" ) ); - archiver.addFile( new File( "src/test/jars/test.jar" ), "META-INF/lib/test.jar" ); - archiver.setRecompressAddedZips( false ); + @EnabledIf("modulesAreSupported") + public void testCompression() throws Exception { + archiver.addDirectory(new File("src/test/resources/java-module-descriptor")); + archiver.addFile(new File("src/test/jars/test.jar"), "META-INF/lib/test.jar"); + archiver.setRecompressAddedZips(false); archiver.createArchive(); // verify that the compression is kept - try ( ZipFile resultingArchive = new ZipFile( archiver.getDestFile() ) ) - { + try (ZipFile resultingArchive = new ZipFile(archiver.getDestFile())) { Enumeration entries = resultingArchive.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); - int expectedMethod = entry.isDirectory() || entry.getName().endsWith( ".jar" ) - ? ZipEntry.STORED - : ZipEntry.DEFLATED; - assertEquals( expectedMethod, entry.getMethod() ); + int expectedMethod = + entry.isDirectory() || entry.getName().endsWith(".jar") ? ZipEntry.STORED : ZipEntry.DEFLATED; + assertEquals(expectedMethod, entry.getMethod()); } } } @@ -243,160 +214,151 @@ public void testCompression() * Verify that a module descriptor in the versioned area is handled correctly. */ @Test - @EnabledIf( "modulesAreSupported" ) - public void testModularMultiReleaseJar() - throws Exception - { + @EnabledIf("modulesAreSupported") + public void testModularMultiReleaseJar() throws Exception { // Add two module-info.class, one on the root and one on the multi-release dir. - archiver.addFile( new File( "src/test/resources/java-module-descriptor/module-info.class" ), - "META-INF/versions/9/module-info.class" ); - archiver.addFile( new File( "src/test/resources/java-module-descriptor/module-info.class" ), - "module-info.class" ); + archiver.addFile( + new File("src/test/resources/java-module-descriptor/module-info.class"), + "META-INF/versions/9/module-info.class"); + archiver.addFile(new File("src/test/resources/java-module-descriptor/module-info.class"), "module-info.class"); Manifest manifest = new Manifest(); - manifest.addConfiguredAttribute( new Manifest.Attribute( "Main-Class", "com.example.app.Main2" ) ); - manifest.addConfiguredAttribute( new Manifest.Attribute( "Multi-Release", "true" ) ); - archiver.addConfiguredManifest( manifest ); + manifest.addConfiguredAttribute(new Manifest.Attribute("Main-Class", "com.example.app.Main2")); + manifest.addConfiguredAttribute(new Manifest.Attribute("Multi-Release", "true")); + archiver.addConfiguredManifest(manifest); - archiver.setModuleVersion( "1.0.0" ); + archiver.setModuleVersion("1.0.0"); // This attribute overwrites the one from the manifest. - archiver.setModuleMainClass( "com.example.app.Main" ); + archiver.setModuleMainClass("com.example.app.Main"); - SimpleDateFormat isoFormat = new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ssXXX" ); - long dateTimeMillis = isoFormat.parse( "2020-02-29T23:59:59Z" ).getTime(); - FileTime lastModTime = FileTime.fromMillis( dateTimeMillis ); + SimpleDateFormat isoFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); + long dateTimeMillis = isoFormat.parse("2020-02-29T23:59:59Z").getTime(); + FileTime lastModTime = FileTime.fromMillis(dateTimeMillis); - archiver.configureReproducibleBuild( lastModTime ); + archiver.configureReproducibleBuild(lastModTime); archiver.createArchive(); // Round-down two seconds precision - long roundedDown = lastModTime.toMillis() - ( lastModTime.toMillis() % 2000 ); + long roundedDown = lastModTime.toMillis() - (lastModTime.toMillis() % 2000); // Normalize to UTC - long expectedLastModifiedTime = normalizeLastModifiedTime( roundedDown ); + long expectedLastModifiedTime = normalizeLastModifiedTime(roundedDown); // verify that the resulting modular jar has the proper version and main class set - try ( ZipFile resultingArchive = new ZipFile( archiver.getDestFile() ) ) - { - ZipEntry moduleDescriptorEntry = resultingArchive.getEntry( "META-INF/versions/9/module-info.class" ); - InputStream resultingModuleDescriptor = resultingArchive.getInputStream( moduleDescriptorEntry ); - assertModuleDescriptor( resultingModuleDescriptor, "1.0.0", "com.example.app.Main", "com.example.app", - "com.example.resources" ); - - ZipEntry rootModuleDescriptorEntry = resultingArchive.getEntry( "module-info.class" ); - InputStream rootResultingModuleDescriptor = resultingArchive.getInputStream( rootModuleDescriptorEntry ); - assertModuleDescriptor( rootResultingModuleDescriptor, "1.0.0", "com.example.app.Main", "com.example.app", - "com.example.resources" ); + try (ZipFile resultingArchive = new ZipFile(archiver.getDestFile())) { + ZipEntry moduleDescriptorEntry = resultingArchive.getEntry("META-INF/versions/9/module-info.class"); + InputStream resultingModuleDescriptor = resultingArchive.getInputStream(moduleDescriptorEntry); + assertModuleDescriptor( + resultingModuleDescriptor, + "1.0.0", + "com.example.app.Main", + "com.example.app", + "com.example.resources"); + + ZipEntry rootModuleDescriptorEntry = resultingArchive.getEntry("module-info.class"); + InputStream rootResultingModuleDescriptor = resultingArchive.getInputStream(rootModuleDescriptorEntry); + assertModuleDescriptor( + rootResultingModuleDescriptor, + "1.0.0", + "com.example.app.Main", + "com.example.app", + "com.example.resources"); // verify every entry has the correct last modified time Enumeration entries = resultingArchive.entries(); - while ( entries.hasMoreElements() ) - { + while (entries.hasMoreElements()) { ZipEntry element = entries.nextElement(); - assertEquals( expectedLastModifiedTime, element.getTime(), - "Last Modified Time does not match with expected" ); - FileTime expectedFileTime = FileTime.fromMillis( expectedLastModifiedTime ); - assertEquals( expectedFileTime, element.getLastModifiedTime(), - "Last Modified Time does not match with expected" ); + assertEquals( + expectedLastModifiedTime, element.getTime(), "Last Modified Time does not match with expected"); + FileTime expectedFileTime = FileTime.fromMillis(expectedLastModifiedTime); + assertEquals( + expectedFileTime, + element.getLastModifiedTime(), + "Last Modified Time does not match with expected"); } } } @Override - protected JarToolModularJarArchiver getJarArchiver() - { + protected JarToolModularJarArchiver getJarArchiver() { return new JarToolModularJarArchiver(); } - private void assertModularJarFile( File jarFile , - String expectedVersion, String expectedMainClass, - String... expectedPackages ) - throws Exception - { - try ( ZipFile resultingArchive = new ZipFile( jarFile ) ) - { - ZipEntry moduleDescriptorEntry = resultingArchive.getEntry( "module-info.class" ); - InputStream resultingModuleDescriptor = resultingArchive.getInputStream( moduleDescriptorEntry ); - - assertModuleDescriptor( resultingModuleDescriptor, - expectedVersion, expectedMainClass, expectedPackages ); + private void assertModularJarFile( + File jarFile, String expectedVersion, String expectedMainClass, String... expectedPackages) + throws Exception { + try (ZipFile resultingArchive = new ZipFile(jarFile)) { + ZipEntry moduleDescriptorEntry = resultingArchive.getEntry("module-info.class"); + InputStream resultingModuleDescriptor = resultingArchive.getInputStream(moduleDescriptorEntry); + + assertModuleDescriptor(resultingModuleDescriptor, expectedVersion, expectedMainClass, expectedPackages); } } - private void assertModuleDescriptor( InputStream moduleDescriptorInputStream, - String expectedVersion, String expectedMainClass, - String... expectedPackages ) - throws Exception - { + private void assertModuleDescriptor( + InputStream moduleDescriptorInputStream, + String expectedVersion, + String expectedMainClass, + String... expectedPackages) + throws Exception { // ModuleDescriptor methods are available from Java 9 so let's get by reflection - Class moduleDescriptorClass = Class.forName( "java.lang.module.ModuleDescriptor" ); - Class optionalClass = Class.forName( "java.util.Optional" ); - Method readMethod = moduleDescriptorClass.getMethod( "read", InputStream.class ); - Method mainClassMethod = moduleDescriptorClass.getMethod( "mainClass" ); - Method rawVersionMethod = moduleDescriptorClass.getMethod( "rawVersion" ); - Method packagesMethod = moduleDescriptorClass.getMethod( "packages" ); - Method isPresentMethod = optionalClass.getMethod( "isPresent" ); - Method getMethod = optionalClass.getMethod( "get" ); + Class moduleDescriptorClass = Class.forName("java.lang.module.ModuleDescriptor"); + Class optionalClass = Class.forName("java.util.Optional"); + Method readMethod = moduleDescriptorClass.getMethod("read", InputStream.class); + Method mainClassMethod = moduleDescriptorClass.getMethod("mainClass"); + Method rawVersionMethod = moduleDescriptorClass.getMethod("rawVersion"); + Method packagesMethod = moduleDescriptorClass.getMethod("packages"); + Method isPresentMethod = optionalClass.getMethod("isPresent"); + Method getMethod = optionalClass.getMethod("get"); // Read the module from the input stream - Object moduleDescriptor = readMethod.invoke( null, moduleDescriptorInputStream ); + Object moduleDescriptor = readMethod.invoke(null, moduleDescriptorInputStream); // Get the module main class - Object mainClassOptional = mainClassMethod.invoke( moduleDescriptor ); + Object mainClassOptional = mainClassMethod.invoke(moduleDescriptor); String actualMainClass = null; - if ( (boolean) isPresentMethod.invoke( mainClassOptional ) ) - { - actualMainClass = (String) getMethod.invoke( mainClassOptional ); + if ((boolean) isPresentMethod.invoke(mainClassOptional)) { + actualMainClass = (String) getMethod.invoke(mainClassOptional); } // Get the module version - Object versionOptional = rawVersionMethod.invoke( moduleDescriptor ); + Object versionOptional = rawVersionMethod.invoke(moduleDescriptor); String actualVersion = null; - if ( (boolean) isPresentMethod.invoke( versionOptional ) ) - { - actualVersion = (String) getMethod.invoke( versionOptional ); + if ((boolean) isPresentMethod.invoke(versionOptional)) { + actualVersion = (String) getMethod.invoke(versionOptional); } // Get the module packages - Set actualPackagesSet = (Set) packagesMethod.invoke( moduleDescriptor ); - Set expectedPackagesSet = new HashSet<>( Arrays.asList( expectedPackages ) ); + Set actualPackagesSet = (Set) packagesMethod.invoke(moduleDescriptor); + Set expectedPackagesSet = new HashSet<>(Arrays.asList(expectedPackages)); - assertEquals( expectedMainClass, actualMainClass ); - assertEquals( expectedVersion, actualVersion ); - assertEquals( expectedPackagesSet, actualPackagesSet ); + assertEquals(expectedMainClass, actualMainClass); + assertEquals(expectedVersion, actualVersion); + assertEquals(expectedPackagesSet, actualPackagesSet); } - private void assertManifestMainClass( File jarFile, String expectedMainClass ) - throws Exception - { - try ( ZipFile resultingArchive = new ZipFile( jarFile ) ) - { - ZipEntry manifestEntry = resultingArchive.getEntry( "META-INF/MANIFEST.MF" ); - InputStream manifestInputStream = resultingArchive.getInputStream( manifestEntry ); + private void assertManifestMainClass(File jarFile, String expectedMainClass) throws Exception { + try (ZipFile resultingArchive = new ZipFile(jarFile)) { + ZipEntry manifestEntry = resultingArchive.getEntry("META-INF/MANIFEST.MF"); + InputStream manifestInputStream = resultingArchive.getInputStream(manifestEntry); // Get the manifest main class attribute - Manifest manifest = new Manifest( manifestInputStream ); - String actualManifestMainClass = manifest.getMainAttributes().getValue( "Main-Class" ); + Manifest manifest = new Manifest(manifestInputStream); + String actualManifestMainClass = manifest.getMainAttributes().getValue("Main-Class"); - assertEquals( expectedMainClass, actualManifestMainClass ); + assertEquals(expectedMainClass, actualManifestMainClass); } - } /* * Returns true if the current version of Java does support modules. */ - private boolean modulesAreSupported() - { - try - { - Class.forName( "java.lang.module.ModuleDescriptor" ); - } - catch ( ClassNotFoundException e ) - { + private boolean modulesAreSupported() { + try { + Class.forName("java.lang.module.ModuleDescriptor"); + } catch (ClassNotFoundException e) { return false; } return true; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/JdkManifestFactoryTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/JdkManifestFactoryTest.java index 8b9067bd6..631fbdcee 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/JdkManifestFactoryTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/JdkManifestFactoryTest.java @@ -5,6 +5,7 @@ import java.io.InputStream; import java.util.jar.Attributes; import java.util.jar.Manifest; + import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.util.Streams; import org.junit.jupiter.api.Test; @@ -16,101 +17,82 @@ /** * @author Kristian Rosenvold */ -public class JdkManifestFactoryTest - extends TestSupport -{ +public class JdkManifestFactoryTest extends TestSupport { @Test - public void testGetDefaultManifest() - throws Exception - { + public void testGetDefaultManifest() throws Exception { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Manifest manifest = JdkManifestFactory.getDefaultManifest(); - manifest.write( byteArrayOutputStream ); - System.out.println( byteArrayOutputStream ); + manifest.write(byteArrayOutputStream); + System.out.println(byteArrayOutputStream); } @Test - public void testGetDefaultManifestString() - throws Exception - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestWithClassPath.mf" ); - Manifest manifestWithout = getManifest( "src/test/resources/manifests/manifest1.mf" ); - String value = manifest.getMainAttributes().getValue( ManifestConstants.ATTRIBUTE_CLASSPATH ); - System.out.println( "value = " + value ); - manifestWithout.getMainAttributes().putValue( ManifestConstants.ATTRIBUTE_CLASSPATH, value ); - String value2 = manifestWithout.getMainAttributes().getValue( ManifestConstants.ATTRIBUTE_CLASSPATH ); - - assertEquals( value, value2 ); + public void testGetDefaultManifestString() throws Exception { + Manifest manifest = getManifest("src/test/resources/manifests/manifestWithClassPath.mf"); + Manifest manifestWithout = getManifest("src/test/resources/manifests/manifest1.mf"); + String value = manifest.getMainAttributes().getValue(ManifestConstants.ATTRIBUTE_CLASSPATH); + System.out.println("value = " + value); + manifestWithout.getMainAttributes().putValue(ManifestConstants.ATTRIBUTE_CLASSPATH, value); + String value2 = manifestWithout.getMainAttributes().getValue(ManifestConstants.ATTRIBUTE_CLASSPATH); + + assertEquals(value, value2); } @Test - public void testIllegals() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifest6.mf" ); - assertNotNull( manifest ); - - try - { - getManifest( "src/test/resources/manifests/manifest5.mf" ); - fail( "We expect to fail" ); - } - catch ( IOException ignore ) - { + public void testIllegals() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifest6.mf"); + assertNotNull(manifest); + + try { + getManifest("src/test/resources/manifests/manifest5.mf"); + fail("We expect to fail"); + } catch (IOException ignore) { } } @Test - public void testMerge() - throws ManifestException, IOException - { - Manifest manifest1 = getManifest( "src/test/resources/manifests/manifestMerge1.mf" ); - Manifest manifest2 = getManifest( "src/test/resources/manifests/manifestMerge2.mf" ); + public void testMerge() throws ManifestException, IOException { + Manifest manifest1 = getManifest("src/test/resources/manifests/manifestMerge1.mf"); + Manifest manifest2 = getManifest("src/test/resources/manifests/manifestMerge2.mf"); Manifest target = new Manifest(); - JdkManifestFactory.merge( target, manifest1, false ); - - assertEquals( "001", target.getMainAttributes().getValue( "Bar" ) ); - Attributes fudz = target.getAttributes( "Fudz" ); - assertNotNull( fudz ); - assertEquals( "002", fudz.getValue( "Bar" ) ); - Attributes redz = target.getAttributes( "Redz" ); - assertNotNull( redz ); - assertEquals( "002", redz.getValue( "Baz" ) ); - - JdkManifestFactory.merge( target, manifest2, false ); - - assertEquals( "001", target.getMainAttributes().getValue( "Bar" ) ); - fudz = target.getAttributes( "Fudz" ); - assertNotNull( fudz ); - assertEquals( "003", fudz.getValue( "Bar" ) ); - redz = target.getAttributes( "Redz" ); - assertNotNull( redz ); - assertEquals( "002", redz.getValue( "Baz" ) ); + JdkManifestFactory.merge(target, manifest1, false); + + assertEquals("001", target.getMainAttributes().getValue("Bar")); + Attributes fudz = target.getAttributes("Fudz"); + assertNotNull(fudz); + assertEquals("002", fudz.getValue("Bar")); + Attributes redz = target.getAttributes("Redz"); + assertNotNull(redz); + assertEquals("002", redz.getValue("Baz")); + + JdkManifestFactory.merge(target, manifest2, false); + + assertEquals("001", target.getMainAttributes().getValue("Bar")); + fudz = target.getAttributes("Fudz"); + assertNotNull(fudz); + assertEquals("003", fudz.getValue("Bar")); + redz = target.getAttributes("Redz"); + assertNotNull(redz); + assertEquals("002", redz.getValue("Baz")); } @Test - public void testDualClassPath() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestWithDualClassPath.mf" ); + public void testDualClassPath() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestWithDualClassPath.mf"); final Attributes mainAttributes = manifest.getMainAttributes(); - final String attribute = mainAttributes.getValue( "Class-Path" ); + final String attribute = mainAttributes.getValue("Class-Path"); // assertEquals( "../config/ classes12.jar baz", attribute ); } /** * Reads a Manifest file. */ - private java.util.jar.Manifest getManifest( String filename ) - throws IOException, ManifestException - { - try ( InputStream r = Streams.fileInputStream( getTestFile( filename ) ) ) - { - return new Manifest( r ); + private java.util.jar.Manifest getManifest(String filename) throws IOException, ManifestException { + try (InputStream r = Streams.fileInputStream(getTestFile(filename))) { + return new Manifest(r); } } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/jar/ManifestTest.java b/src/test/java/org/codehaus/plexus/archiver/jar/ManifestTest.java index 4b2d4458d..68049b67c 100644 --- a/src/test/java/org/codehaus/plexus/archiver/jar/ManifestTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/jar/ManifestTest.java @@ -34,247 +34,201 @@ /** * @author Emmanuel Venisse */ -public class ManifestTest - extends TestSupport -{ +public class ManifestTest extends TestSupport { @Test - public void testManifest1() - throws Exception - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifest1.mf" ); + public void testManifest1() throws Exception { + Manifest manifest = getManifest("src/test/resources/manifests/manifest1.mf"); String version = manifest.getManifestVersion(); - assertEquals( "1.0", version, "Manifest was not created with correct version - " ); + assertEquals("1.0", version, "Manifest was not created with correct version - "); } @Test - public void testManifest2() - throws Exception - { - try - { - getManifest( "src/test/resources/manifests/manifest2.mf" ); - fail( "Manifest isn't well formed. It must be generate an exception." ); - } - catch ( IOException ignore ) - { + public void testManifest2() throws Exception { + try { + getManifest("src/test/resources/manifests/manifest2.mf"); + fail("Manifest isn't well formed. It must be generate an exception."); + } catch (IOException ignore) { } } @Test - public void testManifest3() - throws Exception - { - try - { - getManifest( "src/test/resources/manifests/manifest3.mf" ); - fail( "Manifest isn't well formed. It must be generate an exception." ); - } - catch ( IOException ignore ) - { + public void testManifest3() throws Exception { + try { + getManifest("src/test/resources/manifests/manifest3.mf"); + fail("Manifest isn't well formed. It must be generate an exception."); + } catch (IOException ignore) { } } @Test - public void testManifest5() - throws Exception - { - try - { - getManifest( "src/test/resources/manifests/manifest5.mf" ); + public void testManifest5() throws Exception { + try { + getManifest("src/test/resources/manifests/manifest5.mf"); fail(); - } - catch ( IOException ignore ) - { + } catch (IOException ignore) { } } @Test - public void testAddConfiguredSection() - throws ManifestException - { + public void testAddConfiguredSection() throws ManifestException { Manifest manifest = new Manifest(); Manifest.Section section = new Manifest.Section(); - section.setName( "fud" ); - section.addConfiguredAttribute( new Manifest.Attribute( "bar", "baz" ) ); - manifest.addConfiguredSection( section ); - assertEquals( "baz", manifest.getAttributes( "fud" ).getValue( "bar" ) ); + section.setName("fud"); + section.addConfiguredAttribute(new Manifest.Attribute("bar", "baz")); + manifest.addConfiguredSection(section); + assertEquals("baz", manifest.getAttributes("fud").getValue("bar")); } @Test - public void testAttributeLongLineWrite() - throws Exception - { + public void testAttributeLongLineWrite() throws Exception { StringWriter writer = new StringWriter(); Manifest.Attribute attr = new Manifest.Attribute(); - String longLineOfChars = - "123456789 123456789 123456789 123456789 123456789 123456789 123456789 " + String longLineOfChars = "123456789 123456789 123456789 123456789 123456789 123456789 123456789 " + "123456789 123456789 123456789 "; - attr.setName( "test" ); - attr.setValue( longLineOfChars ); - attr.write( writer ); + attr.setName("test"); + attr.setValue(longLineOfChars); + attr.write(writer); writer.flush(); - assertEquals( "test: 123456789 123456789 123456789 123456789 123456789 123456789 1234" - + Manifest.EOL + " 56789 123456789 123456789 123456789 " + Manifest.EOL, - writer.toString(), "should be multiline" ); - + assertEquals( + "test: 123456789 123456789 123456789 123456789 123456789 123456789 1234" + Manifest.EOL + + " 56789 123456789 123456789 123456789 " + Manifest.EOL, + writer.toString(), + "should be multiline"); } @Test - public void testAttributeLongLineWriteNonAscii() - throws Exception - { + public void testAttributeLongLineWriteNonAscii() throws Exception { StringWriter writer = new StringWriter(); Manifest.Attribute attr = new Manifest.Attribute(); - String longLineOfChars = - "Ед докэндё форынчйбюж зкрипторэм векж, льабятюр ыкжпэтэндяз мэль ут, квюо ут модо " + String longLineOfChars = "Ед докэндё форынчйбюж зкрипторэм векж, льабятюр ыкжпэтэндяз мэль ут, квюо ут модо " + "либриз такематыш. Ыюм йн лаборамюз компльыктётюр, векж ыпикурэи дежпютатионй ед," + " ыам ты хабымуч мальюизчыт. Но вим алёэнюм вюльпутаты, ад нощтыр трётанё льаборэж" + " вэл, кевёбюж атоморюм кончюлату векж экз. Ку щольыат вёртюты ёнэрмйщ ыюм."; - attr.setName( "test" ); - attr.setValue( longLineOfChars ); - attr.write( writer ); + attr.setName("test"); + attr.setValue(longLineOfChars); + attr.write(writer); writer.flush(); - assertEquals( "test: Ед докэндё форынчйбюж зкрипторэм в" - + Manifest.EOL + " екж, льабятюр ыкжпэтэндяз мэль ут, квю" - + Manifest.EOL + " о ут модо либриз такематыш. Ыюм йн лаб" - + Manifest.EOL + " орамюз компльыктётюр, векж ыпикурэи д" - + Manifest.EOL + " ежпютатионй ед, ыам ты хабымуч мальюи" - + Manifest.EOL + " зчыт. Но вим алёэнюм вюльпутаты, ад но" - + Manifest.EOL + " щтыр трётанё льаборэж вэл, кевёбюж ат" - + Manifest.EOL + " оморюм кончюлату векж экз. Ку щольыат " - + Manifest.EOL + " вёртюты ёнэрмйщ ыюм." - + Manifest.EOL, - writer.toString(), "should be multiline" ); - + assertEquals( + "test: Ед докэндё форынчйбюж зкрипторэм в" + + Manifest.EOL + " екж, льабятюр ыкжпэтэндяз мэль ут, квю" + + Manifest.EOL + " о ут модо либриз такематыш. Ыюм йн лаб" + + Manifest.EOL + " орамюз компльыктётюр, векж ыпикурэи д" + + Manifest.EOL + " ежпютатионй ед, ыам ты хабымуч мальюи" + + Manifest.EOL + " зчыт. Но вим алёэнюм вюльпутаты, ад но" + + Manifest.EOL + " щтыр трётанё льаборэж вэл, кевёбюж ат" + + Manifest.EOL + " оморюм кончюлату векж экз. Ку щольыат " + + Manifest.EOL + " вёртюты ёнэрмйщ ыюм." + + Manifest.EOL, + writer.toString(), + "should be multiline"); } @Test - public void testDualClassPath() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestWithDualClassPath.mf" ); - final String attribute = manifest.getMainSection().getAttributeValue( "Class-Path" ); + public void testDualClassPath() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestWithDualClassPath.mf"); + final String attribute = manifest.getMainSection().getAttributeValue("Class-Path"); // According to discussions, we drop support for duplicate class-path attribute - assertEquals( "baz", attribute ); + assertEquals("baz", attribute); } @Test - public void testAttributeMultiLineValue() - throws Exception - { - checkMultiLineAttribute( "123456789" + Manifest.EOL + "123456789", - "123456789" + Manifest.EOL + " 123456789" + Manifest.EOL ); - + public void testAttributeMultiLineValue() throws Exception { + checkMultiLineAttribute( + "123456789" + Manifest.EOL + "123456789", "123456789" + Manifest.EOL + " 123456789" + Manifest.EOL); } @Test - public void testAttributeDifferentLineEndings() - throws Exception - { - checkMultiLineAttribute( "\tA\rB\n\t C\r\n \tD\n\r", "\tA" + Manifest.EOL + " B" + Manifest.EOL + " \t C" - + Manifest.EOL + " \tD" + Manifest.EOL ); - + public void testAttributeDifferentLineEndings() throws Exception { + checkMultiLineAttribute( + "\tA\rB\n\t C\r\n \tD\n\r", + "\tA" + Manifest.EOL + " B" + Manifest.EOL + " \t C" + Manifest.EOL + " \tD" + Manifest.EOL); } @Test - public void testAddAttributes() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestMerge1.mf" ); - Manifest.ExistingSection fudz = manifest.getSection( "Fudz" ); - fudz.addConfiguredAttribute( new Manifest.Attribute( "boz", "bzz" ) ); - assertEquals( "bzz", fudz.getAttribute( "boz" ).getValue() ); - assertEquals( "bzz", manifest.getSection( "Fudz" ).getAttributeValue( "boz" ) ); + public void testAddAttributes() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestMerge1.mf"); + Manifest.ExistingSection fudz = manifest.getSection("Fudz"); + fudz.addConfiguredAttribute(new Manifest.Attribute("boz", "bzz")); + assertEquals("bzz", fudz.getAttribute("boz").getValue()); + assertEquals("bzz", manifest.getSection("Fudz").getAttributeValue("boz")); } @Test - public void testRemoveAttributes() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestMerge1.mf" ); - Manifest.ExistingSection fudz = manifest.getSection( "Fudz" ); - fudz.addConfiguredAttribute( new Manifest.Attribute( "boz", "bzz" ) ); - assertEquals( "bzz", fudz.getAttributeValue( "boz" ) ); - fudz.removeAttribute( "boz" ); - assertNull( fudz.getAttributeValue( "boz" ) ); + public void testRemoveAttributes() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestMerge1.mf"); + Manifest.ExistingSection fudz = manifest.getSection("Fudz"); + fudz.addConfiguredAttribute(new Manifest.Attribute("boz", "bzz")); + assertEquals("bzz", fudz.getAttributeValue("boz")); + fudz.removeAttribute("boz"); + assertNull(fudz.getAttributeValue("boz")); } @Test - public void testAttributeSerialization() - throws IOException, ManifestException - { + public void testAttributeSerialization() throws IOException, ManifestException { Manifest manifest = new Manifest(); - manifest.getMainAttributes().putValue( "mfa1", "fud1" ); - manifest.getMainSection().addAttributeAndCheck( new Manifest.Attribute( "mfa2", "fud2" ) ); + manifest.getMainAttributes().putValue("mfa1", "fud1"); + manifest.getMainSection().addAttributeAndCheck(new Manifest.Attribute("mfa2", "fud2")); Attributes attributes = new Attributes(); - attributes.putValue( "attA", "baz" ); - manifest.getEntries().put( "sub", attributes ); - manifest.getSection( "sub" ).addAttributeAndCheck( new Manifest.Attribute( "attB", "caB" ) ); + attributes.putValue("attA", "baz"); + manifest.getEntries().put("sub", attributes); + manifest.getSection("sub").addAttributeAndCheck(new Manifest.Attribute("attB", "caB")); StringWriter writer = new StringWriter(); - manifest.write( writer ); + manifest.write(writer); String s = writer.toString(); - assertTrue( s.contains( "mfa1: fud1" ) ); - assertTrue( s.contains( "mfa2: fud2" ) ); - assertTrue( s.contains( "attA: baz" ) ); - assertTrue( s.contains( "attB: caB" ) ); + assertTrue(s.contains("mfa1: fud1")); + assertTrue(s.contains("mfa2: fud2")); + assertTrue(s.contains("attA: baz")); + assertTrue(s.contains("attB: caB")); } @Test - public void testDefaultBehaviour() - { + public void testDefaultBehaviour() { Manifest manifest = new Manifest(); Manifest.ExistingSection mainSection = manifest.getMainSection(); - assertNotNull( mainSection ); - String bar = mainSection.getAttributeValue( "Bar" ); - assertNull( bar ); - assertNull( manifest.getSection( "Fud" ) ); + assertNotNull(mainSection); + String bar = mainSection.getAttributeValue("Bar"); + assertNull(bar); + assertNull(manifest.getSection("Fud")); } @Test - public void testGetDefaultManifest() - throws Exception - { + public void testGetDefaultManifest() throws Exception { java.util.jar.Manifest mf = Manifest.getDefaultManifest(); java.util.jar.Attributes mainAttributes = mf.getMainAttributes(); - assertEquals( 2, mainAttributes.size() ); - assertTrue( mainAttributes.containsKey( new java.util.jar.Attributes.Name( "Manifest-Version" ) ) ); - assertTrue( mainAttributes.containsKey( new java.util.jar.Attributes.Name( "Created-By" ) ) ); + assertEquals(2, mainAttributes.size()); + assertTrue(mainAttributes.containsKey(new java.util.jar.Attributes.Name("Manifest-Version"))); + assertTrue(mainAttributes.containsKey(new java.util.jar.Attributes.Name("Created-By"))); - mf = Manifest.getDefaultManifest( true ); + mf = Manifest.getDefaultManifest(true); mainAttributes = mf.getMainAttributes(); - assertEquals( 1, mainAttributes.size() ); - assertTrue( mainAttributes.containsKey( new java.util.jar.Attributes.Name( "Manifest-Version" ) ) ); + assertEquals(1, mainAttributes.size()); + assertTrue(mainAttributes.containsKey(new java.util.jar.Attributes.Name("Manifest-Version"))); } - public void checkMultiLineAttribute( String in, String expected ) - throws Exception - { + public void checkMultiLineAttribute(String in, String expected) throws Exception { StringWriter writer = new StringWriter(); Manifest.Attribute attr = new Manifest.Attribute(); - attr.setName( "test" ); - attr.setValue( in ); - attr.write( writer ); + attr.setName("test"); + attr.setValue(in); + attr.write(writer); writer.flush(); // Print the string with whitespace replaced with special codes // so in case of failure you can see what went wrong. - System.err.println( "String: " + dumpString( writer.toString() ) ); + System.err.println("String: " + dumpString(writer.toString())); - assertEquals( "test: " + expected, writer.toString(), "should be indented multiline" ); + assertEquals("test: " + expected, writer.toString(), "should be indented multiline"); } - private static String dumpString( String in ) - { + private static String dumpString(String in) { String out = ""; char[] chars = in.toCharArray(); - for ( char aChar : chars ) - { - switch ( aChar ) - { + for (char aChar : chars) { + switch (aChar) { case '\t': out += "\\t"; break; @@ -297,68 +251,58 @@ private static String dumpString( String in ) } @Test - public void testAddAttributesPlexusManifest() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestMerge1.mf" ); - Manifest.ExistingSection fudz = manifest.getSection( "Fudz" ); - fudz.addConfiguredAttribute( new Manifest.Attribute( "boz", "bzz" ) ); - assertEquals( "bzz", manifest.getSection( "Fudz" ).getAttributeValue( "boz" ) ); + public void testAddAttributesPlexusManifest() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestMerge1.mf"); + Manifest.ExistingSection fudz = manifest.getSection("Fudz"); + fudz.addConfiguredAttribute(new Manifest.Attribute("boz", "bzz")); + assertEquals("bzz", manifest.getSection("Fudz").getAttributeValue("boz")); } @Test - public void testRemoveAttributesPlexusManifest() - throws ManifestException, IOException - { - Manifest manifest = getManifest( "src/test/resources/manifests/manifestMerge1.mf" ); - Manifest.ExistingSection fudz = manifest.getSection( "Fudz" ); - fudz.addConfiguredAttribute( new Manifest.Attribute( "boz", "bzz" ) ); - assertEquals( "bzz", fudz.getAttributeValue( "boz" ) ); - fudz.removeAttribute( "boz" ); - assertNull( fudz.getAttributeValue( "boz" ) ); + public void testRemoveAttributesPlexusManifest() throws ManifestException, IOException { + Manifest manifest = getManifest("src/test/resources/manifests/manifestMerge1.mf"); + Manifest.ExistingSection fudz = manifest.getSection("Fudz"); + fudz.addConfiguredAttribute(new Manifest.Attribute("boz", "bzz")); + assertEquals("bzz", fudz.getAttributeValue("boz")); + fudz.removeAttribute("boz"); + assertNull(fudz.getAttributeValue("boz")); } @Test - public void testAttributeSerializationPlexusManifest() - throws IOException, ManifestException - { + public void testAttributeSerializationPlexusManifest() throws IOException, ManifestException { Manifest manifest = new Manifest(); - manifest.getMainSection().addConfiguredAttribute( new Manifest.Attribute( "mfa1", "fud1" ) ); - manifest.getMainSection().addConfiguredAttribute( new Manifest.Attribute( "mfa2", "fud2" ) ); + manifest.getMainSection().addConfiguredAttribute(new Manifest.Attribute("mfa1", "fud1")); + manifest.getMainSection().addConfiguredAttribute(new Manifest.Attribute("mfa2", "fud2")); Manifest.Section attributes = new Manifest.Section(); - attributes.setName( "TestSection" ); - attributes.addConfiguredAttribute( new Manifest.Attribute( "attA", "baz" ) ); - attributes.addConfiguredAttribute( new Manifest.Attribute( "attB", "caB" ) ); - manifest.addConfiguredSection( attributes ); + attributes.setName("TestSection"); + attributes.addConfiguredAttribute(new Manifest.Attribute("attA", "baz")); + attributes.addConfiguredAttribute(new Manifest.Attribute("attB", "caB")); + manifest.addConfiguredSection(attributes); StringWriter writer = new StringWriter(); - manifest.write( writer ); + manifest.write(writer); String s = writer.toString(); - assertTrue( s.contains( "mfa1: fud1" ) ); - assertTrue( s.contains( "mfa2: fud2" ) ); - assertTrue( s.contains( "attA: baz" ) ); - assertTrue( s.contains( "attB: caB" ) ); + assertTrue(s.contains("mfa1: fud1")); + assertTrue(s.contains("mfa2: fud2")); + assertTrue(s.contains("attA: baz")); + assertTrue(s.contains("attB: caB")); } @Test - public void testClassPathPlexusManifest() - throws ManifestException - { + public void testClassPathPlexusManifest() throws ManifestException { Manifest manifest = new Manifest(); - manifest.addConfiguredAttribute( new Manifest.Attribute( ManifestConstants.ATTRIBUTE_CLASSPATH, "fud" ) ); - manifest.addConfiguredAttribute( new Manifest.Attribute( ManifestConstants.ATTRIBUTE_CLASSPATH, "duf" ) ); - assertEquals( "fud duf", manifest.getMainSection().getAttributeValue( ManifestConstants.ATTRIBUTE_CLASSPATH ) ); + manifest.addConfiguredAttribute(new Manifest.Attribute(ManifestConstants.ATTRIBUTE_CLASSPATH, "fud")); + manifest.addConfiguredAttribute(new Manifest.Attribute(ManifestConstants.ATTRIBUTE_CLASSPATH, "duf")); + assertEquals("fud duf", manifest.getMainSection().getAttributeValue(ManifestConstants.ATTRIBUTE_CLASSPATH)); } @Test - public void testAddConfiguredSectionPlexusManifest() - throws ManifestException - { + public void testAddConfiguredSectionPlexusManifest() throws ManifestException { Manifest manifest = new Manifest(); Manifest.Section section = new Manifest.Section(); - section.setName( "fud" ); - section.addConfiguredAttribute( new Manifest.Attribute( "bar", "baz" ) ); - manifest.addConfiguredSection( section ); - assertEquals( "baz", manifest.getSection( "fud" ).getAttributeValue( "bar" ) ); + section.setName("fud"); + section.addConfiguredAttribute(new Manifest.Attribute("bar", "baz")); + manifest.addConfiguredSection(section); + assertEquals("baz", manifest.getSection("fud").getAttributeValue("bar")); } /** @@ -371,13 +315,9 @@ public void testAddConfiguredSectionPlexusManifest() * @throws java.io.IOException * @throws ManifestException */ - private Manifest getManifest( String filename ) - throws IOException, ManifestException - { - try ( InputStream is = Files.newInputStream( getTestFile( filename ).toPath() ) ) - { - return new Manifest( is ); + private Manifest getManifest(String filename) throws IOException, ManifestException { + try (InputStream is = Files.newInputStream(getTestFile(filename).toPath())) { + return new Manifest(is); } } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/manager/ArchiverManagerTest.java b/src/test/java/org/codehaus/plexus/archiver/manager/ArchiverManagerTest.java index 8f6341e73..ffe3fd2cd 100644 --- a/src/test/java/org/codehaus/plexus/archiver/manager/ArchiverManagerTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/manager/ArchiverManagerTest.java @@ -45,234 +45,205 @@ /** * @author Dan T. Tran */ -class ArchiverManagerTest - extends TestSupport -{ +class ArchiverManagerTest extends TestSupport { // list of items which support Archiver and UnArchiver - private static Stream getArchiversAndUnArchiverForTests() - { + private static Stream getArchiversAndUnArchiverForTests() { return Stream.of( - "bzip2", - "ear", - "gzip", - "jar", - "rar", - "tar", - "tar.bz2", - "tar.gz", - "tar.snappy", - "tar.xz", - "tar.zst", - "tbz2", - "tgz", - "txz", - "tzst", - "war", - "xz", - "zip", - "snappy", - "zst" - ); + "bzip2", + "ear", + "gzip", + "jar", + "rar", + "tar", + "tar.bz2", + "tar.gz", + "tar.snappy", + "tar.xz", + "tar.zst", + "tbz2", + "tgz", + "txz", + "tzst", + "war", + "xz", + "zip", + "snappy", + "zst"); } // list of items which support UnArchiver - private static Stream getUnArchiversForTests() - { - return Stream.concat( getArchiversAndUnArchiverForTests(), Stream.of( - // only UnArchivers - "car", - "esb", - "nar", - "par", - "sar", - "swc" ) ); + private static Stream getUnArchiversForTests() { + return Stream.concat( + getArchiversAndUnArchiverForTests(), + Stream.of( + // only UnArchivers + "car", "esb", "nar", "par", "sar", "swc")); } // list of Archiver - private static Stream getArchiversForTests() - { - return Stream.concat( getArchiversAndUnArchiverForTests(), Stream.of( - // only Archivers - "dir", - "mjar" ) ); + private static Stream getArchiversForTests() { + return Stream.concat( + getArchiversAndUnArchiverForTests(), + Stream.of( + // only Archivers + "dir", "mjar")); } - private static Stream getResourceCollectionsForTests() - { + private static Stream getResourceCollectionsForTests() { return Stream.concat( - getUnArchiversForTests(), - Stream.of( "default", "files", /* defined in plexus-io */ - "gz", "bz2" /* additional alias only for it */ - ) ); + getUnArchiversForTests(), + Stream.of( + "default", "files", /* defined in plexus-io */ + "gz", "bz2" /* additional alias only for it */)); } @Test - void testReuseArchiver() - throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void testReuseArchiver() throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); - Archiver archiver = manager.getArchiver( "jar" ); - assertNotNull( archiver ); + Archiver archiver = manager.getArchiver("jar"); + assertNotNull(archiver); - archiver.addDirectory( new File( getBasedir() ) ); + archiver.addDirectory(new File(getBasedir())); - Archiver newArchiver = manager.getArchiver( "jar" ); - assertNotNull( newArchiver ); - assertFalse( newArchiver.equals( archiver ) ); + Archiver newArchiver = manager.getArchiver("jar"); + assertNotNull(newArchiver); + assertFalse(newArchiver.equals(archiver)); - assertTrue( !newArchiver.getResources().hasNext() ); + assertTrue(!newArchiver.getResources().hasNext()); } @Test - void allArchiversShouldBeUnderTest() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void allArchiversShouldBeUnderTest() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThat( manager.getAvailableArchivers() ) - .containsExactlyInAnyOrderElementsOf( getArchiversForTests().collect( Collectors.toList() ) ); + assertThat(manager.getAvailableArchivers()) + .containsExactlyInAnyOrderElementsOf(getArchiversForTests().collect(Collectors.toList())); } @Test - void allUnArchiversShouldBeUnderTest() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void allUnArchiversShouldBeUnderTest() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThat( manager.getAvailableUnArchivers() ) - .containsExactlyInAnyOrderElementsOf( getUnArchiversForTests().collect( Collectors.toList() ) ); + assertThat(manager.getAvailableUnArchivers()) + .containsExactlyInAnyOrderElementsOf(getUnArchiversForTests().collect(Collectors.toList())); } @Test - void allResourceCollectionsShouldBeUnderTest() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void allResourceCollectionsShouldBeUnderTest() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThat( manager.getAvailableResourceCollections() ) - .containsExactlyInAnyOrderElementsOf( getResourceCollectionsForTests().collect( Collectors.toList() ) ); + assertThat(manager.getAvailableResourceCollections()) + .containsExactlyInAnyOrderElementsOf( + getResourceCollectionsForTests().collect(Collectors.toList())); } @ParameterizedTest - @MethodSource( "getArchiversForTests" ) - void testLookupArchiver( String archiveName ) throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); - Archiver archiver = manager.getArchiver( archiveName ); + @MethodSource("getArchiversForTests") + void testLookupArchiver(String archiveName) throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); + Archiver archiver = manager.getArchiver(archiveName); - assertThat( archiver ).isNotNull(); + assertThat(archiver).isNotNull(); } @ParameterizedTest - @MethodSource( "getUnArchiversForTests" ) - void testLookupUnArchiver( String archiveName ) throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); - UnArchiver archiver = manager.getUnArchiver( archiveName ); + @MethodSource("getUnArchiversForTests") + void testLookupUnArchiver(String archiveName) throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); + UnArchiver archiver = manager.getUnArchiver(archiveName); - assertThat( archiver ).isNotNull(); + assertThat(archiver).isNotNull(); } @ParameterizedTest - @MethodSource( "getResourceCollectionsForTests" ) - void testLookupResourceCollection( String resourceName ) throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); - PlexusIoResourceCollection resourceCollection = manager.getResourceCollection( resourceName ); + @MethodSource("getResourceCollectionsForTests") + void testLookupResourceCollection(String resourceName) throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); + PlexusIoResourceCollection resourceCollection = manager.getResourceCollection(resourceName); - assertThat( resourceCollection ).isNotNull(); + assertThat(resourceCollection).isNotNull(); } @Test - void testLookupUnknownArchiver() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void testLookupUnknownArchiver() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThrowsExactly( NoSuchArchiverException.class, () -> manager.getArchiver( "Unknown" ) ); + assertThrowsExactly(NoSuchArchiverException.class, () -> manager.getArchiver("Unknown")); } @Test - void testLookupUnknownUnArchiver() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void testLookupUnknownUnArchiver() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThrowsExactly( NoSuchArchiverException.class, () -> manager.getUnArchiver( "Unknown" ) ); + assertThrowsExactly(NoSuchArchiverException.class, () -> manager.getUnArchiver("Unknown")); } @Test - void testLookupUnknownResourceCollection() - { - ArchiverManager manager = lookup( ArchiverManager.class ); + void testLookupUnknownResourceCollection() { + ArchiverManager manager = lookup(ArchiverManager.class); - assertThrowsExactly( NoSuchArchiverException.class, () -> manager.getResourceCollection( "Unknown" ) ); + assertThrowsExactly(NoSuchArchiverException.class, () -> manager.getResourceCollection("Unknown")); } @ParameterizedTest - @MethodSource( "getUnArchiversForTests" ) - void testLookupUnArchiverUsingFile( String archiveName ) - throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); - - UnArchiver archiver = manager.getUnArchiver( new File( "test", "test." + archiveName ) ); - assertThat( archiver ).isNotNull(); + @MethodSource("getUnArchiversForTests") + void testLookupUnArchiverUsingFile(String archiveName) throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); + + UnArchiver archiver = manager.getUnArchiver(new File("test", "test." + archiveName)); + assertThat(archiver).isNotNull(); } @ParameterizedTest - @MethodSource( "getArchiversForTests" ) - void testLookupArchiverUsingFile( String archiveName ) - throws Exception - { - ArchiverManager manager = lookup( ArchiverManager.class ); - - Archiver archiver = manager.getArchiver( new File( "test." + archiveName ) ); - assertThat( archiver ).isNotNull(); + @MethodSource("getArchiversForTests") + void testLookupArchiverUsingFile(String archiveName) throws Exception { + ArchiverManager manager = lookup(ArchiverManager.class); + + Archiver archiver = manager.getArchiver(new File("test." + archiveName)); + assertThat(archiver).isNotNull(); } - private static Stream getUnsupportedFiles() - { + private static Stream getUnsupportedFiles() { return Stream.of( - Arguments.of( "", "" ), - Arguments.of( "test", "" ), - Arguments.of( "test.xxx", "xxx" ), - Arguments.of( "test.tar.xxx", "tar.xxx" ), - Arguments.of( "tar.gz.xxx", "xxx" ) - ); + Arguments.of("", ""), + Arguments.of("test", ""), + Arguments.of("test.xxx", "xxx"), + Arguments.of("test.tar.xxx", "tar.xxx"), + Arguments.of("tar.gz.xxx", "xxx")); } @ParameterizedTest - @MethodSource( "getUnsupportedFiles" ) - void testUnsupportedLookupArchiverUsingFile( String fileName, String fileExtension ) - { - ArchiverManager manager = lookup( ArchiverManager.class ); + @MethodSource("getUnsupportedFiles") + void testUnsupportedLookupArchiverUsingFile(String fileName, String fileExtension) { + ArchiverManager manager = lookup(ArchiverManager.class); NoSuchArchiverException exception = assertThrowsExactly( - NoSuchArchiverException.class, () -> manager.getArchiver( new File( "test", fileName ) ) ); + NoSuchArchiverException.class, () -> manager.getArchiver(new File("test", fileName))); - assertThat( exception.getArchiver() ).isEqualTo( fileExtension ); + assertThat(exception.getArchiver()).isEqualTo(fileExtension); } @ParameterizedTest - @MethodSource( "getUnsupportedFiles" ) - void testUnsupportedLookupUnArchiverUsingFile( String fileName, String fileExtension ) - { - ArchiverManager manager = lookup( ArchiverManager.class ); + @MethodSource("getUnsupportedFiles") + void testUnsupportedLookupUnArchiverUsingFile(String fileName, String fileExtension) { + ArchiverManager manager = lookup(ArchiverManager.class); - NoSuchArchiverException exception = assertThrowsExactly( - NoSuchArchiverException.class, () -> manager.getUnArchiver( new File( fileName ) ) ); + NoSuchArchiverException exception = + assertThrowsExactly(NoSuchArchiverException.class, () -> manager.getUnArchiver(new File(fileName))); - assertThat( exception.getArchiver() ).isEqualTo( fileExtension ); + assertThat(exception.getArchiver()).isEqualTo(fileExtension); } @ParameterizedTest - @MethodSource( "getUnsupportedFiles" ) - void testUnsupportedLookupResourceCollectionUsingFile( String fileName, String fileExtension ) - { - ArchiverManager manager = lookup( ArchiverManager.class ); + @MethodSource("getUnsupportedFiles") + void testUnsupportedLookupResourceCollectionUsingFile(String fileName, String fileExtension) { + ArchiverManager manager = lookup(ArchiverManager.class); NoSuchArchiverException exception = assertThrowsExactly( - NoSuchArchiverException.class, () -> manager.getResourceCollection( new File( fileName ) ) ); + NoSuchArchiverException.class, () -> manager.getResourceCollection(new File(fileName))); - assertThat( exception.getArchiver() ).isEqualTo( fileExtension ); + assertThat(exception.getArchiver()).isEqualTo(fileExtension); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/rar/RarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/rar/RarArchiverTest.java index 7d474b7c4..1c4bc418c 100644 --- a/src/test/java/org/codehaus/plexus/archiver/rar/RarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/rar/RarArchiverTest.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.archiver.rar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.BasePlexusArchiverTest; import org.codehaus.plexus.archiver.UnArchiver; @@ -31,68 +32,57 @@ * @author olamy * @since 13 mars 07 */ -public class RarArchiverTest - extends BasePlexusArchiverTest -{ +public class RarArchiverTest extends BasePlexusArchiverTest { - public File getTargetRarFolder() - { - return new File( getBasedir(), "/target/rartest/" ); + public File getTargetRarFolder() { + return new File(getBasedir(), "/target/rartest/"); } @Override @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); // clean output directory and re create it - if ( getTargetRarFolder().exists() ) - { - FileUtils.deleteDirectory( getTargetRarFolder() ); + if (getTargetRarFolder().exists()) { + FileUtils.deleteDirectory(getTargetRarFolder()); } } @Test - public void testArchive() - throws Exception - { - Archiver archiver = lookup( Archiver.class, "rar" ); - archiver.setDestFile( new File( getTargetRarFolder(), "test.rar" ) ); - //archiver.addDirectory( , "manifests" ); - archiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "manifests/manifest1.mf" ); + public void testArchive() throws Exception { + Archiver archiver = lookup(Archiver.class, "rar"); + archiver.setDestFile(new File(getTargetRarFolder(), "test.rar")); + // archiver.addDirectory( , "manifests" ); + archiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "manifests/manifest1.mf"); archiver.createArchive(); - assertTrue( new File( getTargetRarFolder(), "test.rar" ).exists() ); + assertTrue(new File(getTargetRarFolder(), "test.rar").exists()); - UnArchiver unArchiver = lookup( UnArchiver.class, "rar" ); - unArchiver.setSourceFile( new File( getTargetRarFolder(), "test.rar" ) ); - unArchiver.setDestDirectory( getTargetRarFolder() ); + UnArchiver unArchiver = lookup(UnArchiver.class, "rar"); + unArchiver.setSourceFile(new File(getTargetRarFolder(), "test.rar")); + unArchiver.setDestDirectory(getTargetRarFolder()); unArchiver.extract(); - File manifestsDir = new File( getTargetRarFolder(), "/manifests" ); - assertTrue( manifestsDir.exists() ); + File manifestsDir = new File(getTargetRarFolder(), "/manifests"); + assertTrue(manifestsDir.exists()); - File manifestsFile = new File( getTargetRarFolder(), "/manifests/manifest1.mf" ); - assertTrue( manifestsFile.exists() ); + File manifestsFile = new File(getTargetRarFolder(), "/manifests/manifest1.mf"); + assertTrue(manifestsFile.exists()); } @Test - public void testUnarchive() - throws Exception - { - - UnArchiver unArchiver = lookup( UnArchiver.class, "rar" ); - File rarFile = new File( getBasedir() + "/src/test/jars/test.rar" ); - assertTrue( rarFile.exists() ); - unArchiver.setSourceFile( rarFile ); - unArchiver.setDestDirectory( getTargetRarFolder() ); + public void testUnarchive() throws Exception { + + UnArchiver unArchiver = lookup(UnArchiver.class, "rar"); + File rarFile = new File(getBasedir() + "/src/test/jars/test.rar"); + assertTrue(rarFile.exists()); + unArchiver.setSourceFile(rarFile); + unArchiver.setDestDirectory(getTargetRarFolder()); getTargetRarFolder().mkdir(); unArchiver.extract(); - File dirExtract = new File( getTargetRarFolder(), "META-INF" ); - assertTrue( dirExtract.exists() ); - assertTrue( dirExtract.isDirectory() ); - + File dirExtract = new File(getTargetRarFolder(), "META-INF"); + assertTrue(dirExtract.exists()); + assertTrue(dirExtract.isDirectory()); } /** @@ -102,37 +92,35 @@ public void testUnarchive() * @throws Exception */ @Test - public void testRarIsForcedBehaviour() throws Exception - { - Archiver rarArvhiver = createArchiver( "rar" ); + public void testRarIsForcedBehaviour() throws Exception { + Archiver rarArvhiver = createArchiver("rar"); - assertTrue( rarArvhiver.isSupportingForced() ); + assertTrue(rarArvhiver.isSupportingForced()); rarArvhiver.createArchive(); final long creationTime = rarArvhiver.getDestFile().lastModified(); - rarArvhiver = createArchiver( "rar" ); + rarArvhiver = createArchiver("rar"); - assertTrue( rarArvhiver.isSupportingForced() ); - //Default should be true - rarArvhiver.setForced( true ); + assertTrue(rarArvhiver.isSupportingForced()); + // Default should be true + rarArvhiver.setForced(true); - waitUntilNewTimestamp( rarArvhiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(rarArvhiver.getDestFile(), creationTime); rarArvhiver.createArchive(); final long firstRunTime = rarArvhiver.getDestFile().lastModified(); - assertNotEquals( creationTime, firstRunTime ); + assertNotEquals(creationTime, firstRunTime); - //waitUntilNewTimestamp( rarArvhiver.getDestFile(), firstRunTime ); - rarArvhiver = createArchiver( "rar" ); + // waitUntilNewTimestamp( rarArvhiver.getDestFile(), firstRunTime ); + rarArvhiver = createArchiver("rar"); - rarArvhiver.setForced( false ); + rarArvhiver.setForced(false); rarArvhiver.createArchive(); final long secondRunTime = rarArvhiver.getDestFile().lastModified(); - assertEquals( secondRunTime, firstRunTime ); + assertEquals(secondRunTime, firstRunTime); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/sar/SarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/sar/SarArchiverTest.java index 08d6fab8c..421b38a49 100644 --- a/src/test/java/org/codehaus/plexus/archiver/sar/SarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/sar/SarArchiverTest.java @@ -22,21 +22,16 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; -public class SarArchiverTest - extends BasePlexusArchiverTest -{ +public class SarArchiverTest extends BasePlexusArchiverTest { @Test - public void testLookup() - throws Exception - { - ArchiverManager dam = lookup( ArchiverManager.class ); - PlexusIoResourceCollection sar = dam.getResourceCollection( "sar" ); - assertNotNull( sar ); + public void testLookup() throws Exception { + ArchiverManager dam = lookup(ArchiverManager.class); + PlexusIoResourceCollection sar = dam.getResourceCollection("sar"); + assertNotNull(sar); PlexusIoResourceCollection archiver = - (PlexusIoResourceCollection) lookup( PlexusIoResourceCollection.class, "sar" ); + (PlexusIoResourceCollection) lookup(PlexusIoResourceCollection.class, "sar"); - assertNotNull( archiver ); + assertNotNull(archiver); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/snappy/SnappyArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/snappy/SnappyArchiverTest.java index f9d1e5ff9..9f20c7e0f 100644 --- a/src/test/java/org/codehaus/plexus/archiver/snappy/SnappyArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/snappy/SnappyArchiverTest.java @@ -29,6 +29,7 @@ import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.BasePlexusArchiverTest; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; @@ -45,70 +46,59 @@ /** * Tests for the snappy archiver */ -public class SnappyArchiverTest - extends BasePlexusArchiverTest -{ +public class SnappyArchiverTest extends BasePlexusArchiverTest { @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.addDirectory( getTestFile( "src" ) ); - zipArchiver.setDestFile( getTestFile( "target/output/archiveForSnappy.zip" ) ); + public void testCreateArchive() throws Exception { + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.addDirectory(getTestFile("src")); + zipArchiver.setDestFile(getTestFile("target/output/archiveForSnappy.zip")); zipArchiver.createArchive(); - SnappyArchiver archiver = (SnappyArchiver) lookup( Archiver.class, "snappy" ); - String[] inputFiles = new String[ 1 ]; + SnappyArchiver archiver = (SnappyArchiver) lookup(Archiver.class, "snappy"); + String[] inputFiles = new String[1]; inputFiles[0] = "archiveForSnappy.zip"; - archiver.addDirectory( getTestFile( "target/output" ), inputFiles, null ); - archiver.setDestFile( getTestFile( "target/output/archive.snappy" ) ); + archiver.addDirectory(getTestFile("target/output"), inputFiles, null); + archiver.setDestFile(getTestFile("target/output/archive.snappy")); archiver.createArchive(); } @Test - public void testCreateEmptyArchive() - throws Exception - { - SnappyArchiver archiver = (SnappyArchiver) lookup( Archiver.class, "snappy" ); - archiver.setDestFile( getTestFile( "target/output/empty.snappy" ) ); - try - { + public void testCreateEmptyArchive() throws Exception { + SnappyArchiver archiver = (SnappyArchiver) lookup(Archiver.class, "snappy"); + archiver.setDestFile(getTestFile("target/output/empty.snappy")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testCreateResourceCollection() - throws Exception - { - final File pomFile = new File( "pom.xml" ); - final File snappyFile = new File( "target/output/pom.xml.snappy" ); - SnappyArchiver SnappyArchiver = (SnappyArchiver) lookup( Archiver.class, "snappy" ); - SnappyArchiver.setDestFile( snappyFile ); - SnappyArchiver.addFile( pomFile, "pom.xml" ); - FileUtils.removePath( snappyFile.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File pomFile = new File("pom.xml"); + final File snappyFile = new File("target/output/pom.xml.snappy"); + SnappyArchiver SnappyArchiver = (SnappyArchiver) lookup(Archiver.class, "snappy"); + SnappyArchiver.setDestFile(snappyFile); + SnappyArchiver.addFile(pomFile, "pom.xml"); + FileUtils.removePath(snappyFile.getPath()); SnappyArchiver.createArchive(); - System.out.println( "Created: " + snappyFile.getAbsolutePath() ); + System.out.println("Created: " + snappyFile.getAbsolutePath()); - final File zipFile = new File( "target/output/pom.zip" ); - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.setDestFile( zipFile ); - zipArchiver.addArchivedFileSet( snappyFile, "prfx/" ); - FileUtils.removePath( zipFile.getPath() ); + final File zipFile = new File("target/output/pom.zip"); + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.setDestFile(zipFile); + zipArchiver.addArchivedFileSet(snappyFile, "prfx/"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final ZipFile juZipFile = new ZipFile( zipFile ); - final ZipEntry zipEntry = juZipFile.getEntry( "prfx/target/output/pom.xml" ); - final InputStream archivePom = juZipFile.getInputStream( zipEntry ); - final InputStream pom = Files.newInputStream( pomFile.toPath() ); + final ZipFile juZipFile = new ZipFile(zipFile); + final ZipEntry zipEntry = juZipFile.getEntry("prfx/target/output/pom.xml"); + final InputStream archivePom = juZipFile.getInputStream(zipEntry); + final InputStream pom = Files.newInputStream(pomFile.toPath()); - assertTrue( Arrays.equals( IOUtil.toByteArray( pom ), IOUtil.toByteArray( archivePom ) ) ); + assertTrue(Arrays.equals(IOUtil.toByteArray(pom), IOUtil.toByteArray(archivePom))); archivePom.close(); pom.close(); juZipFile.close(); @@ -121,34 +111,32 @@ public void testCreateResourceCollection() * @throws Exception */ @Test - public void testsnappyIsForcedBehaviour() throws Exception - { - SnappyArchiver SnappyArchiver = (SnappyArchiver) createArchiver( "snappy" ); + public void testsnappyIsForcedBehaviour() throws Exception { + SnappyArchiver SnappyArchiver = (SnappyArchiver) createArchiver("snappy"); - assertTrue( SnappyArchiver.isSupportingForced() ); + assertTrue(SnappyArchiver.isSupportingForced()); SnappyArchiver.createArchive(); final long creationTime = SnappyArchiver.getDestFile().lastModified(); - waitUntilNewTimestamp( SnappyArchiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(SnappyArchiver.getDestFile(), creationTime); - SnappyArchiver = (SnappyArchiver) createArchiver( "snappy" ); + SnappyArchiver = (SnappyArchiver) createArchiver("snappy"); - SnappyArchiver.setForced( true ); + SnappyArchiver.setForced(true); SnappyArchiver.createArchive(); final long firstRunTime = SnappyArchiver.getDestFile().lastModified(); - assertNotEquals( creationTime, firstRunTime ); + assertNotEquals(creationTime, firstRunTime); - SnappyArchiver = (SnappyArchiver) createArchiver( "snappy" ); + SnappyArchiver = (SnappyArchiver) createArchiver("snappy"); - SnappyArchiver.setForced( false ); + SnappyArchiver.setForced(false); SnappyArchiver.createArchive(); final long secondRunTime = SnappyArchiver.getDestFile().lastModified(); - assertEquals( firstRunTime, secondRunTime ); + assertEquals(firstRunTime, secondRunTime); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarArchiverTest.java index 915d3e231..9c370bc17 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarArchiverTest.java @@ -23,13 +23,6 @@ */ package org.codehaus.plexus.archiver.tar; -import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; -import static org.codehaus.plexus.components.io.resources.ResourceFactory.createResource; -import static org.junit.jupiter.api.Assertions.assertEquals; -import static org.junit.jupiter.api.Assertions.assertNotNull; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.junit.jupiter.api.Assertions.fail; - import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; @@ -62,495 +55,407 @@ import org.junit.jupiter.api.condition.OS; import org.junit.jupiter.api.io.TempDir; +import static org.codehaus.plexus.archiver.util.Streams.bufferedInputStream; +import static org.codehaus.plexus.components.io.resources.ResourceFactory.createResource; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.junit.jupiter.api.Assertions.fail; + /** * @author Emmanuel Venisse */ -public class TarArchiverTest - extends TestSupport -{ +public class TarArchiverTest extends TestSupport { @TempDir private File tempDir; @Test - @DisabledOnOs( OS.WINDOWS ) - public void testCreateArchiveWithDetectedModes() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testCreateArchiveWithDetectedModes() throws Exception { - String[] executablePaths = - { - "path/to/executable", "path/to/executable.bat" - }; + String[] executablePaths = {"path/to/executable", "path/to/executable.bat"}; - String[] confPaths = - { - "path/to/etc/file", "path/to/etc/file2" - }; + String[] confPaths = {"path/to/etc/file", "path/to/etc/file2"}; - String[] logPaths = - { - "path/to/logs/log.txt" - }; + String[] logPaths = {"path/to/logs/log.txt"}; int exeMode = 0777; int confMode = 0600; int logMode = 0640; - for ( String executablePath : executablePaths ) - { - writeFile( tempDir, executablePath, exeMode ); + for (String executablePath : executablePaths) { + writeFile(tempDir, executablePath, exeMode); } - for ( String confPath : confPaths ) - { - writeFile( tempDir, confPath, confMode ); + for (String confPath : confPaths) { + writeFile(tempDir, confPath, confMode); } - for ( String logPath : logPaths ) - { - writeFile( tempDir, logPath, logMode ); + for (String logPath : logPaths) { + writeFile(tempDir, logPath, logMode); } { - Map attributesByPath = PlexusIoResourceAttributeUtils.getFileAttributesByPath( tempDir ); - for ( String path : executablePaths ) - { - PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = (PlexusIoResourceAttributes) attributesByPath.get( - new File( tempDir, path ).getAbsolutePath() ); + Map attributesByPath = PlexusIoResourceAttributeUtils.getFileAttributesByPath(tempDir); + for (String path : executablePaths) { + PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path); + if (attrs == null) { + attrs = (PlexusIoResourceAttributes) + attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( exeMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(exeMode, attrs.getOctalMode(), "Wrong mode for: " + path); } - for ( String path : confPaths ) - { - PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = (PlexusIoResourceAttributes) attributesByPath.get( - new File( tempDir, path ).getAbsolutePath() ); + for (String path : confPaths) { + PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path); + if (attrs == null) { + attrs = (PlexusIoResourceAttributes) + attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( confMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(confMode, attrs.getOctalMode(), "Wrong mode for: " + path); } - for ( String path : logPaths ) - { - PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = (PlexusIoResourceAttributes) attributesByPath.get( - new File( tempDir, path ).getAbsolutePath() ); + for (String path : logPaths) { + PlexusIoResourceAttributes attrs = (PlexusIoResourceAttributes) attributesByPath.get(path); + if (attrs == null) { + attrs = (PlexusIoResourceAttributes) + attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( logMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(logMode, attrs.getOctalMode(), "Wrong mode for: " + path); } } - File tarFile = getTestFile( "target/output/tar-with-modes.tar" ); + File tarFile = getTestFile("target/output/tar-with-modes.tar"); TarArchiver archiver = getPosixTarArchiver(); - archiver.setDestFile( tarFile ); + archiver.setDestFile(tarFile); - archiver.addDirectory(tempDir ); + archiver.addDirectory(tempDir); archiver.createArchive(); - assertTrue( tarFile.exists() ); + assertTrue(tarFile.exists()); - File tarFile2 = getTestFile( "target/output/tar-with-modes-L2.tar" ); + File tarFile2 = getTestFile("target/output/tar-with-modes-L2.tar"); archiver = getPosixTarArchiver(); - archiver.setDestFile( tarFile2 ); + archiver.setDestFile(tarFile2); - archiver.addArchivedFileSet( tarFile ); + archiver.addArchivedFileSet(tarFile); archiver.createArchive(); - TarFile tf = new TarFile( tarFile2 ); + TarFile tf = new TarFile(tarFile2); Map entriesByPath = new LinkedHashMap(); - for ( Enumeration e = tf.getEntries(); e.hasMoreElements(); ) - { + for (Enumeration e = tf.getEntries(); e.hasMoreElements(); ) { TarArchiveEntry te = (TarArchiveEntry) e.nextElement(); - entriesByPath.put( te.getName(), te ); + entriesByPath.put(te.getName(), te); } - for ( String path : executablePaths ) - { - TarArchiveEntry te = entriesByPath.get( path ); + for (String path : executablePaths) { + TarArchiveEntry te = entriesByPath.get(path); int mode = te.getMode() & UnixStat.PERM_MASK; - assertEquals( exeMode, mode, "Wrong mode for: " + path ); + assertEquals(exeMode, mode, "Wrong mode for: " + path); } - for ( String path : confPaths ) - { - TarArchiveEntry te = entriesByPath.get( path ); + for (String path : confPaths) { + TarArchiveEntry te = entriesByPath.get(path); int mode = te.getMode() & UnixStat.PERM_MASK; - assertEquals( confMode, mode, "Wrong mode for: " + path ); + assertEquals(confMode, mode, "Wrong mode for: " + path); } - for ( String path : logPaths ) - { - TarArchiveEntry te = entriesByPath.get( path ); + for (String path : logPaths) { + TarArchiveEntry te = entriesByPath.get(path); int mode = te.getMode() & UnixStat.PERM_MASK; - assertEquals( logMode, mode, "Wrong mode for: " + path ); + assertEquals(logMode, mode, "Wrong mode for: " + path); } } @Test - public void testCreateEmptyArchive() - throws Exception - { + public void testCreateEmptyArchive() throws Exception { TarArchiver archiver = getPosixTarArchiver(); - archiver.setDestFile( getTestFile( "target/output/empty.tar" ) ); - try - { + archiver.setDestFile(getTestFile("target/output/empty.tar")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testUnicode() throws Exception - { - File tmpDir = getTestFile( "src/test/resources/utf8" ); + public void testUnicode() throws Exception { + File tmpDir = getTestFile("src/test/resources/utf8"); TarArchiver archiver = getPosixTarArchiver(); - File tarFile = getTestFile( "target/output/tar-with-longFileName.tar" ); - archiver.setDestFile( tarFile ); - archiver.setLongfile( TarLongFileMode.posix ); // Todo: should be gnu. But will fail with high userod - archiver.addDirectory( tmpDir ); + File tarFile = getTestFile("target/output/tar-with-longFileName.tar"); + archiver.setDestFile(tarFile); + archiver.setLongfile(TarLongFileMode.posix); // Todo: should be gnu. But will fail with high userod + archiver.addDirectory(tmpDir); archiver.createArchive(); - assertTrue( tarFile.exists() ); + assertTrue(tarFile.exists()); } - private void writeFile( File dir, String fname, int mode ) - throws IOException, ArchiverException - { - File file = new File( dir, fname ); + private void writeFile(File dir, String fname, int mode) throws IOException, ArchiverException { + File file = new File(dir, fname); - if ( file.getParentFile() != null ) - { + if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } - try ( Writer writer = Files.newBufferedWriter( file.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } - ArchiveEntryUtils.chmod( file, mode ); + ArchiveEntryUtils.chmod(file, mode); } @Test - public void testCreateArchive() - throws Exception - { - createArchive( 0500, - new int[] - { - 0400, 0640, 0664 - } ); - createArchive( 0500, - new int[] - { - 0400, 0640, 0664 - } ); + public void testCreateArchive() throws Exception { + createArchive(0500, new int[] {0400, 0640, 0664}); + createArchive(0500, new int[] {0400, 0640, 0664}); } - public void createArchive( final int directoryMode, final int fileModes[] ) - throws Exception - { + public void createArchive(final int directoryMode, final int fileModes[]) throws Exception { int defaultFileMode = fileModes[0]; int oneFileMode = fileModes[1]; int twoFileMode = fileModes[2]; TarArchiver archiver = getPosixTarArchiver(); - archiver.setDirectoryMode( directoryMode ); + archiver.setDirectoryMode(directoryMode); - archiver.setFileMode( defaultFileMode ); + archiver.setFileMode(defaultFileMode); - archiver.addDirectory( getTestFile( "src/main" ) ); - archiver.setFileMode( oneFileMode ); + archiver.addDirectory(getTestFile("src/main")); + archiver.setFileMode(oneFileMode); - archiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "one.txt" ); - archiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "two.txt", twoFileMode ); - archiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + archiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "one.txt"); + archiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "two.txt", twoFileMode); + archiver.setDestFile(getTestFile("target/output/archive.tar")); - archiver.addSymlink( "link_to_test_destinaton", "../test_destination/" ); + archiver.addSymlink("link_to_test_destinaton", "../test_destination/"); archiver.createArchive(); TarArchiveInputStream tis; - tis = new TarArchiveInputStream( bufferedInputStream( Files.newInputStream( archiver.getDestFile().toPath() ) ) ); + tis = new TarArchiveInputStream( + bufferedInputStream(Files.newInputStream(archiver.getDestFile().toPath()))); TarArchiveEntry te; - while ( ( te = tis.getNextTarEntry() ) != null ) - { - if ( te.isDirectory() ) - { - assertEquals( directoryMode, te.getMode() & UnixStat.PERM_MASK, - "un-expected tar-entry mode for [te.name=" + te.getName() + "]" ); - } - else if ( te.isSymbolicLink() ) - { - assertEquals( "../test_destination/", te.getLinkName() ); - assertEquals( "link_to_test_destinaton", te.getName() ); - assertEquals( 0640, te.getMode() & UnixStat.PERM_MASK ); - } - else - { - if ( te.getName().equals( "one.txt" ) ) - { - assertEquals( oneFileMode, te.getMode() & UnixStat.PERM_MASK ); - } - else if ( te.getName().equals( "two.txt" ) ) - { - assertEquals( twoFileMode, te.getMode() & UnixStat.PERM_MASK ); + while ((te = tis.getNextTarEntry()) != null) { + if (te.isDirectory()) { + assertEquals( + directoryMode, + te.getMode() & UnixStat.PERM_MASK, + "un-expected tar-entry mode for [te.name=" + te.getName() + "]"); + } else if (te.isSymbolicLink()) { + assertEquals("../test_destination/", te.getLinkName()); + assertEquals("link_to_test_destinaton", te.getName()); + assertEquals(0640, te.getMode() & UnixStat.PERM_MASK); + } else { + if (te.getName().equals("one.txt")) { + assertEquals(oneFileMode, te.getMode() & UnixStat.PERM_MASK); + } else if (te.getName().equals("two.txt")) { + assertEquals(twoFileMode, te.getMode() & UnixStat.PERM_MASK); + } else { + assertEquals( + defaultFileMode, + te.getMode() & UnixStat.PERM_MASK, + "un-expected tar-entry mode for [te.name=" + te.getName() + "]"); } - else - { - assertEquals( defaultFileMode, te.getMode() & UnixStat.PERM_MASK, - "un-expected tar-entry mode for [te.name=" + te.getName() + "]" ); - } - } } - IOUtil.close( tis ); - + IOUtil.close(tis); } @Test - public void testCreateArchiveWithJiustASymlink() - throws Exception - { + public void testCreateArchiveWithJiustASymlink() throws Exception { TarArchiver archiver = getPosixTarArchiver(); - archiver.setDirectoryMode( 0500 ); + archiver.setDirectoryMode(0500); - archiver.setFileMode( 0400 ); + archiver.setFileMode(0400); - archiver.setFileMode( 0640 ); + archiver.setFileMode(0640); - archiver.setDestFile( getTestFile( "target/output/symlinkarchive.tar" ) ); + archiver.setDestFile(getTestFile("target/output/symlinkarchive.tar")); - archiver.addSymlink( "link_to_test_destinaton", "../test_destination/" ); + archiver.addSymlink("link_to_test_destinaton", "../test_destination/"); archiver.createArchive(); TarArchiveInputStream tis; - tis = new TarArchiveInputStream( new BufferedInputStream( Files.newInputStream( archiver.getDestFile().toPath() ) ) ); + tis = new TarArchiveInputStream(new BufferedInputStream( + Files.newInputStream(archiver.getDestFile().toPath()))); TarArchiveEntry te; - while ( ( te = tis.getNextTarEntry() ) != null ) - { - if ( te.isDirectory() ) - { - assertEquals( 0500, te.getMode() & UnixStat.PERM_MASK, - "un-expected tar-entry mode for [te.name=" + te.getName() + "]" ); - } - else if ( te.isSymbolicLink() ) - { - assertEquals( "../test_destination/", te.getLinkName() ); - assertEquals( "link_to_test_destinaton", te.getName() ); - assertEquals( 0640, te.getMode() & UnixStat.PERM_MASK ); - } - else - { - assertEquals( 0400, te.getMode() & UnixStat.PERM_MASK, "un-expected tar-entry mode for [te.name=" + te.getName() + "]" ); + while ((te = tis.getNextTarEntry()) != null) { + if (te.isDirectory()) { + assertEquals( + 0500, + te.getMode() & UnixStat.PERM_MASK, + "un-expected tar-entry mode for [te.name=" + te.getName() + "]"); + } else if (te.isSymbolicLink()) { + assertEquals("../test_destination/", te.getLinkName()); + assertEquals("link_to_test_destinaton", te.getName()); + assertEquals(0640, te.getMode() & UnixStat.PERM_MASK); + } else { + assertEquals( + 0400, + te.getMode() & UnixStat.PERM_MASK, + "un-expected tar-entry mode for [te.name=" + te.getName() + "]"); } } tis.close(); - } - private TarArchiver getPosixTarArchiver() throws Exception - { - TarArchiver archiver = (TarArchiver) lookup( Archiver.class, "tar" ); - archiver.setLongfile( TarLongFileMode.posix ); + private TarArchiver getPosixTarArchiver() throws Exception { + TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar"); + archiver.setLongfile(TarLongFileMode.posix); return archiver; } - private class TarHandler - { + private class TarHandler { - File createTarFile() - throws Exception - { - final File srcDir = new File( "src" ); - final File tarFile = new File( "target/output/src.tar" ); + File createTarFile() throws Exception { + final File srcDir = new File("src"); + final File tarFile = new File("target/output/src.tar"); TarArchiver tarArchiver = getPosixTarArchiver(); - tarArchiver.setDestFile( tarFile ); - tarArchiver.addDirectory( srcDir, null, FileUtils.getDefaultExcludes() ); - FileUtils.removePath( tarFile.getPath() ); + tarArchiver.setDestFile(tarFile); + tarArchiver.addDirectory(srcDir, null, FileUtils.getDefaultExcludes()); + FileUtils.removePath(tarFile.getPath()); tarArchiver.createArchive(); return tarFile; } - File createTarfile2( File tarFile ) - throws Exception - { - final File tarFile2 = new File( "target/output/src2.tar" ); + File createTarfile2(File tarFile) throws Exception { + final File tarFile2 = new File("target/output/src2.tar"); TarArchiver tarArchiver2 = getPosixTarArchiver(); - tarArchiver2.setDestFile( tarFile2 ); - tarArchiver2.addArchivedFileSet( tarFile, "prfx/" ); - FileUtils.removePath( tarFile2.getPath() ); + tarArchiver2.setDestFile(tarFile2); + tarArchiver2.addArchivedFileSet(tarFile, "prfx/"); + FileUtils.removePath(tarFile2.getPath()); tarArchiver2.createArchive(); return tarFile2; } - TarFile newTarFile( File tarFile ) - { - return new TarFile( tarFile ); + TarFile newTarFile(File tarFile) { + return new TarFile(tarFile); } - } - private class GZipTarHandler - extends TarHandler - { + private class GZipTarHandler extends TarHandler { @Override - File createTarFile() - throws Exception - { + File createTarFile() throws Exception { File file = super.createTarFile(); - File compressedFile = new File( file.getPath() + ".gz" ); + File compressedFile = new File(file.getPath() + ".gz"); Compressor compressor = new GZipCompressor(); - compressor.setSource( createResource( file, file.getName() ) ); - compressor.setDestFile( compressedFile ); + compressor.setSource(createResource(file, file.getName())); + compressor.setDestFile(compressedFile); compressor.compress(); compressor.close(); return compressedFile; } @Override - TarFile newTarFile( File tarFile ) - { - return new GZipTarFile( tarFile ); + TarFile newTarFile(File tarFile) { + return new GZipTarFile(tarFile); } - } - private class BZip2TarHandler - extends TarHandler - { + private class BZip2TarHandler extends TarHandler { @Override - File createTarFile() - throws Exception - { + File createTarFile() throws Exception { File file = super.createTarFile(); - File compressedFile = new File( file.getPath() + ".bz2" ); + File compressedFile = new File(file.getPath() + ".bz2"); Compressor compressor = new BZip2Compressor(); - compressor.setSource( createResource( file ) ); - compressor.setDestFile( compressedFile ); + compressor.setSource(createResource(file)); + compressor.setDestFile(compressedFile); compressor.compress(); compressor.close(); return compressedFile; } @Override - TarFile newTarFile( File tarFile ) - { - return new BZip2TarFile( tarFile ); + TarFile newTarFile(File tarFile) { + return new BZip2TarFile(tarFile); } - } @Test - public void testUncompressedResourceCollection() - throws Exception - { - testCreateResourceCollection( new TarHandler() ); + public void testUncompressedResourceCollection() throws Exception { + testCreateResourceCollection(new TarHandler()); } @Test - public void testGzipCompressedResourceCollection() - throws Exception - { - testCreateResourceCollection( new GZipTarHandler() ); + public void testGzipCompressedResourceCollection() throws Exception { + testCreateResourceCollection(new GZipTarHandler()); } @Test - public void testGzipFIleHandleLeak() - throws Exception - { + public void testGzipFIleHandleLeak() throws Exception { GZipTarHandler tarHandler = new GZipTarHandler(); final File tarFile = tarHandler.createTarFile(); - final File tarFile2 = tarHandler.createTarfile2( tarFile ); - final TarFile cmp1 = tarHandler.newTarFile( tarFile ); - final TarFile cmp2 = new TarFile( tarFile2 ); - ArchiveFileComparator.forEachTarArchiveEntry( cmp1, ze1 -> assertNotNull( ze1.getName() ) ); + final File tarFile2 = tarHandler.createTarfile2(tarFile); + final TarFile cmp1 = tarHandler.newTarFile(tarFile); + final TarFile cmp2 = new TarFile(tarFile2); + ArchiveFileComparator.forEachTarArchiveEntry(cmp1, ze1 -> assertNotNull(ze1.getName())); cmp1.close(); cmp2.close(); - } @Test - public void testBzip2CompressedResourceCollection() - throws Exception - { - testCreateResourceCollection( new BZip2TarHandler() ); + public void testBzip2CompressedResourceCollection() throws Exception { + testCreateResourceCollection(new BZip2TarHandler()); } @Test - public void testTarFileNotClosingInputStream() - throws Exception - { + public void testTarFileNotClosingInputStream() throws Exception { // Supposedly not closing the stream according to yjp. TarHandler tarHandler = new BZip2TarHandler(); final File fileName = tarHandler.createTarFile(); - final TarFile tarFile = tarHandler.newTarFile( fileName ); + final TarFile tarFile = tarHandler.newTarFile(fileName); tarFile.getEntries(); tarFile.close(); } - private void testCreateResourceCollection( TarHandler tarHandler ) - throws Exception - { + private void testCreateResourceCollection(TarHandler tarHandler) throws Exception { final File tarFile = tarHandler.createTarFile(); - final File tarFile2 = tarHandler.createTarfile2( tarFile ); - final TarFile cmp1 = tarHandler.newTarFile( tarFile ); - final TarFile cmp2 = new TarFile( tarFile2 ); - ArchiveFileComparator.assertTarEquals( cmp1, cmp2, "prfx/" ); + final File tarFile2 = tarHandler.createTarfile2(tarFile); + final TarFile cmp1 = tarHandler.newTarFile(tarFile); + final TarFile cmp2 = new TarFile(tarFile2); + ArchiveFileComparator.assertTarEquals(cmp1, cmp2, "prfx/"); cmp1.close(); cmp2.close(); } @Test - public void testSymlinkArchivedFileSet() - throws Exception - { - final File tarFile = getTestFile( "src/test/resources/symlinks/symlinks.tar" ); - final File tarFile2 = getTestFile( "target/output/pasymlinks-archivedFileset.tar" ); + public void testSymlinkArchivedFileSet() throws Exception { + final File tarFile = getTestFile("src/test/resources/symlinks/symlinks.tar"); + final File tarFile2 = getTestFile("target/output/pasymlinks-archivedFileset.tar"); final TarArchiver tarArchiver = getPosixTarArchiver(); - tarArchiver.setDestFile( tarFile2 ); - DefaultArchivedFileSet archivedFileSet = DefaultArchivedFileSet.archivedFileSet( tarFile ); - archivedFileSet.setUsingDefaultExcludes( false ); - tarArchiver.addArchivedFileSet( archivedFileSet ); + tarArchiver.setDestFile(tarFile2); + DefaultArchivedFileSet archivedFileSet = DefaultArchivedFileSet.archivedFileSet(tarFile); + archivedFileSet.setUsingDefaultExcludes(false); + tarArchiver.addArchivedFileSet(archivedFileSet); tarArchiver.createArchive(); - final TarFile cmp1 = new TarFile( tarFile ); - final TarFile cmp2 = new TarFile( tarFile2 ); - ArchiveFileComparator.assertTarEquals( cmp1, cmp2, "" ); + final TarFile cmp1 = new TarFile(tarFile); + final TarFile cmp2 = new TarFile(tarFile2); + ArchiveFileComparator.assertTarEquals(cmp1, cmp2, ""); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiverTest.java index 7bd2c8a62..f2eaa9c39 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarBZip2UnArchiverTest.java @@ -24,6 +24,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -36,56 +37,48 @@ /** * @author Dan Tran */ -public class TarBZip2UnArchiverTest - extends TestSupport -{ +public class TarBZip2UnArchiverTest extends TestSupport { @Test - public void testExtract() - throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + public void testExtract() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); String fileName1 = "TarBZip2UnArchiverTest1.txt"; String fileName2 = "TarBZip2UnArchiverTest2.txt"; - File file1InTar = getTestFile( "target/output/" + fileName1 ); - File file2InTar = getTestFile( "target/output/" + fileName2 ); + File file1InTar = getTestFile("target/output/" + fileName1); + File file2InTar = getTestFile("target/output/" + fileName2); file1InTar.delete(); file2InTar.delete(); - File testBZip2File = getTestFile( "target/output/archive.tar.bz2" ); + File testBZip2File = getTestFile("target/output/archive.tar.bz2"); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), fileName1 ); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), fileName2, 0664 ); - tarArchiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), fileName1); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), fileName2, 0664); + tarArchiver.setDestFile(getTestFile("target/output/archive.tar")); tarArchiver.createArchive(); - BZip2Archiver bzip2Archiver = (BZip2Archiver) lookup( Archiver.class, "bzip2" ); + BZip2Archiver bzip2Archiver = (BZip2Archiver) lookup(Archiver.class, "bzip2"); - bzip2Archiver.setDestFile( testBZip2File ); - bzip2Archiver.addFile( getTestFile( "target/output/archive.tar" ), "dontcare" ); + bzip2Archiver.setDestFile(testBZip2File); + bzip2Archiver.addFile(getTestFile("target/output/archive.tar"), "dontcare"); bzip2Archiver.createArchive(); - TarBZip2UnArchiver tarBZip2UnArchiver = (TarBZip2UnArchiver) lookup( UnArchiver.class, "tbz2" ); + TarBZip2UnArchiver tarBZip2UnArchiver = (TarBZip2UnArchiver) lookup(UnArchiver.class, "tbz2"); - tarBZip2UnArchiver.setDestDirectory( getTestFile( "target/output" ) ); - tarBZip2UnArchiver.setSourceFile( testBZip2File ); + tarBZip2UnArchiver.setDestDirectory(getTestFile("target/output")); + tarBZip2UnArchiver.setSourceFile(testBZip2File); tarBZip2UnArchiver.extract(); - assertTrue( file1InTar.exists() ); - assertTrue( file2InTar.exists() ); - - //makesure we place the source file back - assertEquals( testBZip2File, tarBZip2UnArchiver.getSourceFile() ); + assertTrue(file1InTar.exists()); + assertTrue(file2InTar.exists()); + // makesure we place the source file back + assertEquals(testBZip2File, tarBZip2UnArchiver.getSourceFile()); } @Test - public void testLookup() - throws Exception - { - lookup( UnArchiver.class, "tar.bz2" ); + public void testLookup() throws Exception { + lookup(UnArchiver.class, "tar.bz2"); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarFileAttributesTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarFileAttributesTest.java index d1699a17a..76155c444 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarFileAttributesTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarFileAttributesTest.java @@ -5,6 +5,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -20,217 +21,199 @@ import static org.junit.jupiter.api.Assertions.assertEquals; -@SuppressWarnings( "ResultOfMethodCallIgnored" ) -public class TarFileAttributesTest - extends TestSupport -{ +@SuppressWarnings("ResultOfMethodCallIgnored") +public class TarFileAttributesTest extends TestSupport { @TempDir private Path tempDir; @Override @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); - System.out.println( "Octal 0660 is decimal " + 0660 ); - System.out.println( "Octal 0644 is decimal " + 0644 ); - System.out.println( "Octal 0440 is decimal " + 0440 ); + System.out.println("Octal 0660 is decimal " + 0660); + System.out.println("Octal 0644 is decimal " + 0644); + System.out.println("Octal 0440 is decimal " + 0440); } - private void printTestHeader() - { + private void printTestHeader() { StackTraceElement e = new Throwable().getStackTrace()[1]; - System.out.println( "\n\nRunning: " + e.getMethodName() + "\n\n" ); + System.out.println("\n\nRunning: " + e.getMethodName() + "\n\n"); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testUseAttributesFromTarArchiveInputInTarArchiverOutput() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testUseAttributesFromTarArchiveInputInTarArchiverOutput() throws Exception { printTestHeader(); - File tempFile = Files.createTempFile( tempDir, "tar-file-attributes.", ".tmp" ).toFile(); + File tempFile = + Files.createTempFile(tempDir, "tar-file-attributes.", ".tmp").toFile(); - try ( Writer writer = Files.newBufferedWriter( tempFile.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(tempFile.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } AttributeUtils.chmod(tempFile, 0440); TarArchiver tarArchiver = getPosixCompliantTarArchiver(); - File tempTarFile = Files.createTempFile( tempDir, "tar-file.", ".tar" ).toFile(); + File tempTarFile = Files.createTempFile(tempDir, "tar-file.", ".tar").toFile(); - tarArchiver.setDestFile( tempTarFile ); - tarArchiver.addFile( tempFile, tempFile.getName(), 0660 ); + tarArchiver.setDestFile(tempTarFile); + tarArchiver.addFile(tempFile, tempFile.getName(), 0660); tarArchiver.createArchive(); TarArchiver tarArchiver2 = getPosixCompliantTarArchiver(); - File tempTarFile2 = Files.createTempFile( tempDir, "tar-file.", ".tar" ).toFile(); + File tempTarFile2 = Files.createTempFile(tempDir, "tar-file.", ".tar").toFile(); - tarArchiver2.setDestFile( tempTarFile2 ); + tarArchiver2.setDestFile(tempTarFile2); - DefaultArchivedFileSet afs = new DefaultArchivedFileSet( tempTarFile ); + DefaultArchivedFileSet afs = new DefaultArchivedFileSet(tempTarFile); - System.out.println( "Adding tar archive to new archiver: " + tempTarFile ); - tarArchiver2.addArchivedFileSet( afs ); + System.out.println("Adding tar archive to new archiver: " + tempTarFile); + tarArchiver2.addArchivedFileSet(afs); tarArchiver2.createArchive(); // Cut from here, and feed it into a new tar archiver...then unarchive THAT. - TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup( UnArchiver.class, "tar" ); + TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar"); - File tempTarDir = Files.createTempDirectory( tempDir, "tar-test." ).toFile(); + File tempTarDir = Files.createTempDirectory(tempDir, "tar-test.").toFile(); - tarUnArchiver.setDestDirectory( tempTarDir ); - tarUnArchiver.setSourceFile( tempTarFile2 ); + tarUnArchiver.setDestDirectory(tempTarDir); + tarUnArchiver.setSourceFile(tempTarFile2); tarUnArchiver.extract(); PlexusIoResourceAttributes fileAttributes = - PlexusIoResourceAttributeUtils.getFileAttributes( new File( tempTarDir, tempFile.getName() ) ); - - assertEquals( 0660, fileAttributes.getOctalMode() ); + PlexusIoResourceAttributeUtils.getFileAttributes(new File(tempTarDir, tempFile.getName())); + assertEquals(0660, fileAttributes.getOctalMode()); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testUseDetectedFileAttributes() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testUseDetectedFileAttributes() throws Exception { printTestHeader(); - File tempFile = Files.createTempFile( tempDir, "tar-file-attributes.", ".tmp" ).toFile(); + File tempFile = + Files.createTempFile(tempDir, "tar-file-attributes.", ".tmp").toFile(); - try ( Writer writer = Files.newBufferedWriter( tempFile.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(tempFile.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } AttributeUtils.chmod(tempFile, 0440); - PlexusIoResourceAttributes fileAttributes = PlexusIoResourceAttributeUtils.getFileAttributes( tempFile ); + PlexusIoResourceAttributes fileAttributes = PlexusIoResourceAttributeUtils.getFileAttributes(tempFile); - assertEquals( 0440, fileAttributes.getOctalMode() ); + assertEquals(0440, fileAttributes.getOctalMode()); TarArchiver tarArchiver = getPosixCompliantTarArchiver(); - File tempTarFile = Files.createTempFile( tempDir, "tar-file.", ".tar" ).toFile(); + File tempTarFile = Files.createTempFile(tempDir, "tar-file.", ".tar").toFile(); - tarArchiver.setDestFile( tempTarFile ); - tarArchiver.addFile( tempFile, tempFile.getName() ); + tarArchiver.setDestFile(tempTarFile); + tarArchiver.addFile(tempFile, tempFile.getName()); tarArchiver.createArchive(); - TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup( UnArchiver.class, "tar" ); + TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar"); - File tempTarDir = Files.createTempDirectory( tempDir, "tar-test." ).toFile(); + File tempTarDir = Files.createTempDirectory(tempDir, "tar-test.").toFile(); - tarUnArchiver.setDestDirectory( tempTarDir ); - tarUnArchiver.setSourceFile( tempTarFile ); + tarUnArchiver.setDestDirectory(tempTarDir); + tarUnArchiver.setSourceFile(tempTarFile); tarUnArchiver.extract(); - fileAttributes = PlexusIoResourceAttributeUtils.getFileAttributes( new File( tempTarDir, tempFile.getName() ) ); + fileAttributes = PlexusIoResourceAttributeUtils.getFileAttributes(new File(tempTarDir, tempFile.getName())); - assertEquals( 0440, fileAttributes.getOctalMode() ); + assertEquals(0440, fileAttributes.getOctalMode()); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testOverrideDetectedFileAttributes() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testOverrideDetectedFileAttributes() throws Exception { printTestHeader(); - File tempFile = Files.createTempFile( tempDir, "tar-file-attributes.", ".tmp" ).toFile(); + File tempFile = + Files.createTempFile(tempDir, "tar-file-attributes.", ".tmp").toFile(); - try ( Writer writer = Files.newBufferedWriter( tempFile.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(tempFile.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } AttributeUtils.chmod(tempFile, 0440); TarArchiver tarArchiver = getPosixCompliantTarArchiver(); - File tempTarFile = Files.createTempFile( tempDir, "tar-file.", ".tar" ).toFile(); + File tempTarFile = Files.createTempFile(tempDir, "tar-file.", ".tar").toFile(); - tarArchiver.setDestFile( tempTarFile ); - tarArchiver.addFile( tempFile, tempFile.getName(), 0660 ); + tarArchiver.setDestFile(tempTarFile); + tarArchiver.addFile(tempFile, tempFile.getName(), 0660); tarArchiver.createArchive(); - TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup( UnArchiver.class, "tar" ); + TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar"); - File tempTarDir = Files.createTempDirectory( tempDir, "tar-test." ).toFile(); + File tempTarDir = Files.createTempDirectory(tempDir, "tar-test.").toFile(); - tarUnArchiver.setDestDirectory( tempTarDir ); - tarUnArchiver.setSourceFile( tempTarFile ); + tarUnArchiver.setDestDirectory(tempTarDir); + tarUnArchiver.setSourceFile(tempTarFile); tarUnArchiver.extract(); PlexusIoResourceAttributes fileAttributes = - PlexusIoResourceAttributeUtils.getFileAttributes( new File( tempTarDir, tempFile.getName() ) ); - - assertEquals( 0660, fileAttributes.getOctalMode() ); + PlexusIoResourceAttributeUtils.getFileAttributes(new File(tempTarDir, tempFile.getName())); + assertEquals(0660, fileAttributes.getOctalMode()); } - private TarArchiver getPosixCompliantTarArchiver() throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + private TarArchiver getPosixCompliantTarArchiver() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); return tarArchiver; } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testOverrideDetectedFileAttributesUsingFileMode() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testOverrideDetectedFileAttributesUsingFileMode() throws Exception { printTestHeader(); - File tempFile = Files.createTempFile( tempDir, "tar-file-attributes.", ".tmp" ).toFile(); + File tempFile = + Files.createTempFile(tempDir, "tar-file-attributes.", ".tmp").toFile(); - try ( Writer writer = Files.newBufferedWriter( tempFile.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(tempFile.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } AttributeUtils.chmod(tempFile, 0440); TarArchiver tarArchiver = getPosixCompliantTarArchiver(); - File tempTarFile = Files.createTempFile( tempDir, "tar-file.", ".tar" ).toFile(); + File tempTarFile = Files.createTempFile(tempDir, "tar-file.", ".tar").toFile(); - tarArchiver.setDestFile( tempTarFile ); - tarArchiver.setFileMode( 0660 ); - tarArchiver.addFile( tempFile, tempFile.getName() ); + tarArchiver.setDestFile(tempTarFile); + tarArchiver.setFileMode(0660); + tarArchiver.addFile(tempFile, tempFile.getName()); tarArchiver.createArchive(); - TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup( UnArchiver.class, "tar" ); + TarUnArchiver tarUnArchiver = (TarUnArchiver) lookup(UnArchiver.class, "tar"); - File tempTarDir = Files.createTempDirectory( tempDir, "tar-test." ).toFile(); + File tempTarDir = Files.createTempDirectory(tempDir, "tar-test.").toFile(); - tarUnArchiver.setDestDirectory( tempTarDir ); - tarUnArchiver.setSourceFile( tempTarFile ); + tarUnArchiver.setDestDirectory(tempTarDir); + tarUnArchiver.setSourceFile(tempTarFile); tarUnArchiver.extract(); PlexusIoResourceAttributes fileAttributes = - PlexusIoResourceAttributeUtils.getFileAttributes( new File( tempTarDir, tempFile.getName() ) ); - - assertEquals( 0660, fileAttributes.getOctalMode() ); + PlexusIoResourceAttributeUtils.getFileAttributes(new File(tempTarDir, tempFile.getName())); + assertEquals(0660, fileAttributes.getOctalMode()); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarFileTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarFileTest.java index 83a522751..bebce92c0 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarFileTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarFileTest.java @@ -6,6 +6,7 @@ import java.nio.file.Files; import java.util.Arrays; import java.util.Enumeration; + import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; @@ -22,114 +23,88 @@ /** * Test case for {@link TarFile}. */ -public class TarFileTest - extends TestSupport -{ - - private interface TarFileCreator - { +public class TarFileTest extends TestSupport { - TarFile newTarFile( File file ) throws IOException; + private interface TarFileCreator { + TarFile newTarFile(File file) throws IOException; } /** * Test for the uncompressed tar file, {@link TarFile}. */ @Test - public void testTarFile() throws Exception - { - testTarFile( null, null, new TarFileCreator() - { + public void testTarFile() throws Exception { + testTarFile(null, null, new TarFileCreator() { @Override - public TarFile newTarFile( File file ) - throws IOException - { - return new TarFile( file ); + public TarFile newTarFile(File file) throws IOException { + return new TarFile(file); } - - } ); + }); } /** * Test for the gzip compressed tar file, {@link GZipTarFile}. */ @Test - public void testGZipTarFile() throws Exception - { + public void testGZipTarFile() throws Exception { final GZipCompressor compressor = new GZipCompressor(); - testTarFile( compressor, ".gz", new TarFileCreator() - { + testTarFile(compressor, ".gz", new TarFileCreator() { @Override - public TarFile newTarFile( File file ) - throws IOException - { - return new GZipTarFile( file ); + public TarFile newTarFile(File file) throws IOException { + return new GZipTarFile(file); } - - } ); + }); } /** * Test for the bzip2 compressed tar file, {@link BZip2TarFile}. */ @Test - public void testBZip2TarFile() throws Exception - { + public void testBZip2TarFile() throws Exception { final BZip2Compressor compressor = new BZip2Compressor(); - testTarFile( compressor, ".bz2", new TarFileCreator() - { + testTarFile(compressor, ".bz2", new TarFileCreator() { @Override - public TarFile newTarFile( File file ) - throws IOException - { - return new BZip2TarFile( file ); + public TarFile newTarFile(File file) throws IOException { + return new BZip2TarFile(file); } - - } ); + }); } - private void testTarFile( Compressor compressor, String extension, - TarFileCreator tarFileCreator ) - throws Exception - { - File file = new File( "target/output/TarFileTest.tar" ); - final TarArchiver archiver = (TarArchiver) lookup( Archiver.class, "tar" ); - archiver.setLongfile( TarLongFileMode.posix ); - archiver.setDestFile( file ); - archiver.addDirectory( new File( "src" ) ); - FileUtils.removePath( file.getPath() ); + private void testTarFile(Compressor compressor, String extension, TarFileCreator tarFileCreator) throws Exception { + File file = new File("target/output/TarFileTest.tar"); + final TarArchiver archiver = (TarArchiver) lookup(Archiver.class, "tar"); + archiver.setLongfile(TarLongFileMode.posix); + archiver.setDestFile(file); + archiver.addDirectory(new File("src")); + FileUtils.removePath(file.getPath()); archiver.createArchive(); - if ( compressor != null ) - { - final File compressedFile = new File( file.getPath() + extension ); - compressor.setSource( createResource( file, file.getName() ) ); - compressor.setDestFile( compressedFile ); + if (compressor != null) { + final File compressedFile = new File(file.getPath() + extension); + compressor.setSource(createResource(file, file.getName())); + compressor.setDestFile(compressedFile); compressor.compress(); compressor.close(); file = compressedFile; } - final TarFile tarFile = tarFileCreator.newTarFile( file ); + final TarFile tarFile = tarFileCreator.newTarFile(file); - for ( Enumeration en = tarFile.getEntries(); en.hasMoreElements(); ) - { + for (Enumeration en = tarFile.getEntries(); en.hasMoreElements(); ) { final TarArchiveEntry te = (TarArchiveEntry) en.nextElement(); - if ( te.isDirectory() || te.isSymbolicLink() ) - { + if (te.isDirectory() || te.isSymbolicLink()) { continue; } - final File teFile = new File( "src", te.getName() ); - final InputStream teStream = tarFile.getInputStream( te ); - final InputStream fileStream = Files.newInputStream( teFile.toPath() ); - assertTrue( Arrays.equals( IOUtil.toByteArray( teStream ), IOUtil.toByteArray( fileStream ) ) ); + final File teFile = new File("src", te.getName()); + final InputStream teStream = tarFile.getInputStream(te); + final InputStream fileStream = Files.newInputStream(teFile.toPath()); + assertTrue(Arrays.equals(IOUtil.toByteArray(teStream), IOUtil.toByteArray(fileStream))); teStream.close(); fileStream.close(); } tarFile.close(); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiverTest.java index 88d8ae5bf..02b887bf7 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarGZipUnArchiverTest.java @@ -24,6 +24,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -36,54 +37,46 @@ /** * @author Dan Tran */ -public class TarGZipUnArchiverTest - extends TestSupport -{ +public class TarGZipUnArchiverTest extends TestSupport { @Test - public void testExtract() - throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + public void testExtract() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); String fileName1 = "TarGZipUnArchiverTest1.txt"; String fileName2 = "TarGZipUnArchiverTest2.txt"; - File file1InTar = getTestFile( "target/output/" + fileName1 ); - File file2InTar = getTestFile( "target/output/" + fileName2 ); + File file1InTar = getTestFile("target/output/" + fileName1); + File file2InTar = getTestFile("target/output/" + fileName2); file1InTar.delete(); file2InTar.delete(); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), fileName1 ); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), fileName2, 0664 ); - tarArchiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), fileName1); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), fileName2, 0664); + tarArchiver.setDestFile(getTestFile("target/output/archive.tar")); tarArchiver.createArchive(); - GZipArchiver gzipArchiver = (GZipArchiver) lookup( Archiver.class, "gzip" ); + GZipArchiver gzipArchiver = (GZipArchiver) lookup(Archiver.class, "gzip"); - File testGZipFile = getTestFile( "target/output/archive.tar.gz" ); - gzipArchiver.setDestFile( testGZipFile ); - gzipArchiver.addFile( getTestFile( "target/output/archive.tar" ), "dontcare" ); + File testGZipFile = getTestFile("target/output/archive.tar.gz"); + gzipArchiver.setDestFile(testGZipFile); + gzipArchiver.addFile(getTestFile("target/output/archive.tar"), "dontcare"); gzipArchiver.createArchive(); - TarGZipUnArchiver tarGZipUnArchiver = (TarGZipUnArchiver) lookup( UnArchiver.class, "tgz" ); - tarGZipUnArchiver.setDestDirectory( getTestFile( "target/output" ) ); - tarGZipUnArchiver.setSourceFile( testGZipFile ); + TarGZipUnArchiver tarGZipUnArchiver = (TarGZipUnArchiver) lookup(UnArchiver.class, "tgz"); + tarGZipUnArchiver.setDestDirectory(getTestFile("target/output")); + tarGZipUnArchiver.setSourceFile(testGZipFile); tarGZipUnArchiver.extract(); - assertTrue( file1InTar.exists() ); - assertTrue( file2InTar.exists() ); - - //make sure we place the source file back - assertEquals( testGZipFile, tarGZipUnArchiver.getSourceFile() ); + assertTrue(file1InTar.exists()); + assertTrue(file2InTar.exists()); + // make sure we place the source file back + assertEquals(testGZipFile, tarGZipUnArchiver.getSourceFile()); } @Test - public void testLookup() - throws Exception - { - lookup( UnArchiver.class, "tar.gz" ); + public void testLookup() throws Exception { + lookup(UnArchiver.class, "tar.gz"); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarRoundTripTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarRoundTripTest.java index 69dcfd4e8..8365236dc 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarRoundTripTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarRoundTripTest.java @@ -19,6 +19,7 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; + import org.apache.commons.compress.archivers.tar.TarArchiveEntry; import org.apache.commons.compress.archivers.tar.TarArchiveInputStream; import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream; @@ -31,36 +32,31 @@ /** * from org.apache.ant.tools.tar.TarRoundTripTest v1.6 */ -public class TarRoundTripTest -{ +public class TarRoundTripTest { - private static final String LONG_NAME = - "this/path/name/contains/more/than/one/hundred/characters/in/order/" + private static final String LONG_NAME = "this/path/name/contains/more/than/one/hundred/characters/in/order/" + "to/test/the/GNU/long/file/name/capability/round/tripped"; /** * test round-tripping long (GNU) entries */ @Test - public void testLongRoundTripping() - throws IOException - { - TarArchiveEntry original = new TarArchiveEntry( LONG_NAME ); - assertTrue( LONG_NAME.length() > 100, "over 100 chars" ); - assertEquals( LONG_NAME, original.getName(), "original name" ); + public void testLongRoundTripping() throws IOException { + TarArchiveEntry original = new TarArchiveEntry(LONG_NAME); + assertTrue(LONG_NAME.length() > 100, "over 100 chars"); + assertEquals(LONG_NAME, original.getName(), "original name"); ByteArrayOutputStream buff = new ByteArrayOutputStream(); - TarArchiveOutputStream tos = new TarArchiveOutputStream( buff ); - tos.setLongFileMode( TarArchiveOutputStream.LONGFILE_GNU ); - tos.putArchiveEntry( original ); + TarArchiveOutputStream tos = new TarArchiveOutputStream(buff); + tos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU); + tos.putArchiveEntry(original); tos.closeArchiveEntry(); tos.close(); - TarArchiveInputStream tis = new TarArchiveInputStream( new ByteArrayInputStream( buff.toByteArray() ) ); + TarArchiveInputStream tis = new TarArchiveInputStream(new ByteArrayInputStream(buff.toByteArray())); TarArchiveEntry tripped = tis.getNextTarEntry(); - assertEquals( LONG_NAME, tripped.getName(), "round-tripped name" ); - assertNull( tis.getNextEntry(), "no more entries" ); + assertEquals(LONG_NAME, tripped.getName(), "round-tripped name"); + assertNull(tis.getNextEntry(), "no more entries"); tis.close(); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiverTest.java index 27cc008d1..4b9338573 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarSnappyUnArchiverTest.java @@ -24,6 +24,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -36,53 +37,46 @@ /** * Snappy tar archives */ -public class TarSnappyUnArchiverTest - extends TestSupport -{ +public class TarSnappyUnArchiverTest extends TestSupport { @Test - public void testExtract() - throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + public void testExtract() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); String fileName1 = "TarSnappyUnArchiverTest1.txt"; String fileName2 = "TarSnappyUnArchiverTest2.txt"; - File file1InTar = getTestFile( "target/output/" + fileName1 ); - File file2InTar = getTestFile( "target/output/" + fileName2 ); + File file1InTar = getTestFile("target/output/" + fileName1); + File file2InTar = getTestFile("target/output/" + fileName2); file1InTar.delete(); file2InTar.delete(); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), fileName1 ); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), fileName2, 0664 ); - tarArchiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), fileName1); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), fileName2, 0664); + tarArchiver.setDestFile(getTestFile("target/output/archive.tar")); tarArchiver.createArchive(); - SnappyArchiver snappyArchiver = (SnappyArchiver) lookup( Archiver.class, "snappy" ); + SnappyArchiver snappyArchiver = (SnappyArchiver) lookup(Archiver.class, "snappy"); - File testSnappyFile = getTestFile( "target/output/archive.tar.snappy" ); - snappyArchiver.setDestFile( testSnappyFile ); - snappyArchiver.addFile( getTestFile( "target/output/archive.tar" ), "dontcare" ); + File testSnappyFile = getTestFile("target/output/archive.tar.snappy"); + snappyArchiver.setDestFile(testSnappyFile); + snappyArchiver.addFile(getTestFile("target/output/archive.tar"), "dontcare"); snappyArchiver.createArchive(); - TarSnappyUnArchiver tarSnappyUnArchiver = (TarSnappyUnArchiver) lookup( UnArchiver.class, "tar.snappy" ); - tarSnappyUnArchiver.setDestDirectory( getTestFile( "target/output" ) ); - tarSnappyUnArchiver.setSourceFile( testSnappyFile ); + TarSnappyUnArchiver tarSnappyUnArchiver = (TarSnappyUnArchiver) lookup(UnArchiver.class, "tar.snappy"); + tarSnappyUnArchiver.setDestDirectory(getTestFile("target/output")); + tarSnappyUnArchiver.setSourceFile(testSnappyFile); tarSnappyUnArchiver.extract(); - assertTrue( file1InTar.exists() ); - assertTrue( file2InTar.exists() ); + assertTrue(file1InTar.exists()); + assertTrue(file2InTar.exists()); - //make sure we place the source file back - assertEquals( testSnappyFile, tarSnappyUnArchiver.getSourceFile() ); + // make sure we place the source file back + assertEquals(testSnappyFile, tarSnappyUnArchiver.getSourceFile()); } @Test - public void testLookup() - throws Exception - { - lookup( UnArchiver.class, "tar.snappy" ); + public void testLookup() throws Exception { + lookup(UnArchiver.class, "tar.snappy"); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarUnArchiverTest.java index 2a53667f6..c69aa4839 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarUnArchiverTest.java @@ -1,6 +1,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; import org.codehaus.plexus.components.io.fileselectors.FileSelector; @@ -13,104 +14,55 @@ /** * @author Viktor Sadovnikov */ -public class TarUnArchiverTest extends TestSupport -{ +public class TarUnArchiverTest extends TestSupport { - private void runUnarchiver( FileSelector[] selectors, boolean[] results ) - throws Exception - { + private void runUnarchiver(FileSelector[] selectors, boolean[] results) throws Exception { String s = "target/tar-unarchiver-tests"; - File testJar = new File( getBasedir(), "src/test/jars/test.tar.gz" ); - - File outputDirectory = new File( getBasedir(), s ); + File testJar = new File(getBasedir(), "src/test/jars/test.tar.gz"); - TarUnArchiver tarUn = (TarUnArchiver) lookup( UnArchiver.class, "tar.gz" ); - tarUn.setSourceFile( testJar ); - tarUn.setDestDirectory( outputDirectory ); - tarUn.setFileSelectors( selectors ); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + TarUnArchiver tarUn = (TarUnArchiver) lookup(UnArchiver.class, "tar.gz"); + tarUn.setSourceFile(testJar); + tarUn.setDestDirectory(outputDirectory); + tarUn.setFileSelectors(selectors); - tarUn.extract( testJar.getAbsolutePath(), outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - assertFileExistance( s, "/resources/artifactId/test.properties", results[0] ); - assertFileExistance( s, "/resources/artifactId/directory/test.properties", results[1] ); - assertFileExistance( s, "/META-INF/MANIFEST.MF", results[2] ); + tarUn.extract(testJar.getAbsolutePath(), outputDirectory); + assertFileExistance(s, "/resources/artifactId/test.properties", results[0]); + assertFileExistance(s, "/resources/artifactId/directory/test.properties", results[1]); + assertFileExistance(s, "/META-INF/MANIFEST.MF", results[2]); } - private void assertFileExistance( String s, String file, boolean exists ) - { - File f0 = new File( getBasedir(), s + file ); - assertEquals( exists, f0.exists(), - String.format( "Did %s expect to find %s file", exists ? "" : "NOT", f0.getAbsoluteFile() ) ); + private void assertFileExistance(String s, String file, boolean exists) { + File f0 = new File(getBasedir(), s + file); + assertEquals( + exists, + f0.exists(), + String.format("Did %s expect to find %s file", exists ? "" : "NOT", f0.getAbsoluteFile())); } @Test - public void testExtractingADirectory() throws Exception - { - runUnarchiver( null, - new boolean[] - { - true, true, true - } ); - + public void testExtractingADirectory() throws Exception { + runUnarchiver(null, new boolean[] {true, true, true}); } @Test - public void testSelectors() - throws Exception - { + public void testSelectors() throws Exception { IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); - runUnarchiver( new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, true, true - } ); - - fileSelector.setExcludes( new String[] - { - "**/test.properties" - } ); - runUnarchiver( new FileSelector[] - { - fileSelector - }, - new boolean[] - { - false, false, true - } ); - - fileSelector.setIncludes( new String[] - { - "**/test.properties" - } ); - fileSelector.setExcludes( null ); - runUnarchiver( new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, true, false - } ); - - fileSelector.setExcludes( new String[] - { - "resources/artifactId/directory/test.properties" - } ); - runUnarchiver( new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, false, false - } ); - } + runUnarchiver(new FileSelector[] {fileSelector}, new boolean[] {true, true, true}); + fileSelector.setExcludes(new String[] {"**/test.properties"}); + runUnarchiver(new FileSelector[] {fileSelector}, new boolean[] {false, false, true}); + + fileSelector.setIncludes(new String[] {"**/test.properties"}); + fileSelector.setExcludes(null); + runUnarchiver(new FileSelector[] {fileSelector}, new boolean[] {true, true, false}); + + fileSelector.setExcludes(new String[] {"resources/artifactId/directory/test.properties"}); + runUnarchiver(new FileSelector[] {fileSelector}, new boolean[] {true, false, false}); + } } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarXzUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarXzUnArchiverTest.java index ec0b0fb12..f6432a768 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarXzUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarXzUnArchiverTest.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -32,62 +33,56 @@ * @author philip.lourandos * @since 3.3 */ -public class TarXzUnArchiverTest extends TestSupport -{ +public class TarXzUnArchiverTest extends TestSupport { @Test - public void testExtract() - throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + public void testExtract() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); String fileName1 = "TarBZip2UnArchiverTest1.txt"; String fileName2 = "TarBZip2UnArchiverTest2.txt"; - File file1InTar = getTestFile( "target/output/" + fileName1 ); - File file2InTar = getTestFile( "target/output/" + fileName2 ); + File file1InTar = getTestFile("target/output/" + fileName1); + File file2InTar = getTestFile("target/output/" + fileName2); file1InTar.delete(); file2InTar.delete(); - assertFalse( file1InTar.exists() ); - assertFalse( file2InTar.exists() ); + assertFalse(file1InTar.exists()); + assertFalse(file2InTar.exists()); - File testXZFile = getTestFile( "target/output/archive.tar.xz" ); - if ( testXZFile.exists() ) - { - FileUtils.fileDelete( testXZFile.getPath() ); + File testXZFile = getTestFile("target/output/archive.tar.xz"); + if (testXZFile.exists()) { + FileUtils.fileDelete(testXZFile.getPath()); } - assertFalse( testXZFile.exists() ); + assertFalse(testXZFile.exists()); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), fileName1 ); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), fileName2, 0664 ); - tarArchiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), fileName1); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), fileName2, 0664); + tarArchiver.setDestFile(getTestFile("target/output/archive.tar")); tarArchiver.createArchive(); - XZArchiver xzArchiver = (XZArchiver) lookup( Archiver.class, "xz" ); + XZArchiver xzArchiver = (XZArchiver) lookup(Archiver.class, "xz"); - xzArchiver.setDestFile( testXZFile ); - xzArchiver.addFile( getTestFile( "target/output/archive.tar" ), "dontcare" ); + xzArchiver.setDestFile(testXZFile); + xzArchiver.addFile(getTestFile("target/output/archive.tar"), "dontcare"); xzArchiver.createArchive(); - assertTrue( testXZFile.exists() ); + assertTrue(testXZFile.exists()); - TarXZUnArchiver tarXZUnArchiver = (TarXZUnArchiver) lookup( UnArchiver.class, "tar.xz" ); + TarXZUnArchiver tarXZUnArchiver = (TarXZUnArchiver) lookup(UnArchiver.class, "tar.xz"); - tarXZUnArchiver.setDestDirectory( getTestFile( "target/output" ) ); - tarXZUnArchiver.setSourceFile( testXZFile ); + tarXZUnArchiver.setDestDirectory(getTestFile("target/output")); + tarXZUnArchiver.setSourceFile(testXZFile); tarXZUnArchiver.extract(); - assertTrue( file1InTar.exists() ); - assertTrue( file2InTar.exists() ); + assertTrue(file1InTar.exists()); + assertTrue(file2InTar.exists()); - assertEquals( testXZFile, tarXZUnArchiver.getSourceFile() ); + assertEquals(testXZFile, tarXZUnArchiver.getSourceFile()); } @Test - public void testLookup() throws Exception - { - assertNotNull( lookup( UnArchiver.class, "tar.xz" ) ); + public void testLookup() throws Exception { + assertNotNull(lookup(UnArchiver.class, "tar.xz")); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiverTest.java index 061449647..563192f3f 100644 --- a/src/test/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/tar/TarZstdUnArchiverTest.java @@ -16,6 +16,7 @@ package org.codehaus.plexus.archiver.tar; import java.io.File; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.archiver.UnArchiver; @@ -28,62 +29,56 @@ import static org.junit.jupiter.api.Assertions.assertNotNull; import static org.junit.jupiter.api.Assertions.assertTrue; -public class TarZstdUnArchiverTest extends TestSupport -{ +public class TarZstdUnArchiverTest extends TestSupport { @Test - public void testExtract() - throws Exception - { - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); - tarArchiver.setLongfile( TarLongFileMode.posix ); + public void testExtract() throws Exception { + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); + tarArchiver.setLongfile(TarLongFileMode.posix); String fileName1 = "TarBZip2UnArchiverTest1.txt"; String fileName2 = "TarBZip2UnArchiverTest2.txt"; - File file1InTar = getTestFile( "target/output/" + fileName1 ); - File file2InTar = getTestFile( "target/output/" + fileName2 ); + File file1InTar = getTestFile("target/output/" + fileName1); + File file2InTar = getTestFile("target/output/" + fileName2); file1InTar.delete(); file2InTar.delete(); - assertFalse( file1InTar.exists() ); - assertFalse( file2InTar.exists() ); + assertFalse(file1InTar.exists()); + assertFalse(file2InTar.exists()); - File testZstdFile = getTestFile( "target/output/archive.tar.zst" ); - if ( testZstdFile.exists() ) - { - FileUtils.fileDelete( testZstdFile.getPath() ); + File testZstdFile = getTestFile("target/output/archive.tar.zst"); + if (testZstdFile.exists()) { + FileUtils.fileDelete(testZstdFile.getPath()); } - assertFalse( testZstdFile.exists() ); + assertFalse(testZstdFile.exists()); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), fileName1 ); - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), fileName2, 0664 ); - tarArchiver.setDestFile( getTestFile( "target/output/archive.tar" ) ); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), fileName1); + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), fileName2, 0664); + tarArchiver.setDestFile(getTestFile("target/output/archive.tar")); tarArchiver.createArchive(); - ZstdArchiver zstdArchiver = (ZstdArchiver) lookup( Archiver.class, "zst" ); + ZstdArchiver zstdArchiver = (ZstdArchiver) lookup(Archiver.class, "zst"); - zstdArchiver.setDestFile( testZstdFile ); - zstdArchiver.addFile( getTestFile( "target/output/archive.tar" ), "dontcare" ); + zstdArchiver.setDestFile(testZstdFile); + zstdArchiver.addFile(getTestFile("target/output/archive.tar"), "dontcare"); zstdArchiver.createArchive(); - assertTrue( testZstdFile.exists() ); + assertTrue(testZstdFile.exists()); - TarZstdUnArchiver tarZstdUnArchiver = (TarZstdUnArchiver) lookup( UnArchiver.class, "tar.zst" ); + TarZstdUnArchiver tarZstdUnArchiver = (TarZstdUnArchiver) lookup(UnArchiver.class, "tar.zst"); - tarZstdUnArchiver.setDestDirectory( getTestFile( "target/output" ) ); - tarZstdUnArchiver.setSourceFile( testZstdFile ); + tarZstdUnArchiver.setDestDirectory(getTestFile("target/output")); + tarZstdUnArchiver.setSourceFile(testZstdFile); tarZstdUnArchiver.extract(); - assertTrue( file1InTar.exists() ); - assertTrue( file2InTar.exists() ); + assertTrue(file1InTar.exists()); + assertTrue(file2InTar.exists()); - assertEquals( testZstdFile, tarZstdUnArchiver.getSourceFile() ); + assertEquals(testZstdFile, tarZstdUnArchiver.getSourceFile()); } @Test - public void testLookup() throws Exception - { - assertNotNull( lookup( UnArchiver.class, "tar.zst" ) ); + public void testLookup() throws Exception { + assertNotNull(lookup(UnArchiver.class, "tar.zst")); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtilsTest.java b/src/test/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtilsTest.java index a3543a92f..2d305e806 100644 --- a/src/test/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/util/ArchiveEntryUtilsTest.java @@ -5,6 +5,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.util.HashMap; + import org.codehaus.plexus.components.io.attributes.FileAttributes; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.condition.DisabledOnOs; @@ -14,41 +15,35 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -public class ArchiveEntryUtilsTest -{ +public class ArchiveEntryUtilsTest { @TempDir private Path tempDir; @Test - @DisabledOnOs( OS.WINDOWS ) - public void testChmodForFileWithDollarPLXCOMP164() throws Exception - { - File temp = Files.createTempFile( tempDir, "A$A", "BB$" ).toFile(); - ArchiveEntryUtils.chmod( temp, 0770 ); - assert0770( temp ); + @DisabledOnOs(OS.WINDOWS) + public void testChmodForFileWithDollarPLXCOMP164() throws Exception { + File temp = Files.createTempFile(tempDir, "A$A", "BB$").toFile(); + ArchiveEntryUtils.chmod(temp, 0770); + assert0770(temp); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testChmodWithJava7() throws Exception - { - File temp = Files.createTempFile( tempDir, "D$D", "BB$" ).toFile(); - ArchiveEntryUtils.chmod( temp, 0770 ); - assert0770( temp ); + @DisabledOnOs(OS.WINDOWS) + public void testChmodWithJava7() throws Exception { + File temp = Files.createTempFile(tempDir, "D$D", "BB$").toFile(); + ArchiveEntryUtils.chmod(temp, 0770); + assert0770(temp); } - private void assert0770( File temp ) throws IOException - { - FileAttributes j7 = new FileAttributes( temp, new HashMap(), - new HashMap() ); - assertTrue( j7.isGroupExecutable() ); - assertTrue( j7.isGroupReadable() ); - assertTrue( j7.isGroupWritable() ); - - assertFalse( j7.isWorldExecutable() ); - assertFalse( j7.isWorldReadable() ); - assertFalse( j7.isWorldWritable() ); - } + private void assert0770(File temp) throws IOException { + FileAttributes j7 = new FileAttributes(temp, new HashMap(), new HashMap()); + assertTrue(j7.isGroupExecutable()); + assertTrue(j7.isGroupReadable()); + assertTrue(j7.isGroupWritable()); + assertFalse(j7.isWorldExecutable()); + assertFalse(j7.isWorldReadable()); + assertFalse(j7.isWorldWritable()); + } } diff --git a/src/test/java/org/codehaus/plexus/archiver/util/DefaultFileSetTest.java b/src/test/java/org/codehaus/plexus/archiver/util/DefaultFileSetTest.java index c917e1b44..2eadc6d71 100644 --- a/src/test/java/org/codehaus/plexus/archiver/util/DefaultFileSetTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/util/DefaultFileSetTest.java @@ -1,6 +1,7 @@ package org.codehaus.plexus.archiver.util; import java.io.File; + import org.junit.jupiter.api.Test; import static org.codehaus.plexus.archiver.util.DefaultFileSet.fileSet; @@ -9,25 +10,17 @@ /** * @author Kristian Rosenvold */ -public class DefaultFileSetTest -{ +public class DefaultFileSetTest { @Test - public void testCreate() - { - final String[] includes = - { - "zz", "yy" - }; - final String[] exc = - { - "xx1", "xx2" - }; - final DefaultFileSet dfs = fileSet( new File( "foo" ) ).prefixed( "pfx" ).include( includes ).exclude( exc ); - assertEquals( "foo", dfs.getDirectory().getName() ); - assertEquals( "pfx", dfs.getPrefix() ); - assertEquals( "zz", dfs.getIncludes()[0] ); - assertEquals( "xx1", dfs.getExcludes()[0] ); + public void testCreate() { + final String[] includes = {"zz", "yy"}; + final String[] exc = {"xx1", "xx2"}; + final DefaultFileSet dfs = + fileSet(new File("foo")).prefixed("pfx").include(includes).exclude(exc); + assertEquals("foo", dfs.getDirectory().getName()); + assertEquals("pfx", dfs.getPrefix()); + assertEquals("zz", dfs.getIncludes()[0]); + assertEquals("xx1", dfs.getExcludes()[0]); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/util/FilePermissionUtilsTest.java b/src/test/java/org/codehaus/plexus/archiver/util/FilePermissionUtilsTest.java index 5eb10aa34..a12a6a208 100644 --- a/src/test/java/org/codehaus/plexus/archiver/util/FilePermissionUtilsTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/util/FilePermissionUtilsTest.java @@ -28,57 +28,50 @@ /** * @author Olivier Lamy */ -public class FilePermissionUtilsTest -{ +public class FilePermissionUtilsTest { - Logger getLogger() - { - return LoggerFactory.getLogger( "foo" ); + Logger getLogger() { + return LoggerFactory.getLogger("foo"); } @Test - public void testOnlyWritableOnlyUser() throws Exception - { - FilePermission fp = FilePermissionUtils.getFilePermissionFromMode( "200", getLogger() ); - assertTrue( fp.isWritable() ); - assertTrue( fp.isOwnerOnlyWritable() ); - assertFalse( fp.isExecutable() ); - assertTrue( fp.isOwnerOnlyExecutable() ); - assertFalse( fp.isReadable() ); + public void testOnlyWritableOnlyUser() throws Exception { + FilePermission fp = FilePermissionUtils.getFilePermissionFromMode("200", getLogger()); + assertTrue(fp.isWritable()); + assertTrue(fp.isOwnerOnlyWritable()); + assertFalse(fp.isExecutable()); + assertTrue(fp.isOwnerOnlyExecutable()); + assertFalse(fp.isReadable()); } @Test - public void testExecAndRead() - { - FilePermission fp = FilePermissionUtils.getFilePermissionFromMode( "500", getLogger() ); - assertFalse( fp.isWritable() ); - assertTrue( fp.isOwnerOnlyWritable() ); - assertTrue( fp.isExecutable() ); - assertTrue( fp.isOwnerOnlyExecutable() ); - assertTrue( fp.isReadable() ); + public void testExecAndRead() { + FilePermission fp = FilePermissionUtils.getFilePermissionFromMode("500", getLogger()); + assertFalse(fp.isWritable()); + assertTrue(fp.isOwnerOnlyWritable()); + assertTrue(fp.isExecutable()); + assertTrue(fp.isOwnerOnlyExecutable()); + assertTrue(fp.isReadable()); } @Test - public void testAllUser() - { - FilePermission fp = FilePermissionUtils.getFilePermissionFromMode( "700", getLogger() ); - assertTrue( fp.isWritable() ); - assertTrue( fp.isOwnerOnlyWritable() ); - assertTrue( fp.isExecutable() ); - assertTrue( fp.isOwnerOnlyExecutable() ); - assertTrue( fp.isReadable() ); + public void testAllUser() { + FilePermission fp = FilePermissionUtils.getFilePermissionFromMode("700", getLogger()); + assertTrue(fp.isWritable()); + assertTrue(fp.isOwnerOnlyWritable()); + assertTrue(fp.isExecutable()); + assertTrue(fp.isOwnerOnlyExecutable()); + assertTrue(fp.isReadable()); } @Test - public void testAllAllUser() - { - FilePermission fp = FilePermissionUtils.getFilePermissionFromMode( "707", getLogger() ); - assertTrue( fp.isWritable() ); - assertFalse( fp.isOwnerOnlyWritable() ); - assertTrue( fp.isExecutable() ); - assertFalse( fp.isOwnerOnlyExecutable() ); - assertTrue( fp.isReadable() ); - assertFalse( fp.isOwnerOnlyReadable() ); + public void testAllAllUser() { + FilePermission fp = FilePermissionUtils.getFilePermissionFromMode("707", getLogger()); + assertTrue(fp.isWritable()); + assertFalse(fp.isOwnerOnlyWritable()); + assertTrue(fp.isExecutable()); + assertFalse(fp.isOwnerOnlyExecutable()); + assertTrue(fp.isReadable()); + assertFalse(fp.isOwnerOnlyReadable()); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/war/WarArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/war/WarArchiverTest.java index 36f8a9ca2..8597f43a7 100644 --- a/src/test/java/org/codehaus/plexus/archiver/war/WarArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/war/WarArchiverTest.java @@ -1,6 +1,7 @@ package org.codehaus.plexus.archiver.war; import java.io.File; + import org.codehaus.plexus.archiver.ArchiveEntry; import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.ResourceIterator; @@ -15,79 +16,65 @@ /** * @author Kristian Rosenvold */ -public class WarArchiverTest - extends TestSupport -{ +public class WarArchiverTest extends TestSupport { private final int expected = 8; @Test - public void testReAddingPlatformSpecificEncoding() - throws Exception - { - WarArchiver archiver = (WarArchiver) lookup( Archiver.class, "war" ); - archiver.setDestFile( new File( getTargetRarFolder(), "test.war" ) ); + public void testReAddingPlatformSpecificEncoding() throws Exception { + WarArchiver archiver = (WarArchiver) lookup(Archiver.class, "war"); + archiver.setDestFile(new File(getTargetRarFolder(), "test.war")); - File dummyContent = getTestFile( "src/test/resources/folders" ); - archiver.addDirectory( dummyContent ); + File dummyContent = getTestFile("src/test/resources/folders"); + archiver.addDirectory(dummyContent); - assertEquals( expected, count( archiver.getResources() ) ); // I wonder what the first entry is + assertEquals(expected, count(archiver.getResources())); // I wonder what the first entry is - File file = getTestFile( "src/test/resources/folders/WEB-INF/web.xml" ); - archiver.setWebxml( file ); + File file = getTestFile("src/test/resources/folders/WEB-INF/web.xml"); + archiver.setWebxml(file); - assertEquals( expected, count( archiver.getResources() ) ); // I wonder what the first entry is + assertEquals(expected, count(archiver.getResources())); // I wonder what the first entry is archiver.createArchive(); - assertTrue( new File( getTargetRarFolder(), "test.war" ).exists() ); + assertTrue(new File(getTargetRarFolder(), "test.war").exists()); } @Test - public void testInfiniteRecursion() - throws Exception - { - WarArchiver archiver = (WarArchiver) lookup( Archiver.class, "war" ); - archiver.setDestFile( new File( getTargetRarFolder(), "test.war" ) ); + public void testInfiniteRecursion() throws Exception { + WarArchiver archiver = (WarArchiver) lookup(Archiver.class, "war"); + archiver.setDestFile(new File(getTargetRarFolder(), "test.war")); // Easy to produce infinite recursion if you just add existing files again and again - File dummyContent = getTestFile( "src/test/resources/folders", "File.txt" ); + File dummyContent = getTestFile("src/test/resources/folders", "File.txt"); final int INFINITY = 10; - for ( int i = 0; i < INFINITY; i++ ) - { - archiver.addFile( dummyContent, "testZ" ); + for (int i = 0; i < INFINITY; i++) { + archiver.addFile(dummyContent, "testZ"); } - assertEquals( 1, count( archiver.getResources() ) ); // I wonder what the first entry is + assertEquals(1, count(archiver.getResources())); // I wonder what the first entry is } - public File getTargetRarFolder() - { - return new File( getBasedir(), "/target/wartest/" ); + public File getTargetRarFolder() { + return new File(getBasedir(), "/target/wartest/"); } @Override @BeforeEach - public void setUp() - throws Exception - { + public void setUp() throws Exception { super.setUp(); // clean output directory and re create it - if ( getTargetRarFolder().exists() ) - { - FileUtils.deleteDirectory( getTargetRarFolder() ); + if (getTargetRarFolder().exists()) { + FileUtils.deleteDirectory(getTargetRarFolder()); } } - private int count( ResourceIterator resourceIterator ) - { + private int count(ResourceIterator resourceIterator) { int i = 0; - while ( resourceIterator.hasNext() ) - { + while (resourceIterator.hasNext()) { i++; ArchiveEntry next = resourceIterator.next(); - System.out.print( next.getMode() ); - System.out.println( next.getName() ); + System.out.print(next.getMode()); + System.out.println(next.getName()); } return i; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/xz/XzArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/xz/XzArchiverTest.java index eb916d959..47a7793e7 100644 --- a/src/test/java/org/codehaus/plexus/archiver/xz/XzArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/xz/XzArchiverTest.java @@ -16,12 +16,12 @@ package org.codehaus.plexus.archiver.xz; import java.io.File; -import java.io.FileInputStream; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.BasePlexusArchiverTest; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; @@ -39,79 +39,69 @@ * @author philip.lourandos * @since 3.3 */ -public class XzArchiverTest extends BasePlexusArchiverTest -{ +public class XzArchiverTest extends BasePlexusArchiverTest { @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.addDirectory( getTestFile( "src" ) ); - zipArchiver.setDestFile( getTestFile( "target/output/archiveForxz.zip" ) ); + public void testCreateArchive() throws Exception { + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.addDirectory(getTestFile("src")); + zipArchiver.setDestFile(getTestFile("target/output/archiveForxz.zip")); zipArchiver.createArchive(); - XZArchiver archiver = (XZArchiver) lookup( Archiver.class, "xz" ); - String[] inputFiles = new String[ 1 ]; + XZArchiver archiver = (XZArchiver) lookup(Archiver.class, "xz"); + String[] inputFiles = new String[1]; inputFiles[0] = "archiveForxz.zip"; - File targetOutputFile = getTestFile( "target/output/archive.xz" ); - if ( targetOutputFile.exists() ) - { - FileUtils.fileDelete( targetOutputFile.getPath() ); + File targetOutputFile = getTestFile("target/output/archive.xz"); + if (targetOutputFile.exists()) { + FileUtils.fileDelete(targetOutputFile.getPath()); } - assertFalse( targetOutputFile.exists() ); + assertFalse(targetOutputFile.exists()); - archiver.addDirectory( getTestFile( "target/output" ), inputFiles, null ); - archiver.setDestFile( targetOutputFile ); + archiver.addDirectory(getTestFile("target/output"), inputFiles, null); + archiver.setDestFile(targetOutputFile); archiver.createArchive(); - assertTrue( targetOutputFile.exists() ); + assertTrue(targetOutputFile.exists()); } @Test - public void testCreateEmptyArchive() - throws Exception - { - XZArchiver archiver = (XZArchiver) lookup( Archiver.class, "xz" ); - archiver.setDestFile( getTestFile( "target/output/empty.xz" ) ); - try - { + public void testCreateEmptyArchive() throws Exception { + XZArchiver archiver = (XZArchiver) lookup(Archiver.class, "xz"); + archiver.setDestFile(getTestFile("target/output/empty.xz")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testCreateResourceCollection() throws Exception - { - final File pomFile = new File( "pom.xml" ); - final File xzFile = new File( "target/output/pom.xml.xz" ); - XZArchiver xzArchiver = (XZArchiver) lookup( Archiver.class, "xz" ); - xzArchiver.setDestFile( xzFile ); - xzArchiver.addFile( pomFile, "pom.xml" ); - FileUtils.removePath( xzFile.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File pomFile = new File("pom.xml"); + final File xzFile = new File("target/output/pom.xml.xz"); + XZArchiver xzArchiver = (XZArchiver) lookup(Archiver.class, "xz"); + xzArchiver.setDestFile(xzFile); + xzArchiver.addFile(pomFile, "pom.xml"); + FileUtils.removePath(xzFile.getPath()); xzArchiver.createArchive(); - System.out.println( "Created: " + xzFile.getAbsolutePath() ); + System.out.println("Created: " + xzFile.getAbsolutePath()); - final File zipFile = new File( "target/output/pomxz.zip" ); - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.setDestFile( zipFile ); - zipArchiver.addArchivedFileSet( xzFile, "prfx/" ); - FileUtils.removePath( zipFile.getPath() ); + final File zipFile = new File("target/output/pomxz.zip"); + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.setDestFile(zipFile); + zipArchiver.addArchivedFileSet(xzFile, "prfx/"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final ZipFile juZipFile = new ZipFile( zipFile ); - final ZipEntry zipEntry = juZipFile.getEntry( "prfx/target/output/pom.xml" ); - final InputStream archivePom = juZipFile.getInputStream( zipEntry ); - final InputStream pom = Files.newInputStream( pomFile.toPath() ); + final ZipFile juZipFile = new ZipFile(zipFile); + final ZipEntry zipEntry = juZipFile.getEntry("prfx/target/output/pom.xml"); + final InputStream archivePom = juZipFile.getInputStream(zipEntry); + final InputStream pom = Files.newInputStream(pomFile.toPath()); - assertTrue( Arrays.equals( IOUtil.toByteArray( pom ), IOUtil.toByteArray( archivePom ) ) ); + assertTrue(Arrays.equals(IOUtil.toByteArray(pom), IOUtil.toByteArray(archivePom))); archivePom.close(); pom.close(); juZipFile.close(); @@ -124,34 +114,32 @@ public void testCreateResourceCollection() throws Exception * @throws Exception */ @Test - public void testXzIsForcedBehaviour() throws Exception - { - XZArchiver xzArchiver = (XZArchiver) createArchiver( "xz" ); + public void testXzIsForcedBehaviour() throws Exception { + XZArchiver xzArchiver = (XZArchiver) createArchiver("xz"); - assertTrue( xzArchiver.isSupportingForced() ); + assertTrue(xzArchiver.isSupportingForced()); xzArchiver.createArchive(); final long creationTime = xzArchiver.getDestFile().lastModified(); - waitUntilNewTimestamp( xzArchiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(xzArchiver.getDestFile(), creationTime); - xzArchiver = (XZArchiver) createArchiver( "xz" ); + xzArchiver = (XZArchiver) createArchiver("xz"); - xzArchiver.setForced( true ); + xzArchiver.setForced(true); xzArchiver.createArchive(); final long firstRunTime = xzArchiver.getDestFile().lastModified(); - assertFalse( creationTime == firstRunTime ); + assertFalse(creationTime == firstRunTime); - xzArchiver = (XZArchiver) createArchiver( "xz" ); + xzArchiver = (XZArchiver) createArchiver("xz"); - xzArchiver.setForced( false ); + xzArchiver.setForced(false); xzArchiver.createArchive(); final long secondRunTime = xzArchiver.getDestFile().lastModified(); - assertEquals( firstRunTime, secondRunTime ); + assertEquals(firstRunTime, secondRunTime); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/ArchiveFileComparator.java b/src/test/java/org/codehaus/plexus/archiver/zip/ArchiveFileComparator.java index c79b86b45..e8d85b6dd 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/ArchiveFileComparator.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/ArchiveFileComparator.java @@ -1,7 +1,5 @@ package org.codehaus.plexus.archiver.zip; -import static org.assertj.core.api.Assertions.assertThat; - import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -17,56 +15,45 @@ import org.apache.commons.compress.archivers.zip.ZipFile; import org.codehaus.plexus.archiver.tar.TarFile; +import static org.assertj.core.api.Assertions.assertThat; + /** * A utility class, which allows to compare archive files. */ -public final class ArchiveFileComparator -{ +public final class ArchiveFileComparator { /** * Iterate over the TarFile and run the consumer on each TarArchiveEntry. */ - public static void forEachTarArchiveEntry( TarFile file, Consumer consumer ) - { - try - { - Collections.list( file.getEntries() ) - .stream() - .filter( entry -> !entry.isDirectory() ) - .map( TarArchiveEntry.class::cast ) - .forEachOrdered( consumer ); - } - catch ( IOException ioe ) - { - throw new UncheckedIOException( ioe ); + public static void forEachTarArchiveEntry(TarFile file, Consumer consumer) { + try { + Collections.list(file.getEntries()).stream() + .filter(entry -> !entry.isDirectory()) + .map(TarArchiveEntry.class::cast) + .forEachOrdered(consumer); + } catch (IOException ioe) { + throw new UncheckedIOException(ioe); } } - private static void forEachZipArchiveEntry( ZipFile file, Consumer consumer ) - { - Collections.list( file.getEntries() ) - .stream() - .filter( entry -> !entry.isDirectory() ) - .forEachOrdered( consumer ); + private static void forEachZipArchiveEntry(ZipFile file, Consumer consumer) { + Collections.list(file.getEntries()).stream() + .filter(entry -> !entry.isDirectory()) + .forEachOrdered(consumer); } /** * Creates a map with the archive files contents. The map keys are the names of file entries in the archive file. * The map values are the respective archive entries. */ - private static Map getFileEntries( TarFile file ) - { - try - { - return Collections.list( file.getEntries() ) - .stream() - .filter( entry -> !entry.isDirectory() ) - .map( TarArchiveEntry.class::cast ) - .collect( Collectors.toMap( ArchiveEntry::getName, Function.identity() ) ); - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); + private static Map getFileEntries(TarFile file) { + try { + return Collections.list(file.getEntries()).stream() + .filter(entry -> !entry.isDirectory()) + .map(TarArchiveEntry.class::cast) + .collect(Collectors.toMap(ArchiveEntry::getName, Function.identity())); + } catch (IOException e) { + throw new UncheckedIOException(e); } } @@ -74,129 +61,108 @@ private static Map getFileEntries( TarFile file ) * Creates a map with the archive files contents. The map keys are the names of file entries in the archive file. * The map values are the respective archive entries. */ - private static Map getFileEntries( ZipFile file ) - { - return Collections.list( file.getEntries() ) - .stream() - .filter( entry -> !entry.isDirectory() ) - .collect( Collectors.toMap( ArchiveEntry::getName, Function.identity() ) ); + private static Map getFileEntries(ZipFile file) { + return Collections.list(file.getEntries()).stream() + .filter(entry -> !entry.isDirectory()) + .collect(Collectors.toMap(ArchiveEntry::getName, Function.identity())); } - private static void assertTarEquals( TarFile file1, TarArchiveEntry entry1, - TarFile file2, TarArchiveEntry entry2 ) - { - assertThat( entry1.isDirectory() ).isEqualTo( entry2.isDirectory() ); - assertThat( entry1.isSymbolicLink() ).isEqualTo( entry2.isSymbolicLink() ); - assertThat( entry1.getLastModifiedDate() ).isEqualTo( entry2.getLastModifiedDate() ); - assertThat( entry1.getUserName() ).isEqualTo( entry2.getUserName() ); - assertThat( entry1.getGroupName() ).isEqualTo( entry2.getGroupName() ); - - try ( InputStream is1 = file1.getInputStream( entry1 ); - InputStream is2 = file2.getInputStream( entry2 ); ) - { - assertThat( is1 ) - .as( "Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName() ) - .hasSameContentAs( is2 ); - } - catch ( IOException ioe ) - { - throw new UncheckedIOException( ioe ); + private static void assertTarEquals(TarFile file1, TarArchiveEntry entry1, TarFile file2, TarArchiveEntry entry2) { + assertThat(entry1.isDirectory()).isEqualTo(entry2.isDirectory()); + assertThat(entry1.isSymbolicLink()).isEqualTo(entry2.isSymbolicLink()); + assertThat(entry1.getLastModifiedDate()).isEqualTo(entry2.getLastModifiedDate()); + assertThat(entry1.getUserName()).isEqualTo(entry2.getUserName()); + assertThat(entry1.getGroupName()).isEqualTo(entry2.getGroupName()); + + try (InputStream is1 = file1.getInputStream(entry1); + InputStream is2 = file2.getInputStream(entry2); ) { + assertThat(is1) + .as("Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName()) + .hasSameContentAs(is2); + } catch (IOException ioe) { + throw new UncheckedIOException(ioe); } } - private static void assertTarZipEquals( TarFile file1, TarArchiveEntry entry1, - ZipFile file2, ZipArchiveEntry entry2 ) - { - assertThat( entry1.isDirectory() ).isEqualTo( entry2.isDirectory() ); - assertThat( entry1.getLastModifiedDate() ).isCloseTo( entry2.getLastModifiedDate(), 1000 ); - - try ( InputStream is1 = file1.getInputStream( entry1 ); - InputStream is2 = file2.getInputStream( entry2 ); ) - { - assertThat( is1 ) - .as( "Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName() ) - .hasSameContentAs( is2 ); - } - catch ( IOException ioe ) - { - throw new UncheckedIOException( ioe ); + private static void assertTarZipEquals( + TarFile file1, TarArchiveEntry entry1, ZipFile file2, ZipArchiveEntry entry2) { + assertThat(entry1.isDirectory()).isEqualTo(entry2.isDirectory()); + assertThat(entry1.getLastModifiedDate()).isCloseTo(entry2.getLastModifiedDate(), 1000); + + try (InputStream is1 = file1.getInputStream(entry1); + InputStream is2 = file2.getInputStream(entry2); ) { + assertThat(is1) + .as("Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName()) + .hasSameContentAs(is2); + } catch (IOException ioe) { + throw new UncheckedIOException(ioe); } } - private static void assertZipEquals( ZipFile file1, ZipArchiveEntry entry1, - ZipFile file2, ZipArchiveEntry entry2 ) - { - assertThat( entry1.isDirectory() ).isEqualTo( entry2.isDirectory() ); - assertThat( entry1.isUnixSymlink() ).isEqualTo( entry2.isUnixSymlink() ); - assertThat( entry1.getLastModifiedDate() ).isCloseTo( entry2.getLastModifiedDate(), 1000 ); - - try ( InputStream is1 = file1.getInputStream( entry1 ); - InputStream is2 = file2.getInputStream( entry2 ); ) - { - assertThat( is1 ) - .as( "Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName() ) - .hasSameContentAs( is2 ); - } - catch ( IOException ioe ) - { - throw new UncheckedIOException( ioe ); + private static void assertZipEquals(ZipFile file1, ZipArchiveEntry entry1, ZipFile file2, ZipArchiveEntry entry2) { + assertThat(entry1.isDirectory()).isEqualTo(entry2.isDirectory()); + assertThat(entry1.isUnixSymlink()).isEqualTo(entry2.isUnixSymlink()); + assertThat(entry1.getLastModifiedDate()).isCloseTo(entry2.getLastModifiedDate(), 1000); + + try (InputStream is1 = file1.getInputStream(entry1); + InputStream is2 = file2.getInputStream(entry2); ) { + assertThat(is1) + .as("Content of the entry1 %s is different of entry2 %s", entry1.getName(), entry2.getName()) + .hasSameContentAs(is2); + } catch (IOException ioe) { + throw new UncheckedIOException(ioe); } } /** * Called to compare the given Tar files. */ - public static void assertTarEquals( final TarFile file1, final TarFile file2, final String prefix ) - { - final Map map2 = getFileEntries( file2 ); - - forEachTarArchiveEntry( file1, entry1 -> { - final String name2 = getNameWithPrefix( prefix, entry1.getName() ); - final TarArchiveEntry entry2 = map2.remove( name2 ); - assertThat( entry2 ).as( "Missing entry in file2: %s", name2 ).isNotNull(); - assertTarEquals( file1, entry1, file2, entry2 ); - } ); - - assertThat( map2 ).as("Found additional entries in file2").isEmpty(); + public static void assertTarEquals(final TarFile file1, final TarFile file2, final String prefix) { + final Map map2 = getFileEntries(file2); + + forEachTarArchiveEntry(file1, entry1 -> { + final String name2 = getNameWithPrefix(prefix, entry1.getName()); + final TarArchiveEntry entry2 = map2.remove(name2); + assertThat(entry2).as("Missing entry in file2: %s", name2).isNotNull(); + assertTarEquals(file1, entry1, file2, entry2); + }); + + assertThat(map2).as("Found additional entries in file2").isEmpty(); } /** * Called to compare the given Tar and Zip files. */ - public static void assertTarZipEquals( final TarFile file1, final ZipFile file2, final String prefix ) - { - final Map map2 = getFileEntries( file2 ); - - forEachTarArchiveEntry( file1, entry1 -> { - final String name2 = getNameWithPrefix( prefix, entry1.getName() ); - final ZipArchiveEntry entry2 = map2.remove( name2 ); - assertThat( entry2 ).as( "Missing entry in file2: %s", name2 ).isNotNull(); - assertTarZipEquals( file1, entry1, file2, entry2 ); - } ); - - assertThat( map2 ).as("Found additional entries in file2").isEmpty(); + public static void assertTarZipEquals(final TarFile file1, final ZipFile file2, final String prefix) { + final Map map2 = getFileEntries(file2); + + forEachTarArchiveEntry(file1, entry1 -> { + final String name2 = getNameWithPrefix(prefix, entry1.getName()); + final ZipArchiveEntry entry2 = map2.remove(name2); + assertThat(entry2).as("Missing entry in file2: %s", name2).isNotNull(); + assertTarZipEquals(file1, entry1, file2, entry2); + }); + + assertThat(map2).as("Found additional entries in file2").isEmpty(); } /** * Called to compare the given Zip files. */ - public static void assertZipEquals( final ZipFile file1, final ZipFile file2, final String prefix ) - { - final Map map2 = getFileEntries( file2 ); - - forEachZipArchiveEntry( file1, entry1 -> { - final String name2 = getNameWithPrefix( prefix, entry1.getName() ); - final ZipArchiveEntry entry2 = map2.remove( name2 ); - assertThat( entry2 ).as( "Missing entry in file2: %s", name2 ).isNotNull(); - assertZipEquals( file1, entry1, file2, entry2 ); - } ); - - assertThat( map2 ).as("Found additional entries in file2").isEmpty(); + public static void assertZipEquals(final ZipFile file1, final ZipFile file2, final String prefix) { + final Map map2 = getFileEntries(file2); + + forEachZipArchiveEntry(file1, entry1 -> { + final String name2 = getNameWithPrefix(prefix, entry1.getName()); + final ZipArchiveEntry entry2 = map2.remove(name2); + assertThat(entry2).as("Missing entry in file2: %s", name2).isNotNull(); + assertZipEquals(file1, entry1, file2, entry2); + }); + + assertThat(map2).as("Found additional entries in file2").isEmpty(); } - private static String getNameWithPrefix( String prefix, String name ) - { + private static String getNameWithPrefix(String prefix, String name) { return prefix == null ? name : prefix + name; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreatorTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreatorTest.java index 7b310256d..9a8bf2fe9 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreatorTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/ConcurrentJarCreatorTest.java @@ -14,129 +14,109 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; -@SuppressWarnings( "ResultOfMethodCallIgnored" ) +@SuppressWarnings("ResultOfMethodCallIgnored") @Disabled -public class ConcurrentJarCreatorTest -{ +public class ConcurrentJarCreatorTest { @Test - public void concurrent() - throws Exception - { - File home = new File( System.getProperty( "user.home" ) ); - File result = new File( home, "multiStream2-parallel.zip" ); - ConcurrentJarCreator zipCreator = new ConcurrentJarCreator( Runtime.getRuntime().availableProcessors() ); - - final File file1 = new File( home, "lsrc/plexus" ); - doAddAll( file1.getPath(), zipCreator ); - - ZipArchiveOutputStream zos = createZipARchiveOutputStream( result ); - zipCreator.writeTo( zos ); + public void concurrent() throws Exception { + File home = new File(System.getProperty("user.home")); + File result = new File(home, "multiStream2-parallel.zip"); + ConcurrentJarCreator zipCreator = + new ConcurrentJarCreator(Runtime.getRuntime().availableProcessors()); + + final File file1 = new File(home, "lsrc/plexus"); + doAddAll(file1.getPath(), zipCreator); + + ZipArchiveOutputStream zos = createZipARchiveOutputStream(result); + zipCreator.writeTo(zos); zos.close(); - System.out.println( "Concurrent:" + zipCreator.getStatisticsMessage() ); + System.out.println("Concurrent:" + zipCreator.getStatisticsMessage()); } @Test - public void concurrent2() throws Exception - { + public void concurrent2() throws Exception { concurrent(); } @Test @Disabled - public void classic() - throws Exception - { + public void classic() throws Exception { long startAt = System.currentTimeMillis(); - File home = new File( System.getProperty( "user.home" ) ); - File result = new File( home, "multiStream2-classic.zip" ); + File home = new File(System.getProperty("user.home")); + File result = new File(home, "multiStream2-classic.zip"); - final File file1 = new File( home, "lsrc/plexus" ); - ZipArchiveOutputStream zos = createZipARchiveOutputStream( result ); - doAddAll( file1.getPath(), zos ); + final File file1 = new File(home, "lsrc/plexus"); + ZipArchiveOutputStream zos = createZipARchiveOutputStream(result); + doAddAll(file1.getPath(), zos); zos.close(); - System.out.println( "linear:" + ( System.currentTimeMillis() - startAt ) + "ms" ); - + System.out.println("linear:" + (System.currentTimeMillis() - startAt) + "ms"); } - private ZipArchiveOutputStream createZipARchiveOutputStream( File result ) throws IOException - { - ZipArchiveOutputStream zos = new ZipArchiveOutputStream( result ); - zos.setEncoding( "UTF-8" ); + private ZipArchiveOutputStream createZipARchiveOutputStream(File result) throws IOException { + ZipArchiveOutputStream zos = new ZipArchiveOutputStream(result); + zos.setEncoding("UTF-8"); return zos; } - private void doAddAll( String base, ConcurrentJarCreator mos ) throws IOException - { + private void doAddAll(String base, ConcurrentJarCreator mos) throws IOException { - DirectoryScanner ds = getIncludedFiles( base ); + DirectoryScanner ds = getIncludedFiles(base); - for ( String fileName : ds.getIncludedFiles() ) - { - final File file = new File( base, fileName ); - ZipArchiveEntry za = createZipArchiveEntry( file, fileName ); + for (String fileName : ds.getIncludedFiles()) { + final File file = new File(base, fileName); + ZipArchiveEntry za = createZipArchiveEntry(file, fileName); - mos.addArchiveEntry( za, () -> { - try - { - return file.isFile() ? Files.newInputStream( file.toPath() ) : null; - } - catch ( IOException e ) - { - throw new UncheckedIOException( e ); - } - }, true ); + mos.addArchiveEntry( + za, + () -> { + try { + return file.isFile() ? Files.newInputStream(file.toPath()) : null; + } catch (IOException e) { + throw new UncheckedIOException(e); + } + }, + true); } - } - private DirectoryScanner getIncludedFiles( String base ) - { + private DirectoryScanner getIncludedFiles(String base) { DirectoryScanner ds = new DirectoryScanner(); - ds.setBasedir( base ); + ds.setBasedir(base); ds.scan(); return ds; } - private void doAddAll( String base, ZipArchiveOutputStream mos ) throws IOException - { - DirectoryScanner ds = getIncludedFiles( base ); + private void doAddAll(String base, ZipArchiveOutputStream mos) throws IOException { + DirectoryScanner ds = getIncludedFiles(base); - for ( String fileName : ds.getIncludedFiles() ) - { - final File file = new File( base, fileName ); - ZipArchiveEntry za = createZipArchiveEntry( file, fileName ); + for (String fileName : ds.getIncludedFiles()) { + final File file = new File(base, fileName); + ZipArchiveEntry za = createZipArchiveEntry(file, fileName); - mos.putArchiveEntry( za ); - if ( file.isFile() ) - { - try (InputStream input = Files.newInputStream( file.toPath() )) { - IOUtils.copy( input, mos ); + mos.putArchiveEntry(za); + if (file.isFile()) { + try (InputStream input = Files.newInputStream(file.toPath())) { + IOUtils.copy(input, mos); } } mos.closeArchiveEntry(); } - } - @SuppressWarnings( "OctalInteger" ) - private ZipArchiveEntry createZipArchiveEntry( File file, String name ) - { - ZipArchiveEntry za = new ZipArchiveEntry( file, name ); - if ( file.isDirectory() ) - { - za.setMethod( ZipArchiveEntry.STORED ); - za.setSize( 0 ); - za.setUnixMode( UnixStat.DIR_FLAG | 0664 ); + @SuppressWarnings("OctalInteger") + private ZipArchiveEntry createZipArchiveEntry(File file, String name) { + ZipArchiveEntry za = new ZipArchiveEntry(file, name); + if (file.isDirectory()) { + za.setMethod(ZipArchiveEntry.STORED); + za.setSize(0); + za.setUnixMode(UnixStat.DIR_FLAG | 0664); + } else { + za.setMethod(ZipArchiveEntry.DEFLATED); + za.setSize(file.length()); + za.setUnixMode(UnixStat.FILE_FLAG | 0664); } - else - { - za.setMethod( ZipArchiveEntry.DEFLATED ); - za.setSize( file.length() ); - za.setUnixMode( UnixStat.FILE_FLAG | 0664 ); - } - za.setTime( file.lastModified() ); + za.setTime(file.lastModified()); return za; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStreamTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStreamTest.java index 62ee2fa27..9d9d88150 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStreamTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/OffloadingOutputStreamTest.java @@ -24,28 +24,19 @@ import static org.assertj.core.api.Assertions.assertThat; - -class OffloadingOutputStreamTest -{ +class OffloadingOutputStreamTest { @Test - void temporaryFileShouldBeCreated() throws IOException - { + void temporaryFileShouldBeCreated() throws IOException { File streamFile = null; - try ( OffloadingOutputStream stream = new OffloadingOutputStream( 100, "test", "test" ) ) - { - stream.write( new byte[256] ); + try (OffloadingOutputStream stream = new OffloadingOutputStream(100, "test", "test")) { + stream.write(new byte[256]); stream.close(); streamFile = stream.getFile(); - assertThat( streamFile ) - .isFile() - .hasSize( 256 ); - } - finally - { - if ( streamFile != null ) - { - Files.delete( streamFile.toPath() ); + assertThat(streamFile).isFile().hasSize(256); + } finally { + if (streamFile != null) { + Files.delete(streamFile.toPath()); } } } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollectionTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollectionTest.java index 9add4f132..d0df3bfa9 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollectionTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/PlexusArchiverZipFileResourceCollectionTest.java @@ -8,6 +8,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; + import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.components.io.functions.ResourceAttributeSupplier; import org.codehaus.plexus.components.io.resources.PlexusIoResource; @@ -16,52 +17,44 @@ import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertTrue; -public class PlexusArchiverZipFileResourceCollectionTest - extends TestSupport -{ +public class PlexusArchiverZipFileResourceCollectionTest extends TestSupport { @Test - public void testFilesWithIllegalHtmlChars() - throws Exception - { - File testZip = new File( getBasedir(), "src/test/resources/archiveWithIllegalHtmlFileName.zip" ); + public void testFilesWithIllegalHtmlChars() throws Exception { + File testZip = new File(getBasedir(), "src/test/resources/archiveWithIllegalHtmlFileName.zip"); Set seen = new HashSet<>(); - seen.add( "AFileThatNeedsHtmlEsc%3F>" ); - seen.add( "Afile<Yo>.txt" ); - seen.add( "File With Space.txt" ); - seen.add( "FileWith%.txt" ); + seen.add("AFileThatNeedsHtmlEsc%3F>"); + seen.add("Afile<Yo>.txt"); + seen.add("File With Space.txt"); + seen.add("FileWith%.txt"); PlexusArchiverZipFileResourceCollection prc = new PlexusArchiverZipFileResourceCollection(); - prc.setFile( testZip ); + prc.setFile(testZip); final Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { final PlexusIoResource next = entries.next(); - assertTrue( seen.remove( next.getName() ), next.getName() + "was not present" ); + assertTrue(seen.remove(next.getName()), next.getName() + "was not present"); final InputStream contents = next.getContents(); contents.close(); } } @Test - public void testFileModes() - throws IOException - { - File testZip = new File( getBasedir(), "src/test/resources/zeroFileMode/mixed-file-mode.zip" ); + public void testFileModes() throws IOException { + File testZip = new File(getBasedir(), "src/test/resources/zeroFileMode/mixed-file-mode.zip"); Map originalUnixModes = new HashMap<>(); - originalUnixModes.put( "platform-fat", -1 ); - originalUnixModes.put( "zero-unix-mode", 0 ); + originalUnixModes.put("platform-fat", -1); + originalUnixModes.put("zero-unix-mode", 0); // ---xrw-r-- the crazy permissions are on purpose so we don't hit some default value - originalUnixModes.put( "non-zero-unix-mode", 0164 ); + originalUnixModes.put("non-zero-unix-mode", 0164); PlexusArchiverZipFileResourceCollection prc = new PlexusArchiverZipFileResourceCollection(); - prc.setFile( testZip ); + prc.setFile(testZip); Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { PlexusIoResource entry = entries.next(); - int entryUnixMode = ( (ResourceAttributeSupplier) entry ).getAttributes().getOctalMode(); - int originalUnixMode = originalUnixModes.get( entry.getName() ); - assertEquals( originalUnixMode, entryUnixMode ); + int entryUnixMode = + ((ResourceAttributeSupplier) entry).getAttributes().getOctalMode(); + int originalUnixMode = originalUnixModes.get(entry.getName()); + assertEquals(originalUnixMode, entryUnixMode); } } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollectionTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollectionTest.java index 0988a3668..9af093641 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollectionTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/PlexusIoZipFileResourceCollectionTest.java @@ -11,6 +11,7 @@ import java.util.Iterator; import java.util.Map; import java.util.Set; + import org.apache.commons.io.IOUtils; import org.codehaus.plexus.archiver.TestSupport; import org.codehaus.plexus.components.io.functions.SymlinkDestinationSupplier; @@ -22,76 +23,62 @@ import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; -public class PlexusIoZipFileResourceCollectionTest - extends TestSupport -{ +public class PlexusIoZipFileResourceCollectionTest extends TestSupport { @Test - public void testNamelessRootFolder() - throws Exception - { + public void testNamelessRootFolder() throws Exception { PlexusIoZipFileResourceCollection resourceCollection = new PlexusIoZipFileResourceCollection(); - resourceCollection.setFile( getTestFile( "src/test/jars/namelessrootfolder.jar" ) ); + resourceCollection.setFile(getTestFile("src/test/jars/namelessrootfolder.jar")); Iterator iterator = resourceCollection.getResources(); PlexusIoURLResource entry = (PlexusIoURLResource) iterator.next(); - assertEquals( "/dummy.txt", entry.getName() ); + assertEquals("/dummy.txt", entry.getName()); final URL url = entry.getURL(); - BufferedReader d = new BufferedReader( new InputStreamReader( entry.getContents() ) ); - assertEquals( "dummy content", d.readLine() ); + BufferedReader d = new BufferedReader(new InputStreamReader(entry.getContents())); + assertEquals("dummy content", d.readLine()); } @Test - public void testDescriptionForError() - throws Exception - { + public void testDescriptionForError() throws Exception { PlexusIoZipFileResourceCollection resourceCollection = new PlexusIoZipFileResourceCollection(); - resourceCollection.setFile( getTestFile( "src/test/jars/namelessrootfolder.jar" ) ); + resourceCollection.setFile(getTestFile("src/test/jars/namelessrootfolder.jar")); Iterator iterator = resourceCollection.getResources(); PlexusIoURLResource entry = (PlexusIoURLResource) iterator.next(); final URL url = entry.getURL(); - String descriptionForError = entry.getDescriptionForError( url ); - assertTrue( descriptionForError.endsWith( "namelessrootfolder.jar!//dummy.txt" ) ); + String descriptionForError = entry.getDescriptionForError(url); + assertTrue(descriptionForError.endsWith("namelessrootfolder.jar!//dummy.txt")); } @Test - public void testFilesWithIllegalHtmlChars() - throws Exception - { - File testZip = new File( getBasedir(), "src/test/resources/bogusManifest.zip" ); + public void testFilesWithIllegalHtmlChars() throws Exception { + File testZip = new File(getBasedir(), "src/test/resources/bogusManifest.zip"); PlexusIoZipFileResourceCollection prc = new PlexusIoZipFileResourceCollection(); - prc.setFile( testZip ); + prc.setFile(testZip); final Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { final PlexusIoResource next = entries.next(); - if ( next.getName().endsWith( "MANIFEST.MF" ) ) - { + if (next.getName().endsWith("MANIFEST.MF")) { final InputStream contents1 = next.getContents(); - final String manifest = IOUtils.toString( contents1, "UTF-8" ); - assertTrue( manifest.contains( "bogs=fus" ) ); + final String manifest = IOUtils.toString(contents1, "UTF-8"); + assertTrue(manifest.contains("bogs=fus")); contents1.close(); } - } } @Test - public void testFilesThatAreNotThere() - throws Exception - { - File testZip = new File( getBasedir(), "src/test/resources/archiveWithIllegalHtmlFileName.zip" ); + public void testFilesThatAreNotThere() throws Exception { + File testZip = new File(getBasedir(), "src/test/resources/archiveWithIllegalHtmlFileName.zip"); Set seen = new HashSet<>(); - seen.add( "AFileThatNeedsHtmlEsc%3F>" ); - seen.add( "Afile<Yo>.txt" ); - seen.add( "File With Space.txt" ); - seen.add( "FileWith%.txt" ); + seen.add("AFileThatNeedsHtmlEsc%3F>"); + seen.add("Afile<Yo>.txt"); + seen.add("File With Space.txt"); + seen.add("FileWith%.txt"); PlexusIoZipFileResourceCollection prc = new PlexusIoZipFileResourceCollection(); - prc.setFile( testZip ); + prc.setFile(testZip); final Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { final PlexusIoResource next = entries.next(); - assertTrue( seen.remove( next.getName() ), next.getName() + "was not present" ); + assertTrue(seen.remove(next.getName()), next.getName() + "was not present"); final URL url = next.getURL(); final InputStream contents = next.getContents(); contents.close(); @@ -99,56 +86,47 @@ public void testFilesThatAreNotThere() } @Test - public void testSymlinkEntries() - throws Exception - { - File testZip = new File( getBasedir(), "src/test/resources/symlinks/symlinks.zip" ); + public void testSymlinkEntries() throws Exception { + File testZip = new File(getBasedir(), "src/test/resources/symlinks/symlinks.zip"); Map symLinks = new HashMap<>(); - symLinks.put( "symDir", "targetDir/" ); - symLinks.put( "symLinkToDirOnTheOutside", "../dirOnTheOutside/" ); - symLinks.put( "symLinkToTheOutside", "../onTheOutside.txt" ); - symLinks.put( "symR", "fileR.txt" ); - symLinks.put( "symW", "fileW.txt" ); - symLinks.put( "symX", "fileX.txt" ); + symLinks.put("symDir", "targetDir/"); + symLinks.put("symLinkToDirOnTheOutside", "../dirOnTheOutside/"); + symLinks.put("symLinkToTheOutside", "../onTheOutside.txt"); + symLinks.put("symR", "fileR.txt"); + symLinks.put("symW", "fileW.txt"); + symLinks.put("symX", "fileX.txt"); PlexusIoZipFileResourceCollection prc = new PlexusIoZipFileResourceCollection(); - prc.setFile( testZip ); + prc.setFile(testZip); final Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { final PlexusIoResource next = entries.next(); - String symLinkTarget = symLinks.remove( next.getName() ); - if ( symLinkTarget != null ) - { - assertTrue( next.isSymbolicLink(), next.getName() + " must be symlink" ); - assertTrue( next instanceof SymlinkDestinationSupplier ); - assertEquals( symLinkTarget, - ( (SymlinkDestinationSupplier) next ).getSymlinkDestination() ); - } - else - { - assertFalse( next.isSymbolicLink(), next.getName() + " must not be symlink" ); + String symLinkTarget = symLinks.remove(next.getName()); + if (symLinkTarget != null) { + assertTrue(next.isSymbolicLink(), next.getName() + " must be symlink"); + assertTrue(next instanceof SymlinkDestinationSupplier); + assertEquals(symLinkTarget, ((SymlinkDestinationSupplier) next).getSymlinkDestination()); + } else { + assertFalse(next.isSymbolicLink(), next.getName() + " must not be symlink"); } } - assertTrue( symLinks.isEmpty() ); + assertTrue(symLinks.isEmpty()); } @Test - public void testUnarchiveUnicodePathExtra() - throws Exception - { + public void testUnarchiveUnicodePathExtra() throws Exception { PlexusIoZipFileResourceCollection prc = new PlexusIoZipFileResourceCollection(); - prc.setFile( getTestFile( "src/test/resources/unicodePathExtra/efsclear.zip" ) ); + prc.setFile(getTestFile("src/test/resources/unicodePathExtra/efsclear.zip")); Set names = new HashSet<>(); final Iterator entries = prc.getEntries(); - while ( entries.hasNext() ) - { + while (entries.hasNext()) { final PlexusIoResource next = entries.next(); names.add(next.getName()); } // a Unicode Path extra field should only be used when its CRC matches the header file name - assertEquals( new HashSet<>( Arrays.asList( "nameonly-name", "goodextra-extra", "badextra-name" ) ), names, - "should use good extra fields but not bad ones" ); + assertEquals( + new HashSet<>(Arrays.asList("nameonly-name", "goodextra-extra", "badextra-name")), + names, + "should use good extra fields but not bad ones"); } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java index 327ec757b..fa8f3bfae 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/ZipArchiverTest.java @@ -23,6 +23,8 @@ */ package org.codehaus.plexus.archiver.zip; +import javax.annotation.Nonnull; + import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -45,8 +47,6 @@ import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; -import javax.annotation.Nonnull; - import org.apache.commons.compress.archivers.zip.ExtraFieldUtils; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipExtraField; @@ -91,528 +91,446 @@ /** * @author Emmanuel Venisse */ -@SuppressWarnings( "OctalInteger" ) -public class ZipArchiverTest - extends BasePlexusArchiverTest -{ +@SuppressWarnings("OctalInteger") +public class ZipArchiverTest extends BasePlexusArchiverTest { @TempDir private File tempDir; @Test - public void testImplicitPermissions() - throws IOException - { - File zipFile = getTestFile( "target/output/zip-with-implicit-dirmode.zip" ); - - ZipArchiver archiver = getZipArchiver( zipFile ); - - archiver.setDefaultDirectoryMode( 0777 ); - archiver.setDirectoryMode( 0641 ); - archiver.setFileMode( 0222 ); - archiver.addFile( new File( "pom.xml" ), "fizz/buzz/pom.xml" ); - archiver.setDefaultDirectoryMode( 0530 ); - archiver.setDirectoryMode( -1 ); // Not forced mode - archiver.setFileMode( 0111 ); - archiver.addFile( new File( "pom.xml" ), "fazz/bazz/pam.xml" ); + public void testImplicitPermissions() throws IOException { + File zipFile = getTestFile("target/output/zip-with-implicit-dirmode.zip"); + + ZipArchiver archiver = getZipArchiver(zipFile); + + archiver.setDefaultDirectoryMode(0777); + archiver.setDirectoryMode(0641); + archiver.setFileMode(0222); + archiver.addFile(new File("pom.xml"), "fizz/buzz/pom.xml"); + archiver.setDefaultDirectoryMode(0530); + archiver.setDirectoryMode(-1); // Not forced mode + archiver.setFileMode(0111); + archiver.addFile(new File("pom.xml"), "fazz/bazz/pam.xml"); archiver.createArchive(); - assertTrue( zipFile.exists() ); - ZipFile zf = new ZipFile( zipFile ); - ZipArchiveEntry fizz = zf.getEntry( "fizz/" ); - assertEquals( 040641, fizz.getUnixMode() ); - ZipArchiveEntry pom = zf.getEntry( "fizz/buzz/pom.xml" ); - assertEquals( 0100222, pom.getUnixMode() ); - - ZipArchiveEntry fazz = zf.getEntry( "fazz/" ); - assertEquals( 040530, fazz.getUnixMode() ); - ZipArchiveEntry pam = zf.getEntry( "fazz/bazz/pam.xml" ); - assertEquals( 0100111, pam.getUnixMode() ); + assertTrue(zipFile.exists()); + ZipFile zf = new ZipFile(zipFile); + ZipArchiveEntry fizz = zf.getEntry("fizz/"); + assertEquals(040641, fizz.getUnixMode()); + ZipArchiveEntry pom = zf.getEntry("fizz/buzz/pom.xml"); + assertEquals(0100222, pom.getUnixMode()); + + ZipArchiveEntry fazz = zf.getEntry("fazz/"); + assertEquals(040530, fazz.getUnixMode()); + ZipArchiveEntry pam = zf.getEntry("fazz/bazz/pam.xml"); + assertEquals(0100111, pam.getUnixMode()); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testOveriddenPermissions() - throws IOException - { - File zipFile = getTestFile( "target/output/zip-with-overriden-modes.zip" ); - - ZipArchiver archiver = getZipArchiver( zipFile ); - archiver.setDefaultDirectoryMode( 0777 ); - archiver.setDirectoryMode( 0641 ); - archiver.setFileMode( 0777 ); - archiver.addDirectory( new File( "src/test/resources/symlinks/src" ) ); + @DisabledOnOs(OS.WINDOWS) + public void testOveriddenPermissions() throws IOException { + File zipFile = getTestFile("target/output/zip-with-overriden-modes.zip"); + + ZipArchiver archiver = getZipArchiver(zipFile); + archiver.setDefaultDirectoryMode(0777); + archiver.setDirectoryMode(0641); + archiver.setFileMode(0777); + archiver.addDirectory(new File("src/test/resources/symlinks/src")); archiver.createArchive(); - assertTrue( zipFile.exists() ); - ZipFile zf = new ZipFile( zipFile ); - ZipArchiveEntry fizz = zf.getEntry( "symDir" ); - assertTrue( fizz.isUnixSymlink() ); - ZipArchiveEntry symR = zf.getEntry( "symR" ); - assertTrue( symR.isUnixSymlink() ); + assertTrue(zipFile.exists()); + ZipFile zf = new ZipFile(zipFile); + ZipArchiveEntry fizz = zf.getEntry("symDir"); + assertTrue(fizz.isUnixSymlink()); + ZipArchiveEntry symR = zf.getEntry("symR"); + assertTrue(symR.isUnixSymlink()); } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testCreateArchiveWithDetectedModes() - throws Exception - { + @DisabledOnOs(OS.WINDOWS) + public void testCreateArchiveWithDetectedModes() throws Exception { - String[] executablePaths = - { - "path/to/executable", "path/to/executable.bat" - }; + String[] executablePaths = {"path/to/executable", "path/to/executable.bat"}; - String[] confPaths = - { - "path/to/etc/file", "path/to/etc/file2" - }; + String[] confPaths = {"path/to/etc/file", "path/to/etc/file2"}; - String[] logPaths = - { - "path/to/logs/log.txt" - }; + String[] logPaths = {"path/to/logs/log.txt"}; int exeMode = 0777; int confMode = 0600; int logMode = 0640; - for ( String executablePath : executablePaths ) - { - writeFile( tempDir, executablePath, exeMode ); + for (String executablePath : executablePaths) { + writeFile(tempDir, executablePath, exeMode); } - for ( String confPath : confPaths ) - { - writeFile( tempDir, confPath, confMode ); + for (String confPath : confPaths) { + writeFile(tempDir, confPath, confMode); } - for ( String logPath : logPaths ) - { - writeFile( tempDir, logPath, logMode ); + for (String logPath : logPaths) { + writeFile(tempDir, logPath, logMode); } { Map attributesByPath = - PlexusIoResourceAttributeUtils.getFileAttributesByPath( tempDir ); - for ( String path : executablePaths ) - { - PlexusIoResourceAttributes attrs = attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = attributesByPath.get( new File( tempDir, path ).getAbsolutePath() ); + PlexusIoResourceAttributeUtils.getFileAttributesByPath(tempDir); + for (String path : executablePaths) { + PlexusIoResourceAttributes attrs = attributesByPath.get(path); + if (attrs == null) { + attrs = attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( exeMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(exeMode, attrs.getOctalMode(), "Wrong mode for: " + path); } - for ( String path : confPaths ) - { - PlexusIoResourceAttributes attrs = attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = attributesByPath.get( new File( tempDir, path ).getAbsolutePath() ); + for (String path : confPaths) { + PlexusIoResourceAttributes attrs = attributesByPath.get(path); + if (attrs == null) { + attrs = attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( confMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(confMode, attrs.getOctalMode(), "Wrong mode for: " + path); } - for ( String path : logPaths ) - { - PlexusIoResourceAttributes attrs = attributesByPath.get( path ); - if ( attrs == null ) - { - attrs = attributesByPath.get( new File( tempDir, path ).getAbsolutePath() ); + for (String path : logPaths) { + PlexusIoResourceAttributes attrs = attributesByPath.get(path); + if (attrs == null) { + attrs = attributesByPath.get(new File(tempDir, path).getAbsolutePath()); } - assertNotNull( attrs ); - assertEquals( logMode, attrs.getOctalMode(), "Wrong mode for: " + path ); + assertNotNull(attrs); + assertEquals(logMode, attrs.getOctalMode(), "Wrong mode for: " + path); } } - File zipFile = getTestFile( "target/output/zip-with-modes.zip" ); + File zipFile = getTestFile("target/output/zip-with-modes.zip"); - ZipArchiver archiver = getZipArchiver( zipFile ); + ZipArchiver archiver = getZipArchiver(zipFile); - archiver.addDirectory( tempDir ); + archiver.addDirectory(tempDir); archiver.createArchive(); - assertTrue( zipFile.exists() ); + assertTrue(zipFile.exists()); - File zipFile2 = getTestFile( "target/output/zip-with-modes-L2.zip" ); + File zipFile2 = getTestFile("target/output/zip-with-modes-L2.zip"); archiver = getZipArchiver(); - archiver.setDestFile( zipFile2 ); + archiver.setDestFile(zipFile2); - archiver.addArchivedFileSet( zipFile ); + archiver.addArchivedFileSet(zipFile); archiver.createArchive(); - ZipFile zf = new ZipFile( zipFile2 ); + ZipFile zf = new ZipFile(zipFile2); - for ( String path : executablePaths ) - { - ZipArchiveEntry ze = zf.getEntry( path ); + for (String path : executablePaths) { + ZipArchiveEntry ze = zf.getEntry(path); int mode = ze.getUnixMode() & UnixStat.PERM_MASK; - assertEquals( exeMode, mode, "Wrong mode for: " + path ); + assertEquals(exeMode, mode, "Wrong mode for: " + path); } - for ( String path : confPaths ) - { - ZipArchiveEntry ze = zf.getEntry( path ); + for (String path : confPaths) { + ZipArchiveEntry ze = zf.getEntry(path); int mode = ze.getUnixMode() & UnixStat.PERM_MASK; - assertEquals( confMode, mode, "Wrong mode for: " + path ); + assertEquals(confMode, mode, "Wrong mode for: " + path); } - for ( String path : logPaths ) - { - ZipArchiveEntry ze = zf.getEntry( path ); + for (String path : logPaths) { + ZipArchiveEntry ze = zf.getEntry(path); int mode = ze.getUnixMode() & UnixStat.PERM_MASK; - assertEquals( logMode, mode, "Wrong mode for: " + path ); + assertEquals(logMode, mode, "Wrong mode for: " + path); } } @Test - public void testCreateEmptyArchive() - throws Exception - { + public void testCreateEmptyArchive() throws Exception { ZipArchiver archiver = getZipArchiver(); - archiver.setDestFile( getTestFile( "target/output/empty.zip" ) ); - try - { + archiver.setDestFile(getTestFile("target/output/empty.zip")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } - private ZipArchiver getZipArchiver() - { - try - { - return (ZipArchiver) lookup( Archiver.class, "zip" ); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + private ZipArchiver getZipArchiver() { + try { + return (ZipArchiver) lookup(Archiver.class, "zip"); + } catch (Exception e) { + throw new RuntimeException(e); } } - private ZipArchiver getZipArchiver( File destFile ) - { + private ZipArchiver getZipArchiver(File destFile) { final ZipArchiver zipArchiver = getZipArchiver(); - zipArchiver.setDestFile( destFile ); + zipArchiver.setDestFile(destFile); return zipArchiver; } - private ZipUnArchiver getZipUnArchiver( File testJar ) - throws Exception - { - ZipUnArchiver zu = (ZipUnArchiver) lookup( UnArchiver.class, "zip" ); - zu.setSourceFile( testJar ); + private ZipUnArchiver getZipUnArchiver(File testJar) throws Exception { + ZipUnArchiver zu = (ZipUnArchiver) lookup(UnArchiver.class, "zip"); + zu.setSourceFile(testJar); return zu; } - private void writeFile( File dir, String fname, int mode ) - throws IOException, ArchiverException - { - File file = new File( dir, fname ); + private void writeFile(File dir, String fname, int mode) throws IOException, ArchiverException { + File file = new File(dir, fname); - if ( file.getParentFile() != null ) - { + if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } - try ( Writer writer = Files.newBufferedWriter( file.toPath(), StandardCharsets.UTF_8 ) ) - { - writer.write( "This is a test file." ); + try (Writer writer = Files.newBufferedWriter(file.toPath(), StandardCharsets.UTF_8)) { + writer.write("This is a test file."); } - ArchiveEntryUtils.chmod( file, mode ); + ArchiveEntryUtils.chmod(file, mode); } @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver archiver = newArchiver( "archive1.zip" ); + public void testCreateArchive() throws Exception { + ZipArchiver archiver = newArchiver("archive1.zip"); - createArchive( archiver ); + createArchive(archiver); } @Test - public void testRecompressAddedZips() throws Exception - { + public void testRecompressAddedZips() throws Exception { // check that by default the zip archives are re-compressed - final File zipFileRecompress = getTestFile( "target/output/recompress-added-zips.zip" ); - final ZipArchiver zipArchiverRecompress = getZipArchiver( zipFileRecompress ); - zipArchiverRecompress.addDirectory( getTestFile( "src/test/jars" ) ); - FileUtils.removePath( zipFileRecompress.getPath() ); + final File zipFileRecompress = getTestFile("target/output/recompress-added-zips.zip"); + final ZipArchiver zipArchiverRecompress = getZipArchiver(zipFileRecompress); + zipArchiverRecompress.addDirectory(getTestFile("src/test/jars")); + FileUtils.removePath(zipFileRecompress.getPath()); zipArchiverRecompress.createArchive(); - final ZipFile zfRecompress = new ZipFile( zipFileRecompress ); - assertEquals( ZipEntry.DEFLATED, zfRecompress.getEntry( "test.zip" ).getMethod() ); - assertEquals( ZipEntry.DEFLATED, zfRecompress.getEntry( "test.jar" ).getMethod() ); - assertEquals( ZipEntry.DEFLATED, zfRecompress.getEntry( "test.rar" ).getMethod() ); - assertEquals( ZipEntry.DEFLATED, zfRecompress.getEntry( "test.tar.gz" ).getMethod() ); + final ZipFile zfRecompress = new ZipFile(zipFileRecompress); + assertEquals(ZipEntry.DEFLATED, zfRecompress.getEntry("test.zip").getMethod()); + assertEquals(ZipEntry.DEFLATED, zfRecompress.getEntry("test.jar").getMethod()); + assertEquals(ZipEntry.DEFLATED, zfRecompress.getEntry("test.rar").getMethod()); + assertEquals(ZipEntry.DEFLATED, zfRecompress.getEntry("test.tar.gz").getMethod()); zfRecompress.close(); // make sure the zip files are not re-compressed when recompressAddedZips is set to false - final File zipFileDontRecompress = getTestFile( "target/output/dont-recompress-added-zips.zip" ); - ZipArchiver zipArchiver = getZipArchiver( zipFileDontRecompress ); - zipArchiver.addDirectory( getTestFile( "src/test/jars" ) ); - zipArchiver.setRecompressAddedZips( false ); - FileUtils.removePath( zipFileDontRecompress.getPath() ); + final File zipFileDontRecompress = getTestFile("target/output/dont-recompress-added-zips.zip"); + ZipArchiver zipArchiver = getZipArchiver(zipFileDontRecompress); + zipArchiver.addDirectory(getTestFile("src/test/jars")); + zipArchiver.setRecompressAddedZips(false); + FileUtils.removePath(zipFileDontRecompress.getPath()); zipArchiver.createArchive(); - final ZipFile zfDontRecompress = new ZipFile( zipFileDontRecompress ); - final ZipArchiveEntry zipEntry = zfDontRecompress.getEntry( "test.zip" ); - final ZipArchiveEntry jarEntry = zfDontRecompress.getEntry( "test.jar" ); - final ZipArchiveEntry rarEntry = zfDontRecompress.getEntry( "test.rar" ); - final ZipArchiveEntry tarEntry = zfDontRecompress.getEntry( "test.tar.gz" ); + final ZipFile zfDontRecompress = new ZipFile(zipFileDontRecompress); + final ZipArchiveEntry zipEntry = zfDontRecompress.getEntry("test.zip"); + final ZipArchiveEntry jarEntry = zfDontRecompress.getEntry("test.jar"); + final ZipArchiveEntry rarEntry = zfDontRecompress.getEntry("test.rar"); + final ZipArchiveEntry tarEntry = zfDontRecompress.getEntry("test.tar.gz"); // check if only zip files are not compressed... - assertEquals( ZipEntry.STORED, zipEntry.getMethod() ); - assertEquals( ZipEntry.STORED, jarEntry.getMethod() ); - assertEquals( ZipEntry.STORED, rarEntry.getMethod() ); - assertEquals( ZipEntry.DEFLATED, tarEntry.getMethod() ); + assertEquals(ZipEntry.STORED, zipEntry.getMethod()); + assertEquals(ZipEntry.STORED, jarEntry.getMethod()); + assertEquals(ZipEntry.STORED, rarEntry.getMethod()); + assertEquals(ZipEntry.DEFLATED, tarEntry.getMethod()); // ...and no file is corrupted in the process - assertTrue( IOUtil.contentEquals( Files.newInputStream( getTestFile( "src/test/jars/test.zip" ).toPath() ), - zfDontRecompress.getInputStream( zipEntry ) ) ); - assertTrue( IOUtil.contentEquals( Files.newInputStream( getTestFile( "src/test/jars/test.jar" ).toPath() ), - zfDontRecompress.getInputStream( jarEntry ) ) ); - assertTrue( IOUtil.contentEquals( Files.newInputStream( getTestFile( "src/test/jars/test.rar" ).toPath() ), - zfDontRecompress.getInputStream( rarEntry ) ) ); - assertTrue( IOUtil.contentEquals( Files.newInputStream( getTestFile( "src/test/jars/test.tar.gz" ).toPath() ), - zfDontRecompress.getInputStream( tarEntry ) ) ); + assertTrue(IOUtil.contentEquals( + Files.newInputStream(getTestFile("src/test/jars/test.zip").toPath()), + zfDontRecompress.getInputStream(zipEntry))); + assertTrue(IOUtil.contentEquals( + Files.newInputStream(getTestFile("src/test/jars/test.jar").toPath()), + zfDontRecompress.getInputStream(jarEntry))); + assertTrue(IOUtil.contentEquals( + Files.newInputStream(getTestFile("src/test/jars/test.rar").toPath()), + zfDontRecompress.getInputStream(rarEntry))); + assertTrue(IOUtil.contentEquals( + Files.newInputStream(getTestFile("src/test/jars/test.tar.gz").toPath()), + zfDontRecompress.getInputStream(tarEntry))); zfDontRecompress.close(); } @Test - public void testAddArchivedFileSet() - throws Exception - { - File toBeAdded = new File( "src/test/resources/test.zip" ); - DefaultArchivedFileSet sfd = DefaultArchivedFileSet.archivedFileSet( toBeAdded ); - File zipFIle = getTestFile( "target/output/withZip.zip" ); - final ZipArchiver zipArchiver = getZipArchiver( zipFIle ); - InputStreamTransformer is = new InputStreamTransformer() - { + public void testAddArchivedFileSet() throws Exception { + File toBeAdded = new File("src/test/resources/test.zip"); + DefaultArchivedFileSet sfd = DefaultArchivedFileSet.archivedFileSet(toBeAdded); + File zipFIle = getTestFile("target/output/withZip.zip"); + final ZipArchiver zipArchiver = getZipArchiver(zipFIle); + InputStreamTransformer is = new InputStreamTransformer() { @Nonnull - public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream ) - throws IOException - { - return new BoundedInputStream( inputStream, 3 ); + public InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream) + throws IOException { + return new BoundedInputStream(inputStream, 3); } - }; - sfd.setStreamTransformer( is ); + sfd.setStreamTransformer(is); PrefixFileMapper mapper = new PrefixFileMapper(); - mapper.setPrefix( "prefix" ); - sfd.setFileMappers( new FileMapper[] { mapper } ); - zipArchiver.addArchivedFileSet( sfd ); + mapper.setPrefix("prefix"); + sfd.setFileMappers(new FileMapper[] {mapper}); + zipArchiver.addArchivedFileSet(sfd); zipArchiver.createArchive(); - final ZipUnArchiver zipUnArchiver = getZipUnArchiver( zipFIle ); - File destFile = new File( "target/output/withZip" ); + final ZipUnArchiver zipUnArchiver = getZipUnArchiver(zipFIle); + File destFile = new File("target/output/withZip"); destFile.mkdirs(); - zipUnArchiver.setDestFile( destFile ); + zipUnArchiver.setDestFile(destFile); zipUnArchiver.extract(); - File a3byteFile = new File( destFile, - "prefixUsers/kristian/lsrc/plexus/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java" ); - assertTrue( a3byteFile.exists() ); - assertTrue( a3byteFile.length() == 3 ); + File a3byteFile = new File( + destFile, + "prefixUsers/kristian/lsrc/plexus/plexus-archiver/src/main/java/org/codehaus/plexus/archiver/zip/ZipArchiver.java"); + assertTrue(a3byteFile.exists()); + assertTrue(a3byteFile.length() == 3); } @Test - public void testCreateArchiveWithStreamTransformer() - throws IOException - { - InputStreamTransformer is = new InputStreamTransformer() - { + public void testCreateArchiveWithStreamTransformer() throws IOException { + InputStreamTransformer is = new InputStreamTransformer() { @Nonnull @Override - public InputStream transform( @Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream ) - throws IOException - { - return new BoundedInputStream( inputStream, 3 ); + public InputStream transform(@Nonnull PlexusIoResource resource, @Nonnull InputStream inputStream) + throws IOException { + return new BoundedInputStream(inputStream, 3); } - }; - final ZipArchiver zipArchiver = getZipArchiver( getTestFile( "target/output/all3bytes.zip" ) ); - File zipFIle = new File( "src/test/resources/test.zip" ); - DefaultArchivedFileSet afs = new DefaultArchivedFileSet( zipFIle ); - afs.setStreamTransformer( is ); - afs.setPrefix( "azip/" ); - zipArchiver.addArchivedFileSet( afs ); + final ZipArchiver zipArchiver = getZipArchiver(getTestFile("target/output/all3bytes.zip")); + File zipFIle = new File("src/test/resources/test.zip"); + DefaultArchivedFileSet afs = new DefaultArchivedFileSet(zipFIle); + afs.setStreamTransformer(is); + afs.setPrefix("azip/"); + zipArchiver.addArchivedFileSet(afs); - DefaultFileSet dfs = new DefaultFileSet( new File( "src/test/resources/mjar179" ) ); - dfs.setStreamTransformer( is ); - dfs.setPrefix( "mj179/" ); - zipArchiver.addFileSet( dfs ); + DefaultFileSet dfs = new DefaultFileSet(new File("src/test/resources/mjar179")); + dfs.setStreamTransformer(is); + dfs.setPrefix("mj179/"); + zipArchiver.addFileSet(dfs); PlexusIoFileResourceCollection files = new PlexusIoFileResourceCollection(); - files.setBaseDir( new File( "src/test/resources" ) ); - files.setStreamTransformer( is ); - files.setPrefix( "plexus/" ); - zipArchiver.addResources( files ); + files.setBaseDir(new File("src/test/resources")); + files.setStreamTransformer(is); + files.setPrefix("plexus/"); + zipArchiver.addResources(files); zipArchiver.createArchive(); - } - private ZipArchiver newArchiver( String name ) - throws Exception - { - ZipArchiver archiver = getZipArchiver( getTestFile( "target/output/" + name ) ); + private ZipArchiver newArchiver(String name) throws Exception { + ZipArchiver archiver = getZipArchiver(getTestFile("target/output/" + name)); - archiver.setFileMode( 0640 ); - archiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), "one.txt" ); - archiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), "two.txt", 0664 ); + archiver.setFileMode(0640); + archiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "one.txt"); + archiver.addFile(getTestFile("src/test/resources/manifests/manifest2.mf"), "two.txt", 0664); // reset default file mode for files included from now on - archiver.setFileMode( 0400 ); - archiver.setDirectoryMode( 0777 ); - archiver.addDirectory( getTestFile( "src/test/resources/world-writable/" ), "worldwritable/" ); + archiver.setFileMode(0400); + archiver.setDirectoryMode(0777); + archiver.addDirectory(getTestFile("src/test/resources/world-writable/"), "worldwritable/"); - archiver.setDirectoryMode( 0070 ); - archiver.addDirectory( getTestFile( "src/test/resources/group-writable/" ), "groupwritable/" ); + archiver.setDirectoryMode(0070); + archiver.addDirectory(getTestFile("src/test/resources/group-writable/"), "groupwritable/"); - archiver.setDirectoryMode( 0500 ); - archiver.setFileMode( 0400 ); - archiver.addDirectory( getTestFile( "src" ) ); + archiver.setDirectoryMode(0500); + archiver.setFileMode(0400); + archiver.addDirectory(getTestFile("src")); return archiver; } - private void fileModeAssert( int expected, int actual ) - { - assertEquals( Integer.toString( expected, 8 ), Integer.toString( actual, 8 ) ); + private void fileModeAssert(int expected, int actual) { + assertEquals(Integer.toString(expected, 8), Integer.toString(actual, 8)); } - private void createArchive( ZipArchiver archiver ) - throws ArchiverException, IOException - { + private void createArchive(ZipArchiver archiver) throws ArchiverException, IOException { archiver.createArchive(); - ZipFile zf = new ZipFile( archiver.getDestFile() ); + ZipFile zf = new ZipFile(archiver.getDestFile()); Enumeration e = zf.getEntries(); - while ( e.hasMoreElements() ) - { + while (e.hasMoreElements()) { ZipArchiveEntry ze = (ZipArchiveEntry) e.nextElement(); - if ( ze.isDirectory() ) - { - if ( ze.getName().startsWith( "worldwritable" ) ) - { - fileModeAssert( 0777, UnixStat.PERM_MASK & ze.getUnixMode() ); - } - else if ( ze.getName().startsWith( "groupwritable" ) ) - { - fileModeAssert( 0070, UnixStat.PERM_MASK & ze.getUnixMode() ); - } - else - { - fileModeAssert( 0500, UnixStat.PERM_MASK & ze.getUnixMode() ); + if (ze.isDirectory()) { + if (ze.getName().startsWith("worldwritable")) { + fileModeAssert(0777, UnixStat.PERM_MASK & ze.getUnixMode()); + } else if (ze.getName().startsWith("groupwritable")) { + fileModeAssert(0070, UnixStat.PERM_MASK & ze.getUnixMode()); + } else { + fileModeAssert(0500, UnixStat.PERM_MASK & ze.getUnixMode()); } - } - else - { - if ( ze.getName().equals( "one.txt" ) ) - { - fileModeAssert( 0640, UnixStat.PERM_MASK & ze.getUnixMode() ); - } - else if ( ze.getName().equals( "two.txt" ) ) - { - fileModeAssert( 0664, UnixStat.PERM_MASK & ze.getUnixMode() ); - } - else if ( ze.isUnixSymlink() ) - { + } else { + if (ze.getName().equals("one.txt")) { + fileModeAssert(0640, UnixStat.PERM_MASK & ze.getUnixMode()); + } else if (ze.getName().equals("two.txt")) { + fileModeAssert(0664, UnixStat.PERM_MASK & ze.getUnixMode()); + } else if (ze.isUnixSymlink()) { // assertEquals( ze.getName(), 0500, UnixStat.PERM_MASK & ze.getUnixMode() ); - } - else - { - fileModeAssert( 0400, UnixStat.PERM_MASK & ze.getUnixMode() ); + } else { + fileModeAssert(0400, UnixStat.PERM_MASK & ze.getUnixMode()); } } - } } @Test - @DisabledOnOs( OS.WINDOWS ) - public void testSymlinkZip() - throws Exception - { - final File zipFile = getTestFile( "target/output/pasymlinks.zip" ); - final ZipArchiver zipArchiver = getZipArchiver( zipFile ); + @DisabledOnOs(OS.WINDOWS) + public void testSymlinkZip() throws Exception { + final File zipFile = getTestFile("target/output/pasymlinks.zip"); + final ZipArchiver zipArchiver = getZipArchiver(zipFile); PlexusIoFileResourceCollection files = new PlexusIoFileResourceCollection(); - files.setFollowingSymLinks( false ); - files.setBaseDir( new File( "src/test/resources/symlinks" ) ); - files.setPrefix( "plexus/" ); - zipArchiver.addResources( files ); + files.setFollowingSymLinks(false); + files.setBaseDir(new File("src/test/resources/symlinks")); + files.setPrefix("plexus/"); + zipArchiver.addResources(files); zipArchiver.createArchive(); - final File output = getTestFile( "target/output/unzipped" ); + final File output = getTestFile("target/output/unzipped"); output.mkdirs(); - final ZipUnArchiver zipUnArchiver = getZipUnArchiver( zipFile ); - zipUnArchiver.setDestFile( output ); + final ZipUnArchiver zipUnArchiver = getZipUnArchiver(zipFile); + zipUnArchiver.setDestFile(output); zipUnArchiver.extract(); - File symDir = new File( "target/output/unzipped/plexus/src/symDir" ); - PlexusIoResourceAttributes fa = FileAttributes.uncached( symDir ); - assertTrue( fa.isSymbolicLink() ); + File symDir = new File("target/output/unzipped/plexus/src/symDir"); + PlexusIoResourceAttributes fa = FileAttributes.uncached(symDir); + assertTrue(fa.isSymbolicLink()); } @Test - @DisabledOnOs( OS.WINDOWS ) - @SuppressWarnings( "ResultOfMethodCallIgnored" ) - public void testSymlinkFileSet() - throws Exception - { - final File zipFile = getTestFile( "target/output/pasymlinks-fileset.zip" ); - final ZipArchiver zipArchiver = getZipArchiver( zipFile ); + @DisabledOnOs(OS.WINDOWS) + @SuppressWarnings("ResultOfMethodCallIgnored") + public void testSymlinkFileSet() throws Exception { + final File zipFile = getTestFile("target/output/pasymlinks-fileset.zip"); + final ZipArchiver zipArchiver = getZipArchiver(zipFile); final DefaultFileSet fs = new DefaultFileSet(); - fs.setPrefix( "bzz/" ); - fs.setDirectory( new File( "src/test/resources/symlinks/src" ) ); - zipArchiver.addFileSet( fs ); + fs.setPrefix("bzz/"); + fs.setDirectory(new File("src/test/resources/symlinks/src")); + zipArchiver.addFileSet(fs); zipArchiver.createArchive(); - final File output = getTestFile( "target/output/unzipped/symlFs" ); + final File output = getTestFile("target/output/unzipped/symlFs"); output.mkdirs(); - final ZipUnArchiver zipUnArchiver = getZipUnArchiver( zipFile ); - zipUnArchiver.setDestFile( output ); + final ZipUnArchiver zipUnArchiver = getZipUnArchiver(zipFile); + zipUnArchiver.setDestFile(output); zipUnArchiver.extract(); - File symDir = new File( output, "bzz/symDir" ); - PlexusIoResourceAttributes fa = FileAttributes.uncached( symDir ); - assertTrue( fa.isSymbolicLink() ); + File symDir = new File(output, "bzz/symDir"); + PlexusIoResourceAttributes fa = FileAttributes.uncached(symDir); + assertTrue(fa.isSymbolicLink()); } @Test - public void testSymlinkArchivedFileSet() - throws Exception - { - final File zipFile = getTestFile( "src/test/resources/symlinks/symlinks.zip" ); - final File zipFile2 = getTestFile( "target/output/pasymlinks-archivedFileset.zip" ); - final ZipArchiver zipArchiver = getZipArchiver( zipFile2 ); - zipArchiver.addArchivedFileSet( zipFile ); + public void testSymlinkArchivedFileSet() throws Exception { + final File zipFile = getTestFile("src/test/resources/symlinks/symlinks.zip"); + final File zipFile2 = getTestFile("target/output/pasymlinks-archivedFileset.zip"); + final ZipArchiver zipArchiver = getZipArchiver(zipFile2); + zipArchiver.addArchivedFileSet(zipFile); zipArchiver.createArchive(); - final ZipFile cmp1 = new ZipFile( zipFile ); - final ZipFile cmp2 = new ZipFile( zipFile2 ); - ArchiveFileComparator.assertZipEquals( cmp1, cmp2, "" ); + final ZipFile cmp1 = new ZipFile(zipFile); + final ZipFile cmp2 = new ZipFile(zipFile2); + ArchiveFileComparator.assertZipEquals(cmp1, cmp2, ""); } /* @@ -620,303 +538,274 @@ public void testSymlinkArchivedFileSet() * Verify that ZipArchiver rounds up the last modified time. */ @Test - public void testLastModifiedTimeRounding() - throws Exception - { - Path oddSecondsTimestampFile = Files.createTempFile( tempDir.toPath(), "odd-seconds-timestamp", null ); + public void testLastModifiedTimeRounding() throws Exception { + Path oddSecondsTimestampFile = Files.createTempFile(tempDir.toPath(), "odd-seconds-timestamp", null); // The milliseconds part is set to zero as not all filesystem support timestamp more granular than second. - Files.setLastModifiedTime( oddSecondsTimestampFile, FileTime.fromMillis( 1534189011_000L ) ); - Path evenSecondsTimestampFile = Files.createTempFile( tempDir.toPath(), "even-seconds-timestamp", null ); - Files.setLastModifiedTime( evenSecondsTimestampFile, FileTime.fromMillis( 1534189012_000L ) ); - - File destFile = getTestFile( "target/output/last-modified-time.zip" ); - ZipArchiver archiver = getZipArchiver( destFile ); - archiver.addFile( oddSecondsTimestampFile.toFile(), "odd-seconds" ); - archiver.addFile( evenSecondsTimestampFile.toFile(), "even-seconds" ); + Files.setLastModifiedTime(oddSecondsTimestampFile, FileTime.fromMillis(1534189011_000L)); + Path evenSecondsTimestampFile = Files.createTempFile(tempDir.toPath(), "even-seconds-timestamp", null); + Files.setLastModifiedTime(evenSecondsTimestampFile, FileTime.fromMillis(1534189012_000L)); + + File destFile = getTestFile("target/output/last-modified-time.zip"); + ZipArchiver archiver = getZipArchiver(destFile); + archiver.addFile(oddSecondsTimestampFile.toFile(), "odd-seconds"); + archiver.addFile(evenSecondsTimestampFile.toFile(), "even-seconds"); archiver.createArchive(); // verify that the last modified time of the entry is equal or newer than the original file - try ( ZipFile resultingZipFile = new ZipFile( destFile ) ) - { - assertEquals( 1534189012_000L, resultingZipFile.getEntry( "odd-seconds" ).getTime() ); - assertEquals( 1534189012_000L, resultingZipFile.getEntry( "even-seconds" ).getTime() ); - - FileTime expected = FileTime.fromMillis( 1534189012_000L ); - assertEquals( expected, resultingZipFile.getEntry( "odd-seconds" ).getLastModifiedTime() ); - assertEquals( expected, resultingZipFile.getEntry( "even-seconds" ).getLastModifiedTime() ); + try (ZipFile resultingZipFile = new ZipFile(destFile)) { + assertEquals( + 1534189012_000L, resultingZipFile.getEntry("odd-seconds").getTime()); + assertEquals( + 1534189012_000L, resultingZipFile.getEntry("even-seconds").getTime()); + + FileTime expected = FileTime.fromMillis(1534189012_000L); + assertEquals(expected, resultingZipFile.getEntry("odd-seconds").getLastModifiedTime()); + assertEquals(expected, resultingZipFile.getEntry("even-seconds").getLastModifiedTime()); } } /* */ @Test - public void testForced() - throws Exception - { - ZipArchiver archiver = newArchiver( "archive2.zip" ); + public void testForced() throws Exception { + ZipArchiver archiver = newArchiver("archive2.zip"); - assertTrue( archiver.isForced() ); + assertTrue(archiver.isForced()); File f = archiver.getDestFile(); - if ( f.exists() ) - { - FileUtils.fileDelete( f.getPath() ); + if (f.exists()) { + FileUtils.fileDelete(f.getPath()); } - assertFalse( f.exists() ); - createArchive( archiver ); + assertFalse(f.exists()); + createArchive(archiver); long l1 = f.lastModified(); - assertTrue( f.exists() ); + assertTrue(f.exists()); - archiver = newArchiver( "archive2.zip" ); - waitUntilNewTimestamp( archiver.getDestFile(), l1 ); - createArchive( archiver ); + archiver = newArchiver("archive2.zip"); + waitUntilNewTimestamp(archiver.getDestFile(), l1); + createArchive(archiver); long l2 = f.lastModified(); - assertTrue( f.exists() ); - assertTrue( l2 > l1 ); + assertTrue(f.exists()); + assertTrue(l2 > l1); - archiver = newArchiver( "archive2.zip" ); - assertTrue( archiver.isSupportingForced() ); - archiver.setForced( false ); - assertFalse( archiver.isForced() ); + archiver = newArchiver("archive2.zip"); + assertTrue(archiver.isSupportingForced()); + archiver.setForced(false); + assertFalse(archiver.isForced()); - createArchive( archiver ); + createArchive(archiver); long l3 = f.lastModified(); - assertTrue( f.exists() ); - assertEquals( l2, l3 ); + assertTrue(f.exists()); + assertEquals(l2, l3); } // Used to investigate extrafields @Test - public void testLookAtExtraZipFields_from_macos() - throws IOException - { - InputStream fis = Streams.fileInputStream( new File( "src/test/resources/zip-timestamp/macOsZipFile.zip" ) ); - ZipInputStream zis = new ZipInputStream( fis ); + public void testLookAtExtraZipFields_from_macos() throws IOException { + InputStream fis = Streams.fileInputStream(new File("src/test/resources/zip-timestamp/macOsZipFile.zip")); + ZipInputStream zis = new ZipInputStream(fis); final java.util.zip.ZipEntry evenEntry = zis.getNextEntry(); - final ZipExtraField[] parse = ExtraFieldUtils.parse( evenEntry.getExtra() ); - System.out.println( Arrays.asList( parse ) ); + final ZipExtraField[] parse = ExtraFieldUtils.parse(evenEntry.getExtra()); + System.out.println(Arrays.asList(parse)); final java.util.zip.ZipEntry oddEntry = zis.getNextEntry(); - System.out.println( Arrays.asList( ExtraFieldUtils.parse( oddEntry.getExtra() ) ) ); - - System.out.println( "oddEntry.getTime() = " + new Date( oddEntry.getTime() ).toString() ); - System.out.println( "oddEntry.getName() = " + oddEntry.getName() ); - System.out.println( "new String(oddEntry.getExtra()) = " + new String( oddEntry.getExtra() ) ); - System.out.println( "evenEntry.getName() = " + evenEntry.getName() ); - System.out.println( "evenEntry.getTime() = " + new Date( evenEntry.getTime() ).toString() ); - System.out.println( "new String(evenEntry.getExtra()) = " + new String( evenEntry.getExtra() ) ); + System.out.println(Arrays.asList(ExtraFieldUtils.parse(oddEntry.getExtra()))); + System.out.println("oddEntry.getTime() = " + new Date(oddEntry.getTime()).toString()); + System.out.println("oddEntry.getName() = " + oddEntry.getName()); + System.out.println("new String(oddEntry.getExtra()) = " + new String(oddEntry.getExtra())); + System.out.println("evenEntry.getName() = " + evenEntry.getName()); + System.out.println("evenEntry.getTime() = " + new Date(evenEntry.getTime()).toString()); + System.out.println("new String(evenEntry.getExtra()) = " + new String(evenEntry.getExtra())); } // Used to investigate date roundtrip behaviour across zip versions @Test - public void testZipStuff() - throws IOException - { + public void testZipStuff() throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); - ZipOutputStream zos = new ZipOutputStream( baos ); + ZipOutputStream zos = new ZipOutputStream(baos); // name the file inside the zip file - final File oddFile = new File( "src/test/resources/zip-timestamp/file-with-odd-time.txt" ); - final File evenFile = new File( "src/test/resources/zip-timestamp/file-with-even-time.txt" ); - final ZipEntry oddZe = new ZipEntry( oddFile.getName() ); - oddZe.setTime( oddFile.lastModified() ); - zos.putNextEntry( oddZe ); - final ZipEntry evenZe = new ZipEntry( evenFile.getName() ); - evenZe.setTime( evenFile.lastModified() ); - zos.putNextEntry( evenZe ); + final File oddFile = new File("src/test/resources/zip-timestamp/file-with-odd-time.txt"); + final File evenFile = new File("src/test/resources/zip-timestamp/file-with-even-time.txt"); + final ZipEntry oddZe = new ZipEntry(oddFile.getName()); + oddZe.setTime(oddFile.lastModified()); + zos.putNextEntry(oddZe); + final ZipEntry evenZe = new ZipEntry(evenFile.getName()); + evenZe.setTime(evenFile.lastModified()); + zos.putNextEntry(evenZe); zos.close(); - ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray() ); - ZipInputStream zipInputStream = new ZipInputStream( bais ); + ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); + ZipInputStream zipInputStream = new ZipInputStream(bais); final java.util.zip.ZipEntry oddEntry = zipInputStream.getNextEntry(); - System.out.println( "oddEntry.getTime() = " + new Date( oddEntry.getTime() ).toString() ); - System.out.println( "oddEntry.getName() = " + oddEntry.getName() ); + System.out.println("oddEntry.getTime() = " + new Date(oddEntry.getTime()).toString()); + System.out.println("oddEntry.getName() = " + oddEntry.getName()); final java.util.zip.ZipEntry evenEntry = zipInputStream.getNextEntry(); - System.out.println( "evenEntry.getName() = " + evenEntry.getName() ); - System.out.println( "evenEntry.getTime() = " + new Date( evenEntry.getTime() ).toString() ); + System.out.println("evenEntry.getName() = " + evenEntry.getName()); + System.out.println("evenEntry.getTime() = " + new Date(evenEntry.getTime()).toString()); } @Disabled("Junit3 method name is notest") @Test - public void notestJustThatOne() - throws Exception - { - final File srcDir = new File( "src" ); - String[] inc = - { - "test/java/org/codehaus/plexus/archiver/zip/ZipShortTest.java" - }; - final File zipFile = new File( "target/output/zz1.zip" ); + public void notestJustThatOne() throws Exception { + final File srcDir = new File("src"); + String[] inc = {"test/java/org/codehaus/plexus/archiver/zip/ZipShortTest.java"}; + final File zipFile = new File("target/output/zz1.zip"); - final File zipFile2 = new File( "target/output/zz2.zip" ); - ZipArchiver zipArchiver2 = getZipArchiver( zipFile2 ); + final File zipFile2 = new File("target/output/zz2.zip"); + ZipArchiver zipArchiver2 = getZipArchiver(zipFile2); // Bugbug: This does not work on 1.8....? - zipArchiver2.addArchivedFileSet( zipFile ); - FileUtils.removePath( zipFile2.getPath() ); + zipArchiver2.addArchivedFileSet(zipFile); + FileUtils.removePath(zipFile2.getPath()); zipArchiver2.createArchive(); } @Test - public void testCreateResourceCollection() - throws Exception - { - final File srcDir = new File( "src" ); - final File zipFile = new File( "target/output/src.zip" ); - ZipArchiver zipArchiver = getZipArchiver( zipFile ); - zipArchiver.addDirectory( srcDir, null, FileUtils.getDefaultExcludes() ); - zipArchiver.setEncoding( "UTF-8" ); - FileUtils.removePath( zipFile.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File srcDir = new File("src"); + final File zipFile = new File("target/output/src.zip"); + ZipArchiver zipArchiver = getZipArchiver(zipFile); + zipArchiver.addDirectory(srcDir, null, FileUtils.getDefaultExcludes()); + zipArchiver.setEncoding("UTF-8"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final File zipFile2 = new File( "target/output/src2.zip" ); - ZipArchiver zipArchiver2 = getZipArchiver( zipFile2 ); - zipArchiver2.addArchivedFileSet( zipFile, "prfx/" ); - zipArchiver2.setEncoding( "UTF-8" ); - FileUtils.removePath( zipFile2.getPath() ); + final File zipFile2 = new File("target/output/src2.zip"); + ZipArchiver zipArchiver2 = getZipArchiver(zipFile2); + zipArchiver2.addArchivedFileSet(zipFile, "prfx/"); + zipArchiver2.setEncoding("UTF-8"); + FileUtils.removePath(zipFile2.getPath()); zipArchiver2.createArchive(); - final ZipFile cmp1 = new ZipFile( zipFile ); - final ZipFile cmp2 = new ZipFile( zipFile2 ); - ArchiveFileComparator.assertZipEquals( cmp1, cmp2, "prfx/" ); + final ZipFile cmp1 = new ZipFile(zipFile); + final ZipFile cmp2 = new ZipFile(zipFile2); + ArchiveFileComparator.assertZipEquals(cmp1, cmp2, "prfx/"); cmp1.close(); cmp2.close(); } @Test - public void testZipNonConcurrentResourceCollection() - throws Exception - { - final File tarFile = getTestFile( "target/output/zip-non-concurrent.tar" ); - TarArchiver tarArchiver = (TarArchiver) lookup( Archiver.class, "tar" ); + public void testZipNonConcurrentResourceCollection() throws Exception { + final File tarFile = getTestFile("target/output/zip-non-concurrent.tar"); + TarArchiver tarArchiver = (TarArchiver) lookup(Archiver.class, "tar"); // Override uId and gId - in standard mode on OS where uId or gId can have long values creation of tar can fail // We can not use posix mode because mTime can have nanoseconds in posix but zip doesn't so assertions can fail tarArchiver.setOverrideUid(100); tarArchiver.setOverrideGid(100); - tarArchiver.setDestFile( tarFile ); + tarArchiver.setDestFile(tarFile); // We're testing concurrency issue so we need large amount of files - for ( int i = 0; i < 100; i++ ) - { - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest1.mf" ), - "manifest1.mf" + i ); + for (int i = 0; i < 100; i++) { + tarArchiver.addFile(getTestFile("src/test/resources/manifests/manifest1.mf"), "manifest1.mf" + i); // Directories are added separately so let's test them too - tarArchiver.addFile( getTestFile( "src/test/resources/manifests/manifest2.mf" ), - "subdir" + i + "/manifest2.mf" ); + tarArchiver.addFile( + getTestFile("src/test/resources/manifests/manifest2.mf"), "subdir" + i + "/manifest2.mf"); } tarArchiver.createArchive(); - final File zipFile = new File( "target/output/zip-non-concurrent.zip" ); - ZipArchiver zipArchive = getZipArchiver( zipFile ); - zipArchive.addArchivedFileSet( tarFile, "prfx/" ); - zipArchive.setEncoding( "UTF-8" ); + final File zipFile = new File("target/output/zip-non-concurrent.zip"); + ZipArchiver zipArchive = getZipArchiver(zipFile); + zipArchive.addArchivedFileSet(tarFile, "prfx/"); + zipArchive.setEncoding("UTF-8"); zipArchive.createArchive(); - final TarFile cmp1 = new TarFile( tarFile ); - final ZipFile cmp2 = new ZipFile( zipFile ); - ArchiveFileComparator.assertTarZipEquals( cmp1, cmp2, "prfx/" ); + final TarFile cmp1 = new TarFile(tarFile); + final ZipFile cmp2 = new ZipFile(zipFile); + ArchiveFileComparator.assertTarZipEquals(cmp1, cmp2, "prfx/"); cmp1.close(); cmp2.close(); } @Test - public void testDefaultUTF8() - throws IOException - { - final ZipArchiver zipArchiver = getZipArchiver( new File( "target/output/utf8-default.zip" ) ); - zipArchiver.addDirectory( new File( "src/test/resources/miscUtf8" ) ); + public void testDefaultUTF8() throws IOException { + final ZipArchiver zipArchiver = getZipArchiver(new File("target/output/utf8-default.zip")); + zipArchiver.addDirectory(new File("src/test/resources/miscUtf8")); zipArchiver.createArchive(); } @Test - public void testDefaultUTF8withUTF8() - throws IOException - { - final ZipArchiver zipArchiver = getZipArchiver( new File( "target/output/utf8-with_utf.zip" ) ); - zipArchiver.setEncoding( "UTF-8" ); - zipArchiver.addDirectory( new File( "src/test/resources/miscUtf8" ) ); + public void testDefaultUTF8withUTF8() throws IOException { + final ZipArchiver zipArchiver = getZipArchiver(new File("target/output/utf8-with_utf.zip")); + zipArchiver.setEncoding("UTF-8"); + zipArchiver.addDirectory(new File("src/test/resources/miscUtf8")); zipArchiver.createArchive(); } @Test - public void testForcedFileModes() - throws IOException - { - File step1file = new File( "target/output/forced-file-mode.zip" ); + public void testForcedFileModes() throws IOException { + File step1file = new File("target/output/forced-file-mode.zip"); { - final ZipArchiver zipArchiver = getZipArchiver( step1file ); - zipArchiver.setFileMode( 0077 ); - zipArchiver.setDirectoryMode( 0007 ); - PlexusIoResourceAttributes attrs = new SimpleResourceAttributes( 123, "fred", 22, "filntstones", 0111 ); - PlexusIoResource resource = - ResourceFactory.createResource( new File( "src/test/resources/folders/File.txt" ), "Test.txt", null, - attrs ); - zipArchiver.addResource( resource, "Test2.txt", 0707 ); + final ZipArchiver zipArchiver = getZipArchiver(step1file); + zipArchiver.setFileMode(0077); + zipArchiver.setDirectoryMode(0007); + PlexusIoResourceAttributes attrs = new SimpleResourceAttributes(123, "fred", 22, "filntstones", 0111); + PlexusIoResource resource = ResourceFactory.createResource( + new File("src/test/resources/folders/File.txt"), "Test.txt", null, attrs); + zipArchiver.addResource(resource, "Test2.txt", 0707); PlexusIoFileResourceCollection files = new PlexusIoFileResourceCollection(); - files.setBaseDir( new File( "src/test/resources/folders" ) ); - files.setPrefix( "sixsixsix/" ); - zipArchiver.addResources( files ); + files.setBaseDir(new File("src/test/resources/folders")); + files.setPrefix("sixsixsix/"); + zipArchiver.addResources(files); zipArchiver.createArchive(); - ZipFile zf = new ZipFile( step1file ); - fileModeAssert( 040007, zf.getEntry( "sixsixsix/a/" ).getUnixMode() ); - fileModeAssert( 0100077, zf.getEntry( "sixsixsix/b/FileInB.txt" ).getUnixMode() ); - fileModeAssert( 0100707, zf.getEntry( "Test2.txt" ).getUnixMode() ); + ZipFile zf = new ZipFile(step1file); + fileModeAssert(040007, zf.getEntry("sixsixsix/a/").getUnixMode()); + fileModeAssert(0100077, zf.getEntry("sixsixsix/b/FileInB.txt").getUnixMode()); + fileModeAssert(0100707, zf.getEntry("Test2.txt").getUnixMode()); zf.close(); } - File Step2file = new File( "target/output/forced-file-mode-from-zip.zip" ); + File Step2file = new File("target/output/forced-file-mode-from-zip.zip"); { - final ZipArchiver za2 = getZipArchiver( Step2file ); - za2.setFileMode( 0666 ); - za2.setDirectoryMode( 0676 ); + final ZipArchiver za2 = getZipArchiver(Step2file); + za2.setFileMode(0666); + za2.setDirectoryMode(0676); PlexusIoZipFileResourceCollection zipSrc = new PlexusIoZipFileResourceCollection(); - zipSrc.setFile( step1file ); - zipSrc.setPrefix( "zz/" ); - za2.addResources( zipSrc ); + zipSrc.setFile(step1file); + zipSrc.setPrefix("zz/"); + za2.addResources(zipSrc); za2.createArchive(); - ZipFile zf = new ZipFile( Step2file ); - fileModeAssert( 040676, zf.getEntry( "zz/sixsixsix/a/" ).getUnixMode() ); - fileModeAssert( 0100666, zf.getEntry( "zz/Test2.txt" ).getUnixMode() ); + ZipFile zf = new ZipFile(Step2file); + fileModeAssert(040676, zf.getEntry("zz/sixsixsix/a/").getUnixMode()); + fileModeAssert(0100666, zf.getEntry("zz/Test2.txt").getUnixMode()); zf.close(); } - File step3file = new File( "target/output/forced-file-mode-from-zip2.zip" ); + File step3file = new File("target/output/forced-file-mode-from-zip2.zip"); { - final ZipArchiver za2 = getZipArchiver( step3file ); - za2.setFileMode( 0666 ); - za2.setDirectoryMode( 0676 ); + final ZipArchiver za2 = getZipArchiver(step3file); + za2.setFileMode(0666); + za2.setDirectoryMode(0676); PlexusArchiverZipFileResourceCollection zipSrc = new PlexusArchiverZipFileResourceCollection(); - zipSrc.setFile( step1file ); - zipSrc.setPrefix( "zz/" ); - za2.addResources( zipSrc ); + zipSrc.setFile(step1file); + zipSrc.setPrefix("zz/"); + za2.addResources(zipSrc); za2.createArchive(); - ZipFile zf = new ZipFile( Step2file ); - fileModeAssert( 040676, zf.getEntry( "zz/sixsixsix/a/" ).getUnixMode() ); - fileModeAssert( 0100666, zf.getEntry( "zz/Test2.txt" ).getUnixMode() ); + ZipFile zf = new ZipFile(Step2file); + fileModeAssert(040676, zf.getEntry("zz/sixsixsix/a/").getUnixMode()); + fileModeAssert(0100666, zf.getEntry("zz/Test2.txt").getUnixMode()); zf.close(); } } @Test - public void testFixedEntryModificationTime() - throws IOException - { - final long almostMinDosTime = toLocalTimeZone( 315532802000L ); - - final File zipFile = getTestFile( "target/output/zip-with-fixed-entry-modification-times.zip" ); - final ZipArchiver archiver = getZipArchiver( zipFile ); - archiver.setLastModifiedTime( FileTime.fromMillis( almostMinDosTime ) ); - archiver.addDirectory( new File( "src/test/resources/zip-timestamp" ) ); + public void testFixedEntryModificationTime() throws IOException { + final long almostMinDosTime = toLocalTimeZone(315532802000L); + + final File zipFile = getTestFile("target/output/zip-with-fixed-entry-modification-times.zip"); + final ZipArchiver archiver = getZipArchiver(zipFile); + archiver.setLastModifiedTime(FileTime.fromMillis(almostMinDosTime)); + archiver.addDirectory(new File("src/test/resources/zip-timestamp")); archiver.createArchive(); - assertTrue( zipFile.exists() ); - try ( final ZipFile zf = new ZipFile( zipFile ) ) - { - assertEquals( almostMinDosTime, zf.getEntry( "file-with-even-time.txt" ).getTime() ); - assertEquals( almostMinDosTime, zf.getEntry( "file-with-odd-time.txt" ).getTime() ); - assertEquals( almostMinDosTime, zf.getEntry( "foo/" ).getTime() ); + assertTrue(zipFile.exists()); + try (final ZipFile zf = new ZipFile(zipFile)) { + assertEquals( + almostMinDosTime, zf.getEntry("file-with-even-time.txt").getTime()); + assertEquals(almostMinDosTime, zf.getEntry("file-with-odd-time.txt").getTime()); + assertEquals(almostMinDosTime, zf.getEntry("foo/").getTime()); } } @@ -933,24 +822,19 @@ public void testFixedEntryModificationTime() * @param timestamp the epoch time to convert. * @return the timestamp matching the same input date but in the local TZ. */ - private long toLocalTimeZone( long timestamp ) - { + private long toLocalTimeZone(long timestamp) { String dateFormat = "dd-MM-yyyy hh:mm:ss a"; - DateFormat formatterWithTimeZone = new SimpleDateFormat( dateFormat ); - formatterWithTimeZone.setTimeZone( TimeZone.getTimeZone( "GMT" ) ); - String sDate = formatterWithTimeZone.format( new Date( timestamp ) ); + DateFormat formatterWithTimeZone = new SimpleDateFormat(dateFormat); + formatterWithTimeZone.setTimeZone(TimeZone.getTimeZone("GMT")); + String sDate = formatterWithTimeZone.format(new Date(timestamp)); - DateFormat formatter = new SimpleDateFormat( dateFormat ); - try - { - Date dateWithTimeZone = formatter.parse( sDate ); + DateFormat formatter = new SimpleDateFormat(dateFormat); + try { + Date dateWithTimeZone = formatter.parse(sDate); return dateWithTimeZone.getTime(); - } - catch ( ParseException e ) - { - fail( "Date '" + sDate + "' can not be parsed!" ); + } catch (ParseException e) { + fail("Date '" + sDate + "' can not be parsed!"); return 0L; } } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zip/ZipUnArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/zip/ZipUnArchiverTest.java index c7e997b65..e3c3e93be 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zip/ZipUnArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zip/ZipUnArchiverTest.java @@ -23,332 +23,244 @@ /** * @author Jason van Zyl */ -public class ZipUnArchiverTest - extends TestSupport -{ +public class ZipUnArchiverTest extends TestSupport { @Test - public void testExtractingZipPreservesExecutableFlag() - throws Exception - { + public void testExtractingZipPreservesExecutableFlag() throws Exception { String s = "target/zip-unarchiver-tests"; - File testZip = new File( getBasedir(), "src/test/jars/test.zip" ); - File outputDirectory = new File( getBasedir(), s ); + File testZip = new File(getBasedir(), "src/test/jars/test.zip"); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - ZipUnArchiver zu = getZipUnArchiver( testZip ); - zu.extract( "", outputDirectory ); - File testScript = new File( outputDirectory, "test.sh" ); + ZipUnArchiver zu = getZipUnArchiver(testZip); + zu.extract("", outputDirectory); + File testScript = new File(outputDirectory, "test.sh"); final Method canExecute; - try - { - canExecute = File.class.getMethod( "canExecute" ); - canExecute.invoke( testScript ); - assertTrue( (Boolean) canExecute.invoke( testScript ) ); - } - catch ( NoSuchMethodException ignore ) - { + try { + canExecute = File.class.getMethod("canExecute"); + canExecute.invoke(testScript); + assertTrue((Boolean) canExecute.invoke(testScript)); + } catch (NoSuchMethodException ignore) { } } @Test - public void testZeroFileModeInZip() - throws Exception - { + public void testZeroFileModeInZip() throws Exception { String s = "target/zip-unarchiver-filemode-tests"; - File testZip = new File( getBasedir(), "src/test/resources/zeroFileMode/foobar.zip" ); - File outputDirectory = new File( getBasedir(), s ); + File testZip = new File(getBasedir(), "src/test/resources/zeroFileMode/foobar.zip"); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - ZipUnArchiver zu = getZipUnArchiver( testZip ); - zu.setIgnorePermissions( false ); - zu.extract( "", outputDirectory ); + ZipUnArchiver zu = getZipUnArchiver(testZip); + zu.setIgnorePermissions(false); + zu.extract("", outputDirectory); - File testScript = new File( outputDirectory, "foo.txt" ); + File testScript = new File(outputDirectory, "foo.txt"); final Method canRead; - try - { - canRead = File.class.getMethod( "canRead" ); - canRead.invoke( testScript ); - assertTrue( (Boolean) canRead.invoke( testScript ) ); - } - catch ( NoSuchMethodException ignore ) - { + try { + canRead = File.class.getMethod("canRead"); + canRead.invoke(testScript); + assertTrue((Boolean) canRead.invoke(testScript)); + } catch (NoSuchMethodException ignore) { } } @Test - public void testUnarchiveUtf8() - throws Exception - { - File dest = new File( "target/output/unzip/utf8" ); + public void testUnarchiveUtf8() throws Exception { + File dest = new File("target/output/unzip/utf8"); dest.mkdirs(); - final File zipFile = new File( "target/output/unzip/utf8-default.zip" ); - final ZipArchiver zipArchiver = getZipArchiver( zipFile ); - zipArchiver.addDirectory( new File( "src/test/resources/miscUtf8" ) ); + final File zipFile = new File("target/output/unzip/utf8-default.zip"); + final ZipArchiver zipArchiver = getZipArchiver(zipFile); + zipArchiver.addDirectory(new File("src/test/resources/miscUtf8")); zipArchiver.createArchive(); - final ZipUnArchiver unarchiver = getZipUnArchiver( zipFile ); - unarchiver.setDestFile( dest ); + final ZipUnArchiver unarchiver = getZipUnArchiver(zipFile); + unarchiver.setDestFile(dest); unarchiver.extract(); - assertTrue( new File( dest, "aPi\u00F1ata.txt" ).exists() ); - assertTrue( new File( dest, "an\u00FCmlaut.txt" ).exists() ); - assertTrue( new File( dest, "\u20acuro.txt" ).exists() ); + assertTrue(new File(dest, "aPi\u00F1ata.txt").exists()); + assertTrue(new File(dest, "an\u00FCmlaut.txt").exists()); + assertTrue(new File(dest, "\u20acuro.txt").exists()); } @Test - public void testUnarchiveUnicodePathExtra() - throws Exception - { - File dest = new File( "target/output/unzip/unicodePathExtra" ); + public void testUnarchiveUnicodePathExtra() throws Exception { + File dest = new File("target/output/unzip/unicodePathExtra"); dest.mkdirs(); - for ( String name : dest.list() ) - { - new File( dest, name ).delete(); + for (String name : dest.list()) { + new File(dest, name).delete(); } - assertEquals( 0, dest.list().length ); + assertEquals(0, dest.list().length); - final ZipUnArchiver unarchiver = getZipUnArchiver( new File( "src/test/resources/unicodePathExtra/efsclear.zip" ) ); - unarchiver.setDestFile( dest ); + final ZipUnArchiver unarchiver = getZipUnArchiver(new File("src/test/resources/unicodePathExtra/efsclear.zip")); + unarchiver.setDestFile(dest); unarchiver.extract(); // a Unicode Path extra field should only be used when its CRC matches the header file name - assertEquals( new HashSet<>( Arrays.asList( "nameonly-name", "goodextra-extra", "badextra-name" ) ), - new HashSet<>( Arrays.asList( dest.list() ) ), - "should use good extra fields but not bad ones" ); + assertEquals( + new HashSet<>(Arrays.asList("nameonly-name", "goodextra-extra", "badextra-name")), + new HashSet<>(Arrays.asList(dest.list())), + "should use good extra fields but not bad ones"); } @Test - public void testUnarchiveUnicodePathExtraSelector() - throws Exception - { - File dest = new File( "target/output/unzip/unicodePathExtraSelector" ); + public void testUnarchiveUnicodePathExtraSelector() throws Exception { + File dest = new File("target/output/unzip/unicodePathExtraSelector"); dest.mkdirs(); - for ( String name : dest.list() ) - { - new File( dest, name ).delete(); + for (String name : dest.list()) { + new File(dest, name).delete(); } - assertEquals( 0, dest.list().length ); + assertEquals(0, dest.list().length); - class CollectingSelector implements FileSelector - { + class CollectingSelector implements FileSelector { public Set collection = new HashSet<>(); + @Override - public boolean isSelected( FileInfo fileInfo ) throws IOException - { - collection.add( fileInfo.getName() ); + public boolean isSelected(FileInfo fileInfo) throws IOException { + collection.add(fileInfo.getName()); return false; } } CollectingSelector selector = new CollectingSelector(); - final ZipUnArchiver unarchiver = getZipUnArchiver( new File( "src/test/resources/unicodePathExtra/efsclear.zip" ) ); - unarchiver.setDestFile( dest ); - unarchiver.setFileSelectors( new FileSelector[] { selector } ); + final ZipUnArchiver unarchiver = getZipUnArchiver(new File("src/test/resources/unicodePathExtra/efsclear.zip")); + unarchiver.setDestFile(dest); + unarchiver.setFileSelectors(new FileSelector[] {selector}); unarchiver.extract(); - assertEquals( 0, dest.list().length, "should not extract anything" ); + assertEquals(0, dest.list().length, "should not extract anything"); // a Unicode Path extra field should only be used when its CRC matches the header file name - assertEquals( new HashSet<>( Arrays.asList( "nameonly-name", "goodextra-extra", "badextra-name" ) ), - selector.collection, "should use good extra fields but not bad ones" ); + assertEquals( + new HashSet<>(Arrays.asList("nameonly-name", "goodextra-extra", "badextra-name")), + selector.collection, + "should use good extra fields but not bad ones"); } - private void runUnarchiver( String path, FileSelector[] selectors, boolean[] results ) - throws Exception - { + private void runUnarchiver(String path, FileSelector[] selectors, boolean[] results) throws Exception { String s = "target/zip-unarchiver-tests"; - File testJar = new File( getBasedir(), "src/test/jars/test.jar" ); + File testJar = new File(getBasedir(), "src/test/jars/test.jar"); - File outputDirectory = new File( getBasedir(), s ); + File outputDirectory = new File(getBasedir(), s); - ZipUnArchiver zu = getZipUnArchiver( testJar ); - zu.setFileSelectors( selectors ); + ZipUnArchiver zu = getZipUnArchiver(testJar); + zu.setFileSelectors(selectors); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - zu.extract( path, outputDirectory ); + zu.extract(path, outputDirectory); - File f0 = new File( getBasedir(), s + "/resources/artifactId/test.properties" ); + File f0 = new File(getBasedir(), s + "/resources/artifactId/test.properties"); - assertEquals( results[0], f0.exists() ); + assertEquals(results[0], f0.exists()); - File f1 = new File( getBasedir(), s + "/resources/artifactId/directory/test.properties" ); + File f1 = new File(getBasedir(), s + "/resources/artifactId/directory/test.properties"); - assertEquals( results[1], f1.exists() ); + assertEquals(results[1], f1.exists()); - File f2 = new File( getBasedir(), s + "/META-INF/MANIFEST.MF" ); + File f2 = new File(getBasedir(), s + "/META-INF/MANIFEST.MF"); - assertEquals( results[2], f2.exists() ); + assertEquals(results[2], f2.exists()); } - private ZipUnArchiver getZipUnArchiver( File testJar ) throws Exception - { - ZipUnArchiver zu = (ZipUnArchiver) lookup( UnArchiver.class, "zip" ); - zu.setSourceFile( testJar ); + private ZipUnArchiver getZipUnArchiver(File testJar) throws Exception { + ZipUnArchiver zu = (ZipUnArchiver) lookup(UnArchiver.class, "zip"); + zu.setSourceFile(testJar); return zu; } @Test - public void testExtractingADirectoryFromAJarFile() - throws Exception - { - runUnarchiver( "resources/artifactId", null, - new boolean[] - { - true, true, false - } ); - runUnarchiver( "", null, - new boolean[] - { - true, true, true - } ); + public void testExtractingADirectoryFromAJarFile() throws Exception { + runUnarchiver("resources/artifactId", null, new boolean[] {true, true, false}); + runUnarchiver("", null, new boolean[] {true, true, true}); } @Test - public void testSelectors() - throws Exception - { + public void testSelectors() throws Exception { IncludeExcludeFileSelector fileSelector = new IncludeExcludeFileSelector(); - runUnarchiver( "", new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, true, true - } ); - fileSelector.setExcludes( new String[] - { - "**/test.properties" - } ); - runUnarchiver( "", new FileSelector[] - { - fileSelector - }, - new boolean[] - { - false, false, true - } ); - fileSelector.setIncludes( new String[] - { - "**/test.properties" - } ); - fileSelector.setExcludes( null ); - runUnarchiver( "", new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, true, false - } ); - fileSelector.setExcludes( new String[] - { - "resources/artifactId/directory/test.properties" - } ); - runUnarchiver( "", new FileSelector[] - { - fileSelector - }, - new boolean[] - { - true, false, false - } ); + runUnarchiver("", new FileSelector[] {fileSelector}, new boolean[] {true, true, true}); + fileSelector.setExcludes(new String[] {"**/test.properties"}); + runUnarchiver("", new FileSelector[] {fileSelector}, new boolean[] {false, false, true}); + fileSelector.setIncludes(new String[] {"**/test.properties"}); + fileSelector.setExcludes(null); + runUnarchiver("", new FileSelector[] {fileSelector}, new boolean[] {true, true, false}); + fileSelector.setExcludes(new String[] {"resources/artifactId/directory/test.properties"}); + runUnarchiver("", new FileSelector[] {fileSelector}, new boolean[] {true, false, false}); } @Test - public void testExtractingZipWithEntryOutsideDestDirThrowsException() - throws Exception - { + public void testExtractingZipWithEntryOutsideDestDirThrowsException() throws Exception { Exception ex = null; String s = "target/zip-unarchiver-slip-tests"; - File testZip = new File( getBasedir(), "src/test/zips/zip-slip.zip" ); - File outputDirectory = new File( getBasedir(), s ); + File testZip = new File(getBasedir(), "src/test/zips/zip-slip.zip"); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - try - { - ZipUnArchiver zu = getZipUnArchiver( testZip ); - zu.extract( "", outputDirectory ); - } - catch ( Exception e ) - { + try { + ZipUnArchiver zu = getZipUnArchiver(testZip); + zu.extract("", outputDirectory); + } catch (Exception e) { ex = e; } - assertNotNull( ex ); - assertTrue( ex.getMessage().startsWith( "Entry is outside of the target directory" ) ); + assertNotNull(ex); + assertTrue(ex.getMessage().startsWith("Entry is outside of the target directory")); } @Test - public void testZipOutputSizeException() - throws Exception - { + public void testZipOutputSizeException() throws Exception { Exception ex = null; String s = "target/zip-size-tests"; - File testZip = new File( getBasedir(), "src/test/jars/test.zip" ); - File outputDirectory = new File( getBasedir(), s ); + File testZip = new File(getBasedir(), "src/test/jars/test.zip"); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - try - { - ZipUnArchiver zu = getZipUnArchiver( testZip ); - zu.setMaxOutputSize( 10L ); - zu.extract( "", outputDirectory ); - } - catch ( Exception e ) - { + try { + ZipUnArchiver zu = getZipUnArchiver(testZip); + zu.setMaxOutputSize(10L); + zu.extract("", outputDirectory); + } catch (Exception e) { ex = e; } - assertNotNull( ex ); - assertTrue( ex.getMessage().startsWith( "Maximum output size limit reached" ) ); + assertNotNull(ex); + assertTrue(ex.getMessage().startsWith("Maximum output size limit reached")); } @Test - public void testZipMaxOutputSizeEqualToExtractedFileSize() - throws Exception - { + public void testZipMaxOutputSizeEqualToExtractedFileSize() throws Exception { long extractedFileSize = 11L; String s = "target/zip-size-tests"; - File testZip = new File( getBasedir(), "src/test/jars/test.zip" ); - File outputDirectory = new File( getBasedir(), s ); + File testZip = new File(getBasedir(), "src/test/jars/test.zip"); + File outputDirectory = new File(getBasedir(), s); - FileUtils.deleteDirectory( outputDirectory ); + FileUtils.deleteDirectory(outputDirectory); - ZipUnArchiver zu = getZipUnArchiver( testZip ); - zu.setMaxOutputSize( extractedFileSize ); - zu.extract( "", outputDirectory ); + ZipUnArchiver zu = getZipUnArchiver(testZip); + zu.setMaxOutputSize(extractedFileSize); + zu.extract("", outputDirectory); - File extractedFile = new File( outputDirectory, "test.sh" ); - assertEquals( extractedFileSize, extractedFile.length() ); + File extractedFile = new File(outputDirectory, "test.sh"); + assertEquals(extractedFileSize, extractedFile.length()); } - private ZipArchiver getZipArchiver() - { - try - { - return (ZipArchiver) lookup( Archiver.class, "zip" ); - } - catch ( Exception e ) - { - throw new RuntimeException( e ); + private ZipArchiver getZipArchiver() { + try { + return (ZipArchiver) lookup(Archiver.class, "zip"); + } catch (Exception e) { + throw new RuntimeException(e); } } - private ZipArchiver getZipArchiver( File destFile ) - { + private ZipArchiver getZipArchiver(File destFile) { final ZipArchiver zipArchiver = getZipArchiver(); - zipArchiver.setDestFile( destFile ); + zipArchiver.setDestFile(destFile); return zipArchiver; } - } diff --git a/src/test/java/org/codehaus/plexus/archiver/zstd/ZstdArchiverTest.java b/src/test/java/org/codehaus/plexus/archiver/zstd/ZstdArchiverTest.java index eed3367e2..8023c129d 100644 --- a/src/test/java/org/codehaus/plexus/archiver/zstd/ZstdArchiverTest.java +++ b/src/test/java/org/codehaus/plexus/archiver/zstd/ZstdArchiverTest.java @@ -21,6 +21,7 @@ import java.util.Arrays; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; + import org.codehaus.plexus.archiver.Archiver; import org.codehaus.plexus.archiver.BasePlexusArchiverTest; import org.codehaus.plexus.archiver.exceptions.EmptyArchiveException; @@ -34,79 +35,69 @@ import static org.junit.jupiter.api.Assertions.assertTrue; import static org.junit.jupiter.api.Assertions.fail; -public class ZstdArchiverTest extends BasePlexusArchiverTest -{ +public class ZstdArchiverTest extends BasePlexusArchiverTest { @Test - public void testCreateArchive() - throws Exception - { - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.addDirectory( getTestFile( "src" ) ); - zipArchiver.setDestFile( getTestFile( "target/output/archiveForxz.zip" ) ); + public void testCreateArchive() throws Exception { + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.addDirectory(getTestFile("src")); + zipArchiver.setDestFile(getTestFile("target/output/archiveForxz.zip")); zipArchiver.createArchive(); - ZstdArchiver archiver = (ZstdArchiver) lookup( Archiver.class, "zst" ); - String[] inputFiles = new String[ 1 ]; + ZstdArchiver archiver = (ZstdArchiver) lookup(Archiver.class, "zst"); + String[] inputFiles = new String[1]; inputFiles[0] = "archiveForxz.zip"; - File targetOutputFile = getTestFile( "target/output/archive.zst" ); - if ( targetOutputFile.exists() ) - { - FileUtils.fileDelete( targetOutputFile.getPath() ); + File targetOutputFile = getTestFile("target/output/archive.zst"); + if (targetOutputFile.exists()) { + FileUtils.fileDelete(targetOutputFile.getPath()); } - assertFalse( targetOutputFile.exists() ); + assertFalse(targetOutputFile.exists()); - archiver.addDirectory( getTestFile( "target/output" ), inputFiles, null ); - archiver.setDestFile( targetOutputFile ); + archiver.addDirectory(getTestFile("target/output"), inputFiles, null); + archiver.setDestFile(targetOutputFile); archiver.createArchive(); - assertTrue( targetOutputFile.exists() ); + assertTrue(targetOutputFile.exists()); } @Test - public void testCreateEmptyArchive() - throws Exception - { - ZstdArchiver archiver = (ZstdArchiver) lookup( Archiver.class, "zst" ); - archiver.setDestFile( getTestFile( "target/output/empty.zst" ) ); - try - { + public void testCreateEmptyArchive() throws Exception { + ZstdArchiver archiver = (ZstdArchiver) lookup(Archiver.class, "zst"); + archiver.setDestFile(getTestFile("target/output/empty.zst")); + try { archiver.createArchive(); - fail( "Creating empty archive should throw EmptyArchiveException" ); - } - catch ( EmptyArchiveException ignore ) - { + fail("Creating empty archive should throw EmptyArchiveException"); + } catch (EmptyArchiveException ignore) { } } @Test - public void testCreateResourceCollection() throws Exception - { - final File pomFile = new File( "pom.xml" ); - final File zstFile = new File( "target/output/pom.xml.zst" ); - ZstdArchiver zstdArchiver = (ZstdArchiver) lookup( Archiver.class, "zst" ); - zstdArchiver.setDestFile( zstFile ); - zstdArchiver.addFile( pomFile, "pom.xml" ); - FileUtils.removePath( zstFile.getPath() ); + public void testCreateResourceCollection() throws Exception { + final File pomFile = new File("pom.xml"); + final File zstFile = new File("target/output/pom.xml.zst"); + ZstdArchiver zstdArchiver = (ZstdArchiver) lookup(Archiver.class, "zst"); + zstdArchiver.setDestFile(zstFile); + zstdArchiver.addFile(pomFile, "pom.xml"); + FileUtils.removePath(zstFile.getPath()); zstdArchiver.createArchive(); - System.out.println( "Created: " + zstFile.getAbsolutePath() ); + System.out.println("Created: " + zstFile.getAbsolutePath()); - final File zipFile = new File( "target/output/pomxz.zip" ); - ZipArchiver zipArchiver = (ZipArchiver) lookup( Archiver.class, "zip" ); - zipArchiver.setDestFile( zipFile ); - zipArchiver.addArchivedFileSet( zstFile, "prfx/" ); - FileUtils.removePath( zipFile.getPath() ); + final File zipFile = new File("target/output/pomxz.zip"); + ZipArchiver zipArchiver = (ZipArchiver) lookup(Archiver.class, "zip"); + zipArchiver.setDestFile(zipFile); + zipArchiver.addArchivedFileSet(zstFile, "prfx/"); + FileUtils.removePath(zipFile.getPath()); zipArchiver.createArchive(); - final ZipFile juZipFile = new ZipFile( zipFile ); - final ZipEntry zipEntry = juZipFile.getEntry( "prfx/target/output/pom.xml" ); - final InputStream archivePom = juZipFile.getInputStream( zipEntry ); - final InputStream pom = Files.newInputStream( pomFile.toPath() ); + final ZipFile juZipFile = new ZipFile(zipFile); + final ZipEntry zipEntry = juZipFile.getEntry("prfx/target/output/pom.xml"); + final InputStream archivePom = juZipFile.getInputStream(zipEntry); + final InputStream pom = Files.newInputStream(pomFile.toPath()); - assertTrue( Arrays.equals( IOUtil.toByteArray( pom ), IOUtil.toByteArray( archivePom ) ) ); + assertTrue(Arrays.equals(IOUtil.toByteArray(pom), IOUtil.toByteArray(archivePom))); archivePom.close(); pom.close(); juZipFile.close(); @@ -119,34 +110,32 @@ public void testCreateResourceCollection() throws Exception * @throws Exception */ @Test - public void testZstIsForcedBehaviour() throws Exception - { - ZstdArchiver zstdArchiver = (ZstdArchiver) createArchiver( "zst" ); + public void testZstIsForcedBehaviour() throws Exception { + ZstdArchiver zstdArchiver = (ZstdArchiver) createArchiver("zst"); - assertTrue( zstdArchiver.isSupportingForced() ); + assertTrue(zstdArchiver.isSupportingForced()); zstdArchiver.createArchive(); final long creationTime = zstdArchiver.getDestFile().lastModified(); - waitUntilNewTimestamp( zstdArchiver.getDestFile(), creationTime ); + waitUntilNewTimestamp(zstdArchiver.getDestFile(), creationTime); - zstdArchiver = (ZstdArchiver) createArchiver( "zst" ); + zstdArchiver = (ZstdArchiver) createArchiver("zst"); - zstdArchiver.setForced( true ); + zstdArchiver.setForced(true); zstdArchiver.createArchive(); final long firstRunTime = zstdArchiver.getDestFile().lastModified(); - assertFalse( creationTime == firstRunTime ); + assertFalse(creationTime == firstRunTime); - zstdArchiver = (ZstdArchiver) createArchiver( "zst" ); + zstdArchiver = (ZstdArchiver) createArchiver("zst"); - zstdArchiver.setForced( false ); + zstdArchiver.setForced(false); zstdArchiver.createArchive(); final long secondRunTime = zstdArchiver.getDestFile().lastModified(); - assertEquals( firstRunTime, secondRunTime ); + assertEquals(firstRunTime, secondRunTime); } - }