From 40de4d6452551ffee824ae0bedd83d62041a72bd Mon Sep 17 00:00:00 2001 From: Gary Gregory Date: Fri, 30 Aug 2024 13:48:03 -0400 Subject: [PATCH] Refactor duplicate code in tests - Add missing Javadoc - Do not allocate Message objects needlessly - Reduce String building - No need to call constructor with the default value, an AtomicBoolean is false by default. - Access ArgumentMatchers static methods directly - Use try-with-resources --- .../http2/impl/nio/ClientH2StreamHandler.java | 6 +- .../impl/nio/ClientPushH2StreamHandler.java | 4 +- .../http2/impl/nio/ServerH2StreamHandler.java | 6 +- .../impl/nio/ServerPushH2StreamHandler.java | 6 +- .../nio/bootstrap/CancellableExecution.java | 2 +- .../nio/TestAbstractH2StreamMultiplexer.java | 25 +- .../core5/reactive/ReactiveDataConsumer.java | 2 +- .../core5/reactive/ReactiveDataProducer.java | 2 +- httpcore5-testing/pom.xml | 5 + .../testing/nio/ClientSessionEndpoint.java | 2 +- .../http2/H2CompatibilityTest.java | 16 +- .../hc/core5/testing/nio/H2ConnPoolTest.java | 57 +--- .../nio/H2CoreTransportMultiplexingTest.java | 24 +- .../testing/reactive/ReactiveClientTest.java | 6 +- .../hc/core5/concurrent/FutureCallback.java | 2 +- .../core5/concurrent/FutureContribution.java | 5 + .../org/apache/hc/core5/http/Message.java | 31 +- .../http/impl/bootstrap/RequestListener.java | 2 +- .../hc/core5/http/impl/io/HttpService.java | 2 +- .../impl/nio/ClientHttp1StreamHandler.java | 4 +- .../impl/nio/ServerHttp1StreamHandler.java | 4 +- .../support/BasicClientExchangeHandler.java | 4 +- .../nio/support/BasicRequestConsumer.java | 6 +- .../nio/support/BasicResponseConsumer.java | 6 +- .../AbstractClassicServerExchangeHandler.java | 2 +- .../org/apache/hc/core5/pool/LaxConnPool.java | 4 +- .../apache/hc/core5/pool/StrictConnPool.java | 4 +- .../core5/reactor/AbstractIOSessionPool.java | 2 +- .../hc/core5/reactor/InternalDataChannel.java | 2 +- .../core5/reactor/ListenerEndpointImpl.java | 2 +- .../hc/core5/reactor/SingleCoreIOReactor.java | 2 +- .../reactor/SingleCoreListeningIOReactor.java | 2 +- .../CountDownLatchFutureCallback.java | 95 ++++++ .../concurrent/CountingFutureCallback.java | 74 +++++ .../concurrent/FutureCallbackAdapter.java | 67 +++++ .../hc/core5/concurrent/TestBasicFuture.java | 41 +-- .../apache/hc/core5/http/TestHttpHost.java | 6 +- .../core5/http/impl/io/TestChunkCoding.java | 271 +++++++++--------- .../impl/io/TestContentLengthInputStream.java | 74 ++--- .../io/TestContentLengthOutputStream.java | 22 +- .../http/impl/io/TestIdentityInputStream.java | 40 +-- .../impl/io/TestIdentityOutputStream.java | 36 +-- ...ractHttp1StreamDuplexerCapacityWindow.java | 5 +- .../core5/http/io/entity/TestFileEntity.java | 18 +- .../http/message/TestBufferedHeader.java | 6 +- .../hc/core5/http/message/TestHeader.java | 6 +- .../core5/http/message/TestHeaderGroup.java | 6 +- .../TestAbstractBinAsyncEntityConsumer.java | 28 +- .../TestAbstractCharAsyncEntityConsumer.java | 51 +--- .../org/apache/hc/core5/net/TestHost.java | 6 +- .../apache/hc/core5/net/TestURIAuthority.java | 6 +- .../hc/core5/ssl/TestSSLContextBuilder.java | 5 +- pom.xml | 6 + 53 files changed, 630 insertions(+), 488 deletions(-) create mode 100644 httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountDownLatchFutureCallback.java create mode 100644 httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountingFutureCallback.java create mode 100644 httpcore5/src/test/java/org/apache/hc/core5/concurrent/FutureCallbackAdapter.java diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2StreamHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2StreamHandler.java index 4caa5c9cde..44271518c3 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2StreamHandler.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2StreamHandler.java @@ -110,9 +110,9 @@ public void endStream() throws IOException { this.exchangeHandler = exchangeHandler; this.pushHandlerFactory = pushHandlerFactory; this.context = context; - this.requestCommitted = new AtomicBoolean(false); - this.failed = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.requestCommitted = new AtomicBoolean(); + this.failed = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.requestState = MessageState.HEADERS; this.responseState = MessageState.HEADERS; } diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientPushH2StreamHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientPushH2StreamHandler.java index fe1a0f3681..d911c689ec 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientPushH2StreamHandler.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientPushH2StreamHandler.java @@ -78,8 +78,8 @@ class ClientPushH2StreamHandler implements H2StreamHandler { this.connMetrics = connMetrics; this.pushHandlerFactory = pushHandlerFactory; this.context = context; - this.failed = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.failed = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.requestState = MessageState.HEADERS; this.responseState = MessageState.HEADERS; } diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java index cc5b85d1c9..b754e8e67b 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2StreamHandler.java @@ -137,9 +137,9 @@ public void pushPromise( this.connMetrics = connMetrics; this.exchangeHandlerFactory = exchangeHandlerFactory; this.context = context; - this.responseCommitted = new AtomicBoolean(false); - this.failed = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.responseCommitted = new AtomicBoolean(); + this.failed = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.requestState = MessageState.HEADERS; this.responseState = MessageState.IDLE; } diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerPushH2StreamHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerPushH2StreamHandler.java index dda20defa5..e13bdf3769 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerPushH2StreamHandler.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerPushH2StreamHandler.java @@ -105,9 +105,9 @@ public void endStream() throws IOException { this.connMetrics = connMetrics; this.pushProducer = pushProducer; this.context = context; - this.responseCommitted = new AtomicBoolean(false); - this.failed = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.responseCommitted = new AtomicBoolean(); + this.failed = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.requestState = MessageState.COMPLETE; this.responseState = MessageState.IDLE; } diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/CancellableExecution.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/CancellableExecution.java index 84e89dc18b..3292371cdf 100644 --- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/CancellableExecution.java +++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/CancellableExecution.java @@ -38,7 +38,7 @@ final class CancellableExecution implements CancellableDependency { private final AtomicReference dependencyRef; CancellableExecution() { - this.cancelled = new AtomicBoolean(false); + this.cancelled = new AtomicBoolean(); this.dependencyRef = new AtomicReference<>(); } diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java index 0400c05761..976d1913bb 100644 --- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java +++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/impl/nio/TestAbstractH2StreamMultiplexer.java @@ -49,6 +49,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -139,9 +140,9 @@ void testInputOneFrame() throws Exception { Assertions.assertThrows(H2ConnectionException.class, () -> streamMultiplexer.onInput(ByteBuffer.wrap(bytes))); Mockito.verify(h2StreamListener).onFrameInput( - Mockito.same(streamMultiplexer), - Mockito.eq(1), - Mockito.any()); + ArgumentMatchers.same(streamMultiplexer), + ArgumentMatchers.eq(1), + ArgumentMatchers.any()); Assertions.assertThrows(H2ConnectionException.class, () -> { int pos = 0; @@ -154,9 +155,9 @@ void testInputOneFrame() throws Exception { } Mockito.verify(h2StreamListener).onFrameInput( - Mockito.same(streamMultiplexer), - Mockito.eq(1), - Mockito.any()); + ArgumentMatchers.same(streamMultiplexer), + ArgumentMatchers.eq(1), + ArgumentMatchers.any()); }); } @@ -190,9 +191,9 @@ void testInputMultipleFrames() throws Exception { Assertions.assertThrows(H2ConnectionException.class, () -> streamMultiplexer.onInput(ByteBuffer.wrap(bytes))); Mockito.verify(h2StreamListener).onFrameInput( - Mockito.same(streamMultiplexer), - Mockito.eq(1), - Mockito.any()); + ArgumentMatchers.same(streamMultiplexer), + ArgumentMatchers.eq(1), + ArgumentMatchers.any()); Assertions.assertThrows(H2ConnectionException.class, () -> { int pos = 0; @@ -205,9 +206,9 @@ void testInputMultipleFrames() throws Exception { } Mockito.verify(h2StreamListener).onFrameInput( - Mockito.same(streamMultiplexer), - Mockito.eq(1), - Mockito.any()); + ArgumentMatchers.same(streamMultiplexer), + ArgumentMatchers.eq(1), + ArgumentMatchers.any()); }); } diff --git a/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataConsumer.java b/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataConsumer.java index 77ff45fbb0..0414326043 100644 --- a/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataConsumer.java +++ b/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataConsumer.java @@ -58,7 +58,7 @@ final class ReactiveDataConsumer implements AsyncDataConsumer, Publisher buffers = new LinkedBlockingQueue<>(); - private final AtomicBoolean flushInProgress = new AtomicBoolean(false); + private final AtomicBoolean flushInProgress = new AtomicBoolean(); private final AtomicInteger windowScalingIncrement = new AtomicInteger(0); private volatile boolean cancelled; private volatile boolean completed; diff --git a/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataProducer.java b/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataProducer.java index 036881c2fe..55981b85cd 100644 --- a/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataProducer.java +++ b/httpcore5-reactive/src/main/java/org/apache/hc/core5/reactive/ReactiveDataProducer.java @@ -55,7 +55,7 @@ final class ReactiveDataProducer implements AsyncDataProducer, Subscriber requestChannel = new AtomicReference<>(); private final AtomicReference exception = new AtomicReference<>(); - private final AtomicBoolean complete = new AtomicBoolean(false); + private final AtomicBoolean complete = new AtomicBoolean(); private final Publisher publisher; private final AtomicReference subscription = new AtomicReference<>(); private final ArrayDeque buffers = new ArrayDeque<>(); // This field requires synchronization diff --git a/httpcore5-testing/pom.xml b/httpcore5-testing/pom.xml index 53647a3fb2..ff2123fa3e 100644 --- a/httpcore5-testing/pom.xml +++ b/httpcore5-testing/pom.xml @@ -70,6 +70,11 @@ rxjava ${rxjava3.version} + + org.apache.httpcomponents.core5 + httpcore5 + tests + org.apache.logging.log4j log4j-slf4j-impl diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/ClientSessionEndpoint.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/ClientSessionEndpoint.java index 824708d767..ba3761b66e 100644 --- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/ClientSessionEndpoint.java +++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/ClientSessionEndpoint.java @@ -66,7 +66,7 @@ public final class ClientSessionEndpoint implements ModalCloseable { public ClientSessionEndpoint(final IOSession ioSession) { super(); this.ioSession = ioSession; - this.closed = new AtomicBoolean(false); + this.closed = new AtomicBoolean(); } public void execute(final Command command, final Command.Priority priority) { diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/compatibility/http2/H2CompatibilityTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/compatibility/http2/H2CompatibilityTest.java index 36322334c4..e2ca5c66fa 100644 --- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/compatibility/http2/H2CompatibilityTest.java +++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/compatibility/http2/H2CompatibilityTest.java @@ -285,24 +285,16 @@ void executeHttpBin(final HttpHost target) throws Exception { System.out.println("*** httpbin.org HTTP/1.1 simple request execution ***"); final List> requestMessages = Arrays.asList( - new Message<>( - new BasicHttpRequest(Method.GET, target, "/headers"), - null), + new Message<>(new BasicHttpRequest(Method.GET, target, "/headers")), new Message<>( new BasicHttpRequest(Method.POST, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), new Message<>( new BasicHttpRequest(Method.PUT, target, "/anything"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), - new Message<>( - new BasicHttpRequest(Method.GET, target, "/drip"), - null), - new Message<>( - new BasicHttpRequest(Method.GET, target, "/bytes/20000"), - null), - new Message<>( - new BasicHttpRequest(Method.GET, target, "/delay/2"), - null), + new Message<>(new BasicHttpRequest(Method.GET, target, "/drip")), + new Message<>(new BasicHttpRequest(Method.GET, target, "/bytes/20000")), + new Message<>(new BasicHttpRequest(Method.GET, target, "/delay/2")), new Message<>( new BasicHttpRequest(Method.POST, target, "/delay/2"), new StringAsyncEntityProducer("some important message", ContentType.TEXT_PLAIN)), diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java index 2a97ce1831..cf80289d34 100644 --- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java +++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2ConnPoolTest.java @@ -28,11 +28,10 @@ package org.apache.hc.core5.testing.nio; import java.net.InetSocketAddress; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.atomic.AtomicLong; -import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.concurrent.CountDownLatchFutureCallback; import org.apache.hc.core5.function.Supplier; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.URIScheme; @@ -113,29 +112,18 @@ void testManyGetSession() throws Exception { final H2MultiplexingRequester requester = clientResource.start(); final H2ConnPool connPool = requester.getConnPool(); - final CountDownLatch latch = new CountDownLatch(n); + final CountDownLatchFutureCallback latch = new CountDownLatchFutureCallback(n) { + + @Override + public void completed(final IOSession session) { + session.enqueue(new PingCommand(new BasicPingHandler( + result -> countDown() + )), Command.Priority.IMMEDIATE); + } + + }; for (int i = 0; i < n; i++) { - connPool.getSession(target, TIMEOUT, new FutureCallback() { - - @Override - public void completed(final IOSession session) { - session.enqueue(new PingCommand(new BasicPingHandler( - result -> { - latch.countDown(); - })), Command.Priority.IMMEDIATE); - } - - @Override - public void failed(final Exception ex) { - latch.countDown(); - } - - @Override - public void cancelled() { - latch.countDown(); - } - - }); + connPool.getSession(target, TIMEOUT, latch); } Assertions.assertTrue(latch.await(TIMEOUT.getDuration(), TIMEOUT.getTimeUnit())); @@ -153,27 +141,10 @@ void testManyGetSessionFailures() throws Exception { final H2MultiplexingRequester requester = clientResource.start(); final H2ConnPool connPool = requester.getConnPool(); - final CountDownLatch latch = new CountDownLatch(n); + final CountDownLatchFutureCallback latch = new CountDownLatchFutureCallback<>(n); for (int i = 0; i < n; i++) { - connPool.getSession(target, TIMEOUT, new FutureCallback() { - - @Override - public void completed(final IOSession session) { - latch.countDown(); - } - - @Override - public void failed(final Exception ex) { - latch.countDown(); - } - - @Override - public void cancelled() { - latch.countDown(); - } - - }); + connPool.getSession(target, TIMEOUT, latch); } requester.initiateShutdown(); diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2CoreTransportMultiplexingTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2CoreTransportMultiplexingTest.java index e2d41af2f7..28b14c5483 100644 --- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2CoreTransportMultiplexingTest.java +++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2CoreTransportMultiplexingTest.java @@ -33,11 +33,10 @@ import java.util.LinkedList; import java.util.Queue; import java.util.Random; -import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import org.apache.hc.core5.concurrent.Cancellable; -import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.concurrent.CountDownLatchFutureCallback; import org.apache.hc.core5.function.Supplier; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpHost; @@ -233,7 +232,7 @@ void testMultiplexedRequestCancellation() throws Exception { final int reqNo = 20; - final CountDownLatch countDownLatch = new CountDownLatch(reqNo); + final CountDownLatchFutureCallback> countDownLatch = new CountDownLatchFutureCallback<>(reqNo); final Random random = new Random(); final HttpHost target = new HttpHost(scheme.id, "localhost", address.getPort()); for (int i = 0; i < reqNo; i++) { @@ -241,24 +240,7 @@ void testMultiplexedRequestCancellation() throws Exception { new BasicClientExchangeHandler<>(new BasicRequestProducer(Method.POST, target, "/stuff", new StringAsyncEntityProducer("some stuff", ContentType.TEXT_PLAIN)), new BasicResponseConsumer<>(new StringAsyncEntityConsumer()), - new FutureCallback>() { - - @Override - public void completed(final Message result) { - countDownLatch.countDown(); - } - - @Override - public void failed(final Exception ex) { - countDownLatch.countDown(); - } - - @Override - public void cancelled() { - countDownLatch.countDown(); - } - - }), + countDownLatch), TIMEOUT, HttpCoreContext.create()); Thread.sleep(random.nextInt(10)); diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/reactive/ReactiveClientTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/reactive/ReactiveClientTest.java index f25bf4a7af..e4bf3a9485 100644 --- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/reactive/ReactiveClientTest.java +++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/reactive/ReactiveClientTest.java @@ -211,7 +211,7 @@ void testRequestError() throws Exception { void testRequestTimeout() throws Exception { final InetSocketAddress address = startServer(); final HttpAsyncRequester requester = clientResource.start(); - final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(false); + final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(); final Publisher publisher = Flowable.never() .doOnCancel(() -> requestPublisherWasCancelled.set(true)); final ReactiveEntityProducer producer = new ReactiveEntityProducer(publisher, -1, null, null); @@ -237,7 +237,7 @@ void testRequestTimeout() throws Exception { void testResponseCancellation() throws Exception { final InetSocketAddress address = startServer(); final HttpAsyncRequester requester = clientResource.start(); - final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(false); + final AtomicBoolean requestPublisherWasCancelled = new AtomicBoolean(); final AtomicReference requestStreamError = new AtomicReference<>(); final Publisher stream = Reactive3TestUtils.produceStream(Long.MAX_VALUE, 1024, null) .doOnCancel(() -> requestPublisherWasCancelled.set(true)) @@ -250,7 +250,7 @@ void testResponseCancellation() throws Exception { final Message> response = consumer.getResponseFuture() .get(RESULT_TIMEOUT.getDuration(), RESULT_TIMEOUT.getTimeUnit()); - final AtomicBoolean responsePublisherWasCancelled = new AtomicBoolean(false); + final AtomicBoolean responsePublisherWasCancelled = new AtomicBoolean(); final List outputBuffers = Flowable.fromPublisher(response.getBody()) .doOnCancel(() -> responsePublisherWasCancelled.set(true)) .take(3) diff --git a/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureCallback.java b/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureCallback.java index c286506a06..5f2b05d2f5 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureCallback.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureCallback.java @@ -29,7 +29,7 @@ /** * A callback interface that gets invoked upon completion of a {@link java.util.concurrent.Future}. * - * @param the future result type returned by this callback. + * @param the future result type consumed by this callback. * @since 4.2 */ public interface FutureCallback { diff --git a/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureContribution.java b/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureContribution.java index 8960b4adb4..88cd68b5b2 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureContribution.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/concurrent/FutureContribution.java @@ -37,6 +37,11 @@ public abstract class FutureContribution implements FutureCallback { private final BasicFuture future; + /** + * Constructs a new instance to callback the given {@link BasicFuture}. + * + * @param future The callback. + */ public FutureContribution(final BasicFuture future) { this.future = future; } diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java b/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java index f726291596..b60d9724b1 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/Message.java @@ -42,25 +42,48 @@ public final class Message { private final H head; private final B body; + /** + * Constructs a new instance. + * + * @param head The message head. + * @since 5.3 + */ + public Message(final H head) { + this(head, null); + } + + /** + * Constructs a new instance. + * + * @param head The message head. + * @param body The message body. + */ public Message(final H head, final B body) { this.head = Args.notNull(head, "Message head"); this.body = body; } + /** + * Gets the message head. + * + * @return the message head. + */ public H getHead() { return head; } + /** + * Gets the message body. + * + * @return the message body. + */ public B getBody() { return body; } @Override public String toString() { - return "[" + - "head=" + head + - ", body=" + body + - ']'; + return "[head=" + head + ", body=" + body + ']'; } } diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/RequestListener.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/RequestListener.java index ae801f7599..1c58748a94 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/RequestListener.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/RequestListener.java @@ -76,7 +76,7 @@ public RequestListener( this.sslSetupHandler = sslSetupHandler; this.exceptionListener = exceptionListener; this.executorService = executorService; - this.terminated = new AtomicBoolean(false); + this.terminated = new AtomicBoolean(); } private HttpServerConnection createConnection(final Socket socket) throws IOException { diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java index 9aad25dc50..d21f69b935 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/HttpService.java @@ -197,7 +197,7 @@ public void handleRequest( final HttpServerConnection conn, final HttpContext localContext) throws IOException, HttpException { - final AtomicBoolean responseSubmitted = new AtomicBoolean(false); + final AtomicBoolean responseSubmitted = new AtomicBoolean(); final HttpCoreContext context = HttpCoreContext.cast(localContext); try { final ClassicHttpRequest request = conn.receiveRequestHeader(); diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ClientHttp1StreamHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ClientHttp1StreamHandler.java index 0d6baa8d1f..62dd4c242e 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ClientHttp1StreamHandler.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ClientHttp1StreamHandler.java @@ -112,8 +112,8 @@ public void endStream() throws IOException { this.connectionReuseStrategy = connectionReuseStrategy; this.exchangeHandler = exchangeHandler; this.context = context; - this.requestCommitted = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.requestCommitted = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.keepAlive = true; this.requestState = MessageState.IDLE; this.responseState = MessageState.HEADERS; diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java index 55a7a457b3..a03ce059ec 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ServerHttp1StreamHandler.java @@ -149,8 +149,8 @@ public String toString() { this.connectionReuseStrategy = connectionReuseStrategy; this.exchangeHandlerFactory = exchangeHandlerFactory; this.context = context; - this.responseCommitted = new AtomicBoolean(false); - this.done = new AtomicBoolean(false); + this.responseCommitted = new AtomicBoolean(); + this.done = new AtomicBoolean(); this.keepAlive = true; this.requestState = MessageState.HEADERS; this.responseState = MessageState.IDLE; diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicClientExchangeHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicClientExchangeHandler.java index 586c21946b..467b9d637b 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicClientExchangeHandler.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicClientExchangeHandler.java @@ -68,9 +68,9 @@ public BasicClientExchangeHandler( final FutureCallback resultCallback) { this.requestProducer = Args.notNull(requestProducer, "Request producer"); this.responseConsumer = Args.notNull(responseConsumer, "Response consumer"); - this.completed = new AtomicBoolean(false); + this.completed = new AtomicBoolean(); this.resultCallback = resultCallback; - this.outputTerminated = new AtomicBoolean(false); + this.outputTerminated = new AtomicBoolean(); } @Override diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicRequestConsumer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicRequestConsumer.java index 6f2c76377d..c1c8e53e54 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicRequestConsumer.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicRequestConsumer.java @@ -84,17 +84,15 @@ public void consumeRequest( @Override public void completed(final T body) { - final Message result = new Message<>(request, body); if (resultCallback != null) { - resultCallback.completed(result); + resultCallback.completed(new Message<>(request, body)); } } }); } else { - final Message result = new Message<>(request, null); if (resultCallback != null) { - resultCallback.completed(result); + resultCallback.completed(new Message<>(request)); } } } diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicResponseConsumer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicResponseConsumer.java index e3bb76db85..6b9e67dc68 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicResponseConsumer.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/BasicResponseConsumer.java @@ -84,17 +84,15 @@ public void consumeResponse( @Override public void completed(final T body) { - final Message result = new Message<>(response, body); if (resultCallback != null) { - resultCallback.completed(result); + resultCallback.completed(new Message<>(response, body)); } } }); } else { - final Message result = new Message<>(response, null); if (resultCallback != null) { - resultCallback.completed(result); + resultCallback.completed(new Message<>(response)); } } } diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/classic/AbstractClassicServerExchangeHandler.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/classic/AbstractClassicServerExchangeHandler.java index 9dda9a0752..421e46d307 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/classic/AbstractClassicServerExchangeHandler.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/support/classic/AbstractClassicServerExchangeHandler.java @@ -111,7 +111,7 @@ public final void handleRequest( final EntityDetails entityDetails, final ResponseChannel responseChannel, final HttpContext context) throws HttpException, IOException { - final AtomicBoolean responseCommitted = new AtomicBoolean(false); + final AtomicBoolean responseCommitted = new AtomicBoolean(); final HttpResponse response = new BasicHttpResponse(HttpStatus.SC_OK); final HttpResponse responseWrapper = new HttpResponseWrapper(response){ diff --git a/httpcore5/src/main/java/org/apache/hc/core5/pool/LaxConnPool.java b/httpcore5/src/main/java/org/apache/hc/core5/pool/LaxConnPool.java index d579b2cdc1..b680ae63df 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/pool/LaxConnPool.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/pool/LaxConnPool.java @@ -96,7 +96,7 @@ public LaxConnPool( this.disposalCallback = disposalCallback; this.connPoolListener = connPoolListener; this.routeToPool = new ConcurrentHashMap<>(); - this.isShutDown = new AtomicBoolean(false); + this.isShutDown = new AtomicBoolean(); this.defaultMaxPerRoute = defaultMaxPerRoute; } @@ -382,7 +382,7 @@ private enum RequestServiceStrategy { FIRST_SUCCESSFUL, ALL } this.leased = new ConcurrentHashMap<>(); this.available = new ConcurrentLinkedDeque<>(); this.pending = new ConcurrentLinkedDeque<>(); - this.terminated = new AtomicBoolean(false); + this.terminated = new AtomicBoolean(); this.allocated = new AtomicInteger(0); this.releaseSeqNum = new AtomicLong(0); this.max = max; diff --git a/httpcore5/src/main/java/org/apache/hc/core5/pool/StrictConnPool.java b/httpcore5/src/main/java/org/apache/hc/core5/pool/StrictConnPool.java index f4154cb73f..819238b38b 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/pool/StrictConnPool.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/pool/StrictConnPool.java @@ -107,7 +107,7 @@ public StrictConnPool( this.completedRequests = new ConcurrentLinkedQueue<>(); this.maxPerRoute = new HashMap<>(); this.lock = new ReentrantLock(); - this.isShutDown = new AtomicBoolean(false); + this.isShutDown = new AtomicBoolean(); this.defaultMaxPerRoute = defaultMaxPerRoute; this.maxTotal = maxTotal; } @@ -695,7 +695,7 @@ public LeaseRequest( this.state = state; this.deadline = Deadline.calculate(requestTimeout); this.future = future; - this.completed = new AtomicBoolean(false); + this.completed = new AtomicBoolean(); } public T getRoute() { diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java index 2651395735..3691264aab 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/AbstractIOSessionPool.java @@ -64,7 +64,7 @@ public abstract class AbstractIOSessionPool implements ModalCloseable { public AbstractIOSessionPool() { super(); this.sessionPool = new ConcurrentHashMap<>(); - this.closed = new AtomicBoolean(false); + this.closed = new AtomicBoolean(); this.lock = new ReentrantLock(); } diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/InternalDataChannel.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/InternalDataChannel.java index 959adf27f2..5d64c00fb4 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/InternalDataChannel.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/InternalDataChannel.java @@ -89,7 +89,7 @@ final class InternalDataChannel extends InternalChannel implements ProtocolIOSes ioSessionDecorator != null ? ioSessionDecorator.decorate(ioSession) : ioSession); this.eventHandlerRef = new AtomicReference<>(); this.protocolUpgradeHandlerMap = new ConcurrentHashMap<>(); - this.closed = new AtomicBoolean(false); + this.closed = new AtomicBoolean(); } @Override diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/ListenerEndpointImpl.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/ListenerEndpointImpl.java index f5ac69827d..224095681b 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/ListenerEndpointImpl.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/ListenerEndpointImpl.java @@ -47,7 +47,7 @@ public ListenerEndpointImpl(final SelectionKey key, final Object attachment, fin this.key = key; this.address = address; this.attachment = attachment; - this.closed = new AtomicBoolean(false); + this.closed = new AtomicBoolean(); } @Override diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreIOReactor.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreIOReactor.java index 4e44155c0b..8661d67f29 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreIOReactor.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreIOReactor.java @@ -82,7 +82,7 @@ class SingleCoreIOReactor extends AbstractSingleCoreIOReactor implements Connect this.ioSessionDecorator = ioSessionDecorator; this.sessionListener = sessionListener; this.sessionShutdownCallback = sessionShutdownCallback; - this.shutdownInitiated = new AtomicBoolean(false); + this.shutdownInitiated = new AtomicBoolean(); this.closedSessions = new ConcurrentLinkedQueue<>(); this.channelQueue = new ConcurrentLinkedQueue<>(); this.requestQueue = new ConcurrentLinkedQueue<>(); diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreListeningIOReactor.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreListeningIOReactor.java index a06b66d927..c00f87081a 100644 --- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreListeningIOReactor.java +++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/SingleCoreListeningIOReactor.java @@ -68,7 +68,7 @@ class SingleCoreListeningIOReactor extends AbstractSingleCoreIOReactor implement this.callback = callback; this.requestQueue = new ConcurrentLinkedQueue<>(); this.endpoints = new ConcurrentHashMap<>(); - this.paused = new AtomicBoolean(false); + this.paused = new AtomicBoolean(); this.selectTimeoutMillis = this.reactorConfig.getSelectInterval().toMilliseconds(); } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountDownLatchFutureCallback.java b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountDownLatchFutureCallback.java new file mode 100644 index 0000000000..d6934a3710 --- /dev/null +++ b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountDownLatchFutureCallback.java @@ -0,0 +1,95 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.core5.concurrent; + +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; + +/** + * Counts down all method calls for a {@link CountDownLatch}. + * + * @param the future result type consumed by this callback. + */ +public class CountDownLatchFutureCallback implements FutureCallback { + + private final CountDownLatch countDownLatch; + + /** + * Constructs a new instance. + * + * @param count the number of times {@link CountDownLatch#countDown()} must be invoked before threads can pass through {@link CountDownLatch#await()} + * @throws IllegalArgumentException if {@code count} is negative. + */ + public CountDownLatchFutureCallback(final int count) { + this.countDownLatch = new CountDownLatch(count); + } + + /** + * Delegates to {@link CountDownLatch#await()}. + * + * @throws InterruptedException if the current thread is interrupted while waiting + */ + public void await() throws InterruptedException { + countDownLatch.await(); + } + + /** + * Delegates to {@link CountDownLatch#await(long, TimeUnit)}. + * + * @param timeout the maximum time to wait. + * @param unit the time unit of the {@code timeout} argument. + * @return {@code true} if the count reached zero and {@code false} if the waiting time elapsed before the count reached zero. + * @throws InterruptedException if the current thread is interrupted while waiting. + */ + public boolean await(final long timeout, final TimeUnit unit) throws InterruptedException { + return countDownLatch.await(timeout, unit); + } + + @Override + public void cancelled() { + countDownLatch.countDown(); + } + + @Override + public void completed(final T result) { + countDownLatch.countDown(); + } + + /** + * Delegates to {@link CountDownLatch#countDown()}. + */ + public void countDown() { + countDownLatch.countDown(); + } + + @Override + public void failed(final Exception ex) { + countDownLatch.countDown(); + } + +} diff --git a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountingFutureCallback.java b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountingFutureCallback.java new file mode 100644 index 0000000000..e141988b20 --- /dev/null +++ b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/CountingFutureCallback.java @@ -0,0 +1,74 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ + +package org.apache.hc.core5.concurrent; + +import java.util.concurrent.atomic.AtomicLong; + +/** + * Counts all method calls. + * + * @param the future result type consumed by this callback. + */ +public class CountingFutureCallback implements FutureCallback { + + private final AtomicLong count = new AtomicLong(); + + @Override + public void cancelled() { + count.incrementAndGet(); + } + + @Override + public void completed(final T result) { + count.incrementAndGet(); + } + + @Override + public void failed(final Exception ex) { + count.incrementAndGet(); + } + + /** + * The atomic count as an AtomicLong. + * + * @return atomic count as an AtomicLong. + */ + public AtomicLong getAtomicCount() { + return count; + } + + /** + * The atomic count as a long. + * + * @return atomic count as a long. + */ + public long getCount() { + return count.longValue(); + } + +} diff --git a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/FutureCallbackAdapter.java b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/FutureCallbackAdapter.java new file mode 100644 index 0000000000..f5b740300e --- /dev/null +++ b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/FutureCallbackAdapter.java @@ -0,0 +1,67 @@ +/* + * ==================================================================== + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + * ==================================================================== + * + * This software consists of voluntary contributions made by many + * individuals on behalf of the Apache Software Foundation. For more + * information on the Apache Software Foundation, please see + * . + * + */ +package org.apache.hc.core5.concurrent; + +/** + * Provides an extensible default adatper for {@link FutureCallback} implementation. + * + * @param the future result type consumed by this callback. + */ +public class FutureCallbackAdapter implements FutureCallback { + + /** + * The singleton instance. + */ + private static final FutureCallbackAdapter INSTANCE = new FutureCallbackAdapter<>(); + + /** + * Get the singleton instance typed as {@code T}. + * + * @param the future result type consumed by this callback. + * @return The singleton instance. + */ + @SuppressWarnings("unchecked") + public static FutureCallbackAdapter getInstance() { + return (FutureCallbackAdapter) INSTANCE; + } + + @Override + public void cancelled() { + // noop + } + + @Override + public void completed(final T result) { + // noop + } + + @Override + public void failed(final Exception ex) { + // noop + } + +} diff --git a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java index 09b10058c6..432ea16da2 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/concurrent/TestBasicFuture.java @@ -44,6 +44,7 @@ import org.apache.hc.core5.util.TimeoutValueException; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; import org.mockito.Mockito; class TestBasicFuture { @@ -60,7 +61,7 @@ void testCompleted() throws Exception { future.completed(result); future.failed(boom); Mockito.verify(callback).completed(result); - Mockito.verify(callback, Mockito.never()).failed(Mockito.any()); + Mockito.verify(callback, Mockito.never()).failed(ArgumentMatchers.any()); Mockito.verify(callback, Mockito.never()).cancelled(); Assertions.assertSame(result, future.get()); @@ -81,7 +82,7 @@ void testCompletedWithTimeout() throws Exception { future.completed(result); future.failed(boom); Mockito.verify(callback).completed(result); - Mockito.verify(callback, Mockito.never()).failed(Mockito.any()); + Mockito.verify(callback, Mockito.never()).failed(ArgumentMatchers.any()); Mockito.verify(callback, Mockito.never()).cancelled(); Assertions.assertSame(result, future.get(1, TimeUnit.MILLISECONDS)); @@ -97,7 +98,7 @@ void testFailed() throws Exception { final Exception boom = new Exception(); future.failed(boom); future.completed(result); - Mockito.verify(callback, Mockito.never()).completed(Mockito.any()); + Mockito.verify(callback, Mockito.never()).completed(ArgumentMatchers.any()); Mockito.verify(callback).failed(boom); Mockito.verify(callback, Mockito.never()).cancelled(); @@ -119,8 +120,8 @@ void testCancelled() { future.cancel(true); future.failed(boom); future.completed(result); - Mockito.verify(callback, Mockito.never()).completed(Mockito.any()); - Mockito.verify(callback, Mockito.never()).failed(Mockito.any()); + Mockito.verify(callback, Mockito.never()).completed(ArgumentMatchers.any()); + Mockito.verify(callback, Mockito.never()).failed(ArgumentMatchers.any()); Mockito.verify(callback).cancelled(); assertThrows(CancellationException.class, future::get); @@ -214,24 +215,15 @@ void testAsyncNegativeTimeout() { @Test void testConcurrentOperations() throws InterruptedException, ExecutionException { - final FutureCallback callback = new FutureCallback() { - public void completed(final Object result) { - } - - public void failed(final Exception ex) { - } - - public void cancelled() { - } - }; + final FutureCallback callback = FutureCallbackAdapter.getInstance(); final ExecutorService executor = Executors.newFixedThreadPool(3); final BasicFuture future = new BasicFuture<>(callback); final Object expectedResult = new Object(); - final AtomicBoolean completedSuccessfully = new AtomicBoolean(false); - final AtomicBoolean failedSuccessfully = new AtomicBoolean(false); - final AtomicBoolean cancelledSuccessfully = new AtomicBoolean(false); + final AtomicBoolean completedSuccessfully = new AtomicBoolean(); + final AtomicBoolean failedSuccessfully = new AtomicBoolean(); + final AtomicBoolean cancelledSuccessfully = new AtomicBoolean(); // Run 3 tasks concurrently: complete, fail, and cancel the future. final Future future1 = executor.submit(() -> completedSuccessfully.set(future.completed(expectedResult))); @@ -260,23 +252,14 @@ public void cancelled() { @Test void testGetWithTimeout() { - final AtomicBoolean isFutureCompleted = new AtomicBoolean(false); + final AtomicBoolean isFutureCompleted = new AtomicBoolean(); - final FutureCallback callback = new FutureCallback() { + final FutureCallback callback = new FutureCallbackAdapter() { @Override public void completed(final String result) { isFutureCompleted.set(true); } - @Override - public void failed(final Exception ex) { - // Nothing to do here for this example - } - - @Override - public void cancelled() { - // Nothing to do here for this example - } }; final BasicFuture future = new BasicFuture<>(callback); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/TestHttpHost.java b/httpcore5/src/test/java/org/apache/hc/core5/http/TestHttpHost.java index fd93e96e01..f7d16c6e97 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/TestHttpHost.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/TestHttpHost.java @@ -174,9 +174,9 @@ void testToHostString() { void testSerialization() throws Exception { final HttpHost orig = new HttpHost("https", "somehost", 8080); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java index 0673d1293a..7a4a976457 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestChunkCoding.java @@ -114,17 +114,16 @@ void testChunkedInputStreamOneByteRead() throws IOException { final String s = "5\r\n01234\r\n5\r\n56789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - int ch; - int i = '0'; - while ((ch = in.read()) != -1) { - Assertions.assertEquals(i, ch); - i++; + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + int ch; + int i = '0'; + while ((ch = in.read()) != -1) { + Assertions.assertEquals(i, ch); + i++; + } + Assertions.assertEquals(-1, in.read()); + Assertions.assertEquals(-1, in.read()); } - Assertions.assertEquals(-1, in.read()); - Assertions.assertEquals(-1, in.read()); - - in.close(); } @Test @@ -132,11 +131,11 @@ void testAvailable() throws IOException { final String s = "5\r\n12345\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - Assertions.assertEquals(0, in.available()); - in.read(); - Assertions.assertEquals(4, in.available()); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + Assertions.assertEquals(0, in.available()); + in.read(); + Assertions.assertEquals(4, in.available()); + } } @Test @@ -159,11 +158,12 @@ void testChunkedInputStreamNoClosingChunk() throws IOException { final String s = "5\r\n01234\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - final byte[] tmp = new byte[5]; - Assertions.assertEquals(5, in.read(tmp)); - Assertions.assertThrows(ConnectionClosedException.class, () -> in.read()); - Assertions.assertThrows(ConnectionClosedException.class, () -> in.close()); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + final byte[] tmp = new byte[5]; + Assertions.assertEquals(5, in.read(tmp)); + Assertions.assertThrows(ConnectionClosedException.class, () -> in.read()); + Assertions.assertThrows(ConnectionClosedException.class, () -> in.close()); + } } // Truncated stream (missing closing CRLF) @@ -172,11 +172,11 @@ void testCorruptChunkedInputStreamTruncatedCRLF() throws IOException { final String s = "5\r\n01234"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - final byte[] tmp = new byte[5]; - Assertions.assertEquals(5, in.read(tmp)); - Assertions.assertThrows(MalformedChunkCodingException.class, () -> in.read()); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + final byte[] tmp = new byte[5]; + Assertions.assertEquals(5, in.read(tmp)); + Assertions.assertThrows(MalformedChunkCodingException.class, () -> in.read()); + } } // Missing \r\n at the end of the first chunk @@ -185,16 +185,16 @@ void testCorruptChunkedInputStreamMissingCRLF() throws IOException { final String s = "5\r\n012345\r\n56789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - final byte[] buffer = new byte[300]; - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - Assertions.assertThrows(MalformedChunkCodingException.class, () -> { - int len; - while ((len = in.read(buffer)) > 0) { - out.write(buffer, 0, len); - } - }); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + final byte[] buffer = new byte[300]; + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + Assertions.assertThrows(MalformedChunkCodingException.class, () -> { + int len; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + }); + } } // Missing LF @@ -203,9 +203,9 @@ void testCorruptChunkedInputStreamMissingLF() throws IOException { final String s = "5\r01234\r\n5\r\n56789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - Assertions.assertThrows(MalformedChunkCodingException.class, in::read); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + Assertions.assertThrows(MalformedChunkCodingException.class, in::read); + } } // Invalid chunk size @@ -214,9 +214,9 @@ void testCorruptChunkedInputStreamInvalidSize() throws IOException { final String s = "whatever\r\n01234\r\n5\r\n56789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - Assertions.assertThrows(MalformedChunkCodingException.class, in::read); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + Assertions.assertThrows(MalformedChunkCodingException.class, in::read); + } } // Negative chunk size @@ -225,9 +225,9 @@ void testCorruptChunkedInputStreamNegativeSize() throws IOException { final String s = "-5\r\n01234\r\n5\r\n56789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - Assertions.assertThrows(MalformedChunkCodingException.class, in::read); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + Assertions.assertThrows(MalformedChunkCodingException.class, in::read); + } } // Truncated chunk @@ -236,11 +236,11 @@ void testCorruptChunkedInputStreamTruncatedChunk() throws IOException { final String s = "3\r\n12"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - final byte[] buffer = new byte[300]; - Assertions.assertEquals(2, in.read(buffer)); - Assertions.assertThrows(MalformedChunkCodingException.class, () -> in.read(buffer)); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + final byte[] buffer = new byte[300]; + Assertions.assertEquals(2, in.read(buffer)); + Assertions.assertThrows(MalformedChunkCodingException.class, () -> in.read(buffer)); + } } // Invalid footer @@ -249,10 +249,10 @@ void testCorruptChunkedInputStreamInvalidFooter() throws IOException { final String s = "1\r\n0\r\n0\r\nstuff\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - in.read(); - Assertions.assertThrows(MalformedChunkCodingException.class, in::read); - in.close(); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + in.read(); + Assertions.assertThrows(MalformedChunkCodingException.class, in::read); + } } @Test @@ -270,15 +270,15 @@ void testEmptyChunkedInputStream() throws IOException { final String s = "0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - final byte[] buffer = new byte[300]; - final ByteArrayOutputStream out = new ByteArrayOutputStream(); - int len; - while ((len = in.read(buffer)) > 0) { - out.write(buffer, 0, len); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + final byte[] buffer = new byte[300]; + final ByteArrayOutputStream out = new ByteArrayOutputStream(); + int len; + while ((len = in.read(buffer)) > 0) { + out.write(buffer, 0, len); + } + Assertions.assertEquals(0, out.size()); } - Assertions.assertEquals(0, out.size()); - in.close(); } @Test @@ -295,6 +295,7 @@ void testTooLongChunkHeader() throws IOException { final ByteArrayInputStream inputStream2 = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); final ChunkedInputStream in2 = new ChunkedInputStream(inBuffer2, inputStream2); Assertions.assertThrows(MessageConstraintException.class, () -> in2.read(buffer)); + // close() would throw here } @Test @@ -313,38 +314,38 @@ void testChunkedConsistence() throws IOException { final String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb"; final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2048); - out.write(input.getBytes(StandardCharsets.US_ASCII)); - out.flush(); - out.close(); - out.close(); + try (ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2048)) { + out.write(input.getBytes(StandardCharsets.US_ASCII)); + out.flush(); + out.close(); + } final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); final ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); + try (ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { - final byte[] d = new byte[10]; - final ByteArrayOutputStream result = new ByteArrayOutputStream(); - int len = 0; - while ((len = in.read(d)) > 0) { - result.write(d, 0, len); - } + final byte[] d = new byte[10]; + final ByteArrayOutputStream result = new ByteArrayOutputStream(); + int len = 0; + while ((len = in.read(d)) > 0) { + result.write(d, 0, len); + } - final String output = new String(result.toByteArray(), StandardCharsets.US_ASCII); - Assertions.assertEquals(input, output); - in.close(); + final String output = new String(result.toByteArray(), StandardCharsets.US_ASCII); + Assertions.assertEquals(input, output); + } } @Test void testChunkedOutputStreamWithTrailers() throws IOException { final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2, () -> Arrays.asList( + try (ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2, () -> Arrays.asList( new BasicHeader("E", ""), new BasicHeader("Y", "Z")) - ); - out.write('x'); - out.finish(); - out.close(); + )) { + out.write('x'); + out.finish(); + } final String content = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); Assertions.assertEquals("1\r\nx\r\n0\r\nE: \r\nY: Z\r\n\r\n", content); @@ -354,13 +355,13 @@ void testChunkedOutputStreamWithTrailers() throws IOException { void testChunkedOutputStream() throws IOException { final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2); - out.write('1'); - out.write('2'); - out.write('3'); - out.write('4'); - out.finish(); - out.close(); + try (ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2)) { + out.write('1'); + out.write('2'); + out.write('3'); + out.write('4'); + out.finish(); + } final String content = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); Assertions.assertEquals("2\r\n12\r\n2\r\n34\r\n0\r\n\r\n", content); @@ -370,10 +371,10 @@ void testChunkedOutputStream() throws IOException { void testChunkedOutputStreamLargeChunk() throws IOException { final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2); - out.write(new byte[] {'1', '2', '3', '4'}); - out.finish(); - out.close(); + try (ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2)) { + out.write(new byte[] { '1', '2', '3', '4' }); + out.finish(); + } final String content = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); Assertions.assertEquals("4\r\n1234\r\n0\r\n\r\n", content); @@ -383,10 +384,10 @@ void testChunkedOutputStreamLargeChunk() throws IOException { void testChunkedOutputStreamSmallChunk() throws IOException { final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - final ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2); - out.write('1'); - out.finish(); - out.close(); + try (ChunkedOutputStream out = new ChunkedOutputStream(outbuffer, outputStream, 2)) { + out.write('1'); + out.finish(); + } final String content = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); Assertions.assertEquals("1\r\n1\r\n0\r\n\r\n", content); @@ -396,56 +397,56 @@ void testChunkedOutputStreamSmallChunk() throws IOException { void testResumeOnSocketTimeoutInData() throws IOException { final String s = "5\r\n01234\r\n5\r\n5\0006789\r\na\r\n0123\000456789\r\n0\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); - final TimeoutByteArrayInputStream inputStream = new TimeoutByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - - final byte[] tmp = new byte[3]; - - int bytesRead = 0; - int timeouts = 0; - - int i = 0; - while (i != -1) { - try { - i = in.read(tmp); - if (i > 0) { - bytesRead += i; + try (TimeoutByteArrayInputStream inputStream = new TimeoutByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); + ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + + final byte[] tmp = new byte[3]; + + int bytesRead = 0; + int timeouts = 0; + + int i = 0; + while (i != -1) { + try { + i = in.read(tmp); + if (i > 0) { + bytesRead += i; + } + } catch (final InterruptedIOException ex) { + timeouts++; } - } catch (final InterruptedIOException ex) { - timeouts++; } + Assertions.assertEquals(20, bytesRead); + Assertions.assertEquals(2, timeouts); } - Assertions.assertEquals(20, bytesRead); - Assertions.assertEquals(2, timeouts); - in.close(); -} + } @Test void testResumeOnSocketTimeoutInChunk() throws IOException { final String s = "5\000\r\000\n\00001234\r\n\0005\r\n56789\r\na\r\n0123456789\r\n\0000\r\n"; final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); - final TimeoutByteArrayInputStream inputStream = new TimeoutByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); - final ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream); - - final byte[] tmp = new byte[3]; - - int bytesRead = 0; - int timeouts = 0; - - int i = 0; - while (i != -1) { - try { - i = in.read(tmp); - if (i > 0) { - bytesRead += i; + try (TimeoutByteArrayInputStream inputStream = new TimeoutByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); + ChunkedInputStream in = new ChunkedInputStream(inBuffer, inputStream)) { + + final byte[] tmp = new byte[3]; + + int bytesRead = 0; + int timeouts = 0; + + int i = 0; + while (i != -1) { + try { + i = in.read(tmp); + if (i > 0) { + bytesRead += i; + } + } catch (final InterruptedIOException ex) { + timeouts++; } - } catch (final InterruptedIOException ex) { - timeouts++; } + Assertions.assertEquals(20, bytesRead); + Assertions.assertEquals(5, timeouts); } - Assertions.assertEquals(20, bytesRead); - Assertions.assertEquals(5, timeouts); - in.close(); } // Test for when buffer is larger than chunk size diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthInputStream.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthInputStream.java index c4b1b398e0..610c877a40 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthInputStream.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthInputStream.java @@ -46,64 +46,64 @@ void testBasics() throws IOException { final String s = "1234567890123456"; final ByteArrayInputStream inputStream = new ByteArrayInputStream(s.getBytes(StandardCharsets.US_ASCII)); final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); - final InputStream in = new ContentLengthInputStream(inBuffer, inputStream, 10L); - final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - - final byte[] buffer = new byte[50]; - int len = in.read(buffer, 0, 2); - outputStream.write(buffer, 0, len); - len = in.read(buffer); - outputStream.write(buffer, 0, len); - - final String result = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); - Assertions.assertEquals("1234567890", result); - in.close(); + try (InputStream in = new ContentLengthInputStream(inBuffer, inputStream, 10L)) { + final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + + final byte[] buffer = new byte[50]; + int len = in.read(buffer, 0, 2); + outputStream.write(buffer, 0, len); + len = in.read(buffer); + outputStream.write(buffer, 0, len); + + final String result = new String(outputStream.toByteArray(), StandardCharsets.US_ASCII); + Assertions.assertEquals("1234567890", result); + } } @Test void testSkip() throws IOException { final ByteArrayInputStream inputStream1 = new ByteArrayInputStream(new byte[20]); final SessionInputBuffer inBuffer1 = new SessionInputBufferImpl(16); - final InputStream in1 = new ContentLengthInputStream(inBuffer1, inputStream1, 10L); - Assertions.assertEquals(10, in1.skip(10)); - Assertions.assertEquals(-1, in1.read()); - in1.close(); + try (InputStream in1 = new ContentLengthInputStream(inBuffer1, inputStream1, 10L)) { + Assertions.assertEquals(10, in1.skip(10)); + Assertions.assertEquals(-1, in1.read()); + } final ByteArrayInputStream inputStream2 = new ByteArrayInputStream(new byte[20]); final SessionInputBuffer inBuffer2 = new SessionInputBufferImpl(16); - final InputStream in2 = new ContentLengthInputStream(inBuffer2, inputStream2, 10L); - in2.read(); - Assertions.assertEquals(9, in2.skip(10)); - Assertions.assertEquals(-1, in2.read()); - in2.close(); + try (InputStream in2 = new ContentLengthInputStream(inBuffer2, inputStream2, 10L)) { + in2.read(); + Assertions.assertEquals(9, in2.skip(10)); + Assertions.assertEquals(-1, in2.read()); + } final ByteArrayInputStream inputStream3 = new ByteArrayInputStream(new byte[20]); final SessionInputBuffer inBuffer3 = new SessionInputBufferImpl(16); - final InputStream in3 = new ContentLengthInputStream(inBuffer3, inputStream3, 2L); - in3.read(); - in3.read(); - Assertions.assertTrue(in3.skip(10) <= 0); - Assertions.assertEquals(0, in3.skip(-1)); - Assertions.assertEquals(-1, in3.read()); - in3.close(); + try (InputStream in3 = new ContentLengthInputStream(inBuffer3, inputStream3, 2L)) { + in3.read(); + in3.read(); + Assertions.assertTrue(in3.skip(10) <= 0); + Assertions.assertEquals(0, in3.skip(-1)); + Assertions.assertEquals(-1, in3.read()); + } final ByteArrayInputStream inputStream4 = new ByteArrayInputStream(new byte[20]); final SessionInputBuffer inBuffer4 = new SessionInputBufferImpl(16); - final InputStream in4 = new ContentLengthInputStream(inBuffer4, inputStream4, 10L); - Assertions.assertEquals(5,in4.skip(5)); - Assertions.assertEquals(5, in4.read(new byte[20])); - in4.close(); + try (InputStream in4 = new ContentLengthInputStream(inBuffer4, inputStream4, 10L)) { + Assertions.assertEquals(5, in4.skip(5)); + Assertions.assertEquals(5, in4.read(new byte[20])); + } } @Test void testAvailable() throws IOException { final ByteArrayInputStream inputStream = new ByteArrayInputStream(new byte[] {1, 2, 3}); final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); - final InputStream in = new ContentLengthInputStream(inBuffer, inputStream, 3L); - Assertions.assertEquals(0, in.available()); - in.read(); - Assertions.assertEquals(2, in.available()); - in.close(); + try (InputStream in = new ContentLengthInputStream(inBuffer, inputStream, 3L)) { + Assertions.assertEquals(0, in.available()); + in.read(); + Assertions.assertEquals(2, in.available()); + } } @Test diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthOutputStream.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthOutputStream.java index 953190a771..638dce2df8 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthOutputStream.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestContentLengthOutputStream.java @@ -41,18 +41,18 @@ class TestContentLengthOutputStream { void testBasics() throws Exception { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); - final OutputStream out = new ContentLengthOutputStream(outbuffer, outputStream, 15L); + try (OutputStream out = new ContentLengthOutputStream(outbuffer, outputStream, 15L)) { - final byte[] tmp = new byte[10]; - out.write(tmp, 0, 10); - out.write(1); - out.write(tmp, 0, 10); - out.write(tmp, 0, 10); - out.write(tmp); - out.write(1); - out.write(2); - out.flush(); - out.close(); + final byte[] tmp = new byte[10]; + out.write(tmp, 0, 10); + out.write(1); + out.write(tmp, 0, 10); + out.write(tmp, 0, 10); + out.write(tmp); + out.write(1); + out.write(2); + out.flush(); + } final byte[] data = outputStream.toByteArray(); Assertions.assertEquals(15, data.length); } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityInputStream.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityInputStream.java index ee9893571c..e6fc9522c6 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityInputStream.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityInputStream.java @@ -45,17 +45,17 @@ void testBasicRead() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final ByteArrayInputStream inputStream = new ByteArrayInputStream(input); final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16); - final IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream); - final byte[] tmp = new byte[2]; - Assertions.assertEquals(2, in.read(tmp, 0, tmp.length)); - Assertions.assertEquals('a', tmp[0]); - Assertions.assertEquals('b', tmp[1]); - Assertions.assertEquals('c', in.read()); - Assertions.assertEquals(-1, in.read(tmp, 0, tmp.length)); - Assertions.assertEquals(-1, in.read()); - Assertions.assertEquals(-1, in.read(tmp, 0, tmp.length)); - Assertions.assertEquals(-1, in.read()); - in.close(); + try (IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream)) { + final byte[] tmp = new byte[2]; + Assertions.assertEquals(2, in.read(tmp, 0, tmp.length)); + Assertions.assertEquals('a', tmp[0]); + Assertions.assertEquals('b', tmp[1]); + Assertions.assertEquals('c', in.read()); + Assertions.assertEquals(-1, in.read(tmp, 0, tmp.length)); + Assertions.assertEquals(-1, in.read()); + Assertions.assertEquals(-1, in.read(tmp, 0, tmp.length)); + Assertions.assertEquals(-1, in.read()); + } } @Test @@ -79,10 +79,10 @@ void testAvailable() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c'}; final ByteArrayInputStream inputStream = new ByteArrayInputStream(input); final SessionInputBuffer inBuffer = new SessionInputBufferImpl(new BasicHttpTransportMetrics(), 16, 16, 1024, null); - final IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream); - in.read(); - Assertions.assertEquals(2, in.available()); - in.close(); + try (IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream)) { + in.read(); + Assertions.assertEquals(2, in.available()); + } } @Test @@ -90,11 +90,11 @@ void testAvailableInStream() throws Exception { final byte[] input = new byte[] {'a', 'b', 'c', 'd', 'e', 'f'}; final ByteArrayInputStream inputStream = new ByteArrayInputStream(input); final SessionInputBuffer inBuffer = new SessionInputBufferImpl(new BasicHttpTransportMetrics(), 16, 0, 1024, null); - final IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream); - final byte[] tmp = new byte[3]; - Assertions.assertEquals(3, in.read(tmp)); - Assertions.assertEquals(3, in.available()); - in.close(); + try (IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream)) { + final byte[] tmp = new byte[3]; + Assertions.assertEquals(3, in.read(tmp)); + Assertions.assertEquals(3, in.available()); + } } } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityOutputStream.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityOutputStream.java index b9337ed2d5..e513c96ac7 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityOutputStream.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestIdentityOutputStream.java @@ -45,14 +45,14 @@ class TestIdentityOutputStream { void testBasics() throws Exception { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); - final OutputStream out = new IdentityOutputStream(outbuffer, outputStream); + try (OutputStream out = new IdentityOutputStream(outbuffer, outputStream)) { - final byte[] tmp = new byte[10]; - out.write(tmp, 0, 10); - out.write(tmp); - out.write(1); - out.flush(); - out.close(); + final byte[] tmp = new byte[10]; + out.write(tmp, 0, 10); + out.write(tmp); + out.write(1); + out.flush(); + } final byte[] data = outputStream.toByteArray(); Assertions.assertEquals(21, data.length); } @@ -73,20 +73,20 @@ void testClose() throws Exception { void testBasicWrite() throws Exception { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final SessionOutputBuffer outbuffer = new SessionOutputBufferImpl(16); - final OutputStream out = new IdentityOutputStream(outbuffer, outputStream); - out.write(new byte[] {'a', 'b'}, 0, 2); - out.write('c'); - out.flush(); + try (OutputStream out = new IdentityOutputStream(outbuffer, outputStream)) { + out.write(new byte[] { 'a', 'b' }, 0, 2); + out.write('c'); + out.flush(); - final byte[] input = outputStream.toByteArray(); + final byte[] input = outputStream.toByteArray(); - Assertions.assertNotNull(input); - final byte[] expected = new byte[] {'a', 'b', 'c'}; - Assertions.assertEquals(expected.length, input.length); - for (int i = 0; i < expected.length; i++) { - Assertions.assertEquals(expected[i], input[i]); + Assertions.assertNotNull(input); + final byte[] expected = new byte[] { 'a', 'b', 'c' }; + Assertions.assertEquals(expected.length, input.length); + for (int i = 0; i < expected.length; i++) { + Assertions.assertEquals(expected[i], input[i]); + } } - out.close(); } @Test diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestAbstractHttp1StreamDuplexerCapacityWindow.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestAbstractHttp1StreamDuplexerCapacityWindow.java index d2db5ec852..2f85e4434d 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestAbstractHttp1StreamDuplexerCapacityWindow.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestAbstractHttp1StreamDuplexerCapacityWindow.java @@ -37,6 +37,7 @@ import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.mockito.ArgumentMatchers; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; @@ -63,7 +64,7 @@ void testWindowUpdate() throws IOException { final CapacityWindow window = new CapacityWindow(0, ioSession); window.update(1); Assertions.assertEquals(1, window.getWindow()); - Mockito.verify(ioSession).setEvent(Mockito.eq(SelectionKey.OP_READ)); + Mockito.verify(ioSession).setEvent(ArgumentMatchers.eq(SelectionKey.OP_READ)); Mockito.verifyNoMoreInteractions(ioSession); } @@ -72,7 +73,7 @@ void testRemoveCapacity() { final CapacityWindow window = new CapacityWindow(1, ioSession); window.removeCapacity(1); Assertions.assertEquals(0, window.getWindow()); - Mockito.verify(ioSession).clearEvent(Mockito.eq(SelectionKey.OP_READ)); + Mockito.verify(ioSession).clearEvent(ArgumentMatchers.eq(SelectionKey.OP_READ)); Mockito.verifyNoMoreInteractions(ioSession); } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestFileEntity.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestFileEntity.java index e3b2c16d03..dfe2198e2f 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestFileEntity.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestFileEntity.java @@ -49,9 +49,9 @@ void testBasics() throws Exception { try (final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN)) { Assertions.assertEquals(tmpfile.length(), httpentity.getContentLength()); - final InputStream content = httpentity.getContent(); - Assertions.assertNotNull(content); - content.close(); + try (InputStream content = httpentity.getContent()) { + Assertions.assertNotNull(content); + } Assertions.assertTrue(httpentity.isRepeatable()); Assertions.assertFalse(httpentity.isStreaming()); Assertions.assertTrue(tmpfile.delete(), "Failed to delete " + tmpfile); @@ -68,12 +68,12 @@ void testWriteTo() throws Exception { final File tmpfile = File.createTempFile("testfile", ".txt"); tmpfile.deleteOnExit(); - final FileOutputStream outStream = new FileOutputStream(tmpfile); - outStream.write(0); - outStream.write(1); - outStream.write(2); - outStream.write(3); - outStream.close(); + try (FileOutputStream outStream = new FileOutputStream(tmpfile)) { + outStream.write(0); + outStream.write(1); + outStream.write(2); + outStream.write(3); + } try (final FileEntity httpentity = new FileEntity(tmpfile, ContentType.TEXT_PLAIN)) { diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBufferedHeader.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBufferedHeader.java index 6155d7bf9c..99409f4b07 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBufferedHeader.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBufferedHeader.java @@ -60,9 +60,9 @@ void testSerialization() throws Exception { buf.append("name: value"); final BufferedHeader orig = new BufferedHeader(buf, false); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeader.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeader.java index 1a8d240a3d..f7323d098a 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeader.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeader.java @@ -72,9 +72,9 @@ void testToString() { void testSerialization() throws Exception { final BasicHeader orig = new BasicHeader("name1", "value1"); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeaderGroup.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeaderGroup.java index 3d42e34e98..9c1b8f83ec 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeaderGroup.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestHeaderGroup.java @@ -199,9 +199,9 @@ void testSerialization() throws Exception { final Header header3 = new BasicHeader("name", "value3"); orig.setHeaders(header1, header2, header3); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractBinAsyncEntityConsumer.java b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractBinAsyncEntityConsumer.java index 221e704014..f20e95232b 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractBinAsyncEntityConsumer.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractBinAsyncEntityConsumer.java @@ -29,9 +29,8 @@ import java.io.IOException; import java.nio.ByteBuffer; -import java.util.concurrent.atomic.AtomicLong; -import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.concurrent.CountingFutureCallback; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.impl.BasicEntityDetails; @@ -78,28 +77,9 @@ public void releaseResources() { @Test void testConsumeData() throws Exception { - final AsyncEntityConsumer consumer = new ByteArrayAsyncEntityConsumer(); - - final AtomicLong count = new AtomicLong(0); - consumer.streamStart(new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), new FutureCallback() { - - @Override - public void completed(final byte[] result) { - count.incrementAndGet(); - } - - @Override - public void failed(final Exception ex) { - count.incrementAndGet(); - } - - @Override - public void cancelled() { - count.incrementAndGet(); - } - - }); + final CountingFutureCallback countingCallback = new CountingFutureCallback<>(); + consumer.streamStart(new BasicEntityDetails(-1, ContentType.APPLICATION_OCTET_STREAM), countingCallback); consumer.consume(ByteBuffer.wrap(new byte[]{'1', '2', '3'})); consumer.consume(ByteBuffer.wrap(new byte[]{'4', '5'})); @@ -109,7 +89,7 @@ public void cancelled() { consumer.streamEnd(null); Assertions.assertArrayEquals(new byte[] {'1', '2', '3', '4', '5'}, consumer.getContent()); - Assertions.assertEquals(1L, count.longValue()); + Assertions.assertEquals(1L, countingCallback.getCount()); } } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractCharAsyncEntityConsumer.java b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractCharAsyncEntityConsumer.java index 1f7d8b28db..71f39b97b2 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractCharAsyncEntityConsumer.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/http/nio/entity/TestAbstractCharAsyncEntityConsumer.java @@ -31,9 +31,8 @@ import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; -import java.util.concurrent.atomic.AtomicLong; -import org.apache.hc.core5.concurrent.FutureCallback; +import org.apache.hc.core5.concurrent.CountingFutureCallback; import org.apache.hc.core5.http.ContentType; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.impl.BasicEntityDetails; @@ -81,28 +80,9 @@ public void releaseResources() { @Test void testConsumeData() throws Exception { - final AsyncEntityConsumer consumer = new StringBuilderAsyncEntityConsumer(); - - final AtomicLong count = new AtomicLong(0); - consumer.streamStart(new BasicEntityDetails(-1, ContentType.TEXT_PLAIN), new FutureCallback() { - - @Override - public void completed(final String result) { - count.incrementAndGet(); - } - - @Override - public void failed(final Exception ex) { - count.incrementAndGet(); - } - - @Override - public void cancelled() { - count.incrementAndGet(); - } - - }); + final CountingFutureCallback countingCallback = new CountingFutureCallback<>(); + consumer.streamStart(new BasicEntityDetails(-1, ContentType.TEXT_PLAIN), countingCallback); consumer.consume(ByteBuffer.wrap(new byte[]{'1', '2', '3'})); consumer.consume(ByteBuffer.wrap(new byte[]{'4', '5'})); @@ -112,7 +92,7 @@ public void cancelled() { consumer.streamEnd(null); Assertions.assertEquals("12345", consumer.getContent()); - Assertions.assertEquals(1L, count.longValue()); + Assertions.assertEquals(1L, countingCallback.getCount()); } @Test @@ -120,25 +100,8 @@ void testConsumeIncompleteData() throws Exception { final AsyncEntityConsumer consumer = new StringBuilderAsyncEntityConsumer(); - final AtomicLong count = new AtomicLong(0); - consumer.streamStart(new BasicEntityDetails(-1, ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), new FutureCallback() { - - @Override - public void completed(final String result) { - count.incrementAndGet(); - } - - @Override - public void failed(final Exception ex) { - count.incrementAndGet(); - } - - @Override - public void cancelled() { - count.incrementAndGet(); - } - - }); + final CountingFutureCallback countingCallback = new CountingFutureCallback<>(); + consumer.streamStart(new BasicEntityDetails(-1, ContentType.TEXT_PLAIN.withCharset(StandardCharsets.UTF_8)), countingCallback); final byte[] stuff = "stuff".getBytes(StandardCharsets.UTF_8); final byte[] splitCharacter = "£".getBytes(StandardCharsets.UTF_8); @@ -162,7 +125,7 @@ public void cancelled() { consumer.streamEnd(null); Assertions.assertEquals("stuff£stuff£stuff", consumer.getContent()); - Assertions.assertEquals(1L, count.longValue()); + Assertions.assertEquals(1L, countingCallback.getCount()); } } diff --git a/httpcore5/src/test/java/org/apache/hc/core5/net/TestHost.java b/httpcore5/src/test/java/org/apache/hc/core5/net/TestHost.java index c63c140a36..96877cd3ff 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/net/TestHost.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/net/TestHost.java @@ -98,9 +98,9 @@ void testToString() { void testSerialization() throws Exception { final Host orig = new Host("somehost", 8080); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIAuthority.java b/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIAuthority.java index 6ec71aaa85..07b4f09362 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIAuthority.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/net/TestURIAuthority.java @@ -110,9 +110,9 @@ void testToString() { void testSerialization() throws Exception { final URIAuthority orig = new URIAuthority("somehost", 8080); final ByteArrayOutputStream outbuffer = new ByteArrayOutputStream(); - final ObjectOutputStream outStream = new ObjectOutputStream(outbuffer); - outStream.writeObject(orig); - outStream.close(); + try (ObjectOutputStream outStream = new ObjectOutputStream(outbuffer)) { + outStream.writeObject(orig); + } final byte[] raw = outbuffer.toByteArray(); final ByteArrayInputStream inBuffer = new ByteArrayInputStream(raw); final ObjectInputStream inStream = new ObjectInputStream(inBuffer); diff --git a/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java b/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java index 713e3f9d34..b4f7a469be 100644 --- a/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java +++ b/httpcore5/src/test/java/org/apache/hc/core5/ssl/TestSSLContextBuilder.java @@ -463,9 +463,8 @@ void testSSLHandshakeClientUnauthenticated() throws Exception { this.executorService = Executors.newSingleThreadExecutor(); final Future future = this.executorService.submit(() -> { - final SSLSocket socket = (SSLSocket) serverSocket.accept(); Principal clientPrincipal = null; - try { + try (SSLSocket socket = (SSLSocket) serverSocket.accept()) { final SSLSession session = socket.getSession(); try { clientPrincipal = session.getPeerPrincipal(); @@ -474,8 +473,6 @@ void testSSLHandshakeClientUnauthenticated() throws Exception { final OutputStream outputStream = socket.getOutputStream(); outputStream.write(new byte [] {'H', 'i'}); outputStream.flush(); - } finally { - socket.close(); } return clientPrincipal; }); diff --git a/pom.xml b/pom.xml index 5144489e3e..d19f9121eb 100644 --- a/pom.xml +++ b/pom.xml @@ -106,6 +106,12 @@ httpcore5-testing ${project.version} + + org.apache.httpcomponents.core5 + httpcore5 + tests + ${project.version} + org.conscrypt conscrypt-openjdk-uber