This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-compress.git


The following commit(s) were added to refs/heads/master by this push:
     new 25fbda208 CompressException.requireNonNull(Class<? super E>, T, 
Supplier<String>) didn't throw on null.
25fbda208 is described below

commit 25fbda20869d2405d1adbe201bcd8a50ca43b497
Author: Gary Gregory <[email protected]>
AuthorDate: Sun Aug 9 09:29:09 2026 -0400

    CompressException.requireNonNull(Class<? super E>, T, Supplier<String>)
    didn't throw on null.
    
    - Add and use ArchiveException.requireNonNegative(int, String)
    - Add and use ArchiveException.requireNonNegative(long, String)
    - Add and use ArchiveException.requireNonNull(T, String)
    - Add and use CompressException.requireNonNull(Class, T, String)
---
 src/changes/changes.xml                            |  5 ++
 .../apache/commons/compress/CompressException.java | 47 ++++++++++++----
 .../compress/archivers/ArchiveException.java       | 46 +++++++++++++++
 .../archivers/ar/ArArchiveInputStream.java         | 18 +++---
 .../archivers/arj/ArjArchiveInputStream.java       |  7 +--
 .../archivers/cpio/CpioArchiveInputStream.java     | 12 +---
 .../archivers/cpio/CpioArchiveOutputStream.java    |  9 +--
 .../compress/archivers/dump/TapeInputStream.java   |  5 +-
 .../archivers/lha/LhaArchiveInputStream.java       | 34 +++++------
 .../compress/archivers/sevenz/LZMA2Decoder.java    |  4 +-
 .../compress/archivers/sevenz/LZMADecoder.java     |  8 +--
 .../compress/archivers/sevenz/SevenZFile.java      |  8 +--
 .../compress/archivers/tar/TarArchiveEntry.java    | 22 ++------
 .../archivers/tar/TarArchiveInputStream.java       | 13 ++---
 .../commons/compress/archivers/tar/TarFile.java    | 13 ++---
 .../commons/compress/archivers/tar/TarUtils.java   | 52 ++++++-----------
 .../archivers/zip/UnshrinkingInputStream.java      |  5 +-
 .../archivers/zip/ZipArchiveOutputStream.java      |  6 +-
 .../commons/compress/archivers/zip/ZipFile.java    | 65 ++++++----------------
 .../archivers/lha/LhaArchiveInputStreamTest.java   |  8 +--
 20 files changed, 172 insertions(+), 215 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 91e22aa11..0d0b7b045 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -159,6 +159,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="fix" dev="ggregory" due-to="Martin Wiesner">Fix typos in 
Javadoc and comments #761.</action>
       <action type="fix" dev="ggregory" due-to="Gary 
Gregory">org.apache.commons.compress.utils.ParsingUtils should set the cause of 
the exceptions it throws.</action>
       <action type="fix" dev="ggregory" due-to="Gary Gregory">Add messages 
when throwing NullPointerException.</action>
+      <action type="fix" dev="ggregory" due-to="Gary 
Gregory">CompressException.requireNonNull(Class, T, Supplier) didn't throw on 
null.</action>
       <!-- ADD -->
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
MemoryLimitException.MemoryLimitException(long, long).</action>
       <action type="add" dev="ggregory" due-to="Gary Gregory">Add 
CompressException.CompressException(String, Object...).</action>
@@ -186,6 +187,10 @@ The <action> type attribute can be add,update,fix,remove.
       <action type="add" dev="ggregory" due-to="Fredrik Kjellberg, Gary 
Gregory, Piotr P. Karwasz" issue="COMPRESS-706">Add support for reading LHA 
archive format (#690).</action>
       <action type="add" dev="ggregory" due-to="Piotr P. Karwasz, Gary 
Gregory">Add BitInputStream.getByteOrder() (#720).</action>
       <action type="add" dev="ggregory" due-to="Piotr P. Karwasz, Gary 
Gregory, Fredrik Kjellberg">Add reusable Huffman decoder (#701, #792, 
#795).</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
ArchiveException.requireNonNegative(int, String).</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
ArchiveException.requireNonNegative(long, String).</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
ArchiveException.requireNonNull(T, String).</action>
+      <action type="add" dev="ggregory" due-to="Gary Gregory">Add and use 
CompressException.requireNonNull(Class, T, String).</action>
       <!-- UPDATE -->
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-parent from 85 to 103 #707, #752.</action>
       <action type="update" dev="ggregory" due-to="Gary Gregory">Bump 
org.apache.commons:commons-lang3 from 3.18.0 to 3.20.0.</action>
diff --git a/src/main/java/org/apache/commons/compress/CompressException.java 
b/src/main/java/org/apache/commons/compress/CompressException.java
index a29bbf1de..955a3181e 100644
--- a/src/main/java/org/apache/commons/compress/CompressException.java
+++ b/src/main/java/org/apache/commons/compress/CompressException.java
@@ -39,9 +39,9 @@ public class CompressException extends IOException {
     /**
      * Delegates to {@link Math#addExact(int, int)} wrapping its {@link 
ArithmeticException} in our {@link ArchiveException}.
      *
-     * @param <E>             The type of the exception.
-     * @param x The first value.
-     * @param y The second value.
+     * @param <E>       The type of the exception.
+     * @param x         The first value.
+     * @param y         The second value.
      * @param eFunction How to create an exception.
      * @return The result.
      * @throws E if the result or input overflows an {@code int}.
@@ -56,25 +56,48 @@ public static <E extends CompressException> int 
addExact(final int x, final long
         }
     }
 
+    @SuppressWarnings("unchecked")
+    private static <E extends CompressException> E newInstance(final Class<E> 
cls, final String string) throws E {
+        try {
+            return cls.getConstructor(String.class).newInstance(string);
+        } catch (ReflectiveOperationException | SecurityException e) {
+            return (E) new CompressException(string, e);
+        }
+    }
+
+    /**
+     * Checks that the specified object reference is not {@code null} and 
throws a customized {@link CompressException} if it is.
+     *
+     * @param <T>     The type of the reference.
+     * @param <E>     The type of the exception.
+     * @param cls     The exception class.
+     * @param obj     The object reference to check for nullity.
+     * @param message The detail message to be used in the event that a {@code 
CompressException} is thrown.
+     * @return {@code obj} if not {@code null}.
+     * @throws E if {@code obj} is {@code null}.
+     * @since 1.29.0
+     */
+    protected static <T, E extends CompressException> T requireNonNull(final 
Class<E> cls, final T obj, final String message) throws E {
+        if (obj == null) {
+            throw (E) newInstance(cls, message);
+        }
+        return obj;
+    }
+
     /**
-     * Checks that the specified object reference is not {@code null} and 
throws a customized {@link CompressException} if it is. *
+     * Checks that the specified object reference is not {@code null} and 
throws a customized {@link CompressException} if it is.
      *
      * @param <T>             The type of the reference.
      * @param <E>             The type of the exception.
      * @param cls             The exception class.
      * @param obj             The object reference to check for nullity.
-     * @param messageSupplier supplier of the detail message to be used in the 
event that a {@code ArchiveException} is thrown.
+     * @param messageSupplier supplier of the detail message to be used in the 
event that a {@code CompressException} is thrown.
      * @return {@code obj} if not {@code null}.
      * @throws E if {@code obj} is {@code null}.
      */
-    protected static <T, E extends Throwable> T requireNonNull(final Class<? 
super E> cls, final T obj, final Supplier<String> messageSupplier) throws E {
+    protected static <T, E extends CompressException> T requireNonNull(final 
Class<E> cls, final T obj, final Supplier<String> messageSupplier) throws E {
         if (obj == null) {
-            final String string = Suppliers.get(messageSupplier);
-            try {
-                cls.getConstructor(String.class).newInstance(string);
-            } catch (ReflectiveOperationException | SecurityException e) {
-                new CompressException(string, e);
-            }
+            throw (E) newInstance(cls, Suppliers.get(messageSupplier));
         }
         return obj;
     }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/ArchiveException.java 
b/src/main/java/org/apache/commons/compress/archivers/ArchiveException.java
index 8f7a01f4f..3cd8dd31f 100644
--- a/src/main/java/org/apache/commons/compress/archivers/ArchiveException.java
+++ b/src/main/java/org/apache/commons/compress/archivers/ArchiveException.java
@@ -65,6 +65,52 @@ public static long addExact(final long x, final long y) 
throws ArchiveException
         }
     }
 
+    /**
+     * Checks that the specified value is not negative and throws a customized 
{@link ArchiveException} if it is.
+     *
+     * @param value   The value to check for negativity.
+     * @param message The detail message to be used in the event that a {@code 
ArchiveException} is thrown.
+     * @return {@code value} if not negative.
+     * @throws ArchiveException if {@code value} is negative.
+     * @since 1.29.0
+     */
+    public static int requireNonNegative(final int value, final String 
message) throws ArchiveException {
+        if (value < 0) {
+            throw new ArchiveException(message);
+        }
+        return value;
+    }
+
+    /**
+     * Checks that the specified value is not negative and throws a customized 
{@link ArchiveException} if it is.
+     *
+     * @param value   The value to check for negativity.
+     * @param message The detail message to be used in the event that a {@code 
ArchiveException} is thrown.
+     * @return {@code value} if not negative.
+     * @throws ArchiveException if {@code value} is negative.
+     * @since 1.29.0
+     */
+    public static long requireNonNegative(final long value, final String 
message) throws ArchiveException {
+        if (value < 0) {
+            throw new ArchiveException(message);
+        }
+        return value;
+    }
+
+    /**
+     * Checks that the specified object reference is not {@code null} and 
throws a customized {@link ArchiveException} if it is. *
+     *
+     * @param obj     The object reference to check for nullity.
+     * @param message The detail message to be used in the event that a {@code 
ArchiveException} is thrown.
+     * @param <T>     the type of the reference.
+     * @return {@code obj} if not {@code null}.
+     * @throws ArchiveException if {@code obj} is {@code null}.
+     * @since 1.29.0
+     */
+    public static <T> T requireNonNull(final T obj, final String message) 
throws ArchiveException {
+        return CompressException.requireNonNull(ArchiveException.class, obj, 
message);
+    }
+
     /**
      * Checks that the specified object reference is not {@code null} and 
throws a customized {@link ArchiveException} if it is. *
      *
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStream.java
index 7d79fd74e..7dacf6df8 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/ar/ArArchiveInputStream.java
@@ -158,7 +158,7 @@ public static boolean matches(final byte[] buffer, final 
int ignored) {
     private ArArchiveEntry currentEntry;
 
     /** Storage area for extra long names (GNU ar). */
-    private byte[] namebuffer;
+    private byte[] nameBuffer;
 
     /**
      * The offset where the data for the current entry starts.
@@ -269,21 +269,19 @@ private String getBSDLongName(final String bsdLongName) 
throws IOException {
      * @throws IOException if name not found or buffer not set up.
      */
     private String getExtendedName(final int offset) throws IOException {
-        if (namebuffer == null) {
-            throw new ArchiveException("Cannot process GNU long file name as 
no GNU string table was found");
-        }
-        if (offset >= namebuffer.length) {
+        ArchiveException.requireNonNull(nameBuffer, "Cannot process GNU long 
file name as no GNU string table was found");
+        if (offset >= nameBuffer.length) {
             throw new ArchiveException("GNU long file name offset out of 
range: " + offset);
         }
-        for (int i = offset; i < namebuffer.length; i++) {
-            final byte c = namebuffer[i];
+        for (int i = offset; i < nameBuffer.length; i++) {
+            final byte c = nameBuffer[i];
             if (c == '\n' || c == 0) {
-                if (i > offset && namebuffer[i - 1] == '/') {
+                if (i > offset && nameBuffer[i - 1] == '/') {
                     i--; // drop trailing '/'
                 }
                 // Check there is a something to return, otherwise break out 
of the loop
                 if (i > offset) {
-                    return ArchiveUtils.toAsciiString(namebuffer, offset, 
checkEntryNameLength(i - offset));
+                    return ArchiveUtils.toAsciiString(nameBuffer, offset, 
checkEntryNameLength(i - offset));
                 }
                 break;
             }
@@ -348,7 +346,7 @@ public ArArchiveEntry getNextEntry() throws IOException {
             foundGNUStringTable = isGNUStringTable(currentEntry);
             if (foundGNUStringTable) {
                 // If this is a GNU string table entry, read the extended 
names and continue
-                namebuffer = readGNUStringTable(currentEntry);
+                nameBuffer = readGNUStringTable(currentEntry);
             }
         } while (foundGNUStringTable);
 
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStream.java
index 6c6849f2f..4f7d345aa 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/arj/ArjArchiveInputStream.java
@@ -199,7 +199,6 @@ public boolean canReadEntryData(final ArchiveEntry ae) {
      * @throws EOFException If the end of the stream is reached before reading 
the checksum.
      * @throws IOException If an I/O error occurs.
      */
-    @SuppressWarnings("Since15")
     private boolean checkCRC32(final byte[] data) throws IOException {
         final CRC32 crc32 = new CRC32();
         crc32.update(data);
@@ -415,10 +414,8 @@ private LocalFileHeader readLocalFileHeader() throws 
IOException {
     }
 
     private MainHeader readMainHeader(final boolean selfExtracting) throws 
IOException {
-        final byte[] basicHeaderBytes = selfExtracting ? findMainHeader() : 
readHeader();
-        if (basicHeaderBytes == null) {
-            throw new ArchiveException("Corrupted ARJ archive: Missing main 
header");
-        }
+        final byte[] basicHeaderBytes = 
ArchiveException.requireNonNull(selfExtracting ? findMainHeader() : 
readHeader(),
+                "Corrupted ARJ archive: Missing main header");
         final MainHeader header = new MainHeader();
         try (InputStream basicHeader = new 
ByteArrayInputStream(basicHeaderBytes)) {
             final int firstHeaderSize = readUnsignedByte(basicHeader);
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStream.java
index f258b2e6b..26da0d860 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveInputStream.java
@@ -440,9 +440,7 @@ private CpioArchiveEntry readNewEntry(final boolean hasCrc) 
throws IOException {
         newEntry.setNumberOfLinks(readAsciiLong(8, 16));
         newEntry.setTime(readAsciiLong(8, 16));
         newEntry.setSize(readAsciiLong(8, 16));
-        if (newEntry.getSize() < 0) {
-            throw new ArchiveException("Found illegal entry with negative 
length");
-        }
+        ArchiveException.requireNonNegative(newEntry.getSize(), "Found illegal 
entry with negative length");
         newEntry.setDeviceMaj(readAsciiLong(8, 16));
         newEntry.setDeviceMin(readAsciiLong(8, 16));
         newEntry.setRemoteDeviceMaj(readAsciiLong(8, 16));
@@ -483,9 +481,7 @@ private CpioArchiveEntry readOldAsciiEntry() throws 
IOException {
             throw new ArchiveException("Found illegal entry with negative name 
length");
         }
         ret.setSize(readAsciiLong(11, 8));
-        if (ret.getSize() < 0) {
-            throw new ArchiveException("Found illegal entry with negative 
length");
-        }
+        ArchiveException.requireNonNegative(ret.getSize(), "Found illegal 
entry with negative length");
         final String name = 
readEntryName(ArchiveException.toIntExact(nameSize));
         ret.setName(name);
         if (CpioUtil.fileType(mode) == 0 && !name.equals(CPIO_TRAILER)) {
@@ -513,9 +509,7 @@ private CpioArchiveEntry readOldBinaryEntry(final boolean 
swapHalfWord) throws I
             throw new ArchiveException("Found illegal entry with negative name 
length");
         }
         oldEntry.setSize(readBinaryLong(4, swapHalfWord));
-        if (oldEntry.getSize() < 0) {
-            throw new ArchiveException("Found illegal entry with negative 
length");
-        }
+        ArchiveException.requireNonNegative(oldEntry.getSize(), "Found illegal 
entry with negative length");
         final String name = 
readEntryName(ArchiveException.toIntExact(nameSize));
         oldEntry.setName(name);
         if (CpioUtil.fileType(mode) == 0 && !name.equals(CPIO_TRAILER)) {
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
index 4fc7d6be4..d627e52b7 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/cpio/CpioArchiveOutputStream.java
@@ -195,10 +195,7 @@ public void close() throws IOException {
     public void closeArchiveEntry() throws IOException {
         checkFinished();
         checkOpen();
-        if (entry == null) {
-            throw new ArchiveException("Trying to close non-existent entry");
-        }
-
+        ArchiveException.requireNonNull(entry, "Trying to close non-existent 
entry");
         if (this.entry.getSize() != this.written) {
             throw new ArchiveException("Invalid entry size (expected " + 
this.entry.getSize() + " but got " + this.written + " bytes)");
         }
@@ -325,9 +322,7 @@ public void write(final byte[] b, final int off, final int 
len) throws IOExcepti
             return;
         }
         checkOpen();
-        if (this.entry == null) {
-            throw new ArchiveException("No current CPIO entry");
-        }
+        ArchiveException.requireNonNull(entry, "No current CPIO entry");
         if (this.written + len > this.entry.getSize()) {
             throw new ArchiveException("Attempt to write past end of STORED 
entry");
         }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/dump/TapeInputStream.java 
b/src/main/java/org/apache/commons/compress/archivers/dump/TapeInputStream.java
index 3154bf2da..91754166a 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/dump/TapeInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/dump/TapeInputStream.java
@@ -173,10 +173,7 @@ public int read(final byte[] b, int off, final int len) 
throws IOException {
      * @throws IOException Thrown if an I/O error occurs.
      */
     private void readBlock(final boolean decompress) throws IOException {
-        if (in == null) {
-            throw new ArchiveException("Input buffer is closed");
-        }
-
+        ArchiveException.requireNonNull(in, "Input buffer is closed");
         if (!isCompressed || currBlkIdx == -1) {
             // file is not compressed
             readFully(blockBuffer, 0, blockSize);
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStream.java
index 4ad86ffa6..7f63cb0c0 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStream.java
@@ -359,27 +359,25 @@ public LhaArchiveEntry getNextEntry() throws IOException {
      * separator char. Any leading file path separator char will be removed to 
avoid extracting to absolute locations.
      *
      * @param buffer         the buffer where to get the pathname from.
-     * @param pathnameLength the length of the pathname.
+     * @param pathNameLength the length of the pathname.
      * @return pathname.
      * @throws ArchiveException if the pathname is too long.
      */
-    String getPathname(final ByteBuffer buffer, final int pathnameLength) 
throws ArchiveException {
+    String getPathName(final ByteBuffer buffer, final int pathNameLength) 
throws ArchiveException {
         // Check pathname length to ensure we don't allocate too much memory
-        if (pathnameLength > MAX_PATHNAME_LENGTH) {
-            throw new ArchiveException("Pathname is longer than the maximum 
allowed (%d > %d)", pathnameLength, MAX_PATHNAME_LENGTH);
+        if (pathNameLength > MAX_PATHNAME_LENGTH) {
+            throw new ArchiveException("Pathname is longer than the maximum 
allowed (%d > %d)", pathNameLength, MAX_PATHNAME_LENGTH);
         }
-        if (pathnameLength < 0) {
-            throw new ArchiveException("Pathname length is negative");
-        }
-        if (pathnameLength > buffer.limit() - buffer.position()) {
+        ArchiveException.requireNonNegative(pathNameLength, "Pathname length 
is negative");
+        if (pathNameLength > buffer.limit() - buffer.position()) {
             throw new ArchiveException("Invalid pathname length");
         }
-        final byte[] pathnameBuffer = new byte[pathnameLength];
+        final byte[] pathnameBuffer = new byte[pathNameLength];
         buffer.get(pathnameBuffer);
         // Split the pathname into parts by 0xFF bytes
         final StringBuilder pathnameStringBuilder = new StringBuilder();
         int start = 0;
-        for (int i = 0; i < pathnameLength; i++) {
+        for (int i = 0; i < pathNameLength; i++) {
             if (pathnameBuffer[i] == (byte) 0xFF) {
                 if (i > start) {
                     // Decode the path segment into a string using the 
specified charset and append it to the result
@@ -389,8 +387,8 @@ String getPathname(final ByteBuffer buffer, final int 
pathnameLength) throws Arc
             }
         }
         // Append the last segment if it exists
-        if (start < pathnameLength) {
-            pathnameStringBuilder.append(new String(pathnameBuffer, start, 
pathnameLength - start, getCharset()));
+        if (start < pathNameLength) {
+            pathnameStringBuilder.append(new String(pathnameBuffer, start, 
pathNameLength - start, getCharset()));
         }
         String pathname = pathnameStringBuilder.toString();
         // If the path separator char is not '\', replace all '\' characters 
with the path separator char
@@ -443,14 +441,14 @@ void parseExtendedHeader(final ByteBuffer 
extendedHeaderBuffer, final LhaArchive
         case EXTENDED_HEADER_TYPE_FILENAME: {
             // File name header
             final int filenameLength = extendedHeaderBuffer.limit() - 
extendedHeaderBuffer.position() - EXTENDED_HEADER_NEXT_HEADER_SIZE_LENGTH;
-            final String filename = getPathname(extendedHeaderBuffer, 
filenameLength);
+            final String filename = getPathName(extendedHeaderBuffer, 
filenameLength);
             entryBuilder.setFileName(filename);
             break;
         }
         case EXTENDED_HEADER_TYPE_DIRECTORY_NAME: {
             // Directory name header
             final int directoryNameLength = extendedHeaderBuffer.limit() - 
extendedHeaderBuffer.position() - EXTENDED_HEADER_NEXT_HEADER_SIZE_LENGTH;
-            final String directoryName = getPathname(extendedHeaderBuffer, 
directoryNameLength);
+            final String directoryName = getPathName(extendedHeaderBuffer, 
directoryNameLength);
             if (directoryName.length() > 0 && 
directoryName.charAt(directoryName.length() - 1) != fileSeparatorChar) {
                 // If the directory name does not end with a file separator, 
append it
                 entryBuilder.setDirectoryName(directoryName + 
fileSeparatorChar);
@@ -615,7 +613,7 @@ private LhaArchiveEntry readHeaderLevel0(ByteBuffer buffer) 
throws IOException {
         buffer.position(HEADER_LEVEL_0_OFFSET_FILENAME);
         // @formatter:off
         entryBuilder
-            .setFileName(getPathname(buffer, filenameLength))
+            .setFileName(getPathName(buffer, filenameLength))
             .setDirectory(isDirectory(compressionMethod))
             .setCrc(Short.toUnsignedInt(buffer.getShort()));
         // @formatter:on
@@ -658,7 +656,7 @@ private LhaArchiveEntry readHeaderLevel1(ByteBuffer buffer) 
throws IOException {
         buffer.position(HEADER_LEVEL_1_OFFSET_FILENAME);
         // @formatter:off
         entryBuilder
-            .setFileName(getPathname(buffer, filenameLength))
+            .setFileName(getPathName(buffer, filenameLength))
             .setDirectory(isDirectory(compressionMethod))
             .setCrc(Short.toUnsignedInt(buffer.getShort()))
             .setOsId(Byte.toUnsignedInt(buffer.get()));
@@ -682,9 +680,7 @@ private LhaArchiveEntry readHeaderLevel1(ByteBuffer buffer) 
throws IOException {
         // The compressed size is derived by subtracting the extended header 
sizes from the skip size. A
         // corrupt archive whose extended headers exceed the skip size would 
yield a negative compressed
         // size, which must be rejected as it would otherwise disable the 
per-entry read bound.
-        if (skipSize < 0) {
-            throw new ArchiveException("Invalid compressed size");
-        }
+        ArchiveException.requireNonNegative(skipSize, "Invalid compressed 
size");
         entryBuilder.setCompressedSize(skipSize);
         final LhaArchiveEntry entry = entryBuilder.get();
         if (entry.getHeaderCrc() != null) {
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMA2Decoder.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMA2Decoder.java
index 838ef709a..8e4bf562a 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMA2Decoder.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMA2Decoder.java
@@ -55,9 +55,7 @@ OutputStream encode(final OutputStream out, final Object 
opts) throws IOExceptio
     }
 
     private int getDictionarySize(final Coder coder) throws IOException {
-        if (coder.properties == null) {
-            throw new ArchiveException("Missing LZMA2 properties");
-        }
+        ArchiveException.requireNonNull(coder.properties, "Missing LZMA2 
properties");
         if (coder.properties.length < 1) {
             throw new ArchiveException("LZMA2 properties too short");
         }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMADecoder.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMADecoder.java
index 6c00f931e..2a384ee9b 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMADecoder.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/LZMADecoder.java
@@ -43,9 +43,7 @@ final class LZMADecoder extends AbstractCoder {
     @Override
     InputStream decode(final String archiveName, final InputStream in, final 
long uncompressedLength, final Coder coder, final byte[] password,
             final int maxMemoryLimitKiB) throws IOException {
-        if (coder.properties == null) {
-            throw new ArchiveException("Missing LZMA properties");
-        }
+        ArchiveException.requireNonNull(coder.properties, "Missing LZMA 
properties");
         if (coder.properties.length < 1) {
             throw new ArchiveException("LZMA properties too short");
         }
@@ -97,9 +95,7 @@ byte[] getOptionsAsProperties(final Object opts) throws 
IOException {
 
     @Override
     Object getOptionsFromCoder(final Coder coder, final InputStream in) throws 
IOException {
-        if (coder.properties == null) {
-            throw new ArchiveException("Missing LZMA properties");
-        }
+        ArchiveException.requireNonNull(coder.properties, "Missing LZMA 
properties");
         if (coder.properties.length < 1) {
             throw new ArchiveException("LZMA properties too short");
         }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java 
b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
index e45c21501..55677407d 100644
--- a/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/sevenz/SevenZFile.java
@@ -953,9 +953,7 @@ public int read(final byte[] b, final int off, final int 
len) throws IOException
      * @throws IOException if there are exceptions when reading the file.
      */
     private void buildDecodingStream(final int entryIndex, final boolean 
isRandomAccess) throws IOException {
-        if (archive.streamMap == null) {
-            throw new ArchiveException("Archive doesn't contain stream 
information to read entries");
-        }
+        ArchiveException.requireNonNull(archive.streamMap, "Archive doesn't 
contain stream information to read entries");
         final int folderIndex = archive.streamMap.fileFolderIndex[entryIndex];
         if (folderIndex < 0) {
             deferredBlockStreams.clear();
@@ -1573,9 +1571,7 @@ private void readFilesInfo(final ByteBuffer header, final 
Archive archive) throw
             }
             entryAtIndex.setHasStream(isEmptyStream == null || 
!isEmptyStream.get(i));
             if (entryAtIndex.hasStream()) {
-                if (archive.subStreamsInfo == null) {
-                    throw new ArchiveException("7z archive: Archive contains 
file with streams but no subStreamsInfo.");
-                }
+                ArchiveException.requireNonNull(archive.subStreamsInfo, "7z 
archive: Archive contains file with streams but no subStreamsInfo.");
                 entryAtIndex.setDirectory(false);
                 entryAtIndex.setAntiItem(false);
                 
entryAtIndex.setHasCrc(archive.subStreamsInfo.hasCrc.get(nonEmptyFileCounter));
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
index a291fb003..f6c8dbb54 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveEntry.java
@@ -1505,9 +1505,7 @@ private int parseTarHeaderBlock(final byte[] header, 
final ZipEncoding encoding,
         groupId = (int) parseOctalOrBinary(header, offset, GIDLEN, lenient);
         offset += GIDLEN;
         size = TarUtils.parseOctalOrBinary(header, offset, SIZELEN);
-        if (size < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
size");
-        }
+        ArchiveException.requireNonNegative(size, "Broken archive, entry with 
negative size");
         offset += SIZELEN;
         mTime = FileTimes.fromUnixTime(parseOctalOrBinary(header, offset, 
MODTIMELEN, lenient));
         offset += MODTIMELEN;
@@ -1661,11 +1659,7 @@ private void processPaxHeader(final String key, final 
String val, final Map<Stri
             setUserName(val);
             break;
         case "size":
-            final long size = ParsingUtils.parseLongValue(val);
-            if (size < 0) {
-                throw new ArchiveException("Corrupted TAR archive. Entry size 
is negative");
-            }
-            setSize(size);
+            
setSize(ArchiveException.requireNonNegative(ParsingUtils.parseLongValue(val), 
"Corrupted TAR archive. Entry size is negative"));
             break;
         case "mtime":
             
setLastModifiedTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
@@ -1680,18 +1674,10 @@ private void processPaxHeader(final String key, final 
String val, final Map<Stri
             
setCreationTime(FileTime.from(parseInstantFromDecimalSeconds(val)));
             break;
         case "SCHILY.devminor":
-            final int devMinor = ParsingUtils.parseIntValue(val);
-            if (devMinor < 0) {
-                throw new ArchiveException("Corrupted TAR archive. Dev-Minor 
is negative");
-            }
-            setDevMinor(devMinor);
+            
setDevMinor(ArchiveException.requireNonNegative(ParsingUtils.parseIntValue(val),
 "Corrupted TAR archive. Dev-Minor is negative"));
             break;
         case "SCHILY.devmajor":
-            final int devMajor = ParsingUtils.parseIntValue(val);
-            if (devMajor < 0) {
-                throw new ArchiveException("Corrupted TAR archive. Dev-Major 
is negative");
-            }
-            setDevMajor(devMajor);
+            
setDevMajor(ArchiveException.requireNonNegative(ParsingUtils.parseIntValue(val),
 "Corrupted TAR archive. Dev-Major is negative"));
             break;
         case TarGnuSparseKeys.SIZE:
             fillGNUSparse0xData(headers);
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
index 495ef60ce..d01a80060 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarArchiveInputStream.java
@@ -369,11 +369,8 @@ private void buildSparseInputStreams() throws IOException {
         // physical bytes read from the archive for this entry
         long dataBytes = 0;
         for (final TarArchiveStructSparse sparseHeader : sparseHeaders) {
-            final long zeroBlockSize = sparseHeader.getOffset() - offset;
-            if (zeroBlockSize < 0) {
-                // sparse header says to move backwards inside the extracted 
entry
-                throw new ArchiveException("Corrupted struct sparse detected");
-            }
+            final long zeroBlockSize = 
ArchiveException.requireNonNegative(sparseHeader.getOffset() - offset, 
"Corrupted struct sparse detected");
+            // sparse header says to move backwards inside the extracted entry
             // only store the zero block if it is not empty
             if (zeroBlockSize > 0) {
                 // @formatter:off
@@ -686,10 +683,8 @@ private void readOldGNUSparse() throws IOException {
         if (currEntry.isExtended()) {
             TarArchiveSparseEntry entry;
             do {
-                final byte[] headerBuf = getRecord();
-                if (headerBuf == null) {
-                    throw new ArchiveException("Premature end of tar archive. 
Didn't find extended_header after header with extended flag.");
-                }
+                final byte[] headerBuf = 
ArchiveException.requireNonNull(getRecord(),
+                        "Premature end of tar archive. Didn't find 
extended_header after header with extended flag.");
                 entry = new TarArchiveSparseEntry(headerBuf);
                 currEntry.getSparseHeaders().addAll(entry.getSparseHeaders());
             } while (entry.isExtended());
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
index f9419dc85..487eeda2a 100644
--- a/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/tar/TarFile.java
@@ -364,11 +364,8 @@ private void buildSparseInputStreams() throws IOException {
         // physical bytes backing this entry
         long dataBytes = 0;
         for (final TarArchiveStructSparse sparseHeader : sparseHeaders) {
-            final long zeroBlockSize = sparseHeader.getOffset() - offset;
-            if (zeroBlockSize < 0) {
-                // sparse header says to move backwards inside the extracted 
entry
-                throw new ArchiveException("Corrupted struct sparse detected");
-            }
+            final long zeroBlockSize = 
ArchiveException.requireNonNegative(sparseHeader.getOffset() - offset, 
"Corrupted struct sparse detected");
+            // sparse header says to move backwards inside the extracted entry
             // only store the zero block if it is not empty
             if (zeroBlockSize > 0) {
                 
streams.add(BoundedInputStream.builder().setInputStream(zeroInputStream).setMaxCount(zeroBlockSize).get());
@@ -569,10 +566,8 @@ private void readOldGNUSparse() throws IOException {
         if (currEntry.isExtended()) {
             TarArchiveSparseEntry entry;
             do {
-                final ByteBuffer headerBuf = getRecord();
-                if (headerBuf == null) {
-                    throw new ArchiveException("Premature end of tar archive. 
Didn't find extended_header after header with extended flag.");
-                }
+                final ByteBuffer headerBuf = 
ArchiveException.requireNonNull(getRecord(),
+                        "Premature end of tar archive. Didn't find 
extended_header after header with extended flag.");
                 entry = new TarArchiveSparseEntry(headerBuf.array());
                 currEntry.getSparseHeaders().addAll(entry.getSparseHeaders());
             } while (entry.isExtended());
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java 
b/src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
index c70837ecf..f24db5496 100644
--- a/src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
+++ b/src/main/java/org/apache/commons/compress/archivers/tar/TarUtils.java
@@ -468,14 +468,10 @@ static List<TarArchiveStructSparse> 
parseFromPAX01SparseHeaders(final String spa
             throw new ArchiveException("Corrupted TAR archive. Bad format in 
GNU.sparse.map PAX Header");
         }
         for (int i = 0; i < sparseHeaderStrings.length; i += 2) {
-            final long sparseOffset = 
ParsingUtils.parseLongValue(sparseHeaderStrings[i]);
-            if (sparseOffset < 0) {
-                throw new ArchiveException("Corrupted TAR archive. Sparse 
struct offset contains negative value");
-            }
-            final long sparseNumbytes = 
ParsingUtils.parseLongValue(sparseHeaderStrings[i + 1]);
-            if (sparseNumbytes < 0) {
-                throw new ArchiveException("Corrupted TAR archive. Sparse 
struct numbytes contains negative value");
-            }
+            final long sparseOffset = 
ArchiveException.requireNonNegative(ParsingUtils.parseLongValue(sparseHeaderStrings[i]),
+                    "Corrupted TAR archive. Sparse struct offset contains 
negative value");
+            final long sparseNumbytes = 
ArchiveException.requireNonNegative(ParsingUtils.parseLongValue(sparseHeaderStrings[i
 + 1]),
+                    "Corrupted TAR archive. Sparse struct numbytes contains 
negative value");
             sparseHeaders.add(new TarArchiveStructSparse(sparseOffset, 
sparseNumbytes));
         }
         return Collections.unmodifiableList(sparseHeaders);
@@ -629,25 +625,17 @@ static List<TarArchiveStructSparse> 
parsePAX1XSparseHeaders(final InputStream in
         final List<TarArchiveStructSparse> sparseHeaders = new ArrayList<>();
         long bytesRead = 0;
         long[] readResult = readLineOfNumberForPax1x(inputStream);
-        long sparseHeadersCount = readResult[0];
-        if (sparseHeadersCount < 0) {
-            // overflow while reading number?
-            throw new ArchiveException("Corrupted TAR archive: Negative value 
in sparse headers block.");
-        }
+        // overflow while reading number?
+        long sparseHeadersCount = 
ArchiveException.requireNonNegative(readResult[0], "Corrupted TAR archive: 
Negative value in sparse headers block.");
         bytesRead += readResult[1];
         while (sparseHeadersCount-- > 0) {
             readResult = readLineOfNumberForPax1x(inputStream);
-            final long sparseOffset = readResult[0];
-            if (sparseOffset < 0) {
-                throw new ArchiveException("Corrupted TAR archive: Sparse 
header block offset contains negative value.");
-            }
+            final long sparseOffset = 
ArchiveException.requireNonNegative(readResult[0],
+                    "Corrupted TAR archive: Sparse header block offset 
contains negative value.");
             bytesRead += readResult[1];
-
             readResult = readLineOfNumberForPax1x(inputStream);
-            final long sparseNumbytes = readResult[0];
-            if (sparseNumbytes < 0) {
-                throw new ArchiveException("Corrupted TAR archive: Sparse 
header block numbytes contains negative value.");
-            }
+            final long sparseNumbytes = 
ArchiveException.requireNonNegative(readResult[0],
+                    "Corrupted TAR archive: Sparse header block numbytes 
contains negative value.");
             bytesRead += readResult[1];
             sparseHeaders.add(new TarArchiveStructSparse(sparseOffset, 
sparseNumbytes));
         }
@@ -757,17 +745,17 @@ static Map<String, String> parsePaxHeaders(final 
InputStream inputStream, final
                                         throw new ArchiveException("Failed to 
read PAX header: %s is expected before GNU.sparse.numbytes shows up.",
                                                 TarGnuSparseKeys.OFFSET);
                                     }
-                                    final long numbytes;
+                                    final long numBytes;
                                     try {
-                                        numbytes = 
ParsingUtils.parseLongValue(value);
+                                        numBytes = 
ParsingUtils.parseLongValue(value);
                                     } catch (final IOException ex) {
                                         throw new ArchiveException("Failed to 
read PAX header: Numbytes %s contains a non-numeric value.",
                                                 TarGnuSparseKeys.NUMBYTES);
                                     }
-                                    if (numbytes < 0) {
+                                    if (numBytes < 0) {
                                         throw new ArchiveException("Failed to 
read PAX header: %s contains negative value.", TarGnuSparseKeys.NUMBYTES);
                                     }
-                                    sparseHeaders.add(new 
TarArchiveStructSparse(offset, numbytes));
+                                    sparseHeaders.add(new 
TarArchiveStructSparse(offset, numBytes));
                                     offset = null;
                                 }
                             }
@@ -866,17 +854,9 @@ static List<TarArchiveStructSparse> 
readSparseStructs(final byte[] buffer, final
         final List<TarArchiveStructSparse> sparseHeaders = new ArrayList<>();
         for (int i = 0; i < entries; i++) {
             try {
-                final TarArchiveStructSparse sparseHeader = parseSparse(buffer,
-                        offset + i * (TarConstants.SPARSE_OFFSET_LEN + 
TarConstants.SPARSE_NUMBYTES_LEN));
-                if (sparseHeader.getOffset() < 0) {
-                    throw new ArchiveException("Corrupted TAR archive: Sparse 
entry with negative offset.");
-                }
-                if (sparseHeader.getNumbytes() < 0) {
-                    throw new ArchiveException("Corrupted TAR archive: Sparse 
entry with negative numbytes.");
-                }
-                sparseHeaders.add(sparseHeader);
+                sparseHeaders.add(parseSparse(buffer, offset + i * 
(TarConstants.SPARSE_OFFSET_LEN + TarConstants.SPARSE_NUMBYTES_LEN)));
             } catch (final IllegalArgumentException e) {
-                // thrown internally by parseOctalOrBinary
+                // thrown internally by parseSparse
                 throw new ArchiveException("Corrupted TAR archive: Sparse 
entry is invalid.", (Throwable) e);
             }
         }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/UnshrinkingInputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/zip/UnshrinkingInputStream.java
index f589e6a36..45d9332dc 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/zip/UnshrinkingInputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/zip/UnshrinkingInputStream.java
@@ -97,10 +97,7 @@ protected int decompressNextSymbol() throws IOException {
             }
             return expandCodeToOutputStack(effectiveCode, 
addedUnfinishedEntry);
         }
-        final int subCode = readNextCode();
-        if (subCode < 0) {
-            throw new ArchiveException("Unexpected EOF");
-        }
+        final int subCode = 
ArchiveException.requireNonNegative(readNextCode(), "Unexpected EOF");
         if (subCode == 1) {
             if (getCodeSize() >= MAX_CODE_SIZE) {
                 throw new ArchiveException("Attempt to increase code size 
beyond maximum");
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.java
 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.java
index 1417b4029..c3cea98d6 100644
--- 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.java
+++ 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipArchiveOutputStream.java
@@ -1162,11 +1162,7 @@ private void preClose() throws IOException {
         if (finished) {
             throw new ArchiveException("Stream has already been finished");
         }
-
-        if (entry == null) {
-            throw new ArchiveException("No current entry to close");
-        }
-
+        ArchiveException.requireNonNull(entry, "No current entry to close");
         if (!entry.hasWritten) {
             write(ArrayUtils.EMPTY_BYTE_ARRAY, 0, 0);
         }
diff --git 
a/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java 
b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
index e43267b69..5b94db97a 100644
--- a/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
+++ b/src/main/java/org/apache/commons/compress/archivers/zip/ZipFile.java
@@ -585,12 +585,6 @@ private static boolean 
positionAtEndOfCentralDirectoryRecord(final SeekableByteC
         return found64;
     }
 
-    private static void requireNonNegative(final long value, final String 
message) throws ArchiveException {
-        if (value < 0) {
-            throw new ArchiveException(message);
-        }
-    }
-
     /**
      * Converts a raw version made by int to a <a 
href="https://pkwaredownloads.blob.core.windows.net/pkware-general/Documentation/APPNOTE_6.2.0.TXT";>platform
      * code</a>.
@@ -1423,14 +1417,14 @@ private void positionAtCentralDirectory64() throws 
IOException {
             dwordBbuf.rewind();
             IOUtils.readFully(archive, dwordBbuf);
             final long relativeOffsetOfEOCD = 
ZipEightByteInteger.getLongValue(dwordBuf);
-            requireNonNegative(relativeOffsetOfEOCD, "Broken archive, ZIP64 
end of central directory locator with negative offset");
+            ArchiveException.requireNonNegative(relativeOffsetOfEOCD, "Broken 
archive, ZIP64 end of central directory locator with negative offset");
             ((ZipSplitReadOnlySeekableByteChannel) 
archive).position(diskNumberOfEOCD, relativeOffsetOfEOCD);
         } else {
             skipBytes(ZIP64_EOCDL_LOCATOR_OFFSET - ZipConstants.WORD /* 
signature has already been read */);
             dwordBbuf.rewind();
             IOUtils.readFully(archive, dwordBbuf);
             final long relativeOffsetOfEOCD = 
ZipEightByteInteger.getLongValue(dwordBuf);
-            requireNonNegative(relativeOffsetOfEOCD, "Broken archive, ZIP64 
end of central directory locator with negative offset");
+            ArchiveException.requireNonNegative(relativeOffsetOfEOCD, "Broken 
archive, ZIP64 end of central directory locator with negative offset");
             archive.position(relativeOffsetOfEOCD);
         }
 
@@ -1451,7 +1445,8 @@ private void positionAtCentralDirectory64() throws 
IOException {
             dwordBbuf.rewind();
             IOUtils.readFully(archive, dwordBbuf);
             centralDirectoryStartRelativeOffset = 
ZipEightByteInteger.getLongValue(dwordBuf);
-            requireNonNegative(centralDirectoryStartRelativeOffset, "Broken 
archive, ZIP64 end of central directory record with negative central directory 
offset");
+            
ArchiveException.requireNonNegative(centralDirectoryStartRelativeOffset,
+                    "Broken archive, ZIP64 end of central directory record 
with negative central directory offset");
             ((ZipSplitReadOnlySeekableByteChannel) 
archive).position(centralDirectoryStartDiskNumber, 
centralDirectoryStartRelativeOffset);
         } else {
             skipBytes(ZIP64_EOCD_CFD_LOCATOR_OFFSET - ZipConstants.WORD /* 
signature has already been read */);
@@ -1459,7 +1454,8 @@ private void positionAtCentralDirectory64() throws 
IOException {
             IOUtils.readFully(archive, dwordBbuf);
             centralDirectoryStartDiskNumber = 0;
             centralDirectoryStartRelativeOffset = 
ZipEightByteInteger.getLongValue(dwordBuf);
-            requireNonNegative(centralDirectoryStartRelativeOffset, "Broken 
archive, ZIP64 end of central directory record with negative central directory 
offset");
+            
ArchiveException.requireNonNegative(centralDirectoryStartRelativeOffset,
+                    "Broken archive, ZIP64 end of central directory record 
with negative central directory offset");
             archive.position(centralDirectoryStartRelativeOffset);
         }
     }
@@ -1506,37 +1502,23 @@ private void readCentralDirectoryEntry(final 
Map<ZipArchiveEntry, NameAndComment
         ze.setCrc(ZipLong.getValue(cfhBuf, off));
         off += ZipConstants.WORD;
 
-        long size = ZipLong.getValue(cfhBuf, off);
-        if (size < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
compressed size");
-        }
+        long size = 
ArchiveException.requireNonNegative(ZipLong.getValue(cfhBuf, off), "Broken 
archive, entry with negative compressed size");
         ze.setCompressedSize(size);
         off += ZipConstants.WORD;
 
-        size = ZipLong.getValue(cfhBuf, off);
-        if (size < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
size");
-        }
+        size = ArchiveException.requireNonNegative(ZipLong.getValue(cfhBuf, 
off), "Broken archive, entry with negative size");
         ze.setSize(size);
         off += ZipConstants.WORD;
 
         final int fileNameLen = 
ArchiveUtils.checkEntryNameLength(ZipShort.getValue(cfhBuf, off), 
maxEntryNameLength, "ZIP");
+        ArchiveException.requireNonNegative(fileNameLen, "Broken archive, 
entry with negative fileNameLen");
         off += ZipConstants.SHORT;
-        if (fileNameLen < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
fileNameLen");
-        }
 
-        final int extraLen = ZipShort.getValue(cfhBuf, off);
+        final int extraLen = 
ArchiveException.requireNonNegative(ZipShort.getValue(cfhBuf, off), "Broken 
archive, entry with negative extraLen");
         off += ZipConstants.SHORT;
-        if (extraLen < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
extraLen");
-        }
 
-        final int commentLen = ZipShort.getValue(cfhBuf, off);
+        final int commentLen = 
ArchiveException.requireNonNegative(ZipShort.getValue(cfhBuf, off), "Broken 
archive, entry with negative commentLen");
         off += ZipConstants.SHORT;
-        if (commentLen < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
commentLen");
-        }
 
         ze.setDiskNumberStart(ZipShort.getValue(cfhBuf, off));
         off += ZipConstants.SHORT;
@@ -1615,12 +1597,8 @@ private void resolveLocalFileHeaderData(final 
Map<ZipArchiveEntry, NameAndCommen
     }
 
     private void sanityCheckLFHOffset(final ZipArchiveEntry entry) throws 
IOException {
-        if (entry.getDiskNumberStart() < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
disk number");
-        }
-        if (entry.getLocalHeaderOffset() < 0) {
-            throw new ArchiveException("Broken archive, entry with negative 
local file header offset");
-        }
+        ArchiveException.requireNonNegative(entry.getDiskNumberStart(), 
"Broken archive, entry with negative disk number");
+        ArchiveException.requireNonNegative(entry.getLocalHeaderOffset(), 
"Broken archive, entry with negative local file header offset");
         if (isSplitZipArchive) {
             if (entry.getDiskNumberStart() > centralDirectoryStartDiskNumber) {
                 throw new ArchiveException("Local file header for '%s' starts 
on a later disk than central directory", entry.getName());
@@ -1676,31 +1654,20 @@ private void setSizesAndOffsetFromZip64Extra(final 
ZipArchiveEntry entry) throws
             final boolean hasRelativeHeaderOffset = 
entry.getLocalHeaderOffset() == ZipConstants.ZIP64_MAGIC;
             final boolean hasDiskStart = entry.getDiskNumberStart() == 
ZipConstants.ZIP64_MAGIC_SHORT;
             z64.reparseCentralDirectoryData(hasUncompressedSize, 
hasCompressedSize, hasRelativeHeaderOffset, hasDiskStart);
-
             if (hasUncompressedSize) {
-                final long size = z64.getSize().getLongValue();
-                if (size < 0) {
-                    throw new ArchiveException("Broken archive, entry with 
negative size");
-                }
-                entry.setSize(size);
+                
entry.setSize(ArchiveException.requireNonNegative(z64.getSize().getLongValue(), 
"Broken archive, entry with negative size"));
             } else if (hasCompressedSize) {
                 z64.setSize(new ZipEightByteInteger(entry.getSize()));
             }
-
             if (hasCompressedSize) {
-                final long size = z64.getCompressedSize().getLongValue();
-                if (size < 0) {
-                    throw new ArchiveException("Broken archive, entry with 
negative compressed size");
-                }
-                entry.setCompressedSize(size);
+                entry.setCompressedSize(
+                        
ArchiveException.requireNonNegative(z64.getCompressedSize().getLongValue(), 
"Broken archive, entry with negative compressed size"));
             } else if (hasUncompressedSize) {
                 z64.setCompressedSize(new 
ZipEightByteInteger(entry.getCompressedSize()));
             }
-
             if (hasRelativeHeaderOffset) {
                 
entry.setLocalHeaderOffset(z64.getRelativeHeaderOffset().getLongValue());
             }
-
             if (hasDiskStart) {
                 entry.setDiskNumberStart(z64.getDiskStartNumber().getValue());
             }
diff --git 
a/src/test/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStreamTest.java
 
b/src/test/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStreamTest.java
index f38aab93e..2b25da5fb 100644
--- 
a/src/test/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStreamTest.java
+++ 
b/src/test/java/org/apache/commons/compress/archivers/lha/LhaArchiveInputStreamTest.java
@@ -129,7 +129,7 @@ private ZonedDateTime convertSystemTimeZoneDateToUTC(final 
Date date) {
     }
 
     private String getPathname(final LhaArchiveInputStream is, final int... 
filepathBuffer) throws ArchiveException, UnsupportedEncodingException {
-        return is.getPathname(ByteBuffer.wrap(toByteArray(filepathBuffer)), 
filepathBuffer.length);
+        return is.getPathName(ByteBuffer.wrap(toByteArray(filepathBuffer)), 
filepathBuffer.length);
     }
 
     private InputStream newEmptyInputStream() {
@@ -237,7 +237,7 @@ void testGetPathnameInvalidLength() throws IOException, 
UnsupportedEncodingExcep
         try (LhaArchiveInputStream is = 
LhaArchiveInputStream.builder().setInputStream(newEmptyInputStream()).get()) {
             try {
                 final byte[] pathname = { 'a', 'b', 'c' };
-                is.getPathname(ByteBuffer.wrap(pathname), pathname.length + 1);
+                is.getPathName(ByteBuffer.wrap(pathname), pathname.length + 1);
                 fail("Expected ArchiveException for invalid pathname length");
             } catch (final ArchiveException e) {
                 assertEquals("Invalid pathname length", e.getMessage());
@@ -249,7 +249,7 @@ void testGetPathnameInvalidLength() throws IOException, 
UnsupportedEncodingExcep
     void testGetPathnameNegativeLength() throws IOException, 
UnsupportedEncodingException {
         try (LhaArchiveInputStream is = 
LhaArchiveInputStream.builder().setInputStream(newEmptyInputStream()).get()) {
             try {
-                is.getPathname(ByteBuffer.wrap(new byte[0]), -1);
+                is.getPathName(ByteBuffer.wrap(new byte[0]), -1);
                 fail("Expected ArchiveException when pathname length is 
negative");
             } catch (final ArchiveException e) {
                 assertEquals("Pathname length is negative", e.getMessage());
@@ -262,7 +262,7 @@ void testGetPathnameTooLong() throws IOException, 
UnsupportedEncodingException {
         try (LhaArchiveInputStream is = 
LhaArchiveInputStream.builder().setInputStream(newEmptyInputStream()).get()) {
             try {
                 final byte[] pathname = new byte[4097];
-                is.getPathname(ByteBuffer.wrap(pathname), pathname.length);
+                is.getPathName(ByteBuffer.wrap(pathname), pathname.length);
                 fail("Expected ArchiveException when pathname is longer than 
the maximum allowed");
             } catch (final ArchiveException e) {
                 assertEquals("Pathname is longer than the maximum allowed 
(4097 > 4096)", e.getMessage());

Reply via email to