You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hc.apache.org by gg...@apache.org on 2022/09/28 04:36:11 UTC
[httpcomponents-core] 02/02: Use Java 8 features and APIs
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/httpcomponents-core.git
commit cf27cce26fa6d599f189021bdd1b181c91629b41
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Wed Sep 28 00:36:01 2022 -0400
Use Java 8 features and APIs
---
.../apache/hc/core5/http2/hpack/HPackEncoder.java | 7 +-
.../http2/impl/DefaultH2RequestConverter.java | 4 +-
.../http2/impl/DefaultH2ResponseConverter.java | 4 +-
.../impl/nio/AbstractH2StreamMultiplexer.java | 46 +---
.../http2/impl/nio/ClientH2PrefaceHandler.java | 2 +-
.../http2/impl/nio/ServerH2PrefaceHandler.java | 4 +-
.../H2MultiplexingRequesterBootstrap.java | 4 +-
.../impl/nio/bootstrap/H2RequesterBootstrap.java | 4 +-
.../impl/nio/bootstrap/H2ServerBootstrap.java | 4 +-
.../core5/http2/nio/support/BasicPingHandler.java | 6 +-
.../H2ConscriptRequestExecutionExample.java | 16 +-
.../core5/http2/examples/H2FileServerExample.java | 8 +-
.../http2/examples/H2FullDuplexClientExample.java | 8 +-
.../http2/examples/H2FullDuplexServerExample.java | 8 +-
.../examples/H2MultiStreamExecutionExample.java | 19 +-
.../http2/examples/H2RequestExecutionExample.java | 10 +-
.../examples/H2TlsAlpnRequestExecutionExample.java | 19 +-
.../examples/H2ViaHttp1ProxyExecutionExample.java | 19 +-
.../core5/http2/frame/TestDefaultFrameFactory.java | 2 +-
.../hc/core5/http2/hpack/TestHPackCoding.java | 4 +-
.../hc/core5/reactive/ReactiveDataProducer.java | 6 +-
.../examples/ReactiveFullDuplexClientExample.java | 6 +-
.../apache/hc/core5/benchmark/HttpBenchmark.java | 27 +-
.../org/apache/hc/core5/testing/SocksProxy.java | 4 +-
.../classic/LoggingBHttpClientConnection.java | 14 +-
.../classic/LoggingBHttpServerConnection.java | 14 +-
.../framework/ClassicTestClientAdapter.java | 17 +-
.../hc/core5/testing/framework/FrameworkTest.java | 6 +-
.../framework/TestingFrameworkRequestHandler.java | 20 +-
.../core5/testing/nio/LoggingH2StreamListener.java | 8 +-
.../testing/nio/LoggingHttp1StreamListener.java | 13 +-
.../compatibility/http2/H2CompatibilityTest.java | 2 +-
.../testing/framework/TestTestingFramework.java | 5 +-
.../hc/core5/testing/nio/H2IntegrationTest.java | 161 ++++++------
.../hc/core5/testing/nio/Http1IntegrationTest.java | 8 +-
.../java/org/apache/hc/core5/http/ContentType.java | 4 +-
.../java/org/apache/hc/core5/http/HttpVersion.java | 6 +-
.../http/impl/EnglishReasonPhraseCatalog.java | 2 +-
.../http/impl/bootstrap/AsyncServerBootstrap.java | 4 +-
.../hc/core5/http/impl/bootstrap/HttpServer.java | 7 +-
.../core5/http/impl/io/AbstractMessageParser.java | 3 +-
.../hc/core5/http/impl/io/ChunkedOutputStream.java | 3 +-
.../http/impl/io/SessionOutputBufferImpl.java | 2 +-
.../hc/core5/http/impl/nio/ChunkEncoder.java | 3 +-
.../http/impl/nio/SessionOutputBufferImpl.java | 2 +-
.../hc/core5/http/io/entity/EntityUtils.java | 14 +-
.../hc/core5/http/io/entity/HttpEntities.java | 9 +-
.../hc/core5/http/message/BasicHeaderElement.java | 11 +-
.../apache/hc/core5/http/message/HeaderGroup.java | 288 +++++++++------------
.../http/nio/entity/AsyncEntityProducers.java | 8 +-
.../hc/core5/http/nio/ssl/FixedPortStrategy.java | 8 +-
.../hc/core5/http/protocol/ChainBuilder.java | 17 +-
.../hc/core5/http/protocol/HttpDateGenerator.java | 2 +-
.../java/org/apache/hc/core5/http/ssl/TLS.java | 10 +-
.../org/apache/hc/core5/http/ssl/TlsCiphers.java | 26 +-
.../core5/http/support/AbstractRequestBuilder.java | 5 +-
.../java/org/apache/hc/core5/net/URIBuilder.java | 16 +-
.../java/org/apache/hc/core5/pool/LaxConnPool.java | 21 +-
.../org/apache/hc/core5/pool/StrictConnPool.java | 22 +-
.../hc/core5/reactor/AbstractIOSessionPool.java | 8 +-
.../hc/core5/reactor/MultiCoreIOReactor.java | 24 +-
.../hc/core5/reactor/SingleCoreIOReactor.java | 12 +-
.../org/apache/hc/core5/ssl/SSLContextBuilder.java | 9 +-
.../java/org/apache/hc/core5/util/TextUtils.java | 4 +-
.../java/org/apache/hc/core5/util/VersionInfo.java | 25 +-
.../hc/core5/http/ReadableByteChannelMock.java | 6 +-
.../AsyncPipelinedRequestExecutionExample.java | 12 +-
.../examples/AsyncRequestExecutionExample.java | 12 +-
.../http/examples/AsyncReverseProxyExample.java | 11 +-
.../http/examples/ClassicGetExecutionExample.java | 5 +-
.../http/examples/ClassicPostExecutionExample.java | 4 +-
.../http/examples/ClassicReverseProxyExample.java | 12 +-
.../hc/core5/http/examples/PrintVersionInfo.java | 13 +-
.../http/impl/TestEnglishReasonPhraseCatalog.java | 4 +-
.../http/impl/io/TestIdentityInputStream.java | 8 +-
.../http/impl/io/TestIdentityOutputStream.java | 2 +-
.../http/impl/io/TestSessionInOutBuffers.java | 5 +-
.../http/impl/nio/TestSessionInOutBuffers.java | 5 +-
.../hc/core5/http/io/entity/TestEntityUtils.java | 5 +-
.../hc/core5/http/io/entity/TestStringEntity.java | 5 +-
.../message/TestBasicHeaderElementIterator.java | 6 +-
.../http/message/TestBasicHeaderIterator.java | 8 +-
.../message/TestBasicHeaderValueFormatter.java | 10 +-
.../core5/http/message/TestBasicTokenIterator.java | 12 +-
.../http/protocol/TestStandardInterceptors.java | 2 +-
.../java/org/apache/hc/core5/http/ssl/TLSTest.java | 3 +-
.../apache/hc/core5/http/ssl/TestTlsCiphers.java | 6 +-
.../java/org/apache/hc/core5/util/TestArgs.java | 2 +-
.../apache/hc/core5/util/TestByteArrayBuffer.java | 10 +-
.../apache/hc/core5/util/TestCharArrayBuffer.java | 10 +-
90 files changed, 481 insertions(+), 781 deletions(-)
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/hpack/HPackEncoder.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/hpack/HPackEncoder.java
index b64b27a51..b2927be97 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/hpack/HPackEncoder.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/hpack/HPackEncoder.java
@@ -243,8 +243,7 @@ public final class HPackEncoder {
if (entries == null || entries.isEmpty()) {
return 0;
}
- for (int i = 0; i < entries.size(); i++) {
- final HPackEntry entry = entries.get(i);
+ for (final HPackEntry entry : entries) {
if (Objects.equals(value, entry.getHeader().getValue())) {
return entry.getIndex();
}
@@ -303,8 +302,8 @@ public final class HPackEncoder {
void encodeHeaders(
final ByteArrayBuffer dst, final List<? extends Header> headers,
final boolean noIndexing, final boolean useHuffman) throws CharacterCodingException {
- for (int i = 0; i < headers.size(); i++) {
- encodeHeader(dst, headers.get(i), noIndexing, useHuffman);
+ for (final Header header : headers) {
+ encodeHeader(dst, header, noIndexing, useHuffman);
}
}
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2RequestConverter.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2RequestConverter.java
index d8f2611c6..62a388a5d 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2RequestConverter.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2RequestConverter.java
@@ -148,9 +148,7 @@ public final class DefaultH2RequestConverter implements H2MessageConverter<HttpR
throw new ProtocolException(ex.getMessage(), ex);
}
httpRequest.setPath(path);
- for (int i = 0; i < messageHeaders.size(); i++) {
- httpRequest.addHeader(messageHeaders.get(i));
- }
+ messageHeaders.forEach(httpRequest::addHeader);
return httpRequest;
}
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2ResponseConverter.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2ResponseConverter.java
index 0b860be8b..82dd1d4d8 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2ResponseConverter.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/DefaultH2ResponseConverter.java
@@ -102,9 +102,7 @@ public class DefaultH2ResponseConverter implements H2MessageConverter<HttpRespon
}
final HttpResponse response = new BasicHttpResponse(statusCode, null);
response.setVersion(HttpVersion.HTTP_2);
- for (int i = 0; i < messageHeaders.size(); i++) {
- response.addHeader(messageHeaders.get(i));
- }
+ messageHeaders.forEach(response::addHeader);
return response;
}
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
index a6020d8d8..b9e0daf22 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/AbstractH2StreamMultiplexer.java
@@ -35,6 +35,7 @@ import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Queue;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedDeque;
@@ -476,8 +477,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
final int pendingOutputRequests = outputRequests.get();
boolean outputPending = false;
if (!streamMap.isEmpty() && connOutputWindow.get() > 0) {
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
+ for (final Entry<Integer, H2Stream> entry : streamMap.entrySet()) {
final H2Stream stream = entry.getValue();
if (!stream.isLocalClosed()
&& stream.getOutputWindow().get() > 0
@@ -523,9 +523,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
}
if (connState.compareTo(ConnectionHandshake.SHUTDOWN) >= 0) {
if (!streamMap.isEmpty()) {
- for (final H2Stream stream : streamMap.values()) {
- stream.releaseResources();
- }
+ streamMap.values().forEach(H2Stream::releaseResources);
streamMap.clear();
}
ioSession.getLock().lock();
@@ -551,11 +549,8 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
"Timeout due to inactivity (" + timeout + ")");
}
commitFrame(goAway);
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
- final H2Stream stream = entry.getValue();
- stream.reset(new H2StreamResetException(H2Error.NO_ERROR, "Timeout due to inactivity (" + timeout + ")"));
- }
+ streamMap.values().forEach(stream -> stream
+ .reset(new H2StreamResetException(H2Error.NO_ERROR, "Timeout due to inactivity (" + timeout + ")")));
streamMap.clear();
}
@@ -568,11 +563,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
break;
}
}
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
- final H2Stream stream = entry.getValue();
- stream.cancel();
- }
+ streamMap.values().forEach(H2Stream::cancel);
for (;;) {
final Command command = ioSession.poll();
if (command != null) {
@@ -596,11 +587,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
if (command instanceof ShutdownCommand) {
final ShutdownCommand shutdownCommand = (ShutdownCommand) command;
if (shutdownCommand.getType() == CloseMode.IMMEDIATE) {
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
- final H2Stream stream = entry.getValue();
- stream.cancel();
- }
+ streamMap.values().forEach(H2Stream::cancel);
streamMap.clear();
connState = ConnectionHandshake.SHUTDOWN;
} else {
@@ -671,11 +658,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
break;
}
}
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
- final H2Stream stream = entry.getValue();
- stream.reset(cause);
- }
+ streamMap.values().forEach(e -> e.reset(cause));
streamMap.clear();
if (!(cause instanceof ConnectionClosedException)) {
if (connState.compareTo(ConnectionHandshake.GRACEFUL_SHUTDOWN) <= 0) {
@@ -1005,11 +988,8 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
}
connState = streamMap.isEmpty() ? ConnectionHandshake.SHUTDOWN : ConnectionHandshake.GRACEFUL_SHUTDOWN;
} else {
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
- final H2Stream stream = entry.getValue();
- stream.reset(new H2StreamResetException(errorCode, "Connection terminated by the peer (" + errorCode + ")"));
- }
+ streamMap.values().forEach(v -> v.reset(new H2StreamResetException(errorCode,
+ "Connection terminated by the peer (" + errorCode + ")")));
streamMap.clear();
connState = ConnectionHandshake.SHUTDOWN;
}
@@ -1225,8 +1205,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
if (delta != 0) {
if (!streamMap.isEmpty()) {
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
+ for (final Entry<Integer, H2Stream> entry : streamMap.entrySet()) {
final H2Stream stream = entry.getValue();
try {
updateOutputWindow(stream.getId(), stream.getOutputWindow(), delta);
@@ -1246,8 +1225,7 @@ abstract class AbstractH2StreamMultiplexer implements Identifiable, HttpConnecti
initInputWinSize = localConfig.getInitialWindowSize();
if (delta != 0 && !streamMap.isEmpty()) {
- for (final Iterator<Map.Entry<Integer, H2Stream>> it = streamMap.entrySet().iterator(); it.hasNext(); ) {
- final Map.Entry<Integer, H2Stream> entry = it.next();
+ for (final Entry<Integer, H2Stream> entry : streamMap.entrySet()) {
final H2Stream stream = entry.getValue();
try {
updateInputWindow(stream.getId(), stream.getInputWindow(), delta);
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2PrefaceHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2PrefaceHandler.java
index 9730b3a38..36dc50afc 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2PrefaceHandler.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ClientH2PrefaceHandler.java
@@ -53,7 +53,7 @@ import org.apache.hc.core5.util.TextUtils;
public class ClientH2PrefaceHandler extends PrefaceHandlerBase {
// PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n
- final static byte[] PREFACE = new byte[] {
+ final static byte[] PREFACE = {
0x50, 0x52, 0x49, 0x20, 0x2a, 0x20, 0x48, 0x54, 0x54, 0x50,
0x2f, 0x32, 0x2e, 0x30, 0x0d, 0x0a, 0x0d, 0x0a, 0x53, 0x4d,
0x0d, 0x0a, 0x0d, 0x0a};
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2PrefaceHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2PrefaceHandler.java
index 35c80c20a..1efbc9c3b 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2PrefaceHandler.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/ServerH2PrefaceHandler.java
@@ -85,8 +85,8 @@ public class ServerH2PrefaceHandler extends PrefaceHandlerBase {
}
final ByteBuffer data = inBuf.data();
if (data.remaining() >= PREFACE.length) {
- for (int i = 0; i < PREFACE.length; i++) {
- if (data.get() != PREFACE[i]) {
+ for (final byte element : PREFACE) {
+ if (data.get() != element) {
throw new ProtocolNegotiationException("Unexpected HTTP/2 preface");
}
}
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequesterBootstrap.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequesterBootstrap.java
index 57cd21d63..23d5921ae 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequesterBootstrap.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2MultiplexingRequesterBootstrap.java
@@ -196,9 +196,7 @@ public class H2MultiplexingRequesterBootstrap {
public H2MultiplexingRequester create() {
final RequestHandlerRegistry<Supplier<AsyncPushConsumer>> registry = new RequestHandlerRegistry<>(uriPatternType);
- for (final HandlerEntry<Supplier<AsyncPushConsumer>> entry: pushConsumerList) {
- registry.register(entry.hostname, entry.uriPattern, entry.handler);
- }
+ pushConsumerList.forEach(entry -> registry.register(entry.hostname, entry.uriPattern, entry.handler));
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(
httpProcessor != null ? httpProcessor : H2Processors.client(),
new DefaultAsyncPushConsumerFactory(registry),
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2RequesterBootstrap.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2RequesterBootstrap.java
index 8ea1490ef..adf19aa31 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2RequesterBootstrap.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2RequesterBootstrap.java
@@ -310,9 +310,7 @@ public class H2RequesterBootstrap {
break;
}
final RequestHandlerRegistry<Supplier<AsyncPushConsumer>> registry = new RequestHandlerRegistry<>(uriPatternType);
- for (final HandlerEntry<Supplier<AsyncPushConsumer>> entry: pushConsumerList) {
- registry.register(entry.hostname, entry.uriPattern, entry.handler);
- }
+ pushConsumerList.forEach(entry -> registry.register(entry.hostname, entry.uriPattern, entry.handler));
final ClientH2StreamMultiplexerFactory http2StreamHandlerFactory = new ClientH2StreamMultiplexerFactory(
httpProcessor != null ? httpProcessor : H2Processors.client(),
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2ServerBootstrap.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2ServerBootstrap.java
index d60f84276..b5806f8cd 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2ServerBootstrap.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/impl/nio/bootstrap/H2ServerBootstrap.java
@@ -346,9 +346,7 @@ public class H2ServerBootstrap {
actualCanonicalHostName,
() -> lookupRegistry != null ? lookupRegistry :
UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
- for (final HandlerEntry<Supplier<AsyncServerExchangeHandler>> entry: handlerList) {
- registry.register(entry.hostname, entry.uriPattern, entry.handler);
- }
+ handlerList.forEach(entry -> registry.register(entry.hostname, entry.uriPattern, entry.handler));
final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
if (!filters.isEmpty()) {
diff --git a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/nio/support/BasicPingHandler.java b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/nio/support/BasicPingHandler.java
index 9a52223d4..ba70fe85a 100644
--- a/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/nio/support/BasicPingHandler.java
+++ b/httpcore5-h2/src/main/java/org/apache/hc/core5/http2/nio/support/BasicPingHandler.java
@@ -41,7 +41,7 @@ import org.apache.hc.core5.util.Args;
*/
public class BasicPingHandler implements AsyncPingHandler {
- private static final byte[] PING_MESSAGE = new byte[] {'*', '*', 'p', 'i', 'n', 'g', '*', '*'};
+ private static final byte[] PING_MESSAGE = {'*', '*', 'p', 'i', 'n', 'g', '*', '*'};
private final Callback<Boolean> callback;
@@ -57,8 +57,8 @@ public class BasicPingHandler implements AsyncPingHandler {
@Override
public void consumeResponse(final ByteBuffer feedback) throws HttpException, IOException {
boolean result = true;
- for (int i = 0; i < PING_MESSAGE.length; i++) {
- if (!feedback.hasRemaining() || PING_MESSAGE[i] != feedback.get()) {
+ for (final byte element : PING_MESSAGE) {
+ if (!feedback.hasRemaining() || element != feedback.get()) {
result = false;
break;
}
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ConscriptRequestExecutionExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ConscriptRequestExecutionExample.java
index e33f4e248..7e81098d9 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ConscriptRequestExecutionExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ConscriptRequestExecutionExample.java
@@ -26,6 +26,7 @@
*/
package org.apache.hc.core5.http2.examples;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
@@ -54,8 +55,7 @@ import org.apache.hc.core5.util.Timeout;
import org.conscrypt.Conscrypt;
/**
- * This example demonstrates how to execute HTTP/2 requests over TLS connections
- * with Java 1.7 or Java 1.8 and Conscrypt TLS library
+ * This example demonstrates how to execute HTTP/2 requests over TLS connections Java 8 and Conscrypt TLS library.
*/
public class H2ConscriptRequestExecutionExample {
@@ -77,16 +77,12 @@ public class H2ConscriptRequestExecutionExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
@@ -114,9 +110,9 @@ public class H2ConscriptRequestExecutionExample {
requester.start();
final HttpHost target = new HttpHost("https", "nghttp2.org", 443);
- final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
+ final List<String> requestUris = Arrays.asList("/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers");
- final CountDownLatch latch = new CountDownLatch(requestUris.length);
+ final CountDownLatch latch = new CountDownLatch(requestUris.size());
for (final String requestUri: requestUris) {
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofDays(5));
final AsyncClientEndpoint clientEndpoint = future.get();
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FileServerExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FileServerExample.java
index c4d24f0e8..5a291d5d1 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FileServerExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FileServerExample.java
@@ -94,16 +94,12 @@ public class H2FileServerExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexClientExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexClientExample.java
index c75217509..8d716cf40 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexClientExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexClientExample.java
@@ -82,16 +82,12 @@ public class H2FullDuplexClientExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexServerExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexServerExample.java
index d09f09b8c..68448c89f 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexServerExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2FullDuplexServerExample.java
@@ -88,16 +88,12 @@ public class H2FullDuplexServerExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2MultiStreamExecutionExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2MultiStreamExecutionExample.java
index 2628387f3..9c60c81a0 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2MultiStreamExecutionExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2MultiStreamExecutionExample.java
@@ -26,6 +26,7 @@
*/
package org.apache.hc.core5.http2.examples;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
@@ -76,16 +77,12 @@ public class H2MultiStreamExecutionExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
@@ -113,13 +110,13 @@ public class H2MultiStreamExecutionExample {
requester.start();
final HttpHost target = new HttpHost("nghttp2.org");
- final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
+ final List<String> requestUris = Arrays.asList("/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers");
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
- final CountDownLatch latch = new CountDownLatch(requestUris.length);
- for (final String requestUri: requestUris) {
+ final CountDownLatch latch = new CountDownLatch(requestUris.size());
+ requestUris.forEach(requestUri ->
clientEndpoint.execute(
AsyncRequestBuilder.get()
.setHttpHost(target)
@@ -149,8 +146,8 @@ public class H2MultiStreamExecutionExample {
System.out.println(requestUri + " cancelled");
}
- });
- }
+ })
+ );
latch.await();
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2RequestExecutionExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2RequestExecutionExample.java
index 3653baeeb..f9adecca9 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2RequestExecutionExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2RequestExecutionExample.java
@@ -68,16 +68,12 @@ public class H2RequestExecutionExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
@@ -105,7 +101,7 @@ public class H2RequestExecutionExample {
requester.start();
final HttpHost target = new HttpHost("nghttp2.org");
- final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
+ final String[] requestUris = {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) {
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2TlsAlpnRequestExecutionExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2TlsAlpnRequestExecutionExample.java
index 5a67e0965..24187e482 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2TlsAlpnRequestExecutionExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2TlsAlpnRequestExecutionExample.java
@@ -65,28 +65,17 @@ public class H2TlsAlpnRequestExecutionExample {
final HttpAsyncRequester requester = H2RequesterBootstrap.bootstrap()
.setH2Config(h2Config)
- .setTlsStrategy(new H2ClientTlsStrategy(SSLContexts.createSystemDefault(), (endpoint, sslEngine) -> {
- // IMPORTANT uncomment the following line when running Java 9 or older
- // in order to avoid the illegal reflective access operation warning
- // ====
- // return new TlsDetails(sslEngine.getSession(), sslEngine.getApplicationProtocol());
- // ====
- return null;
- }))
+ .setTlsStrategy(new H2ClientTlsStrategy(SSLContexts.createSystemDefault(), (endpoint, sslEngine) -> null))
.setStreamListener(new H2StreamListener() {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
@@ -114,7 +103,7 @@ public class H2TlsAlpnRequestExecutionExample {
requester.start();
final HttpHost target = new HttpHost("https", "nghttp2.org", 443);
- final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
+ final String[] requestUris = {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
final CountDownLatch latch = new CountDownLatch(requestUris.length);
for (final String requestUri: requestUris) {
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ViaHttp1ProxyExecutionExample.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ViaHttp1ProxyExecutionExample.java
index 6ebebc732..9fb49482e 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ViaHttp1ProxyExecutionExample.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/examples/H2ViaHttp1ProxyExecutionExample.java
@@ -26,6 +26,7 @@
*/
package org.apache.hc.core5.http2.examples;
+import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -103,16 +104,12 @@ public class H2ViaHttp1ProxyExecutionExample {
@Override
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") << " + header));
}
@Override
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
- for (int i = 0; i < headers.size(); i++) {
- System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + headers.get(i));
- }
+ headers.forEach(header -> System.out.println(connection.getRemoteAddress() + " (" + streamId + ") >> " + header));
}
@Override
@@ -187,11 +184,11 @@ public class H2ViaHttp1ProxyExecutionExample {
}));
- final String[] requestUris = new String[] {"/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers"};
+ final List<String> requestUris = Arrays.asList("/httpbin/ip", "/httpbin/user-agent", "/httpbin/headers");
final AsyncClientEndpoint endpoint = tunnelFuture.get(1, TimeUnit.MINUTES);
try {
- final CountDownLatch latch = new CountDownLatch(requestUris.length);
- for (final String requestUri : requestUris) {
+ final CountDownLatch latch = new CountDownLatch(requestUris.size());
+ requestUris.forEach(requestUri ->
endpoint.execute(
new BasicRequestProducer(Method.GET, target, requestUri),
new BasicResponseConsumer<>(new StringAsyncEntityConsumer()),
@@ -218,8 +215,8 @@ public class H2ViaHttp1ProxyExecutionExample {
latch.countDown();
}
- });
- }
+ })
+ );
latch.await();
} finally {
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/frame/TestDefaultFrameFactory.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/frame/TestDefaultFrameFactory.java
index 676744236..66d988aca 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/frame/TestDefaultFrameFactory.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/frame/TestDefaultFrameFactory.java
@@ -42,7 +42,7 @@ public class TestDefaultFrameFactory {
final FrameFactory frameFactory = new DefaultFrameFactory();
- final byte[] data = new byte[]{'a', 'b', 'c', 'd', 'e', 'f'};
+ final byte[] data = {'a', 'b', 'c', 'd', 'e', 'f'};
final Frame<ByteBuffer> dataFrame = frameFactory.createData(23, ByteBuffer.wrap(data), true);
Assertions.assertEquals(FrameType.DATA.value, dataFrame.getType());
diff --git a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
index 47dc1ce7f..27d06dd26 100644
--- a/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
+++ b/httpcore5-h2/src/test/java/org/apache/hc/core5/http2/hpack/TestHPackCoding.java
@@ -241,8 +241,8 @@ public class TestHPackCoding {
if (j > 0) {
buffer.append("; ");
}
- for (int i = 0; i < raw.length; i++) {
- buffer.append((char) raw[i]);
+ for (final int element : raw) {
+ buffer.append((char) element);
}
}
return buffer.toString();
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 61813caeb..871c13d3c 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
@@ -114,11 +114,7 @@ final class ReactiveDataProducer implements AsyncDataProducer, Subscriber<ByteBu
return 1;
} else {
synchronized (buffers) {
- int sum = 0;
- for (final ByteBuffer buffer : buffers) {
- sum += buffer.remaining();
- }
- return sum;
+ return buffers.stream().mapToInt(ByteBuffer::remaining).sum();
}
}
}
diff --git a/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/examples/ReactiveFullDuplexClientExample.java b/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/examples/ReactiveFullDuplexClientExample.java
index 8c87b5013..12716252f 100644
--- a/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/examples/ReactiveFullDuplexClientExample.java
+++ b/httpcore5-reactive/src/test/java/org/apache/hc/core5/reactive/examples/ReactiveFullDuplexClientExample.java
@@ -33,9 +33,9 @@ import java.nio.ByteBuffer;
import java.util.Random;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ContentType;
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpConnection;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
@@ -118,9 +118,7 @@ public class ReactiveFullDuplexClientExample {
final Message<HttpResponse, Publisher<ByteBuffer>> streamingResponse = consumer.getResponseFuture().get();
System.out.println(streamingResponse.getHead());
- for (final Header header : streamingResponse.getHead().getHeaders()) {
- System.out.println(header);
- }
+ Stream.of(streamingResponse.getHead().getHeaders()).forEach(System.out::println);
System.out.println();
Observable.fromPublisher(streamingResponse.getBody())
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/HttpBenchmark.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/HttpBenchmark.java
index 5cda8b208..5fa0b90c6 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/HttpBenchmark.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/benchmark/HttpBenchmark.java
@@ -38,6 +38,7 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
+import java.util.stream.Stream;
import javax.net.ssl.SSLContext;
@@ -319,10 +320,7 @@ public class HttpBenchmark {
public void onRequestHead(final HttpConnection connection, final HttpRequest request) {
if (config.getVerbosity() >= 3) {
System.out.println(">> " + request.getMethod() + " " + request.getRequestUri());
- final Header[] headers = request.getHeaders();
- for (final Header header : headers) {
- System.out.println(">> " + header);
- }
+ Stream.of(request.getHeaders()).forEach(header -> System.out.println(">> " + header));
System.out.println();
}
}
@@ -331,10 +329,7 @@ public class HttpBenchmark {
public void onResponseHead(final HttpConnection connection, final HttpResponse response) {
if (config.getVerbosity() >= 3) {
System.out.println("<< " + response.getCode() + " " + response.getReasonPhrase());
- final Header[] headers = response.getHeaders();
- for (final Header header : headers) {
- System.out.println("<< " + header);
- }
+ Stream.of(response.getHeaders()).forEach(header -> System.out.println("<< " + header));
System.out.println();
}
}
@@ -354,9 +349,7 @@ public class HttpBenchmark {
final int streamId,
final List<? extends Header> headers) {
if (config.getVerbosity() >= 3) {
- for (final Header header : headers) {
- System.out.println("<< " + header);
- }
+ headers.forEach(header -> System.out.println("<< " + header));
System.out.println();
}
}
@@ -367,9 +360,7 @@ public class HttpBenchmark {
final int streamId,
final List<? extends Header> headers) {
if (config.getVerbosity() >= 3) {
- for (final Header header : headers) {
- System.out.println(">> " + header);
- }
+ headers.forEach(header -> System.out.println(">> " + header));
System.out.println();
}
}
@@ -475,8 +466,8 @@ public class HttpBenchmark {
final long startTime = System.currentTimeMillis();
- for (int i = 0; i < workers.length; i++) {
- workers[i].execute();
+ for (final BenchmarkWorker worker : workers) {
+ worker.execute();
}
completionLatch.await(deadline, TimeUnit.MILLISECONDS);
@@ -487,8 +478,8 @@ public class HttpBenchmark {
final long endTime = System.currentTimeMillis();
- for (int i = 0; i < workers.length; i++) {
- workers[i].releaseResources();
+ for (final BenchmarkWorker worker : workers) {
+ worker.releaseResources();
}
return new Results(
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/SocksProxy.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/SocksProxy.java
index 7d8234d8e..5f6824b61 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/SocksProxy.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/SocksProxy.java
@@ -256,9 +256,7 @@ public class SocksProxy {
t = this.serverThread;
this.serverThread = null;
}
- for (final SocksProxyHandler handler : this.handlers) {
- handler.shutdown();
- }
+ this.handlers.forEach(SocksProxyHandler::shutdown);
while (!this.handlers.isEmpty()) {
final long waitTime = waitUntil - System.currentTimeMillis();
if (waitTime > 0) {
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnection.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnection.java
index 7fcdd4afc..27ebe96b8 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnection.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpClientConnection.java
@@ -32,11 +32,11 @@ import java.net.Socket;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentLengthStrategy;
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.http.impl.io.DefaultBHttpClientConnection;
import org.apache.hc.core5.http.impl.io.SocketHolder;
@@ -46,8 +46,8 @@ import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.util.Identifiable;
-import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class LoggingBHttpClientConnection extends DefaultBHttpClientConnection implements Identifiable {
@@ -109,10 +109,7 @@ public class LoggingBHttpClientConnection extends DefaultBHttpClientConnection i
protected void onResponseReceived(final ClassicHttpResponse response) {
if (response != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} << {}", this.id, new StatusLine(response));
- final Header[] headers = response.getHeaders();
- for (final Header header : headers) {
- this.headerLog.debug("{} << {}", this.id, header);
- }
+ Stream.of(response.getHeaders()).forEach(header -> this.headerLog.debug("{} << {}", this.id, header));
}
}
@@ -120,10 +117,7 @@ public class LoggingBHttpClientConnection extends DefaultBHttpClientConnection i
protected void onRequestSubmitted(final ClassicHttpRequest request) {
if (request != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} >> {}", id, new RequestLine(request));
- final Header[] headers = request.getHeaders();
- for (final Header header : headers) {
- this.headerLog.debug("{} >> {}", this.id, header);
- }
+ Stream.of(request.getHeaders()).forEach(header -> this.headerLog.debug("{} >> {}", this.id, header));
}
}
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnection.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnection.java
index 94ed2f38e..bd64cdc5a 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnection.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/classic/LoggingBHttpServerConnection.java
@@ -32,11 +32,11 @@ import java.net.Socket;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.concurrent.atomic.AtomicLong;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentLengthStrategy;
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.http.impl.io.DefaultBHttpServerConnection;
import org.apache.hc.core5.http.impl.io.SocketHolder;
@@ -46,8 +46,8 @@ import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.util.Identifiable;
-import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class LoggingBHttpServerConnection extends DefaultBHttpServerConnection implements Identifiable {
private static final AtomicLong COUNT = new AtomicLong();
@@ -109,10 +109,7 @@ public class LoggingBHttpServerConnection extends DefaultBHttpServerConnection i
protected void onRequestReceived(final ClassicHttpRequest request) {
if (request != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} >> {}", id, new RequestLine(request));
- final Header[] headers = request.getHeaders();
- for (final Header header : headers) {
- this.headerLog.debug("{} >> {}", this.id, header);
- }
+ Stream.of(request.getHeaders()).forEach(header -> this.headerLog.debug("{} >> {}", this.id, header));
}
}
@@ -120,10 +117,7 @@ public class LoggingBHttpServerConnection extends DefaultBHttpServerConnection i
protected void onResponseSubmitted(final ClassicHttpResponse response) {
if (response != null && this.headerLog.isDebugEnabled()) {
this.headerLog.debug("{} << {}", this.id, new StatusLine(response));
- final Header[] headers = response.getHeaders();
- for (final Header header : headers) {
- this.headerLog.debug("{} << {}", this.id, header);
- }
+ Stream.of(response.getHeaders()).forEach(header -> this.headerLog.debug("{} << {}", this.id, header));
}
}
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/ClassicTestClientAdapter.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/ClassicTestClientAdapter.java
index 1c4b097c6..17e8c7556 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/ClassicTestClientAdapter.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/ClassicTestClientAdapter.java
@@ -30,7 +30,8 @@ package org.apache.hc.core5.testing.framework;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
-import java.util.Map.Entry;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ContentType;
@@ -94,9 +95,7 @@ public class ClassicTestClientAdapter extends ClientPOJOAdapter {
final StringBuilder newQuery = new StringBuilder(existingQuery == null ? "" : existingQuery);
// append each parm to the query
- for (final Entry<String, String> parm : queryMap.entrySet()) {
- newQuery.append("&").append(parm.getKey()).append("=").append(parm.getValue());
- }
+ queryMap.forEach((k, v) -> newQuery.append("&").append(k).append("=").append(v));
// create a uri with the new query.
uri = new URI(
startingURI.getRawSchemeSpecificPart(),
@@ -120,9 +119,7 @@ public class ClassicTestClientAdapter extends ClientPOJOAdapter {
@SuppressWarnings("unchecked")
final Map<String, String> headersMap = (Map<String, String>) request.get(HEADERS);
if (headersMap != null) {
- for (final Entry<String, String> header : headersMap.entrySet()) {
- httpRequest.addHeader(header.getKey(), header.getValue());
- }
+ headersMap.forEach(httpRequest::addHeader);
}
// call setEntity if a body is specified.
@@ -151,10 +148,8 @@ public class ClassicTestClientAdapter extends ClientPOJOAdapter {
ret.put(STATUS, response.getCode());
// convert the headers to a Map
- final Map<String, Object> headerMap = new HashMap<>();
- for (final Header header : response.getHeaders()) {
- headerMap.put(header.getName(), header.getValue());
- }
+ final Map<String, Object> headerMap = Stream.of(response.getHeaders())
+ .collect(Collectors.toMap(Header::getName, Header::getValue));
ret.put(HEADERS, headerMap);
ret.put(BODY, body);
ret.put(CONTENT_TYPE, contentType);
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/FrameworkTest.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/FrameworkTest.java
index 968548793..155870043 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/FrameworkTest.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/FrameworkTest.java
@@ -116,10 +116,8 @@ public class FrameworkTest {
final List<NameValuePair> params = uriBuilder.getQueryParams();
@SuppressWarnings("unchecked")
final Map<String, Object> queryMap = (Map<String, Object>) request.get(QUERY);
- for (final NameValuePair param : params) {
- queryMap.put(param.getName(), param.getValue());
- }
- if (! params.isEmpty()) {
+ params.forEach(param -> queryMap.put(param.getName(), param.getValue()));
+ if (!params.isEmpty()) {
request.put(PATH, uri.getPath());
}
}
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/TestingFrameworkRequestHandler.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/TestingFrameworkRequestHandler.java
index e757b6232..e7df6f71d 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/TestingFrameworkRequestHandler.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/framework/TestingFrameworkRequestHandler.java
@@ -38,10 +38,11 @@ import static org.apache.hc.core5.testing.framework.ClientPOJOAdapter.STATUS;
import java.io.IOException;
import java.net.URI;
import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
@@ -139,10 +140,8 @@ public class TestingFrameworkRequestHandler implements HttpRequestHandler {
final URI uri = request.getUri();
final URIBuilder uriBuilder = new URIBuilder(uri, StandardCharsets.UTF_8);
final List<NameValuePair> actualParams = uriBuilder.getQueryParams();
- final Map<String, String> actualParamsMap = new HashMap<>();
- for (final NameValuePair actualParam : actualParams) {
- actualParamsMap.put(actualParam.getName(), actualParam.getValue());
- }
+ final Map<String, String> actualParamsMap = actualParams.stream()
+ .collect(Collectors.toMap(NameValuePair::getName, NameValuePair::getValue));
for (final Map.Entry<String, String> expectedParam : expectedQuery.entrySet()) {
final String key = expectedParam.getKey();
if (! actualParamsMap.containsKey(key)) {
@@ -163,11 +162,8 @@ public class TestingFrameworkRequestHandler implements HttpRequestHandler {
@SuppressWarnings("unchecked")
final Map<String, String> expectedHeaders = (Map<String, String>) requestExpectations.get(HEADERS);
if (expectedHeaders != null) {
- final Map<String, String> actualHeadersMap = new HashMap<>();
- final Header[] actualHeaders = request.getHeaders();
- for (final Header header : actualHeaders) {
- actualHeadersMap.put(header.getName(), header.getValue());
- }
+ final Map<String, String> actualHeadersMap = Stream.of(request.getHeaders())
+ .collect(Collectors.toMap(Header::getName, Header::getValue));
for (final Entry<String, String> expectedHeader : expectedHeaders.entrySet()) {
final String key = expectedHeader.getKey();
if (! actualHeadersMap.containsKey(key)) {
@@ -239,9 +235,7 @@ public class TestingFrameworkRequestHandler implements HttpRequestHandler {
@SuppressWarnings("unchecked")
final Map<String, String> desiredHeaders = (Map<String, String>) desiredResponse.get(HEADERS);
if (desiredHeaders != null) {
- for (final Entry<String, String> entry : desiredHeaders.entrySet()) {
- response.setHeader(entry.getKey(), entry.getValue());
- }
+ desiredHeaders.forEach(response::setHeader);
}
} catch (final Throwable t) {
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingH2StreamListener.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingH2StreamListener.java
index 8ef7d720a..bfd0736aa 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingH2StreamListener.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingH2StreamListener.java
@@ -85,9 +85,7 @@ public class LoggingH2StreamListener implements H2StreamListener {
public void onHeaderInput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
final String prefix = LoggingSupport.getId(connection);
- for (int i = 0; i < headers.size(); i++) {
- headerLog.debug("{} << {}", prefix, headers.get(i));
- }
+ headers.forEach(header -> headerLog.debug("{} << {}", prefix, header));
}
}
@@ -95,9 +93,7 @@ public class LoggingH2StreamListener implements H2StreamListener {
public void onHeaderOutput(final HttpConnection connection, final int streamId, final List<? extends Header> headers) {
if (headerLog.isDebugEnabled()) {
final String prefix = LoggingSupport.getId(connection);
- for (int i = 0; i < headers.size(); i++) {
- headerLog.debug("{} >> {}", prefix, headers.get(i));
- }
+ headers.forEach(header -> headerLog.debug("{} >> {}", prefix, header));
}
}
diff --git a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingHttp1StreamListener.java b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingHttp1StreamListener.java
index 72796c2c7..98bee8370 100644
--- a/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingHttp1StreamListener.java
+++ b/httpcore5-testing/src/main/java/org/apache/hc/core5/testing/nio/LoggingHttp1StreamListener.java
@@ -27,9 +27,6 @@
package org.apache.hc.core5.testing.nio;
-import java.util.Iterator;
-
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpConnection;
import org.apache.hc.core5.http.HttpRequest;
import org.apache.hc.core5.http.HttpResponse;
@@ -37,8 +34,8 @@ import org.apache.hc.core5.http.impl.Http1StreamListener;
import org.apache.hc.core5.http.message.RequestLine;
import org.apache.hc.core5.http.message.StatusLine;
import org.apache.hc.core5.testing.classic.LoggingSupport;
-import org.slf4j.LoggerFactory;
import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class LoggingHttp1StreamListener implements Http1StreamListener {
@@ -62,9 +59,7 @@ public class LoggingHttp1StreamListener implements Http1StreamListener {
if (headerLog.isDebugEnabled()) {
final String idRequestDirection = LoggingSupport.getId(connection) + requestDirection;
headerLog.debug("{}{}", idRequestDirection, new RequestLine(request));
- for (final Iterator<Header> it = request.headerIterator(); it.hasNext(); ) {
- headerLog.debug("{}{}", idRequestDirection, it.next());
- }
+ request.headerIterator().forEachRemaining(h -> headerLog.debug("{}{}", idRequestDirection, h));
}
}
@@ -73,9 +68,7 @@ public class LoggingHttp1StreamListener implements Http1StreamListener {
if (headerLog.isDebugEnabled()) {
final String id = LoggingSupport.getId(connection);
headerLog.debug("{}{}{}", id, responseDirection, new StatusLine(response));
- for (final Iterator<Header> it = response.headerIterator(); it.hasNext(); ) {
- headerLog.debug("{}{}{}", id, responseDirection, it.next());
- }
+ response.headerIterator().forEachRemaining(h -> headerLog.debug("{}{}{}", id, responseDirection, h));
}
}
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 b82ad06bb..8c82a6c7e 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
@@ -77,7 +77,7 @@ public class H2CompatibilityTest {
public static void main(final String... args) throws Exception {
- final HttpHost[] h2servers = new HttpHost[]{
+ final HttpHost[] h2servers = {
new HttpHost("http", "localhost", 8080),
new HttpHost("http", "localhost", 8081)
};
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/framework/TestTestingFramework.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/framework/TestTestingFramework.java
index dfb09be96..edcba516e 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/framework/TestTestingFramework.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/framework/TestTestingFramework.java
@@ -885,9 +885,8 @@ public class TestTestingFramework {
framework.runTests();
- for (final String method : TestingFramework.ALL_METHODS) {
- Assertions.assertTrue(calledMethodSet.contains(method), "Method not in default tests. method=" + method);
- }
+ TestingFramework.ALL_METHODS.forEach(method -> Assertions.assertTrue(calledMethodSet.contains(method),
+ "Method not in default tests. method=" + method));
}
@Test
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
index b41db879e..433d6ef4e 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/H2IntegrationTest.java
@@ -45,7 +45,6 @@ import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
-import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -60,8 +59,8 @@ import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
-import org.apache.hc.core5.function.Supplier;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.EndpointDetails;
import org.apache.hc.core5.http.EntityDetails;
@@ -581,47 +580,40 @@ public class H2IntegrationTest extends InternalH2ServerTestBase {
public void testPushRefused() throws Exception {
final BlockingQueue<Exception> pushResultQueue = new LinkedBlockingDeque<>();
final InetSocketAddress serverEndpoint = server.start();
- server.register("/hello", new Supplier<AsyncServerExchangeHandler>() {
+ server.register("/hello", () -> new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {
@Override
- public AsyncServerExchangeHandler get() {
- return new MessageExchangeHandler<Void>(new DiscardingEntityConsumer<>()) {
+ protected void handle(
+ final Message<HttpRequest, Void> request,
+ final AsyncServerRequestHandler.ResponseTrigger responseTrigger,
+ final HttpContext context) throws IOException, HttpException {
- @Override
- protected void handle(
- final Message<HttpRequest, Void> request,
- final AsyncServerRequestHandler.ResponseTrigger responseTrigger,
- final HttpContext context) throws IOException, HttpException {
-
- responseTrigger.pushPromise(
- new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")),
- context, new BasicPushProducer(AsyncEntityProducers.create("Pushing all sorts of stuff")) {
-
- @Override
- public void failed(final Exception cause) {
- pushResultQueue.add(cause);
- super.failed(cause);
- }
+ responseTrigger.pushPromise(
+ new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/stuff")),
+ context, new BasicPushProducer(AsyncEntityProducers.create("Pushing all sorts of stuff")) {
- });
- responseTrigger.pushPromise(
- new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/more-stuff")),
- context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)) {
+ @Override
+ public void failed(final Exception cause) {
+ pushResultQueue.add(cause);
+ super.failed(cause);
+ }
- @Override
- public void failed(final Exception cause) {
- pushResultQueue.add(cause);
- super.failed(cause);
- }
+ });
+ responseTrigger.pushPromise(
+ new BasicHttpRequest(Method.GET, createRequestURI(serverEndpoint, "/more-stuff")),
+ context, new BasicPushProducer(new MultiLineEntityProducer("Pushing lots of stuff", 500)) {
- });
- responseTrigger.submitResponse(
- new BasicResponseProducer(HttpStatus.SC_OK, AsyncEntityProducers.create("Hi there")),
- context);
+ @Override
+ public void failed(final Exception cause) {
+ pushResultQueue.add(cause);
+ super.failed(cause);
}
- };
- }
+ });
+ responseTrigger.submitResponse(
+ new BasicResponseProducer(HttpStatus.SC_OK, AsyncEntityProducers.create("Hi there")),
+ context);
+ }
});
client.start(H2Config.custom().setPushEnabled(true).build());
@@ -738,66 +730,59 @@ public class H2IntegrationTest extends InternalH2ServerTestBase {
@Test
public void testPrematureResponse() throws Exception {
- server.register("*", new Supplier<AsyncServerExchangeHandler>() {
+ server.register("*", () -> new AsyncServerExchangeHandler() {
- @Override
- public AsyncServerExchangeHandler get() {
- return new AsyncServerExchangeHandler() {
-
- private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();
-
- @Override
- public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
- capacityChannel.update(Integer.MAX_VALUE);
- }
+ private final AtomicReference<AsyncResponseProducer> responseProducer = new AtomicReference<>();
- @Override
- public void consume(final ByteBuffer src) throws IOException {
- }
+ @Override
+ public void updateCapacity(final CapacityChannel capacityChannel) throws IOException {
+ capacityChannel.update(Integer.MAX_VALUE);
+ }
- @Override
- public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
- }
+ @Override
+ public void consume(final ByteBuffer src) throws IOException {
+ }
- @Override
- public void handleRequest(
- final HttpRequest request,
- final EntityDetails entityDetails,
- final ResponseChannel responseChannel,
- final HttpContext context) throws HttpException, IOException {
- final AsyncResponseProducer producer;
- final Header h = request.getFirstHeader("password");
- if (h != null && "secret".equals(h.getValue())) {
- producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
- } else {
- producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
- }
- responseProducer.set(producer);
- producer.sendResponse(responseChannel, context);
- }
+ @Override
+ public void streamEnd(final List<? extends Header> trailers) throws HttpException, IOException {
+ }
- @Override
- public int available() {
- final AsyncResponseProducer producer = this.responseProducer.get();
- return producer.available();
- }
+ @Override
+ public void handleRequest(
+ final HttpRequest request,
+ final EntityDetails entityDetails,
+ final ResponseChannel responseChannel,
+ final HttpContext context) throws HttpException, IOException {
+ final AsyncResponseProducer producer;
+ final Header h = request.getFirstHeader("password");
+ if (h != null && "secret".equals(h.getValue())) {
+ producer = new BasicResponseProducer(HttpStatus.SC_OK, "All is well");
+ } else {
+ producer = new BasicResponseProducer(HttpStatus.SC_UNAUTHORIZED, "You shall not pass");
+ }
+ responseProducer.set(producer);
+ producer.sendResponse(responseChannel, context);
+ }
- @Override
- public void produce(final DataStreamChannel channel) throws IOException {
- final AsyncResponseProducer producer = this.responseProducer.get();
- producer.produce(channel);
- }
+ @Override
+ public int available() {
+ final AsyncResponseProducer producer = this.responseProducer.get();
+ return producer.available();
+ }
- @Override
- public void failed(final Exception cause) {
- }
+ @Override
+ public void produce(final DataStreamChannel channel) throws IOException {
+ final AsyncResponseProducer producer = this.responseProducer.get();
+ producer.produce(channel);
+ }
- @Override
- public void releaseResources() {
- }
- };
+ @Override
+ public void failed(final Exception cause) {
}
+ @Override
+ public void releaseResources() {
+ }
});
final InetSocketAddress serverEndpoint = server.start();
@@ -864,10 +849,8 @@ public class H2IntegrationTest extends InternalH2ServerTestBase {
final List<Header> trailers = entityConsumer.getTrailers();
Assertions.assertNotNull(trailers);
Assertions.assertEquals(2, trailers.size());
- final Map<String, String> map = new HashMap<>();
- for (final Header header: trailers) {
- map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
- }
+ final Map<String, String> map = trailers.stream()
+ .collect(Collectors.toMap(h -> TextUtils.toLowerCase(h.getName()), Header::getValue));
final String digest = TextUtils.toHexString(entityConsumer.getDigest());
Assertions.assertEquals("MD5", map.get("digest-algo"));
Assertions.assertEquals(digest, map.get("digest"));
diff --git a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
index 4f4cdc59e..ee3c48bc8 100644
--- a/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
+++ b/httpcore5-testing/src/test/java/org/apache/hc/core5/testing/nio/Http1IntegrationTest.java
@@ -46,7 +46,6 @@ import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collection;
-import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -58,6 +57,7 @@ import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Collectors;
import org.apache.hc.core5.http.ConnectionReuseStrategy;
import org.apache.hc.core5.http.ContentLengthStrategy;
@@ -1622,10 +1622,8 @@ public class Http1IntegrationTest extends InternalHttp1ServerTestBase {
final List<Header> trailers = entityConsumer.getTrailers();
Assertions.assertNotNull(trailers);
Assertions.assertEquals(2, trailers.size());
- final Map<String, String> map = new HashMap<>();
- for (final Header header: trailers) {
- map.put(TextUtils.toLowerCase(header.getName()), header.getValue());
- }
+ final Map<String, String> map = trailers.stream()
+ .collect(Collectors.toMap(h -> TextUtils.toLowerCase(h.getName()), Header::getValue));
final String digest = TextUtils.toHexString(entityConsumer.getDigest());
Assertions.assertEquals("MD5", map.get("digest-algo"));
Assertions.assertEquals(digest, map.get("digest"));
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java b/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
index 4fae21c47..7a17d7228 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/ContentType.java
@@ -505,9 +505,7 @@ public final class ContentType implements Serializable {
if (this.charset != null && !paramMap.containsKey(CHARSET)) {
newParams.add(new BasicNameValuePair(CHARSET, this.charset.name()));
}
- for (final Map.Entry<String, String> entry: paramMap.entrySet()) {
- newParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
- }
+ paramMap.forEach((k, v) -> newParams.add(new BasicNameValuePair(k, v)));
return create(this.getMimeType(), newParams.toArray(EMPTY_NAME_VALUE_PAIR_ARRAY), true);
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/HttpVersion.java b/httpcore5/src/main/java/org/apache/hc/core5/http/HttpVersion.java
index c9a3b1082..77a4aec4f 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/HttpVersion.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/HttpVersion.java
@@ -80,9 +80,9 @@ public final class HttpVersion extends ProtocolVersion {
* @since 5.0
*/
public static HttpVersion get(final int major, final int minor) {
- for (int i = 0; i < ALL.length; i++) {
- if (ALL[i].equals(major, minor)) {
- return ALL[i];
+ for (final HttpVersion element : ALL) {
+ if (element.equals(major, minor)) {
+ return element;
}
}
// argument checking is done in the constructor
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/EnglishReasonPhraseCatalog.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/EnglishReasonPhraseCatalog.java
index 597c9a306..6485c018f 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/EnglishReasonPhraseCatalog.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/EnglishReasonPhraseCatalog.java
@@ -86,7 +86,7 @@ public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog {
/** Reason phrases lookup table. */
- private static final String[][] REASON_PHRASES = new String[][]{
+ private static final String[][] REASON_PHRASES = {
null,
new String[4], // 1xx
new String[27], // 2xx
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/AsyncServerBootstrap.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/AsyncServerBootstrap.java
index dfbe1fabe..da03db1e3 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/AsyncServerBootstrap.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/AsyncServerBootstrap.java
@@ -323,9 +323,7 @@ public class AsyncServerBootstrap {
canonicalHostName != null ? canonicalHostName : InetAddressUtils.getCanonicalLocalHostName(),
() -> lookupRegistry != null ? lookupRegistry :
UriPatternType.newMatcher(UriPatternType.URI_PATTERN));
- for (final HandlerEntry<Supplier<AsyncServerExchangeHandler>> entry: handlerList) {
- registry.register(entry.hostname, entry.uriPattern, entry.handler);
- }
+ handlerList.forEach(entry -> registry.register(entry.hostname, entry.uriPattern, entry.handler));
final HandlerFactory<AsyncServerExchangeHandler> handlerFactory;
if (!filters.isEmpty()) {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/HttpServer.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/HttpServer.java
index 410d6bed2..364c82cc3 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/HttpServer.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/bootstrap/HttpServer.java
@@ -29,7 +29,6 @@ package org.apache.hc.core5.http.impl.bootstrap;
import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
-import java.util.Set;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@@ -206,10 +205,8 @@ public class HttpServer implements ModalCloseable {
Thread.currentThread().interrupt();
}
}
- final Set<Worker> workers = this.workerExecutorService.getWorkers();
- for (final Worker worker: workers) {
- Closer.close(worker.getConnection(), CloseMode.GRACEFUL);
- }
+ this.workerExecutorService.getWorkers()
+ .forEach(worker -> Closer.close(worker.getConnection(), CloseMode.GRACEFUL));
}
@Override
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/AbstractMessageParser.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/AbstractMessageParser.java
index 43329b2ce..0f2df58e7 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/AbstractMessageParser.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/AbstractMessageParser.java
@@ -199,8 +199,7 @@ public abstract class AbstractMessageParser<T extends HttpMessage> implements Ht
}
final Header[] headers = new Header[headerLines.size()];
for (int i = 0; i < headerLines.size(); i++) {
- final CharArrayBuffer buffer = headerLines.get(i);
- headers[i] = parser.parseHeader(buffer);
+ headers[i] = parser.parseHeader(headerLines.get(i));
}
return headers;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/ChunkedOutputStream.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/ChunkedOutputStream.java
index b7d9faf4c..347def627 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/ChunkedOutputStream.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/ChunkedOutputStream.java
@@ -159,8 +159,7 @@ public class ChunkedOutputStream extends OutputStream {
private void writeTrailers() throws IOException {
final List<? extends Header> trailers = this.trailerSupplier != null ? this.trailerSupplier.get() : null;
if (trailers != null) {
- for (int i = 0; i < trailers.size(); i++) {
- final Header header = trailers.get(i);
+ for (final Header header : trailers) {
if (header instanceof FormattedHeader) {
final CharArrayBuffer chbuffer = ((FormattedHeader) header).getBuffer();
this.buffer.writeLine(chbuffer, this.outputStream);
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/SessionOutputBufferImpl.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/SessionOutputBufferImpl.java
index c186f0041..b30dbcc62 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/SessionOutputBufferImpl.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/io/SessionOutputBufferImpl.java
@@ -54,7 +54,7 @@ import org.apache.hc.core5.util.CharArrayBuffer;
*/
public class SessionOutputBufferImpl implements SessionOutputBuffer {
- private static final byte[] CRLF = new byte[] {Chars.CR, Chars.LF};
+ private static final byte[] CRLF = {Chars.CR, Chars.LF};
private final BasicHttpTransportMetrics metrics;
private final ByteArrayBuffer buffer;
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ChunkEncoder.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ChunkEncoder.java
index 223f6fbc7..94456b0e7 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ChunkEncoder.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/ChunkEncoder.java
@@ -137,8 +137,7 @@ public class ChunkEncoder extends AbstractContentEncoder {
private void writeTrailers(final List<? extends Header> trailers) throws IOException {
if (trailers != null) {
- for (int i = 0; i < trailers.size(); i++) {
- final Header header = trailers.get(i);
+ for (final Header header : trailers) {
if (header instanceof FormattedHeader) {
final CharArrayBuffer chbuffer = ((FormattedHeader) header).getBuffer();
buffer.writeLine(chbuffer);
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/SessionOutputBufferImpl.java b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/SessionOutputBufferImpl.java
index 77cd9951f..e434cd4d9 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/SessionOutputBufferImpl.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/impl/nio/SessionOutputBufferImpl.java
@@ -44,7 +44,7 @@ import org.apache.hc.core5.util.CharArrayBuffer;
class SessionOutputBufferImpl extends ExpandableBuffer implements SessionOutputBuffer {
- private static final byte[] CRLF = new byte[] {Chars.CR, Chars.LF};
+ private static final byte[] CRLF = {Chars.CR, Chars.LF};
private final CharsetEncoder charEncoder;
private final int lineBufferSize;
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
index 37c6f0d3f..cd3828418 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/EntityUtils.java
@@ -36,9 +36,11 @@ import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
@@ -183,7 +185,9 @@ public final class EntityUtils {
}
private static final Map<String, ContentType> CONTENT_TYPE_MAP;
+
static {
+ // @formatter:off
final ContentType[] contentTypes = {
ContentType.APPLICATION_ATOM_XML,
ContentType.APPLICATION_FORM_URLENCODED,
@@ -195,11 +199,9 @@ public final class EntityUtils {
ContentType.TEXT_HTML,
ContentType.TEXT_PLAIN,
ContentType.TEXT_XML };
- final HashMap<String, ContentType> map = new HashMap<>();
- for (final ContentType contentType: contentTypes) {
- map.put(contentType.getMimeType(), contentType);
- }
- CONTENT_TYPE_MAP = Collections.unmodifiableMap(map);
+ // @formatter:on
+ CONTENT_TYPE_MAP = Collections.unmodifiableMap(
+ Stream.of(contentTypes).collect(Collectors.toMap(ContentType::getMimeType, Function.identity())));
}
private static String toString(final HttpEntity entity, final ContentType contentType, final int maxResultLength)
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/HttpEntities.java b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/HttpEntities.java
index bcdbb982e..1852dd696 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/HttpEntities.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/io/entity/HttpEntities.java
@@ -38,6 +38,8 @@ import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import java.util.zip.GZIPOutputStream;
import org.apache.hc.core5.function.Supplier;
@@ -179,11 +181,8 @@ public final class HttpEntities {
@Override
public Set<String> getTrailerNames() {
- final Set<String> names = new LinkedHashSet<>();
- for (final Header trailer: trailers) {
- names.add(trailer.getName());
- }
- return names;
+ return Stream.of(trailers)
+ .collect(Collectors.mapping(Header::getName, Collectors.toCollection(LinkedHashSet::new)));
}
};
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderElement.java b/httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderElement.java
index d35324712..8c59f67a3 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderElement.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/message/BasicHeaderElement.java
@@ -27,6 +27,8 @@
package org.apache.hc.core5.http.message;
+import java.util.stream.Stream;
+
import org.apache.hc.core5.http.HeaderElement;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.util.Args;
@@ -105,14 +107,7 @@ public class BasicHeaderElement implements HeaderElement {
@Override
public NameValuePair getParameterByName(final String name) {
Args.notNull(name, "Name");
- NameValuePair found = null;
- for (final NameValuePair current : this.parameters) {
- if (current.getName().equalsIgnoreCase(name)) {
- found = current;
- break;
- }
- }
- return found;
+ return Stream.of(this.parameters).filter(p -> p.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
}
@Override
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/message/HeaderGroup.java b/httpcore5/src/main/java/org/apache/hc/core5/http/message/HeaderGroup.java
index 072ea7ca5..eec21eddb 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/message/HeaderGroup.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/message/HeaderGroup.java
@@ -33,6 +33,8 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
+import java.util.function.Predicate;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.MessageHeaders;
@@ -50,7 +52,7 @@ public class HeaderGroup implements MessageHeaders, Serializable {
private static final long serialVersionUID = 2608834160639271617L;
- private static final Header[] EMPTY = new Header[] {};
+ private static final Header[] EMPTY = {};
/** The list of headers for this group, in the order in which they were added */
private final List<Header> headers;
@@ -63,13 +65,6 @@ public class HeaderGroup implements MessageHeaders, Serializable {
this.headers = new ArrayList<>(16);
}
- /**
- * Removes all headers.
- */
- public void clear() {
- headers.clear();
- }
-
/**
* Adds the given header to the group. The order in which this header was
* added is preserved.
@@ -84,89 +79,36 @@ public class HeaderGroup implements MessageHeaders, Serializable {
}
/**
- * Removes the first given header.
- *
- * @param header the header to remove
- * @return {@code true} if a header was removed as a result of this call.
- */
- public boolean removeHeader(final Header header) {
- if (header == null) {
- return false;
- }
- for (int i = 0; i < this.headers.size(); i++) {
- final Header current = this.headers.get(i);
- if (headerEquals(header, current)) {
- this.headers.remove(current);
- return true;
- }
- }
- return false;
- }
-
- private boolean headerEquals(final Header header1, final Header header2) {
- return header2 == header1 || header2.getName().equalsIgnoreCase(header1.getName())
- && Objects.equals(header1.getValue(), header2.getValue());
- }
-
- /**
- * Removes all headers that match the given header.
- *
- * @param header the header to remove
- * @return {@code true} if any header was removed as a result of this call.
- *
- * @since 5.0
+ * Removes all headers.
*/
- public boolean removeHeaders(final Header header) {
- if (header == null) {
- return false;
- }
- boolean removed = false;
- for (final Iterator<Header> iterator = headerIterator(); iterator.hasNext();) {
- final Header current = iterator.next();
- if (headerEquals(header, current)) {
- iterator.remove();
- removed = true;
- }
- }
- return removed;
+ public void clear() {
+ headers.clear();
}
/**
- * Replaces the first occurrence of the header with the same name. If no header with
- * the same name is found the given header is added to the end of the list.
+ * Tests if headers with the given name are contained within this group.
*
- * @param header the new header that should replace the first header with the same
- * name if present in the list.
+ * <p>Header name comparison is case insensitive.
*
- * @since 5.0
+ * @param name the header name to test for
+ * @return {@code true} if at least one header with the name is
+ * contained, {@code false} otherwise
*/
- public void setHeader(final Header header) {
- if (header == null) {
- return;
- }
- for (int i = 0; i < this.headers.size(); i++) {
- final Header current = this.headers.get(i);
- if (current.getName().equalsIgnoreCase(header.getName())) {
- this.headers.set(i, header);
- return;
- }
- }
- this.headers.add(header);
+ @Override
+ public boolean containsHeader(final String name) {
+ return stream().anyMatch(ignoreCasePredicate(name));
}
/**
- * Sets all of the headers contained within this group overriding any
- * existing headers. The headers are added in the order in which they appear
- * in the array.
+ * Checks if a certain header is present in this message and how many times.
+ * <p>Header name comparison is case insensitive.
*
- * @param headers the headers to set
+ * @param name the header name to check for.
+ * @return number of occurrences of the header in the message.
*/
- public void setHeaders(final Header... headers) {
- clear();
- if (headers == null) {
- return;
- }
- Collections.addAll(this.headers, headers);
+ @Override
+ public int countHeaders(final String name) {
+ return (int) stream().filter(ignoreCasePredicate(name)).count();
}
/**
@@ -199,31 +141,6 @@ public class HeaderGroup implements MessageHeaders, Serializable {
}
}
- /**
- * Gets all of the headers with the given name. The returned array
- * maintains the relative order in which the headers were added.
- *
- * <p>Header name comparison is case insensitive.
- *
- * @param name the name of the header(s) to get
- *
- * @return an array of length ≥ 0
- */
- @Override
- public Header[] getHeaders(final String name) {
- List<Header> headersFound = null;
- for (int i = 0; i < this.headers.size(); i++) {
- final Header header = this.headers.get(i);
- if (header.getName().equalsIgnoreCase(name)) {
- if (headersFound == null) {
- headersFound = new ArrayList<>();
- }
- headersFound.add(header);
- }
- }
- return headersFound != null ? headersFound.toArray(EMPTY) : EMPTY;
- }
-
/**
* Gets the first header with the given name.
*
@@ -234,13 +151,7 @@ public class HeaderGroup implements MessageHeaders, Serializable {
*/
@Override
public Header getFirstHeader(final String name) {
- for (int i = 0; i < this.headers.size(); i++) {
- final Header header = this.headers.get(i);
- if (header.getName().equalsIgnoreCase(name)) {
- return header;
- }
- }
- return null;
+ return stream().filter(ignoreCasePredicate(name)).findFirst().orElse(null);
}
/**
@@ -256,8 +167,7 @@ public class HeaderGroup implements MessageHeaders, Serializable {
public Header getHeader(final String name) throws ProtocolException {
int count = 0;
Header singleHeader = null;
- for (int i = 0; i < this.headers.size(); i++) {
- final Header header = this.headers.get(i);
+ for (final Header header : this.headers) {
if (header.getName().equalsIgnoreCase(name)) {
singleHeader = header;
count++;
@@ -269,27 +179,6 @@ public class HeaderGroup implements MessageHeaders, Serializable {
return singleHeader;
}
- /**
- * Gets the last header with the given name.
- *
- * <p>Header name comparison is case insensitive.
- *
- * @param name the name of the header to get
- * @return the last header or {@code null}
- */
- @Override
- public Header getLastHeader(final String name) {
- // start at the end of the list and work backwards
- for (int i = headers.size() - 1; i >= 0; i--) {
- final Header header = headers.get(i);
- if (header.getName().equalsIgnoreCase(name)) {
- return header;
- }
- }
-
- return null;
- }
-
/**
* Gets all of the headers contained within this group.
*
@@ -301,43 +190,44 @@ public class HeaderGroup implements MessageHeaders, Serializable {
}
/**
- * Tests if headers with the given name are contained within this group.
+ * Gets all of the headers with the given name. The returned array
+ * maintains the relative order in which the headers were added.
*
* <p>Header name comparison is case insensitive.
*
- * @param name the header name to test for
- * @return {@code true} if at least one header with the name is
- * contained, {@code false} otherwise
+ * @param name the name of the header(s) to get
+ *
+ * @return an array of length ≥ 0
*/
@Override
- public boolean containsHeader(final String name) {
- for (int i = 0; i < this.headers.size(); i++) {
- final Header header = this.headers.get(i);
- if (header.getName().equalsIgnoreCase(name)) {
- return true;
- }
- }
-
- return false;
+ public Header[] getHeaders(final String name) {
+ return stream().filter(ignoreCasePredicate(name)).toArray(Header[]::new);
}
/**
- * Checks if a certain header is present in this message and how many times.
+ * Gets the last header with the given name.
+ *
* <p>Header name comparison is case insensitive.
*
- * @param name the header name to check for.
- * @return number of occurrences of the header in the message.
+ * @param name the name of the header to get
+ * @return the last header or {@code null}
*/
@Override
- public int countHeaders(final String name) {
- int count = 0;
- for (int i = 0; i < this.headers.size(); i++) {
- final Header header = this.headers.get(i);
+ public Header getLastHeader(final String name) {
+ // start at the end of the list and work backwards
+ for (int i = headers.size() - 1; i >= 0; i--) {
+ final Header header = headers.get(i);
if (header.getName().equalsIgnoreCase(name)) {
- count++;
+ return header;
}
}
- return count;
+
+ return null;
+ }
+
+ private boolean headerEquals(final Header header1, final Header header2) {
+ return header2 == header1 || header2.getName().equalsIgnoreCase(header1.getName())
+ && Objects.equals(header1.getValue(), header2.getValue());
}
/**
@@ -367,6 +257,42 @@ public class HeaderGroup implements MessageHeaders, Serializable {
return new BasicListHeaderIterator(this.headers, name);
}
+ private Predicate<? super Header> ignoreCasePredicate(final String name) {
+ return h -> h.getName().equalsIgnoreCase(name);
+ }
+
+ /**
+ * Removes the first given header.
+ *
+ * @param header the header to remove
+ * @return {@code true} if a header was removed as a result of this call.
+ */
+ public boolean removeHeader(final Header header) {
+ if (header == null) {
+ return false;
+ }
+ for (int i = 0; i < this.headers.size(); i++) {
+ final Header current = this.headers.get(i);
+ if (headerEquals(header, current)) {
+ this.headers.remove(current);
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Removes all headers that match the given header.
+ *
+ * @param header the header to remove
+ * @return {@code true} if any header was removed as a result of this call.
+ *
+ * @since 5.0
+ */
+ public boolean removeHeaders(final Header header) {
+ return header != null ? headers.removeIf(h -> headerEquals(header, h)) : false;
+ }
+
/**
* Removes all headers with a given name in this group.
*
@@ -376,23 +302,53 @@ public class HeaderGroup implements MessageHeaders, Serializable {
* @since 5.0
*/
public boolean removeHeaders(final String name) {
- if (name == null) {
- return false;
+ return name != null ? headers.removeIf(ignoreCasePredicate(name)) : false;
+ }
+
+ /**
+ * Replaces the first occurrence of the header with the same name. If no header with
+ * the same name is found the given header is added to the end of the list.
+ *
+ * @param header the new header that should replace the first header with the same
+ * name if present in the list.
+ *
+ * @since 5.0
+ */
+ public void setHeader(final Header header) {
+ if (header == null) {
+ return;
}
- boolean removed = false;
- for (final Iterator<Header> iterator = headerIterator(); iterator.hasNext(); ) {
- final Header header = iterator.next();
- if (header.getName().equalsIgnoreCase(name)) {
- iterator.remove();
- removed = true;
+ for (int i = 0; i < headers.size(); i++) {
+ if (ignoreCasePredicate(header.getName()).test(headers.get(i))) {
+ headers.set(i, header);
+ return;
}
}
- return removed;
+ headers.add(header);
+ }
+
+ /**
+ * Sets all of the headers contained within this group overriding any
+ * existing headers. The headers are added in the order in which they appear
+ * in the array.
+ *
+ * @param headers the headers to set
+ */
+ public void setHeaders(final Header... headers) {
+ clear();
+ if (headers == null) {
+ return;
+ }
+ Collections.addAll(this.headers, headers);
+ }
+
+ private Stream<Header> stream() {
+ return headers.stream();
}
@Override
public String toString() {
- return this.headers.toString();
+ return headers.toString();
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AsyncEntityProducers.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AsyncEntityProducers.java
index 44a7246f3..b4fb54348 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AsyncEntityProducers.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/entity/AsyncEntityProducers.java
@@ -40,6 +40,8 @@ import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.apache.hc.core5.function.Callback;
import org.apache.hc.core5.http.ContentType;
@@ -158,11 +160,7 @@ public final class AsyncEntityProducers {
@Override
public Set<String> getTrailerNames() {
- final Set<String> names = new LinkedHashSet<>();
- for (final Header trailer: trailers) {
- names.add(trailer.getName());
- }
- return names;
+ return Stream.of(trailers).map(Header::getName).collect(Collectors.toCollection(LinkedHashSet::new));
}
@Override
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/ssl/FixedPortStrategy.java b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/ssl/FixedPortStrategy.java
index 7d45df2bd..cb2548e3c 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/nio/ssl/FixedPortStrategy.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/nio/ssl/FixedPortStrategy.java
@@ -29,6 +29,7 @@ package org.apache.hc.core5.http.nio.ssl;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
+import java.util.stream.IntStream;
import org.apache.hc.core5.util.Args;
@@ -51,12 +52,7 @@ public final class FixedPortStrategy implements SecurePortStrategy {
@Override
public boolean isSecure(final SocketAddress localAddress) {
final int port = ((InetSocketAddress) localAddress).getPort();
- for (final int securePort: securePorts) {
- if (port == securePort) {
- return true;
- }
- }
- return false;
+ return IntStream.of(securePorts).anyMatch(securePort -> port == securePort);
}
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/ChainBuilder.java b/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/ChainBuilder.java
index d9d0e8109..a49dadb26 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/ChainBuilder.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/ChainBuilder.java
@@ -31,6 +31,7 @@ import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
+import java.util.stream.Stream;
/**
* Builder class to build a linked list (chain) of unique class instances. Each class can have
@@ -80,9 +81,7 @@ final class ChainBuilder<E> {
if (c == null) {
return this;
}
- for (final E e: c) {
- addFirst(e);
- }
+ c.forEach(this::addFirst);
return this;
}
@@ -91,9 +90,7 @@ final class ChainBuilder<E> {
if (c == null) {
return this;
}
- for (final E e: c) {
- addFirst(e);
- }
+ Stream.of(c).forEach(this::addFirst);
return this;
}
@@ -101,9 +98,7 @@ final class ChainBuilder<E> {
if (c == null) {
return this;
}
- for (final E e: c) {
- addLast(e);
- }
+ c.forEach(this::addLast);
return this;
}
@@ -112,9 +107,7 @@ final class ChainBuilder<E> {
if (c == null) {
return this;
}
- for (final E e: c) {
- addLast(e);
- }
+ Stream.of(c).forEach(this::addLast);
return this;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/HttpDateGenerator.java b/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/HttpDateGenerator.java
index 8bfd09046..e82ea8db1 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/HttpDateGenerator.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/protocol/HttpDateGenerator.java
@@ -64,7 +64,7 @@ public class HttpDateGenerator {
private final DateTimeFormatter dateTimeFormatter;
private long dateAsMillis;
private String dateAsText;
- private ZoneId zoneId;
+ private final ZoneId zoneId;
HttpDateGenerator() {
dateTimeFormatter =new DateTimeFormatterBuilder()
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TLS.java b/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TLS.java
index d1884f146..578ddea09 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TLS.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TLS.java
@@ -27,8 +27,9 @@
package org.apache.hc.core5.http.ssl;
-import java.util.ArrayList;
import java.util.List;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.ProtocolVersion;
@@ -102,12 +103,7 @@ public enum TLS {
if (protocols == null) {
return null;
}
- final List<String> enabledProtocols = new ArrayList<>();
- for (final String protocol : protocols) {
- if (isSecure(protocol)) {
- enabledProtocols.add(protocol);
- }
- }
+ final List<String> enabledProtocols = Stream.of(protocols).filter(TLS::isSecure).collect(Collectors.toList());
if (enabledProtocols.isEmpty()) {
enabledProtocols.add(V_1_2.id);
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TlsCiphers.java b/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TlsCiphers.java
index 140f92563..245a870bd 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TlsCiphers.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/ssl/TlsCiphers.java
@@ -27,13 +27,14 @@
package org.apache.hc.core5.http.ssl;
-import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
/**
* TLS cipher suite support methods
@@ -337,24 +338,15 @@ public final class TlsCiphers {
Pattern.compile(WEAK_CIPHERS, Pattern.CASE_INSENSITIVE)));
public static boolean isWeak(final String cipherSuite) {
- for (final Pattern pattern : WEAK_CIPHER_SUITE_PATTERNS) {
- if (pattern.matcher(cipherSuite).matches()) {
- return true;
- }
- }
- return false;
+ return WEAK_CIPHER_SUITE_PATTERNS.stream().anyMatch(pattern -> pattern.matcher(cipherSuite).matches());
}
public static String[] excludeH2Blacklisted(final String... ciphers) {
if (ciphers == null) {
return null;
}
- final List<String> enabledCiphers = new ArrayList<>();
- for (final String cipher: ciphers) {
- if (!TlsCiphers.isH2Blacklisted(cipher)) {
- enabledCiphers.add(cipher);
- }
- }
+ final List<String> enabledCiphers = Stream.of(ciphers).filter(cipher -> !TlsCiphers.isH2Blacklisted(cipher))
+ .collect(Collectors.toList());
return !enabledCiphers.isEmpty() ? enabledCiphers.toArray(new String[0]) : ciphers;
}
@@ -362,12 +354,8 @@ public final class TlsCiphers {
if (ciphers == null) {
return null;
}
- final List<String> enabledCiphers = new ArrayList<>();
- for (final String cipher: ciphers) {
- if (!TlsCiphers.isWeak(cipher)) {
- enabledCiphers.add(cipher);
- }
- }
+ final List<String> enabledCiphers = Stream.of(ciphers).filter(cipher -> !TlsCiphers.isWeak(cipher))
+ .collect(Collectors.toList());
return !enabledCiphers.isEmpty() ? enabledCiphers.toArray(new String[0]) : ciphers;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/http/support/AbstractRequestBuilder.java b/httpcore5/src/main/java/org/apache/hc/core5/http/support/AbstractRequestBuilder.java
index be0b9ab7d..aff585c28 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/http/support/AbstractRequestBuilder.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/http/support/AbstractRequestBuilder.java
@@ -33,6 +33,7 @@ import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
+import java.util.stream.Stream;
import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpHost;
@@ -275,9 +276,7 @@ public abstract class AbstractRequestBuilder<T> extends AbstractMessageBuilder<T
}
public AbstractRequestBuilder<T> addParameters(final NameValuePair... nvps) {
- for (final NameValuePair nvp : nvps) {
- addParameter(nvp);
- }
+ Stream.of(nvps).forEach(this::addParameter);
return this;
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java b/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java
index 8212db616..861bd4bfe 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/net/URIBuilder.java
@@ -38,6 +38,7 @@ import java.util.BitSet;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
+import java.util.stream.Collectors;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.NameValuePair;
@@ -271,12 +272,7 @@ public class URIBuilder {
if (s == null) {
return null;
}
- final List<String> segments = splitPath(s);
- final List<String> list = new ArrayList<>(segments.size());
- for (final String segment: segments) {
- list.add(PercentCodec.decode(segment, charset));
- }
- return list;
+ return splitPath(s).stream().map(segment -> PercentCodec.decode(segment, charset)).collect(Collectors.toList());
}
static void formatPath(final StringBuilder buf, final Iterable<String> segments, final boolean rootless, final Charset charset) {
@@ -952,9 +948,7 @@ public class URIBuilder {
return null;
}
final StringBuilder result = new StringBuilder();
- for (final String segment : this.pathSegments) {
- result.append('/').append(segment);
- }
+ this.pathSegments.forEach(segment -> result.append('/').append(segment));
return result.toString();
}
@@ -1034,7 +1028,7 @@ public class URIBuilder {
final List<String> inputSegments = this.pathSegments;
if (!inputSegments.isEmpty()) {
final LinkedList<String> outputSegments = new LinkedList<>();
- for (final String inputSegment : inputSegments) {
+ inputSegments.forEach(inputSegment -> {
if (!inputSegment.isEmpty() && !".".equals(inputSegment)) {
if ("..".equals(inputSegment)) {
if (!outputSegments.isEmpty()) {
@@ -1044,7 +1038,7 @@ public class URIBuilder {
outputSegments.addLast(inputSegment);
}
}
- }
+ });
if (!inputSegments.isEmpty()) {
final String lastSegment = inputSegments.get(inputSegments.size() - 1);
if (lastSegment.isEmpty()) {
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 4a40470ee..e0b0957eb 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
@@ -122,10 +122,7 @@ public class LaxConnPool<T, C extends ModalCloseable> implements ManagedConnPool
@Override
public void close(final CloseMode closeMode) {
if (isShutDown.compareAndSet(false, true)) {
- for (final Iterator<PerRoutePool<T, C>> it = routeToPool.values().iterator(); it.hasNext(); ) {
- final PerRoutePool<T, C> routePool = it.next();
- routePool.shutdown(closeMode);
- }
+ routeToPool.values().forEach(routePool -> routePool.shutdown(closeMode));
routeToPool.clear();
}
}
@@ -182,9 +179,7 @@ public class LaxConnPool<T, C extends ModalCloseable> implements ManagedConnPool
}
public void validatePendingRequests() {
- for (final PerRoutePool<T, C> routePool : routeToPool.values()) {
- routePool.validatePendingRequests();
- }
+ routeToPool.values().forEach(PerRoutePool::validatePendingRequests);
}
@Override
@@ -253,15 +248,11 @@ public class LaxConnPool<T, C extends ModalCloseable> implements ManagedConnPool
}
public void enumAvailable(final Callback<PoolEntry<T, C>> callback) {
- for (final PerRoutePool<T, C> routePool : routeToPool.values()) {
- routePool.enumAvailable(callback);
- }
+ routeToPool.values().forEach(routePool -> routePool.enumAvailable(callback));
}
public void enumLeased(final Callback<PoolEntry<T, C>> callback) {
- for (final PerRoutePool<T, C> routePool : routeToPool.values()) {
- routePool.enumLeased(callback);
- }
+ routeToPool.values().forEach(routePool -> routePool.enumLeased(callback));
}
@Override
@@ -394,9 +385,7 @@ public class LaxConnPool<T, C extends ModalCloseable> implements ManagedConnPool
while ((entryRef = available.poll()) != null) {
entryRef.getReference().discardConnection(closeMode);
}
- for (final PoolEntry<T, C> entry : leased.keySet()) {
- entry.discardConnection(closeMode);
- }
+ leased.keySet().forEach(entry -> entry.discardConnection(closeMode));
leased.clear();
LeaseRequest<T, C> leaseRequest;
while ((leaseRequest = pending.poll()) != null) {
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 9801cf82e..c676b9dd8 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
@@ -139,9 +139,7 @@ public class StrictConnPool<T, C extends ModalCloseable> implements ManagedConnP
fireCallbacks();
this.lock.lock();
try {
- for (final PerRoutePool<T, C> pool: this.routeToPool.values()) {
- pool.shutdown(closeMode);
- }
+ this.routeToPool.values().forEach(pool -> pool.shutdown(closeMode));
this.routeToPool.clear();
this.leased.clear();
this.available.clear();
@@ -529,12 +527,8 @@ public class StrictConnPool<T, C extends ModalCloseable> implements ManagedConnP
this.lock.lock();
try {
final PerRoutePool<T, C> pool = getPool(route);
- int pendingCount = 0;
- for (final LeaseRequest<T, C> request: pendingRequests) {
- if (Objects.equals(route, request.getRoute())) {
- pendingCount++;
- }
- }
+ final int pendingCount = (int) pendingRequests.stream()
+ .filter(request -> Objects.equals(route, request.getRoute())).count();
return new PoolStats(
pool.getLeasedCount(),
pendingCount,
@@ -593,11 +587,7 @@ public class StrictConnPool<T, C extends ModalCloseable> implements ManagedConnP
public void enumLeased(final Callback<PoolEntry<T, C>> callback) {
this.lock.lock();
try {
- final Iterator<PoolEntry<T, C>> it = this.leased.iterator();
- while (it.hasNext()) {
- final PoolEntry<T, C> entry = it.next();
- callback.execute(entry);
- }
+ this.leased.forEach(callback::execute);
processPendingRequests();
} finally {
this.lock.unlock();
@@ -822,9 +812,7 @@ public class StrictConnPool<T, C extends ModalCloseable> implements ManagedConnP
while ((availableEntry = available.poll()) != null) {
availableEntry.discardConnection(closeMode);
}
- for (final PoolEntry<T, C> entry: this.leased) {
- entry.discardConnection(closeMode);
- }
+ this.leased.forEach(entry -> entry.discardConnection(closeMode));
this.leased.clear();
}
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 efe855d95..0fadfe1e5 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
@@ -233,7 +233,7 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
}
public final void enumAvailable(final Callback<IOSession> callback) {
- for (final PoolEntry poolEntry: sessionPool.values()) {
+ sessionPool.values().forEach(poolEntry -> {
if (poolEntry.session != null) {
synchronized (poolEntry) {
if (poolEntry.session != null) {
@@ -244,12 +244,12 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
}
}
}
- }
+ });
}
public final void closeIdle(final TimeValue idleTime) {
final long deadline = System.currentTimeMillis() - (TimeValue.isPositive(idleTime) ? idleTime.toMilliseconds() : 0);
- for (final PoolEntry poolEntry: sessionPool.values()) {
+ sessionPool.values().forEach(poolEntry -> {
if (poolEntry.session != null) {
synchronized (poolEntry) {
if (poolEntry.session != null && poolEntry.session.getLastReadTime() <= deadline) {
@@ -258,7 +258,7 @@ public abstract class AbstractIOSessionPool<T> implements ModalCloseable {
}
}
}
- }
+ });
}
public final Set<T> getRoutes() {
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/reactor/MultiCoreIOReactor.java b/httpcore5/src/main/java/org/apache/hc/core5/reactor/MultiCoreIOReactor.java
index 7be876463..8d61b433d 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/reactor/MultiCoreIOReactor.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/reactor/MultiCoreIOReactor.java
@@ -30,6 +30,7 @@ package org.apache.hc.core5.reactor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
+import java.util.stream.Stream;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.io.Closer;
@@ -66,9 +67,7 @@ class MultiCoreIOReactor implements IOReactor {
*/
public final void start() {
if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.ACTIVE)) {
- for (int i = 0; i < this.threads.length; i++) {
- this.threads[i].start();
- }
+ Stream.of(this.threads).forEach(Thread::start);
}
}
@@ -76,10 +75,7 @@ class MultiCoreIOReactor implements IOReactor {
public final void initiateShutdown() {
if (this.status.compareAndSet(IOReactorStatus.INACTIVE, IOReactorStatus.SHUT_DOWN) ||
this.status.compareAndSet(IOReactorStatus.ACTIVE, IOReactorStatus.SHUTTING_DOWN)) {
- for (int i = 0; i < this.ioReactors.length; i++) {
- final IOReactor ioReactor = this.ioReactors[i];
- ioReactor.initiateShutdown();
- }
+ Stream.of(this.ioReactors).forEach(IOReactor::initiateShutdown);
}
}
@@ -88,8 +84,7 @@ class MultiCoreIOReactor implements IOReactor {
Args.notNull(waitTime, "Wait time");
final long deadline = System.currentTimeMillis() + waitTime.toMilliseconds();
long remaining = waitTime.toMilliseconds();
- for (int i = 0; i < this.ioReactors.length; i++) {
- final IOReactor ioReactor = this.ioReactors[i];
+ for (final IOReactor ioReactor : this.ioReactors) {
if (ioReactor.getStatus().compareTo(IOReactorStatus.SHUT_DOWN) < 0) {
ioReactor.awaitShutdown(TimeValue.of(remaining, TimeUnit.MILLISECONDS));
remaining = deadline - System.currentTimeMillis();
@@ -98,8 +93,7 @@ class MultiCoreIOReactor implements IOReactor {
}
}
}
- for (int i = 0; i < this.threads.length; i++) {
- final Thread thread = this.threads[i];
+ for (final Thread thread : this.threads) {
thread.join(remaining);
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
@@ -135,12 +129,8 @@ class MultiCoreIOReactor implements IOReactor {
}
this.status.set(IOReactorStatus.SHUT_DOWN);
if (this.terminated.compareAndSet(false, true)) {
- for (int i = 0; i < this.ioReactors.length; i++) {
- Closer.close(this.ioReactors[i], CloseMode.IMMEDIATE);
- }
- for (int i = 0; i < this.threads.length; i++) {
- this.threads[i].interrupt();
- }
+ Stream.of(this.ioReactors).forEach(ioReactor -> Closer.close(ioReactor, CloseMode.IMMEDIATE));
+ Stream.of(this.threads).forEach(Thread::interrupt);
}
}
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 d494c3ad4..1aacdf0a7 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
@@ -151,12 +151,12 @@ class SingleCoreIOReactor extends AbstractSingleCoreIOReactor implements Connect
private void initiateSessionShutdown() {
if (this.sessionShutdownCallback != null) {
final Set<SelectionKey> keys = this.selector.keys();
- for (final SelectionKey key : keys) {
+ keys.forEach(key -> {
final InternalChannel channel = (InternalChannel) key.attachment();
if (channel instanceof InternalDataChannel) {
this.sessionShutdownCallback.execute((InternalDataChannel) channel);
}
- }
+ });
}
}
@@ -164,14 +164,12 @@ class SingleCoreIOReactor extends AbstractSingleCoreIOReactor implements Connect
final long currentTimeMillis = System.currentTimeMillis();
if ((currentTimeMillis - this.lastTimeoutCheckMillis) >= this.selectTimeoutMillis) {
this.lastTimeoutCheckMillis = currentTimeMillis;
- for (final SelectionKey key : this.selector.keys()) {
- checkTimeout(key, currentTimeMillis);
- }
+ this.selector.keys().forEach(key -> checkTimeout(key, currentTimeMillis));
}
}
private void processEvents(final Set<SelectionKey> selectedKeys) {
- for (final SelectionKey key : selectedKeys) {
+ selectedKeys.forEach(key -> {
final InternalChannel channel = (InternalChannel) key.attachment();
if (channel != null) {
try {
@@ -180,7 +178,7 @@ class SingleCoreIOReactor extends AbstractSingleCoreIOReactor implements Connect
channel.close(CloseMode.GRACEFUL);
}
}
- }
+ });
selectedKeys.clear();
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/ssl/SSLContextBuilder.java b/httpcore5/src/main/java/org/apache/hc/core5/ssl/SSLContextBuilder.java
index 97f2b4b1f..b89e420c4 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/ssl/SSLContextBuilder.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/ssl/SSLContextBuilder.java
@@ -54,6 +54,7 @@ import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
+import java.util.stream.Stream;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
@@ -527,9 +528,8 @@ public class SSLContextBuilder {
public Map<String, PrivateKeyDetails> getClientAliasMap(
final String[] keyTypes, final Principal[] issuers) {
final Map<String, PrivateKeyDetails> validAliases = new HashMap<>();
- for (final String keyType: keyTypes) {
- putPrivateKeyDetails(validAliases, keyType, this.keyManager.getClientAliases(keyType, issuers));
- }
+ Stream.of(keyTypes).forEach(keyType -> putPrivateKeyDetails(validAliases, keyType,
+ this.keyManager.getClientAliases(keyType, issuers)));
return validAliases;
}
@@ -540,13 +540,14 @@ public class SSLContextBuilder {
return validAliases;
}
- private void putPrivateKeyDetails(final Map<String, PrivateKeyDetails> validAliases, final String keyType,
+ private Map<String, PrivateKeyDetails> putPrivateKeyDetails(final Map<String, PrivateKeyDetails> validAliases, final String keyType,
final String[] aliases) {
if (aliases != null) {
for (final String alias: aliases) {
validAliases.put(alias, new PrivateKeyDetails(keyType, this.keyManager.getCertificateChain(alias)));
}
}
+ return validAliases;
}
@Override
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/util/TextUtils.java b/httpcore5/src/main/java/org/apache/hc/core5/util/TextUtils.java
index a8b6a6e28..1f2551d31 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/util/TextUtils.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/util/TextUtils.java
@@ -118,8 +118,8 @@ public final class TextUtils {
return null;
}
final StringBuilder buffer = new StringBuilder();
- for (int i = 0; i < bytes.length; i++) {
- final int unsignedB = bytes[i] & 0xff;
+ for (final byte element : bytes) {
+ final int unsignedB = element & 0xff;
if (unsignedB < 16) {
buffer.append('0');
}
diff --git a/httpcore5/src/main/java/org/apache/hc/core5/util/VersionInfo.java b/httpcore5/src/main/java/org/apache/hc/core5/util/VersionInfo.java
index 7801efba4..473b171c9 100644
--- a/httpcore5/src/main/java/org/apache/hc/core5/util/VersionInfo.java
+++ b/httpcore5/src/main/java/org/apache/hc/core5/util/VersionInfo.java
@@ -29,10 +29,10 @@ package org.apache.hc.core5.util;
import java.io.IOException;
import java.io.InputStream;
-import java.util.ArrayList;
-import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Properties;
+import java.util.stream.Stream;
/**
* Provides access to version information for HTTP components.
@@ -80,12 +80,6 @@ public class VersionInfo {
/** The classloader from which the version info was obtained. */
private final String infoClassloader;
- /**
- * An empty immutable {@code VersionInfo} array.
- */
- private static final VersionInfo[] EMPTY_VERSION_INFO_ARRAY = {};
-
-
/**
* Instantiates version information.
*
@@ -202,21 +196,12 @@ public class VersionInfo {
* @return the version information for all packages found,
* never {@code null}
*/
- public static VersionInfo[] loadVersionInfo(final String[] pckgs,
- final ClassLoader clsldr) {
+ public static VersionInfo[] loadVersionInfo(final String[] pckgs, final ClassLoader clsldr) {
Args.notNull(pckgs, "Package identifier array");
- final List<VersionInfo> vil = new ArrayList<>(pckgs.length);
- for (final String pckg : pckgs) {
- final VersionInfo vi = loadVersionInfo(pckg, clsldr);
- if (vi != null) {
- vil.add(vi);
- }
- }
-
- return vil.toArray(EMPTY_VERSION_INFO_ARRAY);
+ return Stream.of(pckgs).map(pckg -> loadVersionInfo(pckg, clsldr)).filter(Objects::nonNull)
+ .toArray(VersionInfo[]::new);
}
-
/**
* Loads version information for a package.
*
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/ReadableByteChannelMock.java b/httpcore5/src/test/java/org/apache/hc/core5/http/ReadableByteChannelMock.java
index dc9582f1e..48d9c0877 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/ReadableByteChannelMock.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/ReadableByteChannelMock.java
@@ -32,6 +32,7 @@ import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.Charset;
+import java.util.stream.Stream;
public class ReadableByteChannelMock implements ReadableByteChannel {
@@ -45,10 +46,7 @@ public class ReadableByteChannelMock implements ReadableByteChannel {
public ReadableByteChannelMock(final String[] strings, final Charset charset) {
super();
- this.chunks = new byte[strings.length][];
- for (int i = 0; i < strings.length; i++) {
- this.chunks[i] = strings[i].getBytes(charset);
- }
+ this.chunks = Stream.of(strings).map(s -> s.getBytes(charset)).toArray(byte[][]::new);
}
public ReadableByteChannelMock(final byte[]... chunks) {
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncPipelinedRequestExecutionExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncPipelinedRequestExecutionExample.java
index 5989e75d2..4ef7d9a96 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncPipelinedRequestExecutionExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncPipelinedRequestExecutionExample.java
@@ -26,6 +26,8 @@
*/
package org.apache.hc.core5.http.examples;
+import java.util.Arrays;
+import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
@@ -95,13 +97,13 @@ public class AsyncPipelinedRequestExecutionExample {
requester.start();
final HttpHost target = new HttpHost("httpbin.org");
- final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
+ final List<String> requestUris = Arrays.asList("/", "/ip", "/user-agent", "/headers");
final Future<AsyncClientEndpoint> future = requester.connect(target, Timeout.ofSeconds(5));
final AsyncClientEndpoint clientEndpoint = future.get();
- final CountDownLatch latch = new CountDownLatch(requestUris.length);
- for (final String requestUri: requestUris) {
+ final CountDownLatch latch = new CountDownLatch(requestUris.size());
+ requestUris.forEach(requestUri ->
clientEndpoint.execute(
AsyncRequestBuilder.get()
.setHttpHost(target)
@@ -131,8 +133,8 @@ public class AsyncPipelinedRequestExecutionExample {
System.out.println(requestUri + " cancelled");
}
- });
- }
+ })
+ );
latch.await();
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncRequestExecutionExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncRequestExecutionExample.java
index 30ff900ec..25d987cb4 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncRequestExecutionExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncRequestExecutionExample.java
@@ -26,6 +26,8 @@
*/
package org.apache.hc.core5.http.examples;
+import java.util.Arrays;
+import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@@ -92,10 +94,10 @@ public class AsyncRequestExecutionExample {
requester.start();
final HttpHost target = new HttpHost("httpbin.org");
- final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
+ final List<String> requestUris = Arrays.asList("/", "/ip", "/user-agent", "/headers");
- final CountDownLatch latch = new CountDownLatch(requestUris.length);
- for (final String requestUri: requestUris) {
+ final CountDownLatch latch = new CountDownLatch(requestUris.size());
+ requestUris.forEach(requestUri ->
requester.execute(
AsyncRequestBuilder.get()
.setHttpHost(target)
@@ -126,8 +128,8 @@ public class AsyncRequestExecutionExample {
latch.countDown();
}
- });
- }
+ })
+ );
latch.await();
System.out.println("Shutting down I/O reactor");
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncReverseProxyExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncReverseProxyExample.java
index 96726c70c..93db19009 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncReverseProxyExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/AsyncReverseProxyExample.java
@@ -35,7 +35,6 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
@@ -482,12 +481,11 @@ public class AsyncReverseProxyExample {
incomingRequest.getMethod(),
targetHost,
incomingRequest.getPath());
- for (final Iterator<Header> it = incomingRequest.headerIterator(); it.hasNext(); ) {
- final Header header = it.next();
+ incomingRequest.headerIterator().forEachRemaining(header -> {
if (!HOP_BY_HOP.contains(TextUtils.toLowerCase(header.getName()))) {
outgoingRequest.addHeader(header);
}
- }
+ });
println("[proxy->origin] " + exchangeState.id + " " +
outgoingRequest.getMethod() + " " + outgoingRequest.getRequestUri());
@@ -549,12 +547,11 @@ public class AsyncReverseProxyExample {
}
final HttpResponse outgoingResponse = new BasicHttpResponse(incomingResponse.getCode());
- for (final Iterator<Header> it = incomingResponse.headerIterator(); it.hasNext(); ) {
- final Header header = it.next();
+ incomingResponse.headerIterator().forEachRemaining(header -> {
if (!HOP_BY_HOP.contains(TextUtils.toLowerCase(header.getName()))) {
outgoingResponse.addHeader(header);
}
- }
+ });
exchangeState.response = outgoingResponse;
exchangeState.responseEntityDetails = entityDetails;
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicGetExecutionExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicGetExecutionExample.java
index 1b12d9979..a7953d3ed 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicGetExecutionExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicGetExecutionExample.java
@@ -83,10 +83,9 @@ public class ClassicGetExecutionExample {
final HttpCoreContext coreContext = HttpCoreContext.create();
final HttpHost target = new HttpHost("httpbin.org");
- final String[] requestUris = new String[] {"/", "/ip", "/user-agent", "/headers"};
+ final String[] requestUris = {"/", "/ip", "/user-agent", "/headers"};
- for (int i = 0; i < requestUris.length; i++) {
- final String requestUri = requestUris[i];
+ for (final String requestUri : requestUris) {
final ClassicHttpRequest request = ClassicRequestBuilder.get()
.setHttpHost(target)
.setPath(requestUri)
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicPostExecutionExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicPostExecutionExample.java
index fa79ae635..428936fec 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicPostExecutionExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicPostExecutionExample.java
@@ -105,12 +105,12 @@ public class ClassicPostExecutionExample {
};
final String requestUri = "/post";
- for (int i = 0; i < requestBodies.length; i++) {
+ for (final HttpEntity element : requestBodies) {
final ClassicHttpRequest request = ClassicRequestBuilder.get()
.setHttpHost(target)
.setPath(requestUri)
.build();
- request.setEntity(requestBodies[i]);
+ request.setEntity(element);
try (ClassicHttpResponse response = httpRequester.execute(target, request, Timeout.ofSeconds(5), coreContext)) {
System.out.println(requestUri + "->" + response.getCode());
System.out.println(EntityUtils.toString(response.getEntity()));
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicReverseProxyExample.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicReverseProxyExample.java
index b2fc53502..910082315 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicReverseProxyExample.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/ClassicReverseProxyExample.java
@@ -33,14 +33,12 @@ import java.net.SocketTimeoutException;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.Set;
import org.apache.hc.core5.http.ClassicHttpRequest;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.ConnectionClosedException;
import org.apache.hc.core5.http.ExceptionListener;
-import org.apache.hc.core5.http.Header;
import org.apache.hc.core5.http.HttpConnection;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHeaders;
@@ -222,22 +220,20 @@ public class ClassicReverseProxyExample {
incomingRequest.getMethod(),
targetHost,
incomingRequest.getPath());
- for (final Iterator<Header> it = incomingRequest.headerIterator(); it.hasNext(); ) {
- final Header header = it.next();
+ incomingRequest.headerIterator().forEachRemaining(header -> {
if (!HOP_BY_HOP.contains(TextUtils.toLowerCase(header.getName()))) {
outgoingRequest.addHeader(header);
}
- }
+ });
outgoingRequest.setEntity(incomingRequest.getEntity());
final ClassicHttpResponse incomingResponse = requester.execute(
targetHost, outgoingRequest, Timeout.ofMinutes(1), clientContext);
outgoingResponse.setCode(incomingResponse.getCode());
- for (final Iterator<Header> it = incomingResponse.headerIterator(); it.hasNext(); ) {
- final Header header = it.next();
+ incomingResponse.headerIterator().forEachRemaining(header -> {
if (!HOP_BY_HOP.contains(TextUtils.toLowerCase(header.getName()))) {
outgoingResponse.addHeader(header);
}
- }
+ });
outgoingResponse.setEntity(incomingResponse.getEntity());
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/PrintVersionInfo.java b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/PrintVersionInfo.java
index 85f1a6e1e..a38c10e52 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/examples/PrintVersionInfo.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/examples/PrintVersionInfo.java
@@ -27,6 +27,8 @@
package org.apache.hc.core5.http.examples;
+import java.util.stream.Stream;
+
import org.apache.hc.core5.util.VersionInfo;
/**
@@ -53,11 +55,10 @@ public class PrintVersionInfo {
* a list of packages for which to get version info.
*/
public static void main(final String args[]) {
- final String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
+ final String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null);
System.out.println("version info for thread context classloader:");
- for (int i=0; i<via.length; i++)
- System.out.println(via[i]);
+ Stream.of(via).forEach(System.out::println);
System.out.println();
@@ -65,11 +66,9 @@ public class PrintVersionInfo {
// is different from that for the thread context classloader,
// there may be a problem with multiple versions in the classpath
- via = VersionInfo.loadVersionInfo
- (pckgs, PrintVersionInfo.class.getClassLoader());
+ via = VersionInfo.loadVersionInfo(pckgs, PrintVersionInfo.class.getClassLoader());
System.out.println("version info for static classloader:");
- for (int i=0; i<via.length; i++)
- System.out.println(via[i]);
+ Stream.of(via).forEach(System.out::println);
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestEnglishReasonPhraseCatalog.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestEnglishReasonPhraseCatalog.java
index ae89fb19e..49633d84a 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestEnglishReasonPhraseCatalog.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/TestEnglishReasonPhraseCatalog.java
@@ -45,9 +45,9 @@ public class TestEnglishReasonPhraseCatalog {
public void testReasonPhrases() throws IllegalAccessException {
final Field[] publicFields = HttpStatus.class.getFields();
- Assertions.assertNotNull( publicFields );
+ Assertions.assertNotNull(publicFields);
- Assertions.assertTrue( publicFields.length > 0 );
+ Assertions.assertTrue(publicFields.length > 0);
for (final Field f : publicFields) {
final int modifiers = f.getModifiers();
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 e822d4640..e87ef8fd5 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
@@ -42,7 +42,7 @@ public class TestIdentityInputStream {
@Test
public void testBasicRead() throws Exception {
- final byte[] input = new byte[] {'a', 'b', 'c'};
+ final byte[] input = {'a', 'b', 'c'};
final ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream);
@@ -60,7 +60,7 @@ public class TestIdentityInputStream {
@Test
public void testClosedCondition() throws Exception {
- final byte[] input = new byte[] {'a', 'b', 'c'};
+ final byte[] input = {'a', 'b', 'c'};
final ByteArrayInputStream inputStream = new ByteArrayInputStream(input);
final SessionInputBuffer inBuffer = new SessionInputBufferImpl(16);
final IdentityInputStream in = new IdentityInputStream(inBuffer, inputStream);
@@ -76,7 +76,7 @@ public class TestIdentityInputStream {
@Test
public void testAvailable() throws Exception {
- final byte[] input = new byte[] {'a', 'b', 'c'};
+ final byte[] input = {'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);
@@ -87,7 +87,7 @@ public class TestIdentityInputStream {
@Test
public void testAvailableInStream() throws Exception {
- final byte[] input = new byte[] {'a', 'b', 'c', 'd', 'e', 'f'};
+ final byte[] input = {'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);
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 9c49c3760..b74e8e57f 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
@@ -81,7 +81,7 @@ public class TestIdentityOutputStream {
final byte[] input = outputStream.toByteArray();
Assertions.assertNotNull(input);
- final byte[] expected = new byte[] {'a', 'b', 'c'};
+ final byte[] expected = {'a', 'b', 'c'};
Assertions.assertEquals(expected.length, input.length);
for (int i = 0; i < expected.length; i++) {
Assertions.assertEquals(expected[i], input[i]);
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
index e6b25b79f..05cedf639 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/io/TestSessionInOutBuffers.java
@@ -36,6 +36,7 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
+import java.util.stream.IntStream;
import org.apache.hc.core5.http.MessageConstraintException;
import org.apache.hc.core5.http.impl.BasicHttpTransportMetrics;
@@ -471,9 +472,7 @@ public class TestSessionInOutBuffers {
private static String constructString(final int [] unicodeChars) {
final StringBuilder buffer = new StringBuilder();
if (unicodeChars != null) {
- for (final int unicodeChar : unicodeChars) {
- buffer.append((char)unicodeChar);
- }
+ IntStream.of(unicodeChars).forEach(i -> buffer.append((char) i));
}
return buffer.toString();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
index 7579a1fc5..b5fa0bd1c 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/impl/nio/TestSessionInOutBuffers.java
@@ -39,6 +39,7 @@ import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
+import java.util.stream.IntStream;
import org.apache.hc.core5.http.MessageConstraintException;
import org.apache.hc.core5.http.nio.SessionInputBuffer;
@@ -449,9 +450,7 @@ public class TestSessionInOutBuffers {
private static String constructString(final int [] unicodeChars) {
final StringBuilder buffer = new StringBuilder();
if (unicodeChars != null) {
- for (final int unicodeChar : unicodeChars) {
- buffer.append((char)unicodeChar);
- }
+ IntStream.of(unicodeChars).forEach(i -> buffer.append((char) i));
}
return buffer.toString();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
index 111389b79..d59b0c12f 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestEntityUtils.java
@@ -37,6 +37,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import java.util.stream.IntStream;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.HttpEntity;
@@ -135,9 +136,7 @@ public class TestEntityUtils {
private static String constructString(final int [] unicodeChars) {
final StringBuilder buffer = new StringBuilder();
if (unicodeChars != null) {
- for (final int unicodeChar : unicodeChars) {
- buffer.append((char)unicodeChar);
- }
+ IntStream.of(unicodeChars).forEach(i -> buffer.append((char) i));
}
return buffer.toString();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestStringEntity.java b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestStringEntity.java
index 819f7fa2e..abc4f6b13 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestStringEntity.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/io/entity/TestStringEntity.java
@@ -30,6 +30,7 @@ package org.apache.hc.core5.http.io.entity;
import java.io.ByteArrayOutputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
+import java.util.stream.IntStream;
import org.apache.hc.core5.http.ContentType;
import org.junit.jupiter.api.Assertions;
@@ -71,9 +72,7 @@ public class TestStringEntity {
private static String constructString(final int [] unicodeChars) {
final StringBuilder buffer = new StringBuilder();
if (unicodeChars != null) {
- for (final int unicodeChar : unicodeChars) {
- buffer.append((char)unicodeChar);
- }
+ IntStream.of(unicodeChars).forEach(i -> buffer.append((char) i));
}
return buffer.toString();
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderElementIterator.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderElementIterator.java
index 72dd92048..d38c818d9 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderElementIterator.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderElementIterator.java
@@ -42,7 +42,7 @@ public class TestBasicHeaderElementIterator {
@Test
public void testMultiHeader() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "value0"),
new BasicHeader("Name", "value1")
};
@@ -67,7 +67,7 @@ public class TestBasicHeaderElementIterator {
@Test
public void testMultiHeaderSameLine() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("name", "value0,value1"),
new BasicHeader("nAme", "cookie1=1,cookie2=2")
};
@@ -90,7 +90,7 @@ public class TestBasicHeaderElementIterator {
@Test
public void testFringeCases() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", null),
new BasicHeader("Name", " "),
new BasicHeader("Name", ",,,")
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderIterator.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderIterator.java
index 10e5eaffa..28f8406c3 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderIterator.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderIterator.java
@@ -42,7 +42,7 @@ public class TestBasicHeaderIterator {
@Test
public void testAllSame() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "value0"),
new BasicHeader("nAme", "value1, value1.1"),
new BasicHeader("naMe", "value2=whatever"),
@@ -77,7 +77,7 @@ public class TestBasicHeaderIterator {
@Test
public void testFirstLastOneNone() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("match" , "value0"),
new BasicHeader("mismatch", "value1, value1.1"),
new BasicHeader("single" , "value2=whatever"),
@@ -118,7 +118,7 @@ public class TestBasicHeaderIterator {
@Test
public void testInterspersed() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("yellow", "00"),
new BasicHeader("maroon", "01"),
new BasicHeader("orange", "02"),
@@ -229,7 +229,7 @@ public class TestBasicHeaderIterator {
public void testRemaining() {
// to satisfy Clover and take coverage to 100%
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "value0"),
new BasicHeader("nAme", "value1, value1.1"),
new BasicHeader("naMe", "value2=whatever"),
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderValueFormatter.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderValueFormatter.java
index 6d18d8850..de48ce26a 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderValueFormatter.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicHeaderValueFormatter.java
@@ -109,7 +109,7 @@ public class TestBasicHeaderValueFormatter {
final NameValuePair param1 = new BasicNameValuePair("param", "regular_stuff");
final NameValuePair param2 = new BasicNameValuePair("param", "this\\that");
final NameValuePair param3 = new BasicNameValuePair("param", "this,that");
- final NameValuePair[] params = new NameValuePair[] {param1, param2, param3};
+ final NameValuePair[] params = {param1, param2, param3};
final CharArrayBuffer buf = new CharArrayBuffer(64);
@@ -129,7 +129,7 @@ public class TestBasicHeaderValueFormatter {
final NameValuePair param2 = new BasicNameValuePair("param", "this\\that");
final NameValuePair param3 = new BasicNameValuePair("param", "this,that");
final NameValuePair param4 = new BasicNameValuePair("param", null);
- final NameValuePair[] params = new NameValuePair[] {param1, param2, param3, param4};
+ final NameValuePair[] params = {param1, param2, param3, param4};
final HeaderElement element = new BasicHeaderElement("name", "value", params);
final CharArrayBuffer buf = new CharArrayBuffer(64);
@@ -150,7 +150,7 @@ public class TestBasicHeaderValueFormatter {
final HeaderElement element3 = new BasicHeaderElement("name3", "value3", new NameValuePair[] {param3});
final HeaderElement element4 = new BasicHeaderElement("name4", "value4", new NameValuePair[] {param4});
final HeaderElement element5 = new BasicHeaderElement("name5", null);
- final HeaderElement[] elements = new HeaderElement[] {element1, element2, element3, element4, element5};
+ final HeaderElement[] elements = {element1, element2, element3, element4, element5};
final CharArrayBuffer buf = new CharArrayBuffer(64);
@@ -165,9 +165,9 @@ public class TestBasicHeaderValueFormatter {
public void testInvalidArguments() throws Exception {
final CharArrayBuffer buf = new CharArrayBuffer(64);
final NameValuePair param = new BasicNameValuePair("param", "regular_stuff");
- final NameValuePair[] params = new NameValuePair[] {param};
+ final NameValuePair[] params = {param};
final HeaderElement element = new BasicHeaderElement("name1", "value1", null);
- final HeaderElement[] elements = new HeaderElement[] {element};
+ final HeaderElement[] elements = {element};
Assertions.assertThrows(NullPointerException.class, () ->
formatter.formatNameValuePair(null, param, false));
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicTokenIterator.java b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicTokenIterator.java
index e41f0252b..b8ef51ece 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicTokenIterator.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/message/TestBasicTokenIterator.java
@@ -43,7 +43,7 @@ public class TestBasicTokenIterator {
@Test
public void testSingleHeader() {
- Header[] headers = new Header[]{
+ Header[] headers = {
new BasicHeader("Name", "token0,token1, token2 , token3")
};
Iterator<Header> hit = new BasicHeaderIterator(headers, null);
@@ -74,7 +74,7 @@ public class TestBasicTokenIterator {
@Test
public void testMultiHeader() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "token0,token1"),
new BasicHeader("Name", ""),
new BasicHeader("Name", "token2"),
@@ -102,7 +102,7 @@ public class TestBasicTokenIterator {
@Test
public void testEmpty() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", " "),
new BasicHeader("Name", ""),
new BasicHeader("Name", ","),
@@ -123,7 +123,7 @@ public class TestBasicTokenIterator {
@Test
public void testValueStart() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "token0"),
new BasicHeader("Name", " token1"),
new BasicHeader("Name", ",token2"),
@@ -152,7 +152,7 @@ public class TestBasicTokenIterator {
@Test
public void testValueEnd() {
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", "token0"),
new BasicHeader("Name", "token1 "),
new BasicHeader("Name", "token2,"),
@@ -182,7 +182,7 @@ public class TestBasicTokenIterator {
public void testWrongPublic() {
Assertions.assertThrows(NullPointerException.class, () -> new BasicTokenIterator(null));
- final Header[] headers = new Header[]{
+ final Header[] headers = {
new BasicHeader("Name", " "),
new BasicHeader("Name", ""),
new BasicHeader("Name", ","),
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
index a28328780..dfe75fd3a 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/protocol/TestStandardInterceptors.java
@@ -584,7 +584,7 @@ public class TestStandardInterceptors {
final ResponseConnControl interceptor = new ResponseConnControl();
- final int [] statusCodes = new int[] {
+ final int [] statusCodes = {
HttpStatus.SC_BAD_REQUEST,
HttpStatus.SC_REQUEST_TIMEOUT,
HttpStatus.SC_LENGTH_REQUIRED,
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TLSTest.java b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TLSTest.java
index e9a2730a4..c25a23a5b 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TLSTest.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TLSTest.java
@@ -81,8 +81,7 @@ class TLSTest {
"TLS 1.2",
"TLS 1.1"
};
- final String[] strongProtocols = TLS.excludeWeak(mixProtocol);
- for (final String protocol : strongProtocols) {
+ for (final String protocol : TLS.excludeWeak(mixProtocol)) {
Assertions.assertTrue(TLS.isSecure(protocol));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsCiphers.java b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsCiphers.java
index 8313b9e39..0af3159a7 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsCiphers.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/http/ssl/TestTlsCiphers.java
@@ -85,8 +85,7 @@ public class TestTlsCiphers {
"TLS_RSA_WITH_AES_256_GCM_SHA384"
};
- final String[] strongCipherSuites = TlsCiphers.excludeH2Blacklisted(mixCipherSuites);
- for (final String cipherSuite : strongCipherSuites) {
+ for (final String cipherSuite : TlsCiphers.excludeH2Blacklisted(mixCipherSuites)) {
Assertions.assertFalse(TlsCiphers.isWeak(cipherSuite));
}
}
@@ -117,8 +116,7 @@ public class TestTlsCiphers {
"TLS_RSA_WITH_AES_256_GCM_SHA384"
};
- final String[] strongCipherSuites = TlsCiphers.excludeWeak(weakCiphersSuites);
- for (final String cipherSuite : strongCipherSuites) {
+ for (final String cipherSuite : TlsCiphers.excludeWeak(weakCiphersSuites)) {
Assertions.assertFalse(TlsCiphers.isWeak(cipherSuite));
}
}
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
index af4be3bf0..3a52a6fe8 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestArgs.java
@@ -263,7 +263,7 @@ public class TestArgs {
@Test
public void testIsEmpty() {
- final String[] NON_EMPTY_ARRAY = new String[] { "ABG", "NML", };
+ final String[] NON_EMPTY_ARRAY = { "ABG", "NML", };
final List<String> NON_EMPTY_LIST = Arrays.asList(NON_EMPTY_ARRAY);
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestByteArrayBuffer.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestByteArrayBuffer.java
index 2d9a0e7ba..01173c3d1 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestByteArrayBuffer.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestByteArrayBuffer.java
@@ -64,7 +64,7 @@ public class TestByteArrayBuffer {
Assertions.assertTrue(buffer.isEmpty());
Assertions.assertFalse(buffer.isFull());
- final byte[] tmp = new byte[] { 1, 2, 3, 4};
+ final byte[] tmp = { 1, 2, 3, 4};
buffer.append(tmp, 0, tmp.length);
Assertions.assertEquals(16, buffer.capacity());
Assertions.assertEquals(4, buffer.length());
@@ -90,7 +90,7 @@ public class TestByteArrayBuffer {
final ByteArrayBuffer buffer = new ByteArrayBuffer(4);
Assertions.assertEquals(4, buffer.capacity());
- final byte[] tmp = new byte[] { 1, 2, 3, 4};
+ final byte[] tmp = { 1, 2, 3, 4};
buffer.append(tmp, 0, 2);
buffer.append(tmp, 0, 4);
buffer.append(tmp, 0, 0);
@@ -176,7 +176,7 @@ public class TestByteArrayBuffer {
final ByteArrayBuffer buffer = new ByteArrayBuffer(4);
buffer.append((byte[])null, 0, 0);
- final byte[] tmp = new byte[] { 1, 2, 3, 4};
+ final byte[] tmp = { 1, 2, 3, 4};
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, -1, 0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, -1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, 8));
@@ -189,7 +189,7 @@ public class TestByteArrayBuffer {
final ByteArrayBuffer buffer = new ByteArrayBuffer(4);
Assertions.assertEquals(4, buffer.capacity());
- final byte[] tmp = new byte[] { 1, 127, -1, -128, 1, -2};
+ final byte[] tmp = { 1, 127, -1, -128, 1, -2};
for (final byte element : tmp) {
buffer.append(element);
}
@@ -291,7 +291,7 @@ public class TestByteArrayBuffer {
final ByteArrayBuffer buffer = new ByteArrayBuffer(4);
buffer.append((char[])null, 0, 0);
- final char[] tmp = new char[] { '1', '2', '3', '4'};
+ final char[] tmp = { '1', '2', '3', '4'};
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, -1, 0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, -1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, 8));
diff --git a/httpcore5/src/test/java/org/apache/hc/core5/util/TestCharArrayBuffer.java b/httpcore5/src/test/java/org/apache/hc/core5/util/TestCharArrayBuffer.java
index 1aa9f8dd9..483bf6961 100644
--- a/httpcore5/src/test/java/org/apache/hc/core5/util/TestCharArrayBuffer.java
+++ b/httpcore5/src/test/java/org/apache/hc/core5/util/TestCharArrayBuffer.java
@@ -63,7 +63,7 @@ public class TestCharArrayBuffer {
Assertions.assertTrue(buffer.isEmpty());
Assertions.assertFalse(buffer.isFull());
- final char[] tmp = new char[] { '1', '2', '3', '4'};
+ final char[] tmp = { '1', '2', '3', '4'};
buffer.append(tmp, 0, tmp.length);
Assertions.assertEquals(16, buffer.capacity());
Assertions.assertEquals(4, buffer.length());
@@ -91,7 +91,7 @@ public class TestCharArrayBuffer {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
Assertions.assertEquals(4, buffer.capacity());
- final char[] tmp = new char[] { '1', '2', '3', '4'};
+ final char[] tmp = { '1', '2', '3', '4'};
buffer.append(tmp, 0, 2);
buffer.append(tmp, 0, 4);
buffer.append(tmp, 0, 0);
@@ -157,7 +157,7 @@ public class TestCharArrayBuffer {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.append((char[])null, 0, 0);
- final char[] tmp = new char[] { '1', '2', '3', '4'};
+ final char[] tmp = { '1', '2', '3', '4'};
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, -1, 0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, -1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, 8));
@@ -239,7 +239,7 @@ public class TestCharArrayBuffer {
@Test
public void testAppendISOByteArray() throws Exception {
- final byte[] b = new byte[] {0x00, 0x20, 0x7F, -0x80, -0x01};
+ final byte[] b = {0x00, 0x20, 0x7F, -0x80, -0x01};
final CharArrayBuffer buffer = new CharArrayBuffer(8);
buffer.append(b, 0, b.length);
@@ -272,7 +272,7 @@ public class TestCharArrayBuffer {
final CharArrayBuffer buffer = new CharArrayBuffer(4);
buffer.append((byte[])null, 0, 0);
- final byte[] tmp = new byte[] { '1', '2', '3', '4'};
+ final byte[] tmp = { '1', '2', '3', '4'};
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, -1, 0));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, -1));
Assertions.assertThrows(IndexOutOfBoundsException.class, () -> buffer.append(tmp, 0, 8));