fix issue in IOUtils.toByteArrayWithMaxLength

git-svn-id: https://svn.apache.org/repos/asf/poi/trunk@1898862 13f79535-47bb-0310-9956-ffa450edef68
This commit is contained in:
PJ Fanning 2022-03-11 21:45:02 +00:00
parent f4bfcaeec9
commit 5b5f286a30
2 changed files with 31 additions and 5 deletions

View File

@ -216,13 +216,15 @@ public final class IOUtils {
checkByteSizeLimit(totalBytes);
} while (totalBytes < derivedLen && readBytes > -1);
if (checkEOFException) {
if (derivedMaxLength != Integer.MAX_VALUE && totalBytes == derivedMaxLength) {
throw new IOException("MaxLength (" + derivedMaxLength + ") reached - stream seems to be invalid.");
}
if (checkEOFException && derivedLen != Integer.MAX_VALUE && totalBytes < derivedLen) {
if (derivedLen != Integer.MAX_VALUE && totalBytes < derivedLen) {
throw new EOFException("unexpected EOF - expected len: " + derivedLen + " - actual len: " + totalBytes);
}
}
return baos.toByteArray();
}

View File

@ -143,6 +143,30 @@ final class TestIOUtils {
IOUtils.toByteArray(ByteBuffer.wrap(new byte[]{1, 2, 3, 4, 5, 6, 7}), 3));
}
@Test
void testToByteArrayMaxLength() throws IOException {
final byte[] array = new byte[]{1, 2, 3, 4, 5, 6, 7};
try (ByteArrayInputStream is = new ByteArrayInputStream(array)) {
assertArrayEquals(array, IOUtils.toByteArrayWithMaxLength(is, 7));
}
}
@Test
void testToByteArrayMaxLengthLongerThanArray() throws IOException {
final byte[] array = new byte[]{1, 2, 3, 4, 5, 6, 7};
try (ByteArrayInputStream is = new ByteArrayInputStream(array)) {
assertArrayEquals(array, IOUtils.toByteArrayWithMaxLength(is, 8));
}
}
@Test
void testToByteArrayMaxLengthShorterThanArray() throws IOException {
final byte[] array = new byte[]{1, 2, 3, 4, 5, 6, 7};
try (ByteArrayInputStream is = new ByteArrayInputStream(array)) {
assertArrayEquals(new byte[]{1, 2, 3}, IOUtils.toByteArrayWithMaxLength(is, 3));
}
}
@Test
void testSkipFully() throws IOException {
try (InputStream is = new FileInputStream(TMP)) {