From a063e18b656851f7db469f20e52b5fbde9778d12 Mon Sep 17 00:00:00 2001 From: Joaquin Azcarate Date: Fri, 14 Oct 2022 09:17:55 +0200 Subject: [PATCH] Use `int` for the ByteAggregator to not overflow when creating the underlying ByteArrayOutputStream. Bonus: Fix warnings on the `ByteAggregatorTest` --- .../com/king/platform/net/http/ByteAggregator.java | 12 ++++++++++-- .../king/platform/net/http/ByteAggregatorTest.java | 14 +++++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/client/src/main/java/com/king/platform/net/http/ByteAggregator.java b/client/src/main/java/com/king/platform/net/http/ByteAggregator.java index 3070c86..49f5ba8 100644 --- a/client/src/main/java/com/king/platform/net/http/ByteAggregator.java +++ b/client/src/main/java/com/king/platform/net/http/ByteAggregator.java @@ -16,16 +16,24 @@ public class ByteAggregator { private final ByteArrayOutputStream byteArrayOutputStream; private final WritableByteChannel channel; - public ByteAggregator(long contentLength) { + public ByteAggregator(int contentLength) { if (contentLength < 0) { contentLength = 1024; } - byteArrayOutputStream = new ByteArrayOutputStream((int) contentLength); + byteArrayOutputStream = new ByteArrayOutputStream(contentLength); channel = Channels.newChannel(byteArrayOutputStream); } + /** + * @deprecated Use the {@link ByteAggregator#ByteAggregator(int)} constructor instead + */ + @Deprecated + public ByteAggregator(long contentLength) { + this(Math.toIntExact(contentLength)); + } + public void write(ByteBuffer buffer) throws IOException { channel.write(buffer); } diff --git a/client/src/test/java/com/king/platform/net/http/ByteAggregatorTest.java b/client/src/test/java/com/king/platform/net/http/ByteAggregatorTest.java index 762697a..6c671f3 100644 --- a/client/src/test/java/com/king/platform/net/http/ByteAggregatorTest.java +++ b/client/src/test/java/com/king/platform/net/http/ByteAggregatorTest.java @@ -8,12 +8,20 @@ import org.junit.jupiter.api.Test; -import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertThrows; public class ByteAggregatorTest { @Test - public void constructorShouldNotThrowExceptionWhenSuppliedWithNegativeLength() throws Exception { - assertNotNull(new ByteAggregator(-100)); + public void constructorShouldNotThrowExceptionWhenSuppliedWithNegativeLength() { + assertDoesNotThrow(() -> new ByteAggregator(-100)); + } + + + @Test + @SuppressWarnings("deprecation") + public void constructorShouldThrowExceptionWhenSuppliedWithABigLongNumber() { + assertThrows(ArithmeticException.class, () -> new ByteAggregator((long) Integer.MAX_VALUE + 3)); } }